mirror of
https://github.com/aziascreations/BakaShrot.git
synced 2026-11-23 20:58:46 +01:00
Protocol 6: node identities, error codes, Synchronous, schema v8, examples
- Protocol 5: a client authenticates as a node (Node), its pushes go to the section's DefaultTopic unless they name one; old Identities refused at start with what to write instead. - Topics listed by name, ids picked and kept by the server; nodes come from client sections, [BakaShrot.Nodes] optional, AcceptNodes = * by default. - Protocol 6: every refusal carries a code, every client failure too (BakaShrot_ErrorCodes.pbi, BakaShrot_GetLastError(), ErrorCode in Python); nothing reconnects by itself, delivery is at least once. - [BakaShrot.Server] Synchronous = FULL (default) or NORMAL, benchmarked. - Schema v8: browse table and browse_messages view for database tools. - Tools renamed BakaShrot<Name>, wait for Enter when started from Explorer. - Examples/SingleServer: a server and a client with scripts (example keys, public on purpose). - Restart-Test.ps1: servers killed mid-traffic and mid-catch-up. - Docs: one server per node rule, DatabaseError() checked per thread, release notes' Compatibility section, Notes "Right now". Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01RwFeVQrLqMQPw9AZnsHqQH
This commit is contained in:
@@ -21,3 +21,8 @@ Release/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
|
||||
# The examples run their server in their own folder: its database, and
|
||||
# what their client scripts write
|
||||
Examples/**/*.sqlite*
|
||||
Examples/**/out/
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
# 0. Extracts libsodium's dynamic build from Libs/libsodium-*-msvc.zip, and
|
||||
# sqlite3.dll from the latest Libs/sqlite-dll-win-*.zip, if not done yet.
|
||||
# Delete Libs/libsodium/x64 or Libs/sqlite/x64 to extract them again.
|
||||
# 1. Compiles KeyGen, the server, the client DLL, its example app and the
|
||||
# tools (PushMessage, GetLatestMessage, GetMessages, Query, Resolve,
|
||||
# ListNames) into ./Build, next to copies of
|
||||
# 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
|
||||
@@ -21,11 +22,11 @@
|
||||
# run raw queries
|
||||
# client2.ini logs:local2 through server2, same client key, may not query
|
||||
# Both servers replicate logs and sensors to each other, e.g.:
|
||||
# .\PushMessage.exe -t sensors @msg.json client.ini
|
||||
# .\GetLatestMessage.exe sensors local client2.ini
|
||||
# .\GetMessages.exe logs local --follow client2.ini
|
||||
# .\Resolve.exe topic sensors client2.ini (201 there, 2 on server)
|
||||
# .\Query.exe "SELECT topic, node, message_id FROM messages" client.ini
|
||||
# .\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
|
||||
@@ -137,10 +138,10 @@ function Invoke-Compiler($Source, $Executable, $Flags) {
|
||||
}
|
||||
|
||||
function New-KeyPair {
|
||||
# KeyGen prints "PrivateKey = ..." then "PublicKey = ...".
|
||||
$Lines = & (Join-Path $Output "KeyGen.exe")
|
||||
# BakaShrotGenerateKeyPairs prints "PrivateKey = ..." then "PublicKey = ...".
|
||||
$Lines = & (Join-Path $Output "BakaShrotGenerateKeyPairs.exe")
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
throw "KeyGen failed: $Lines"
|
||||
throw "BakaShrotGenerateKeyPairs failed: $Lines"
|
||||
}
|
||||
return @{
|
||||
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
|
||||
@@ -166,26 +167,26 @@ try {
|
||||
Copy-Item (Join-Path $SqliteDir "sqlite3.dll") $Output -Force
|
||||
|
||||
# 1. Compile
|
||||
Invoke-Compiler "Tools\KeyGen\KeyGen.pb" "KeyGen.exe" @("/CONSOLE")
|
||||
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:
|
||||
# PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||
# GetLatestMessage <Topic> <Node> [ClientIni]
|
||||
Invoke-Compiler "Tools\PushMessage\PushMessage.pb" "PushMessage.exe" @("/CONSOLE")
|
||||
Invoke-Compiler "Tools\GetLatestMessage\GetLatestMessage.pb" "GetLatestMessage.exe" @("/CONSOLE")
|
||||
# GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [ClientIni]
|
||||
Invoke-Compiler "Tools\GetMessages\GetMessages.pb" "GetMessages.exe" @("/CONSOLE")
|
||||
# GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||
Invoke-Compiler "Tools\GetAttachment\GetAttachment.pb" "GetAttachment.exe" @("/CONSOLE")
|
||||
# Query <Sql|@SqlFile> [ClientIni]
|
||||
Invoke-Compiler "Tools\Query\Query.pb" "Query.exe" @("/CONSOLE")
|
||||
# Resolve <topic|node> <NameOrId> [ClientIni]
|
||||
Invoke-Compiler "Tools\Resolve\Resolve.pb" "Resolve.exe" @("/CONSOLE")
|
||||
# ListNames [topics|nodes|all] [ClientIni] [--json]
|
||||
Invoke-Compiler "Tools\ListNames\ListNames.pb" "ListNames.exe" @("/CONSOLE")
|
||||
# BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||
Invoke-Compiler "Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb" "BakaShrotPushMessage.exe" @("/CONSOLE")
|
||||
# BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]
|
||||
Invoke-Compiler "Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb" "BakaShrotGetLatestMessage.exe" @("/CONSOLE")
|
||||
# BakaShrotGetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [ClientIni]
|
||||
Invoke-Compiler "Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb" "BakaShrotGetMessages.exe" @("/CONSOLE")
|
||||
# BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||
Invoke-Compiler "Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb" "BakaShrotGetAttachment.exe" @("/CONSOLE")
|
||||
# BakaShrotQuery <Sql|@SqlFile> [ClientIni]
|
||||
Invoke-Compiler "Tools\BakaShrotQuery\BakaShrotQuery.pb" "BakaShrotQuery.exe" @("/CONSOLE")
|
||||
# BakaShrotResolveIds <topic|node> <NameOrId> [ClientIni]
|
||||
Invoke-Compiler "Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb" "BakaShrotResolveIds.exe" @("/CONSOLE")
|
||||
# BakaShrotList [topics|nodes|all] [ClientIni] [--json]
|
||||
Invoke-Compiler "Tools\BakaShrotList\BakaShrotList.pb" "BakaShrotList.exe" @("/CONSOLE")
|
||||
|
||||
# 2. Keys
|
||||
Write-Host "Generating keys"
|
||||
@@ -199,7 +200,6 @@ try {
|
||||
$ServerConfig = @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($ServerKeys.PrivateKey)
|
||||
Topic = logs
|
||||
Node = server1
|
||||
|
||||
; This server's ids for the names every server shares.
|
||||
@@ -221,13 +221,13 @@ PeerBatchSize = $PeerBatchSize
|
||||
[BakaShrot.Peer.server2]
|
||||
Host = $ServerHost
|
||||
Port = $Server2Port
|
||||
Topic = logs
|
||||
Node = server2
|
||||
PublicKey = $($Server2Keys.PublicKey)
|
||||
|
||||
[BakaShrot.Client.local]
|
||||
PublicKeys = $($ClientKeys.PublicKey)
|
||||
Identities = logs:local
|
||||
Node = local
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;sensors
|
||||
ReadTopics = *
|
||||
AllowRead = 1
|
||||
@@ -237,7 +237,7 @@ AllowQuery = 1
|
||||
; The peer only replicates, it has no business reading or writing as a client.
|
||||
[BakaShrot.Client.server2]
|
||||
PublicKeys = $($Server2Keys.PublicKey)
|
||||
Identities = logs:server2
|
||||
Node = server2
|
||||
AllowRead = 0
|
||||
AllowWrite = 0
|
||||
AllowQuery = 0
|
||||
@@ -247,7 +247,6 @@ AllowQuery = 0
|
||||
$Server2Config = @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($Server2Keys.PrivateKey)
|
||||
Topic = logs
|
||||
Node = server2
|
||||
|
||||
; Other ids than server's, same names: replication goes by name.
|
||||
@@ -269,14 +268,13 @@ PeerBatchSize = $PeerBatchSize
|
||||
[BakaShrot.Peer.server]
|
||||
Host = $ServerHost
|
||||
Port = $ServerPort
|
||||
Topic = logs
|
||||
Node = server1
|
||||
PublicKey = $($ServerKeys.PublicKey)
|
||||
|
||||
; The peer only replicates, it has no business reading or writing as a client.
|
||||
[BakaShrot.Client.server]
|
||||
PublicKeys = $($ServerKeys.PublicKey)
|
||||
Identities = logs:server1
|
||||
Node = server1
|
||||
AllowRead = 0
|
||||
AllowWrite = 0
|
||||
AllowQuery = 0
|
||||
@@ -284,7 +282,8 @@ AllowQuery = 0
|
||||
; No raw queries through this server.
|
||||
[BakaShrot.Client.local]
|
||||
PublicKeys = $($ClientKeys.PublicKey)
|
||||
Identities = logs:local2
|
||||
Node = local2
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;sensors
|
||||
ReadTopics = *
|
||||
AllowRead = 1
|
||||
@@ -297,7 +296,6 @@ AllowQuery = 0
|
||||
[BakaShrot]
|
||||
PrivateKey = $($ClientKeys.PrivateKey)
|
||||
PublicKey = $($ClientKeys.PublicKey)
|
||||
Topic = logs
|
||||
Node = local2
|
||||
ServerHost = $ServerHost
|
||||
ServerPort = $Server2Port
|
||||
@@ -310,7 +308,6 @@ ServerPublicKey = $($Server2Keys.PublicKey)
|
||||
[BakaShrot]
|
||||
PrivateKey = $($ClientKeys.PrivateKey)
|
||||
PublicKey = $($ClientKeys.PublicKey)
|
||||
Topic = logs
|
||||
Node = local
|
||||
ServerHost = $ServerHost
|
||||
ServerPort = $ServerPort
|
||||
|
||||
@@ -8,8 +8,8 @@ operations come before security hardening (`Notes.md`, "Threat model").
|
||||
|
||||
## Read first
|
||||
|
||||
1. `Notes.md`: where things stand, "Open items, by importance" (the to-do
|
||||
list, item 3 is the next known bug), "Testing tips".
|
||||
1. `Notes.md`: "Right now" (what's committed, what's next), where things
|
||||
stand, "Open items, by importance" (the to-do list), "Testing tips".
|
||||
2. `Design/`, by topic: `Packets.md` (the protocol, where every file lives,
|
||||
code conventions), `Attachments.md`, `Cryptography.md`,
|
||||
`StorageConcurrency.md`, `ReplicationIssues.md`, `Release.md`,
|
||||
@@ -30,7 +30,7 @@ operations come before security hardening (`Notes.md`, "Threat model").
|
||||
|---|---|---|
|
||||
| `Server\BakaShrot_Server.pb` | `Build\BakaShrot_Server.exe` | `/CONSOLE /THREAD` |
|
||||
| `Client\BakaShrot_Client.pbi` | `Build\BakaShrot_Client.dll` | `/DLL /THREAD` |
|
||||
| `Tools\<Name>\<Name>.pb` (PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, Resolve, ListNames, KeyGen) | `Build\<Name>.exe` | `/CONSOLE` |
|
||||
| `Tools\<Name>\<Name>.pb` (BakaShrot + PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query, ResolveIds, List, GenerateKeyPairs) | `Build\<Name>.exe` | `/CONSOLE` |
|
||||
| `Client\BakaShrot_Client_Prototypes.pbi` | `Build\ClientExample.exe` | `/CONSOLE` |
|
||||
| `Tests\Bench\BenchServer.pb` (the server with a stop file, used by every test) | `Build\Bench\BenchServer.exe` | `/CONSOLE /THREAD` |
|
||||
| `Tests\Bench\BenchClient.pb`, `BenchSeed.pb` | `Build\Bench\` | `/CONSOLE /THREAD` |
|
||||
@@ -55,21 +55,29 @@ all passed. `powershell -ExecutionPolicy Bypass -File Tests\<Suite>.ps1`:
|
||||
| `Retention-Test.ps1` | 12408-12409 | `pushed_at`, retention, schema upgrade (Python) |
|
||||
| `Attachments-Test.ps1` | 12410-12411 | attachments through the tools, replication, limits |
|
||||
| `AttachmentEdges-Test.ps1` | 12413-12414 | raw-protocol edge cases, expiry, resuming, corruption (Python) |
|
||||
| `Restart-Test.ps1` | 12415-12416 | servers killed mid-traffic and mid-catch-up: nothing acknowledged lost, ids carry on, both catch up (Python pushers) |
|
||||
|
||||
Plus `Build\HandshakeTest.exe` and `Build\CipherTest.exe` (no server), and
|
||||
the release's smoke test. Speed: `Tests\Bench\Bench-Replication.ps1 -Ramp 10x0 -Parts Ramp`
|
||||
(push ceiling, ~40,800 msg/s for 4 servers). After a change, run every
|
||||
(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.
|
||||
- **`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.
|
||||
@@ -84,9 +92,9 @@ suite: they take a few minutes in all.
|
||||
## Working rules
|
||||
|
||||
- **Commit only when the owner asks**, on a branch, not `master`.
|
||||
- **Wire changes bump `#BakaShrot_ProtocolVersion`** (`Packets.pbi`, 4 at
|
||||
- **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` (v7 at this
|
||||
- **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
|
||||
|
||||
+155
-131
@@ -4,14 +4,16 @@
|
||||
; Lets an app connect to a BakaShrot server, one step at a time:
|
||||
; 1. BakaShrot_SetPrivateKey(), BakaShrot_SetPublicKey(),
|
||||
; BakaShrot_SetServerPublicKey() (the server's, from its log or its
|
||||
; KeyGen output), BakaShrot_SetTopic() and BakaShrot_SetNode() (names
|
||||
; or ids), or BakaShrot_SetTopicId() and BakaShrot_SetNodeId()
|
||||
; 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 own topic, or
|
||||
; 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
|
||||
@@ -45,6 +47,15 @@
|
||||
; 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.
|
||||
@@ -88,7 +99,6 @@ Global BakaShrot_HasPrivateKey.i = #False
|
||||
Global BakaShrot_PublicKey.s = ""
|
||||
Global BakaShrot_ServerPublicKey.BakaShrot_ClientServerKey
|
||||
Global BakaShrot_HasServerPublicKey.i = #False
|
||||
Global BakaShrot_Topic.s = ""
|
||||
Global BakaShrot_Node.s = ""
|
||||
|
||||
; The connection, see Commons/Networking/Outbound.pbi.
|
||||
@@ -115,16 +125,42 @@ Global BakaShrot_NamesList.s = ""
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False)
|
||||
EndIf
|
||||
|
||||
If Not DecodeKeyFromString(PrivateKey, @BakaShrot_PrivateKey\Bytes[0], #BakaShrot_Ed25519_PrivateKeySize)
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
|
||||
BakaShrot_HasPrivateKey = #True
|
||||
@@ -133,14 +169,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_SetPrivateKeyA(*PrivateKey)
|
||||
If Not *PrivateKey
|
||||
ProcedureReturn #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetPrivateKeyString(PeekS(*PrivateKey, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
@@ -149,12 +185,13 @@ 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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False)
|
||||
EndIf
|
||||
|
||||
If PublicKey = ""
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
|
||||
BakaShrot_PublicKey = PublicKey
|
||||
@@ -163,14 +200,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_SetPublicKeyA(*PublicKey)
|
||||
If Not *PublicKey
|
||||
ProcedureReturn #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
@@ -180,12 +217,13 @@ EndProcedure
|
||||
; 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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False)
|
||||
EndIf
|
||||
|
||||
If Not DecodeKeyFromString(PublicKey, @BakaShrot_ServerPublicKey\Bytes[0], #BakaShrot_Ed25519_PublicKeySize)
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
|
||||
BakaShrot_HasServerPublicKey = #True
|
||||
@@ -194,57 +232,28 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_SetServerPublicKeyA(*PublicKey)
|
||||
If Not *PublicKey
|
||||
ProcedureReturn #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetServerPublicKeyString(PeekS(*PublicKey, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Sets the topic the client identifies as, a name or an id in digits.
|
||||
; Must be done before connecting.
|
||||
Procedure.i BakaShrot_SetTopicString(Topic.s)
|
||||
If BakaShrot_Outbound\ConnectionId Or Not BakaShrot_IsValidRef(Topic)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
BakaShrot_Topic = Topic
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_SetTopicA(*Topic)
|
||||
If Not *Topic
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetTopicString(PeekS(*Topic, -1, #PB_UTF8))
|
||||
EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_SetTopicW(*Topic)
|
||||
If Not *Topic
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetTopicString(PeekS(*Topic, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
|
||||
; Same, by id, 0-65535.
|
||||
ProcedureCDLL.i BakaShrot_SetTopicId(TopicId.l)
|
||||
If TopicId < 0 Or TopicId > 65535
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetTopicString(Str(TopicId))
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Sets the node the client identifies as, a name or an id in digits.
|
||||
; Must be done before connecting.
|
||||
Procedure.i BakaShrot_SetNodeString(Node.s)
|
||||
If BakaShrot_Outbound\ConnectionId Or Not BakaShrot_IsValidRef(Node)
|
||||
ProcedureReturn #False
|
||||
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
|
||||
@@ -252,14 +261,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_SetNodeA(*Node)
|
||||
If Not *Node
|
||||
ProcedureReturn #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetNodeString(PeekS(*Node, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
@@ -267,7 +276,7 @@ EndProcedure
|
||||
; Same, by id, 0-65535.
|
||||
ProcedureCDLL.i BakaShrot_SetNodeId(NodeId.l)
|
||||
If NodeId < 0 Or NodeId > 65535
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_SetNodeString(Str(NodeId))
|
||||
EndProcedure
|
||||
@@ -279,34 +288,36 @@ EndProcedure
|
||||
; 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
|
||||
Protected Identity.BakaShrot_OutboundIdentity, Connected.i
|
||||
|
||||
BakaShrot_ResetError()
|
||||
If BakaShrot_Outbound\ConnectionId
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_AlreadyConnected, #False)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_HasPrivateKey Or BakaShrot_PublicKey = "" Or Not BakaShrot_HasServerPublicKey Or BakaShrot_Topic = "" Or BakaShrot_Node = ""
|
||||
ProcedureReturn #False
|
||||
If Not BakaShrot_HasPrivateKey Or BakaShrot_PublicKey = "" Or Not BakaShrot_HasServerPublicKey Or BakaShrot_Node = ""
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
|
||||
Identity\Topic = BakaShrot_Topic
|
||||
Identity\Node = BakaShrot_Node
|
||||
Identity\PublicKey = BakaShrot_PublicKey
|
||||
Identity\PrivateKey = @BakaShrot_PrivateKey\Bytes[0]
|
||||
|
||||
ProcedureReturn BakaShrot_Outbound_Connect(@BakaShrot_Outbound, Host, Port, @Identity, @BakaShrot_ServerPublicKey\Bytes[0])
|
||||
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 #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_ConnectString(PeekS(*Host, -1, #PB_Unicode), Port)
|
||||
EndProcedure
|
||||
@@ -332,8 +343,12 @@ EndProcedure
|
||||
|
||||
; --- Requests ----------------------------------------------------------------
|
||||
|
||||
; Closes the connection after something went wrong in a request.
|
||||
; 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
|
||||
|
||||
@@ -346,12 +361,14 @@ 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
|
||||
@@ -376,6 +393,7 @@ Procedure.i BakaShrot_ReadRefusal(*Answer, AnswerSize.i)
|
||||
EndIf
|
||||
|
||||
BakaShrot_RefusalReason = *Refused\Reason
|
||||
BakaShrot_LastError = *Refused\Code
|
||||
FreeStructure(*Refused)
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
@@ -402,8 +420,8 @@ EndProcedure
|
||||
|
||||
|
||||
; Pushes a message (JSON or anything else, the server flags which in its
|
||||
; is_json column) into Topic (a name or an id, "" for the client's own
|
||||
; topic), the server stores it under that topic and this client's node, with
|
||||
; 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.
|
||||
@@ -415,20 +433,20 @@ Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0)
|
||||
Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer
|
||||
Protected *View.MsgPackData, IsRefusal.i, MessageId.q
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1)
|
||||
EndIf
|
||||
|
||||
If Topic <> "" And Not BakaShrot_IsValidRef(Topic)
|
||||
ProcedureReturn -1
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
|
||||
Push\Topic = Topic
|
||||
@@ -436,7 +454,7 @@ Procedure.q BakaShrot_PushMessageToString(Topic.s, JsonData.s, UploadId.q = 0)
|
||||
Push\UploadId = UploadId
|
||||
*Request = BakaShrot_PushMessagePacket_Encode(@Push, @RequestSize)
|
||||
If Not *Request
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1)
|
||||
EndIf
|
||||
*Answer = BakaShrot_SendRequest(*Request, RequestSize\i, @AnswerSize)
|
||||
FreeMemory(*Request)
|
||||
@@ -486,7 +504,7 @@ ProcedureCDLL.q BakaShrot_PushMessageW(*JsonData)
|
||||
ProcedureReturn BakaShrot_PushMessageToString("", PeekS(*JsonData, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
|
||||
; A null *Topic is the client's own topic, like "", and a null *JsonData an
|
||||
; 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
|
||||
@@ -524,7 +542,7 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s)
|
||||
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
|
||||
Protected *View.MsgPackData, IsRefusal.i, IsExpected.i
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
BakaShrot_MessageId = 0
|
||||
BakaShrot_MessagePushedAt = 0
|
||||
BakaShrot_MessageAttachmentSize = 0
|
||||
@@ -538,18 +556,18 @@ Procedure.i BakaShrot_GetLatestMessageOfString(Topic.s, Node.s)
|
||||
BakaShrot_MessagesMore = #False
|
||||
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, #False)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node)
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
|
||||
Request\Topic = Topic
|
||||
Request\Node = Node
|
||||
*Packet = BakaShrot_GetLatestMessagePacket_Encode(@Request, @PacketSize)
|
||||
If Not *Packet
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, #False)
|
||||
EndIf
|
||||
*Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
@@ -609,14 +627,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_GetLatestMessageOfA(*Topic, *Node)
|
||||
If Not *Topic Or Not *Node
|
||||
ProcedureReturn #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_GetLatestMessageOfString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
@@ -624,7 +642,7 @@ EndProcedure
|
||||
; Same, by ids, 0-65535.
|
||||
ProcedureCDLL.i BakaShrot_GetLatestMessage(TopicId.l, NodeId.l)
|
||||
If TopicId < 0 Or TopicId > 65535 Or NodeId < 0 Or NodeId > 65535
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_GetLatestMessageOfString(Str(TopicId), Str(NodeId))
|
||||
EndProcedure
|
||||
@@ -649,7 +667,7 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit
|
||||
Protected *Packet, PacketSize.Integer, *AnswerPacket, AnswerSize.Integer
|
||||
Protected *View.MsgPackData, IsRefusal.i, IsExpected.i, Count.l
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
BakaShrot_MessageId = 0
|
||||
BakaShrot_MessagePushedAt = 0
|
||||
BakaShrot_MessageAttachmentSize = 0
|
||||
@@ -663,14 +681,14 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit
|
||||
BakaShrot_MessagesMore = #False
|
||||
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node)
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
If AfterMessageId < 0 Or Limit < 1 Or Limit > #BakaShrot_MaxGetMessages
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
|
||||
Request\Topic = Topic
|
||||
@@ -679,7 +697,7 @@ Procedure.l BakaShrot_GetMessagesString(Topic.s, Node.s, AfterMessageId.q, Limit
|
||||
Request\Limit = Limit
|
||||
*Packet = BakaShrot_GetMessagesPacket_Encode(@Request, @PacketSize)
|
||||
If Not *Packet
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1)
|
||||
EndIf
|
||||
*AnswerPacket = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
@@ -746,14 +764,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.l BakaShrot_GetMessagesA(*Topic, *Node, AfterMessageId.q, Limit.l)
|
||||
If Not *Topic Or Not *Node
|
||||
ProcedureReturn -1
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_GetMessagesString(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), AfterMessageId, Limit)
|
||||
EndProcedure
|
||||
@@ -768,8 +786,9 @@ EndProcedure
|
||||
; 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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
SelectElement(BakaShrot_Messages(), Index)
|
||||
BakaShrot_MessageId = BakaShrot_Messages()\MessageId
|
||||
@@ -837,22 +856,22 @@ Procedure.l BakaShrot_ResolveString(Kind.i, Ref.s)
|
||||
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
|
||||
Protected *View.MsgPackData, IsRefusal.i, Id.l
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
BakaShrot_ResolvedName = ""
|
||||
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_IsValidRef(Ref)
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
|
||||
Request\Kind = Kind
|
||||
Request\Ref = Ref
|
||||
*Packet = BakaShrot_ResolveNamePacket_Encode(@Request, @PacketSize)
|
||||
If Not *Packet
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1)
|
||||
EndIf
|
||||
*Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
@@ -896,28 +915,28 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.l BakaShrot_ResolveTopicA(*Ref)
|
||||
If Not *Ref
|
||||
ProcedureReturn -1
|
||||
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 -1
|
||||
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 -1
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_ResolveString(#BakaShrot_NameKind_Node, PeekS(*Ref, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
@@ -937,17 +956,17 @@ Procedure.l BakaShrot_ListNamesOf(Kind.i)
|
||||
Protected *View.MsgPackData, IsRefusal.i, Count.l
|
||||
Protected Json.i, Root.i, Items.i, Item.i
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
BakaShrot_NamesList = ""
|
||||
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, -1)
|
||||
EndIf
|
||||
|
||||
Request\Kind = Kind
|
||||
*Packet = BakaShrot_ListNamesPacket_Encode(@Request, @PacketSize)
|
||||
If Not *Packet
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1)
|
||||
EndIf
|
||||
*Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
@@ -982,7 +1001,7 @@ Procedure.l BakaShrot_ListNamesOf(Kind.i)
|
||||
Json = CreateJSON(#PB_Any)
|
||||
If Not Json
|
||||
FreeStructure(*List)
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, -1)
|
||||
EndIf
|
||||
Root = SetJSONObject(JSONValue(Json))
|
||||
If Kind = #BakaShrot_NameKind_Topic
|
||||
@@ -1068,17 +1087,17 @@ Procedure.i BakaShrot_QueryString(Sql.s)
|
||||
Protected *Packet, PacketSize.Integer, *Answer, AnswerSize.Integer
|
||||
Protected *View.MsgPackData, IsRefusal.i
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
BakaShrot_QueryResult = ""
|
||||
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, #False)
|
||||
EndIf
|
||||
|
||||
Request\Sql = Sql
|
||||
*Packet = BakaShrot_QueryRequestPacket_Encode(@Request, @PacketSize)
|
||||
If Not *Packet
|
||||
ProcedureReturn #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, #False)
|
||||
EndIf
|
||||
*Answer = BakaShrot_SendRequest(*Packet, PacketSize\i, @AnswerSize)
|
||||
FreeMemory(*Packet)
|
||||
@@ -1114,14 +1133,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.i BakaShrot_QueryA(*Sql)
|
||||
If Not *Sql
|
||||
ProcedureReturn #False
|
||||
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 #False
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, #False)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_QueryString(PeekS(*Sql, -1, #PB_Unicode))
|
||||
EndProcedure
|
||||
@@ -1180,7 +1199,7 @@ 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 own). Its SHA-256 is computed first, so the file is read twice.
|
||||
; 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
|
||||
@@ -1188,26 +1207,26 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q)
|
||||
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_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_NotConnected, 0)
|
||||
EndIf
|
||||
If Topic <> "" And Not BakaShrot_IsValidRef(Topic)
|
||||
ProcedureReturn 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, 0)
|
||||
EndIf
|
||||
If Size < 1
|
||||
BakaShrot_RefusalReason = "The attachment is empty"
|
||||
ProcedureReturn 0
|
||||
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 0
|
||||
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 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0)
|
||||
EndIf
|
||||
Count = BakaShrot_AttachmentChunkCount(Size)
|
||||
|
||||
@@ -1219,7 +1238,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q)
|
||||
If ReadData(FileId, *Buffer, Bytes) <> Bytes
|
||||
BakaShrot_RefusalReason = "The file couldn't be read"
|
||||
FreeMemory(*Buffer)
|
||||
ProcedureReturn 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, 0)
|
||||
EndIf
|
||||
BakaShrot_Sha256_Add(@Hash, *Buffer, Bytes)
|
||||
Next
|
||||
@@ -1235,7 +1254,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q)
|
||||
*Request = BakaShrot_UploadStartPacket_Encode(@Start, @RequestSize)
|
||||
If Not *Request
|
||||
FreeMemory(*Buffer)
|
||||
ProcedureReturn 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0)
|
||||
EndIf
|
||||
*Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_UploadStarted, @AnswerSize)
|
||||
FreeMemory(*Request)
|
||||
@@ -1267,7 +1286,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q)
|
||||
If ReadData(FileId, *Buffer, Bytes) <> Bytes
|
||||
BakaShrot_RefusalReason = "The file couldn't be read"
|
||||
FreeMemory(*Buffer)
|
||||
ProcedureReturn 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, 0)
|
||||
EndIf
|
||||
Chunk\Data = *Buffer
|
||||
Else
|
||||
@@ -1278,7 +1297,7 @@ Procedure.q BakaShrot_Upload(Topic.s, FileId.i, *Memory, Size.q)
|
||||
*Request = BakaShrot_UploadChunkPacket_Encode(@Chunk, @RequestSize)
|
||||
If Not *Request
|
||||
FreeMemory(*Buffer)
|
||||
ProcedureReturn 0
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_Internal, 0)
|
||||
EndIf
|
||||
*Answer = BakaShrot_RequestExpecting(*Request, RequestSize\i, #BakaShrot_PacketType_ChunkStored, @AnswerSize)
|
||||
FreeMemory(*Request)
|
||||
@@ -1322,15 +1341,15 @@ EndProcedure
|
||||
Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s)
|
||||
Protected FileId.i, UploadId.q
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
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 -1
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, -1)
|
||||
EndIf
|
||||
UploadId = BakaShrot_Upload(Topic, FileId, 0, Lof(FileId))
|
||||
CloseFile(FileId)
|
||||
@@ -1340,11 +1359,11 @@ Procedure.q BakaShrot_PushMessageWithFileString(Topic.s, JsonData.s, FilePath.s)
|
||||
ProcedureReturn BakaShrot_PushMessageToString(Topic, JsonData, UploadId)
|
||||
EndProcedure
|
||||
|
||||
; A null *Topic is the client's own topic, a null *JsonData an empty message.
|
||||
; 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 -1
|
||||
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
|
||||
@@ -1354,7 +1373,7 @@ EndProcedure
|
||||
ProcedureCDLL.q BakaShrot_PushMessageWithFileW(*Topic, *JsonData, *FilePath)
|
||||
Protected Topic.s, JsonData.s
|
||||
If Not *FilePath
|
||||
ProcedureReturn -1
|
||||
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
|
||||
@@ -1366,14 +1385,14 @@ EndProcedure
|
||||
Procedure.q BakaShrot_PushMessageWithDataString(Topic.s, JsonData.s, *Data, Size.q)
|
||||
Protected UploadId.q
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
If Not *Data
|
||||
BakaShrot_RefusalReason = "The attachment is empty"
|
||||
ProcedureReturn -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
UploadId = BakaShrot_Upload(Topic, 0, *Data, Size)
|
||||
If Not UploadId
|
||||
@@ -1408,12 +1427,12 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i)
|
||||
Protected Dim Expected.a(#BakaShrot_Sha256Size - 1), Dim Result.a(#BakaShrot_Sha256Size - 1)
|
||||
Protected *Request, RequestSize.Integer, *Answer, AnswerSize.Integer, *View.MsgPackData
|
||||
|
||||
BakaShrot_RefusalReason = ""
|
||||
BakaShrot_ResetError()
|
||||
If Not BakaShrot_Outbound\ConnectionId Or BakaShrot_Outbound\Metadata\Status <> #BakaShrot_ConnectionStatus_Authenticated
|
||||
ProcedureReturn -1
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
|
||||
Request\Topic = Topic
|
||||
@@ -1425,6 +1444,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i)
|
||||
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)
|
||||
@@ -1454,6 +1474,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i)
|
||||
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
|
||||
@@ -1469,6 +1490,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i)
|
||||
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
|
||||
@@ -1481,6 +1503,7 @@ Procedure.q BakaShrot_Download(Topic.s, Node.s, MessageId.q, FileId.i)
|
||||
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
|
||||
|
||||
@@ -1507,10 +1530,11 @@ EndProcedure
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_FileError, -1)
|
||||
EndIf
|
||||
Size = BakaShrot_Download(Topic, Node, MessageId, FileId)
|
||||
CloseFile(FileId)
|
||||
@@ -1522,14 +1546,14 @@ EndProcedure
|
||||
|
||||
ProcedureCDLL.q BakaShrot_SaveAttachmentA(*Topic, *Node, MessageId.q, *FilePath)
|
||||
If Not *Topic Or Not *Node Or Not *FilePath
|
||||
ProcedureReturn -1
|
||||
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 -1
|
||||
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
|
||||
@@ -1541,14 +1565,14 @@ EndProcedure
|
||||
; Returns its size, -1 on failure, see BakaShrot_Download().
|
||||
ProcedureCDLL.q BakaShrot_LoadAttachmentA(*Topic, *Node, MessageId.q)
|
||||
If Not *Topic Or Not *Node
|
||||
ProcedureReturn -1
|
||||
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 -1
|
||||
ProcedureReturn BakaShrot_Fail(#BakaShrot_Error_InvalidArgument, -1)
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_Download(PeekS(*Topic, -1, #PB_Unicode), PeekS(*Node, -1, #PB_Unicode), MessageId, 0)
|
||||
EndProcedure
|
||||
|
||||
@@ -13,15 +13,18 @@
|
||||
;
|
||||
; 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_SetTopicId_Prototype(TopicId.l)
|
||||
PrototypeC.i BakaShrot_SetNodeId_Prototype(NodeId.l)
|
||||
PrototypeC.i BakaShrot_SetTopic_Prototype(Topic.p-unicode)
|
||||
PrototypeC.i BakaShrot_SetNode_Prototype(Node.p-unicode)
|
||||
PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l)
|
||||
PrototypeC.i BakaShrot_IsConnected_Prototype()
|
||||
@@ -44,6 +47,7 @@ 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)
|
||||
@@ -63,9 +67,7 @@ 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_SetTopicId.BakaShrot_SetTopicId_Prototype
|
||||
Global BakaShrot_SetNodeId.BakaShrot_SetNodeId_Prototype
|
||||
Global BakaShrot_SetTopic.BakaShrot_SetTopic_Prototype
|
||||
Global BakaShrot_SetNode.BakaShrot_SetNode_Prototype
|
||||
Global BakaShrot_Connect.BakaShrot_Connect_Prototype
|
||||
Global BakaShrot_IsConnected.BakaShrot_IsConnected_Prototype
|
||||
@@ -88,6 +90,7 @@ 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
|
||||
@@ -131,9 +134,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
||||
BakaShrot_SetPrivateKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPrivateKeyW")
|
||||
BakaShrot_SetPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetPublicKeyW")
|
||||
BakaShrot_SetServerPublicKey = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetServerPublicKeyW")
|
||||
BakaShrot_SetTopicId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetTopicId")
|
||||
BakaShrot_SetNodeId = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeId")
|
||||
BakaShrot_SetTopic = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetTopicW")
|
||||
BakaShrot_SetNode = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_SetNodeW")
|
||||
BakaShrot_Connect = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_ConnectW")
|
||||
BakaShrot_IsConnected = GetFunction(BakaShrot_ClientLibrary, "BakaShrot_IsConnected")
|
||||
@@ -144,6 +145,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
||||
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")
|
||||
@@ -171,12 +173,12 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
||||
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_SetTopicId Or Not BakaShrot_SetNodeId Or Not BakaShrot_Connect Or Not BakaShrot_IsConnected Or Not BakaShrot_Disconnect
|
||||
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
|
||||
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
|
||||
@@ -186,7 +188,7 @@ Procedure.i BakaShrot_LoadClient(DllPath.s)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_SetTopic Or Not BakaShrot_SetNode Or Not BakaShrot_PushMessageTo Or Not BakaShrot_GetLatestMessageOf Or
|
||||
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
|
||||
@@ -301,7 +303,7 @@ EndProcedure
|
||||
; run it from the Build folder while BakaShrot_Server.exe is running.
|
||||
CompilerIf #PB_Compiler_IsMainFile
|
||||
|
||||
Define PrivateKey.s, PublicKey.s, ServerPublicKey.s, Topic.s, Node.s, ServerHost.s, ServerPort.l
|
||||
Define PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l
|
||||
|
||||
OpenConsole()
|
||||
|
||||
@@ -313,7 +315,6 @@ CompilerIf #PB_Compiler_IsMainFile
|
||||
PrivateKey = ReadPreferenceString("PrivateKey", "")
|
||||
PublicKey = ReadPreferenceString("PublicKey", "")
|
||||
ServerPublicKey = ReadPreferenceString("ServerPublicKey", "")
|
||||
Topic = ReadPreferenceString("Topic", ReadPreferenceString("TopicId", ""))
|
||||
Node = ReadPreferenceString("Node", ReadPreferenceString("NodeId", ""))
|
||||
ServerHost = ReadPreferenceString("ServerHost", "")
|
||||
ServerPort = ReadPreferenceLong("ServerPort", 0)
|
||||
@@ -339,11 +340,6 @@ CompilerIf #PB_Compiler_IsMainFile
|
||||
End 1
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_SetTopic(Topic)
|
||||
PrintN("Failed to set the topic")
|
||||
End 1
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_SetNode(Node)
|
||||
PrintN("Failed to set the node")
|
||||
End 1
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
; ============================================================================
|
||||
; BakaShrot error codes
|
||||
;
|
||||
; What BakaShrot_GetLastError() returns after a failed call of the client DLL
|
||||
; (BakaShrot_Client.pbi), and the code a server sends with each refusal
|
||||
; (RequestRefused, protocol 6). The Python client has the same numbers in
|
||||
; bakashrot.ErrorCode. Shipped next to BakaShrot_Client_Prototypes.pbi,
|
||||
; which includes it.
|
||||
;
|
||||
; 0 no error (the last call succeeded)
|
||||
; 1-99 refused by the server: the connection is still open, see
|
||||
; BakaShrot_GetRefusalReason() for the details
|
||||
; 100+ the client's own: the connection, the arguments, the files
|
||||
;
|
||||
; What to do about each:
|
||||
; reconnect, then retry: NotConnected, ConnectFailed, ConnectionLost,
|
||||
; ProtocolError (the connection is closed)
|
||||
; retry later: NotReady (an attachment still on its way),
|
||||
; ServerError (the server's storage failed)
|
||||
; fix the config: AuthRejected, ServerNotVerified, NotAllowed,
|
||||
; UnknownName, NoDefaultTopic
|
||||
; fix the call: InvalidArgument, InvalidRequest, TooBig,
|
||||
; QueryFailed, FileError
|
||||
; gone, or not yet there: NotFound
|
||||
; sent again by itself: DataMismatch (an upload that doesn't match its
|
||||
; SHA-256: upload it again), AttachmentMismatch (a
|
||||
; downloaded one that doesn't: read it again)
|
||||
;
|
||||
; A push whose answer was lost (ConnectionLost) may still have been stored:
|
||||
; pushing it again can store it twice, under the next id. Delivery is at
|
||||
; least once; check the latest message first if a duplicate matters.
|
||||
; ============================================================================
|
||||
|
||||
; --- Refused by the server (RequestRefused's Code) ----------------------------
|
||||
|
||||
; Not allowed to this client: AllowRead / AllowWrite / AllowQuery, its
|
||||
; PushTopics / ReadTopics, or a request only peers may make.
|
||||
#BakaShrot_Refused_NotAllowed = 1
|
||||
; A topic or node name (or id) this server doesn't know.
|
||||
#BakaShrot_Refused_UnknownName = 2
|
||||
; No such message, attachment or upload.
|
||||
#BakaShrot_Refused_NotFound = 3
|
||||
; The attachment isn't on this server yet (still being replicated).
|
||||
#BakaShrot_Refused_NotReady = 4
|
||||
; A message, attachment or query result over a limit, or an attachment
|
||||
; bigger than this server keeps.
|
||||
#BakaShrot_Refused_TooBig = 5
|
||||
; A push without a topic, and no DefaultTopic for this client.
|
||||
#BakaShrot_Refused_NoDefaultTopic = 6
|
||||
; A request that doesn't fit: parts out of order, an upload for another
|
||||
; topic or already attached, a part that doesn't exist...
|
||||
#BakaShrot_Refused_InvalidRequest = 7
|
||||
; An uploaded attachment that doesn't match its SHA-256: dropped.
|
||||
#BakaShrot_Refused_DataMismatch = 8
|
||||
; The SQL of a query failed (its error in the reason).
|
||||
#BakaShrot_Refused_QueryFailed = 9
|
||||
; The server couldn't store or read something: its database failed.
|
||||
#BakaShrot_Refused_ServerError = 10
|
||||
|
||||
; The highest a refusal can have, anything above is the client's own.
|
||||
#BakaShrot_Refused_Max = 99
|
||||
|
||||
; --- The client's own (BakaShrot_GetLastError()) --------------------------------
|
||||
|
||||
#BakaShrot_Error_None = 0
|
||||
; Not connected: never, or the connection was closed or lost before.
|
||||
#BakaShrot_Error_NotConnected = 100
|
||||
; The server couldn't be reached at that host and port.
|
||||
#BakaShrot_Error_ConnectFailed = 101
|
||||
; The server closed the connection during the handshake: wrong
|
||||
; ServerPublicKey, a key or node it doesn't allow, or another protocol
|
||||
; version (its log says which).
|
||||
#BakaShrot_Error_AuthRejected = 102
|
||||
; The server couldn't prove it holds ServerPublicKey's private key.
|
||||
#BakaShrot_Error_ServerNotVerified = 103
|
||||
; The connection broke during a request (it's closed now). A push may
|
||||
; still have been stored.
|
||||
#BakaShrot_Error_ConnectionLost = 104
|
||||
; The server answered something unexpected or malformed: the connection is
|
||||
; closed.
|
||||
#BakaShrot_Error_ProtocolError = 105
|
||||
; A bad argument: a ref that's neither a name nor an id, a null pointer, a
|
||||
; message or attachment over the limits, a setting missing before connecting.
|
||||
#BakaShrot_Error_InvalidArgument = 106
|
||||
; A file couldn't be opened, read or written.
|
||||
#BakaShrot_Error_FileError = 107
|
||||
; A downloaded attachment doesn't match its SHA-256.
|
||||
#BakaShrot_Error_AttachmentMismatch = 108
|
||||
; Already connected: disconnect first.
|
||||
#BakaShrot_Error_AlreadyConnected = 109
|
||||
; Out of memory, or another failure inside the client.
|
||||
#BakaShrot_Error_Internal = 110
|
||||
|
||||
|
||||
; The name of an error code, as the constants have it ("NotFound"), or
|
||||
; "Error <code>" for an unknown one.
|
||||
Procedure.s BakaShrot_ErrorName(Code.l)
|
||||
Select Code
|
||||
Case #BakaShrot_Error_None : ProcedureReturn "None"
|
||||
Case #BakaShrot_Refused_NotAllowed : ProcedureReturn "NotAllowed"
|
||||
Case #BakaShrot_Refused_UnknownName : ProcedureReturn "UnknownName"
|
||||
Case #BakaShrot_Refused_NotFound : ProcedureReturn "NotFound"
|
||||
Case #BakaShrot_Refused_NotReady : ProcedureReturn "NotReady"
|
||||
Case #BakaShrot_Refused_TooBig : ProcedureReturn "TooBig"
|
||||
Case #BakaShrot_Refused_NoDefaultTopic : ProcedureReturn "NoDefaultTopic"
|
||||
Case #BakaShrot_Refused_InvalidRequest : ProcedureReturn "InvalidRequest"
|
||||
Case #BakaShrot_Refused_DataMismatch : ProcedureReturn "DataMismatch"
|
||||
Case #BakaShrot_Refused_QueryFailed : ProcedureReturn "QueryFailed"
|
||||
Case #BakaShrot_Refused_ServerError : ProcedureReturn "ServerError"
|
||||
Case #BakaShrot_Error_NotConnected : ProcedureReturn "NotConnected"
|
||||
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "ConnectFailed"
|
||||
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "AuthRejected"
|
||||
Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "ServerNotVerified"
|
||||
Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "ConnectionLost"
|
||||
Case #BakaShrot_Error_ProtocolError : ProcedureReturn "ProtocolError"
|
||||
Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "InvalidArgument"
|
||||
Case #BakaShrot_Error_FileError : ProcedureReturn "FileError"
|
||||
Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "AttachmentMismatch"
|
||||
Case #BakaShrot_Error_AlreadyConnected : ProcedureReturn "AlreadyConnected"
|
||||
Case #BakaShrot_Error_Internal : ProcedureReturn "Internal"
|
||||
EndSelect
|
||||
ProcedureReturn "Error " + Str(Code)
|
||||
EndProcedure
|
||||
|
||||
; #True for a code a server sends with a refusal (1-99).
|
||||
Procedure.i BakaShrot_IsRefusalCode(Code.l)
|
||||
ProcedureReturn Bool(Code >= 1 And Code <= #BakaShrot_Refused_Max)
|
||||
EndProcedure
|
||||
@@ -129,9 +129,11 @@ CompilerEndIf
|
||||
Structure BakaShrot_ConnectionMetadata
|
||||
Status.i
|
||||
|
||||
; Identity from the Hello, as the server's own ids (unused on the client
|
||||
; side), only trusted once Status is Authenticated.
|
||||
TopicId.u
|
||||
; Server side only, trusted once Status is Authenticated: the node from
|
||||
; the Hello, and the default topic of its pushes from its client
|
||||
; section's DefaultTopic (-1 without one: pushes must name their topic),
|
||||
; both as the server's own ids.
|
||||
DefaultTopicId.l
|
||||
NodeId.u
|
||||
; The client's Ed25519 public key, on both sides.
|
||||
PublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
|
||||
|
||||
@@ -22,8 +22,8 @@ XIncludeFile "SocketWait.pbi"
|
||||
|
||||
; Who to authenticate as.
|
||||
Structure BakaShrot_OutboundIdentity
|
||||
; Each a name or an id in digits (Names.pbi), resolved by the server.
|
||||
Topic.s
|
||||
; The node it writes as, a name or an id in digits (Names.pbi), resolved
|
||||
; by the server, which must allow it for this key.
|
||||
Node.s
|
||||
|
||||
; Ed25519 public key (Base64), sent in the Hello.
|
||||
@@ -45,6 +45,10 @@ Structure BakaShrot_Outbound
|
||||
; for the server's packets give up right away, as if they timed out.
|
||||
; Lets a server stop its peer links without waiting out their timeouts.
|
||||
*StopRequested.Integer
|
||||
|
||||
; Why BakaShrot_Outbound_Connect() failed, a #BakaShrot_Error_* of
|
||||
; Client/BakaShrot_ErrorCodes.pbi, 0 once it succeeded.
|
||||
LastError.l
|
||||
EndStructure
|
||||
|
||||
|
||||
@@ -158,22 +162,27 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
Protected KeyPair.BakaShrot_SessionKeyPair
|
||||
Protected ChallengeDecoded.i, ServerProved.i
|
||||
|
||||
If *Outbound\ConnectionId Or Not *ServerPublicKey
|
||||
*Outbound\LastError = #BakaShrot_Error_None
|
||||
If *Outbound\ConnectionId
|
||||
*Outbound\LastError = #BakaShrot_Error_AlreadyConnected
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
If Port < 1 Or Port > 65535
|
||||
If Not *ServerPublicKey Or Port < 1 Or Port > 65535
|
||||
*Outbound\LastError = #BakaShrot_Error_InvalidArgument
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; Only needed before PureBasic 6.00.
|
||||
CompilerIf #PB_Compiler_Version < 600
|
||||
If Not InitNetwork()
|
||||
*Outbound\LastError = #BakaShrot_Error_Internal
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
CompilerEndIf
|
||||
|
||||
If Not InitCryptography()
|
||||
*Outbound\LastError = #BakaShrot_Error_Internal
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
@@ -181,6 +190,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
ClearStructure(@*Outbound\Metadata, BakaShrot_ConnectionMetadata)
|
||||
If Not DecodeKeyFromString(*Identity\PublicKey, @*Outbound\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
|
||||
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted
|
||||
*Outbound\LastError = #BakaShrot_Error_InvalidArgument
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
CopyMemory(*ServerPublicKey, @*Outbound\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
|
||||
@@ -188,6 +198,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
*Outbound\ConnectionId = OpenNetworkConnection(Host, Port, #PB_Network_TCP | #PB_Network_IPv4)
|
||||
If Not *Outbound\ConnectionId
|
||||
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted
|
||||
*Outbound\LastError = #BakaShrot_Error_ConnectFailed
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_New
|
||||
@@ -198,11 +209,11 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
|
||||
|
||||
; 1. Hello, sealed for the server
|
||||
Hello\ClientTopic = *Identity\Topic
|
||||
Hello\ClientNode = *Identity\Node
|
||||
Hello\ClientPubKeyB64 = *Identity\PublicKey
|
||||
CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
|
||||
|
||||
*Outbound\LastError = #BakaShrot_Error_Internal
|
||||
*Packet = BakaShrot_HelloPacket_Encode(@Hello, @PacketSize)
|
||||
If Not *Packet
|
||||
Goto ConnectFailed
|
||||
@@ -212,6 +223,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
If Not *Sealed
|
||||
Goto ConnectFailed
|
||||
EndIf
|
||||
*Outbound\LastError = #BakaShrot_Error_ConnectFailed
|
||||
Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0)
|
||||
FreeMemory(*Sealed)
|
||||
If Not Sent
|
||||
@@ -219,12 +231,17 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
EndIf
|
||||
|
||||
|
||||
; 2. Challenge request, in plain text
|
||||
; 2. Challenge request, in plain text. No answer: the server closed the
|
||||
; connection, it couldn't open the Hello or doesn't allow this key and
|
||||
; node (or speaks another protocol version).
|
||||
*Outbound\LastError = #BakaShrot_Error_AuthRejected
|
||||
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
|
||||
If Not *Packet
|
||||
Goto ConnectFailed
|
||||
EndIf
|
||||
|
||||
*Outbound\LastError = #BakaShrot_Error_ProtocolError
|
||||
|
||||
*Request = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i)
|
||||
If *View
|
||||
@@ -250,10 +267,12 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptServerLabel, @Proof)
|
||||
ServerProved = BakaShrot_VerifyHandshake(@Proof, *ServerPublicKey)
|
||||
If Not ServerProved
|
||||
*Outbound\LastError = #BakaShrot_Error_ServerNotVerified
|
||||
Goto ConnectFailed
|
||||
EndIf
|
||||
|
||||
; Every packet is encrypted from now on.
|
||||
*Outbound\LastError = #BakaShrot_Error_Internal
|
||||
If Not BakaShrot_Session_StartClient(@*Outbound\Metadata\Cipher, @KeyPair, @*Outbound\Metadata\ServerSessionKey[0])
|
||||
Goto ConnectFailed
|
||||
EndIf
|
||||
@@ -274,6 +293,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
If Not *Packet
|
||||
Goto ConnectFailed
|
||||
EndIf
|
||||
*Outbound\LastError = #BakaShrot_Error_AuthRejected
|
||||
Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i)
|
||||
FreeMemory(*Packet)
|
||||
If Not Sent
|
||||
@@ -281,11 +301,12 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
EndIf
|
||||
|
||||
|
||||
; 4. Accepted
|
||||
; 4. Accepted. No answer: the server didn't accept this key's signature.
|
||||
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
|
||||
If Not *Packet
|
||||
Goto ConnectFailed
|
||||
EndIf
|
||||
*Outbound\LastError = #BakaShrot_Error_ProtocolError
|
||||
|
||||
*Accepted = 0
|
||||
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i)
|
||||
@@ -302,6 +323,7 @@ Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Por
|
||||
; The server's answers may be big from now on.
|
||||
BakaShrot_Inbox_Lift(@*Outbound\Inbox)
|
||||
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated
|
||||
*Outbound\LastError = #BakaShrot_Error_None
|
||||
ProcedureReturn #True
|
||||
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
|
||||
XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi"
|
||||
XIncludeFile "Names.pbi"
|
||||
; The refusal codes (RequestRefused) and the client's error codes.
|
||||
XIncludeFile "../../Client/BakaShrot_ErrorCodes.pbi"
|
||||
|
||||
|
||||
; Represents the root of all BakaShrot packets.
|
||||
@@ -21,7 +23,10 @@ EndStructure
|
||||
; the ChallengeRequest encrypted (Connections.pbi). Messages carry when
|
||||
; they were pushed (PushedAt).
|
||||
; 4: attachments (Design/Attachments.md).
|
||||
#BakaShrot_ProtocolVersion = 4
|
||||
; 5: the Hello carries the client's node only: its default topic is the
|
||||
; server's to say (DefaultTopic in its client section).
|
||||
; 6: RequestRefused carries a Code (Client/BakaShrot_ErrorCodes.pbi).
|
||||
#BakaShrot_ProtocolVersion = 6
|
||||
|
||||
; Size in bytes of the nonce sent in a challenge request and echoed in its response.
|
||||
; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the
|
||||
|
||||
@@ -6,12 +6,12 @@
|
||||
XIncludeFile "../Packets.pbi"
|
||||
|
||||
; C2S auth request, sent sealed for the server's public key (Connections.pbi).
|
||||
; ClientTopic, ClientNode: who the client is, each a name or an id in digits
|
||||
; (Commons/Networking/Names.pbi), resolved by the server in its own names.
|
||||
; ClientNode: who the client is, the node it writes as, a name or an id in
|
||||
; digits (Commons/Networking/Names.pbi), resolved by the server in its own
|
||||
; names. Its default topic is the server's to say, not the client's.
|
||||
; ClientSessionKey: the public half of the client's key pair for this
|
||||
; connection (Commons/Cryptography/Session.pbi).
|
||||
Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase
|
||||
ClientTopic.s
|
||||
ClientNode.s
|
||||
ClientPubKeyB64.s
|
||||
ClientSessionKey.a[#BakaShrot_SessionKeySize]
|
||||
@@ -37,10 +37,6 @@ Procedure.i BakaShrot_HelloPacket_Encode(*Hello.BakaShrot_AuthHello, *OutSize.In
|
||||
Goto EncodeFailed
|
||||
EndIf
|
||||
|
||||
If MsgPackWriteString(*MsgPackData, *Hello\ClientTopic) <> #MsgPack_Error_Success
|
||||
Goto EncodeFailed
|
||||
EndIf
|
||||
|
||||
If MsgPackWriteString(*MsgPackData, *Hello\ClientNode) <> #MsgPack_Error_Success
|
||||
Goto EncodeFailed
|
||||
EndIf
|
||||
@@ -84,15 +80,6 @@ Procedure.i BakaShrot_HelloPacket_Decode(*MsgPackData.MsgPackData)
|
||||
Goto DecodeFailed
|
||||
EndIf
|
||||
|
||||
; ClientTopic
|
||||
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||
Goto DecodeFailed
|
||||
EndIf
|
||||
*Hello\ClientTopic = MsgPackReadString(*MsgPackData)
|
||||
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
|
||||
Goto DecodeFailed
|
||||
EndIf
|
||||
|
||||
; ClientNode
|
||||
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||
Goto DecodeFailed
|
||||
|
||||
@@ -6,8 +6,11 @@
|
||||
XIncludeFile "../Packets.pbi"
|
||||
|
||||
; S2C, answers a request the server won't fulfill, the connection stays open.
|
||||
; Reason is only meant for logs and humans.
|
||||
; Code: what kind of refusal, 1-#BakaShrot_Refused_Max, one of the
|
||||
; #BakaShrot_Refused_* in Client/BakaShrot_ErrorCodes.pbi: what clients act
|
||||
; on (protocol 6). Reason is only meant for logs and humans.
|
||||
Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase
|
||||
Code.l
|
||||
Reason.s
|
||||
EndStructure
|
||||
|
||||
@@ -22,6 +25,10 @@ Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefu
|
||||
*Refused\Version = #BakaShrot_ProtocolVersion
|
||||
*Refused\PacketType = #BakaShrot_PacketType_RequestRefused
|
||||
|
||||
If Not BakaShrot_IsRefusalCode(*Refused\Code)
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
*MsgPackData = MsgPackCreate(64)
|
||||
If Not *MsgPackData
|
||||
ProcedureReturn 0
|
||||
@@ -31,6 +38,10 @@ Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefu
|
||||
Goto EncodeFailed
|
||||
EndIf
|
||||
|
||||
If MsgPackWriteInteger(*MsgPackData, *Refused\Code) <> #MsgPack_Error_Success
|
||||
Goto EncodeFailed
|
||||
EndIf
|
||||
|
||||
If MsgPackWriteString(*MsgPackData, *Refused\Reason) <> #MsgPack_Error_Success
|
||||
Goto EncodeFailed
|
||||
EndIf
|
||||
@@ -53,7 +64,7 @@ EndProcedure
|
||||
; *MsgPackData stays owned by the caller, and should be discarded on failure.
|
||||
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
|
||||
Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData)
|
||||
Protected *Refused.BakaShrot_RequestRefused
|
||||
Protected *Refused.BakaShrot_RequestRefused, Value.q
|
||||
|
||||
*Refused = AllocateStructure(BakaShrot_RequestRefused)
|
||||
If Not *Refused
|
||||
@@ -65,6 +76,16 @@ Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData)
|
||||
Goto DecodeFailed
|
||||
EndIf
|
||||
|
||||
; Code
|
||||
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
|
||||
Goto DecodeFailed
|
||||
EndIf
|
||||
Value = MsgPackReadInteger(*MsgPackData)
|
||||
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsRefusalCode(Value)
|
||||
Goto DecodeFailed
|
||||
EndIf
|
||||
*Refused\Code = Value
|
||||
|
||||
; Reason
|
||||
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
|
||||
Goto DecodeFailed
|
||||
|
||||
@@ -33,7 +33,7 @@ keys sit in plain-text ini files (see the end).
|
||||
| libsodium | Wrapper | Notes |
|
||||
|---|---|---|
|
||||
| `sodium_init` | `InitCryptography()` | Called before any use; repeated calls are fine. |
|
||||
| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/KeyGen`. |
|
||||
| `crypto_sign_keypair` | `GenerateKeyPair()` | Used by `Tools/BakaShrotGenerateKeyPairs`. |
|
||||
| `crypto_sign_detached` | `EncodeData()`, `BakaShrot_SignHandshake()` | **Signs**, the name `EncodeData` is wrong. |
|
||||
| `crypto_sign_verify_detached` | `DecodeData()`, `BakaShrot_VerifyHandshake()` | **Verifies**, the name `DecodeData` is wrong. |
|
||||
| `crypto_sign_ed25519_sk_to_pk` | `GetPublicKeyFromPrivateKey()` | Lets a server only keep its private key in its config. |
|
||||
@@ -69,9 +69,10 @@ keys sit in plain-text ini files (see the end).
|
||||
- **Connection keys: X25519**, made for each connection by both ends, the
|
||||
secrets wiped once the cipher has its keys. So a recorded connection
|
||||
can't be decrypted later, even with both identity keys (forward secrecy).
|
||||
- **Generated** by `Tools/KeyGen`, which `Build.ps1` runs on every build.
|
||||
- **Generated** by `Tools/BakaShrotGenerateKeyPairs`, which `Build.ps1` runs
|
||||
on every build.
|
||||
- **Wiping:**
|
||||
- Wiped from memory after use: KeyGen; a server's key when it stops, and
|
||||
- Wiped from memory after use: BakaShrotGenerateKeyPairs; a server's key when it stops, and
|
||||
its peer links'; every connection's keys when it ends.
|
||||
- Not wiped: the client DLL's global copy of its private key, and the
|
||||
config structures holding the Base64 text.
|
||||
@@ -91,11 +92,11 @@ See `Design/Packets.md` for the packets, `Connections.pbi` for the code.
|
||||
The client knows the server's public key beforehand.
|
||||
|
||||
1. **Hello, sealed** (`crypto_box_seal` for the server's key): the client's
|
||||
identity (topic, node), its Base64 public key, and the public half of a
|
||||
key pair it made for this connection.
|
||||
node (the one it writes as), its Base64 public key, and the public half
|
||||
of a key pair it made for this connection.
|
||||
2. The server opens it (another server can't: abort), decodes the key and
|
||||
checks that a `[BakaShrot.Client.<name>]` lists both this key and this
|
||||
identity.
|
||||
checks that a `[BakaShrot.Client.<name>]` has this `Node` and lists this
|
||||
key.
|
||||
3. **ChallengeRequest, in plain text:** a fresh random challenge and nonce,
|
||||
the public half of the server's own pair for this connection, and the
|
||||
server's signature of the transcript.
|
||||
|
||||
+31
-17
@@ -26,6 +26,8 @@ Reference for working on BakaShrot's networking. Related docs:
|
||||
| Server: the root thread, which stops and starts every worker (restart, vacuum) | `Server/Root.pbi` |
|
||||
| Client DLL (one connection) | `Client/BakaShrot_Client.pbi`, used through `BakaShrot_Client_Prototypes.pbi` |
|
||||
| Python client, over the DLL | `Interactors/Python/bakashrot.py` |
|
||||
| Ready-to-run setups (configs, start scripts, a README each) | `Examples/`, listed in `Examples/README.md` |
|
||||
| Tools: connecting through the DLL from an ini; ending (waits for Enter when started from Explorer) | `Tools/Common/ToolClient.pbi`, `Tools/Common/ToolConsole.pbi` |
|
||||
| Tests of the packets alone, without sockets | `Tests/HandshakeTest.pb` |
|
||||
| Tests of the cipher and the session crypto, without sockets | `Tests/CipherTest.pb` |
|
||||
| What goes over the wire (a recording proxy) | `Tests/wire_check.py`, run by `Tests/Python-Test.ps1` |
|
||||
@@ -74,8 +76,9 @@ Reference for working on BakaShrot's networking. Related docs:
|
||||
array, read in order with PB-MessagePack:
|
||||
1. `Magic` (integer), always `#BakaShrot_ProtocolMagic` (`0x42534854`,
|
||||
"BSHT").
|
||||
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (4:
|
||||
attachments; 3: the Hello sealed, a key per connection, everything
|
||||
2. `Version` (integer), always `#BakaShrot_ProtocolVersion` (6:
|
||||
refusals carry a code; 5: the Hello carries the node only, the default
|
||||
topic is the server's; 4: attachments; 3: the Hello sealed, a key per connection, everything
|
||||
after the ChallengeRequest encrypted, times; 2 had topics and nodes by
|
||||
name, in plain text; 1 had ids only).
|
||||
3. `PacketType` (integer), one of the ids below.
|
||||
@@ -90,10 +93,13 @@ Reference for working on BakaShrot's networking. Related docs:
|
||||
|
||||
### Topics and nodes: names and ids
|
||||
|
||||
- **Each server has its own ids** (0-65535) for topics and nodes, and the
|
||||
config can name them (`[BakaShrot.Topics]`, `[BakaShrot.Nodes]`). The
|
||||
**name is what's shared**: "logs" can be 1 on one server and 200 on
|
||||
another.
|
||||
- **Each server has its own ids** (0-65535) for topics and nodes, and
|
||||
gives them to the names: the config lists the topics
|
||||
(`[BakaShrot.Topics]`), the nodes come from the sections that define
|
||||
them (its own, its peers', its clients') and optionally
|
||||
`[BakaShrot.Nodes]`; a name keeps the id the database has for it, a new
|
||||
one gets the lowest free one (`Server/Storage/Names.pbi`). The **name is
|
||||
what's shared**: "logs" can be 1 on one server and 200 on another.
|
||||
- **A ref** is how a packet gives a topic or node: a name (1-64 of
|
||||
`A-Z a-z 0-9 _ . -`, not only digits, any case), or an id in digits,
|
||||
which always means that id on the receiving server. An unnamed topic or
|
||||
@@ -105,7 +111,7 @@ Reference for working on BakaShrot's networking. Related docs:
|
||||
- **Only what's named on both servers replicates.** Unnamed topics and
|
||||
nodes, and names the other server doesn't have, are dropped, unless the
|
||||
receiver's `AcceptTopics` / `AcceptNodes` for that peer has a wildcard
|
||||
(`*`, `sensors.*`) matching it: it's then added there with an id of its
|
||||
(`*`, `sensors.*`; `AcceptNodes` is `*` by default) matching it: it's then added there with an id of its
|
||||
own. The sync state lists every name the receiver takes, and its
|
||||
wildcards, so the sender only sends those and nothing gets refused at
|
||||
every check-in.
|
||||
@@ -119,7 +125,7 @@ over its own link to another server.
|
||||
|---|---|---|---|---|
|
||||
| 0 | None | | Never valid. | |
|
||||
| 1-3 | | | Used by the removed `AuthenticationPacket.pbi`, don't reuse. | |
|
||||
| 4 | ClientHello | C→S | `ClientTopic` str (ref), `ClientNode` str (ref), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest |
|
||||
| 4 | ClientHello | C→S | `ClientNode` str (ref, the node it writes as), `ClientPubKeyB64` str, `ClientSessionKey` bin (32 bytes). Sent sealed for the server's key | ChallengeRequest |
|
||||
| 5 | ChallengeRequest | S→C | `ChallengeB64` str (32 bytes), `Nonce` bin (32 bytes), `ServerSessionKey` bin (32 bytes), `ServerSignature` bin (64 bytes, of the transcript). The last packet in plain text | ChallengeResponse |
|
||||
| 6 | ChallengeResponse | C→S | `ChallengeResponseB64` str (64-byte signature of the transcript), `Nonce` bin (32 bytes) | AuthAccepted |
|
||||
| 7 | AuthAccepted | S→C | None. | |
|
||||
@@ -127,7 +133,7 @@ over its own link to another server.
|
||||
| 9 | MessagePushed | S→C | `MessageId` int ≥ 1 | |
|
||||
| 10 | GetLatestMessage | C→S | `Topic` str (ref), `Node` str (ref) | LatestMessage / RequestRefused |
|
||||
| 11 | LatestMessage | S→C | `TopicId`, `NodeId` int 0-65535 (the server's), `TopicName`, `NodeName` str (names, or ids in digits), `MessageId` int ≥ 1, `PushedAt` int (time, see below), `JsonData` str, `AttachmentSize` int (0 for none), `AttachmentReady` int 0/1 | |
|
||||
| 12 | RequestRefused | S→C | `Reason` str, for logs and humans | |
|
||||
| 12 | RequestRefused | S→C | `Code` int 1-99 (what kind, `#BakaShrot_Refused_*` in `Client/BakaShrot_ErrorCodes.pbi`: what clients act on), `Reason` str, for logs and humans | |
|
||||
| 13 | SyncStateRequest | P→S | None. | SyncState / RequestRefused |
|
||||
| 14 | SyncState | S→P | `TopicCount` int, then each topic's `Id` int and `Name` str (the named topics S takes from P); `NodeCount` int, then each node's `Id` and `Name` (the named nodes S takes from P); `TopicPatternCount` int, then each pattern str; `NodePatternCount` int, then each pattern str (S's wildcards for P, `*` included); `PairCount` int, then each pair's `TopicId`, `NodeId`, `MessageId`. Ids are S's own, names are never digits | |
|
||||
| 15 | ReplicateMessages | P→S | `Topic` str, `Node` str (names, never digits), `Count` int 1-10000, then each message's `MessageId` int (≥ 1, strictly increasing), `PushedAt` int (as stored, from its origin), `JsonData` str, `AttachmentSize` int (0 for none) and `AttachmentSha256` bin (32 bytes, empty for none) | MessagePushed (last id) / RequestRefused |
|
||||
@@ -165,7 +171,13 @@ the client's), and keeps that time on every server it's replicated to.
|
||||
- **Refuse or abort:**
|
||||
- **Refuse** (RequestRefused, the connection stays open) for things that
|
||||
are valid but not allowed: permissions, no message found, too big,
|
||||
a failed query, a regular client sending replication packets.
|
||||
a failed query, a regular client sending replication packets. Each with
|
||||
a code (`Client/BakaShrot_ErrorCodes.pbi`): NotAllowed, UnknownName,
|
||||
NotFound, NotReady, TooBig, NoDefaultTopic, InvalidRequest,
|
||||
DataMismatch, QueryFailed, ServerError. Clients get them from
|
||||
`BakaShrot_GetLastError()` (the DLL) or `error.code` (Python), with
|
||||
their own codes (100+) for what never reached the server or broke the
|
||||
connection.
|
||||
- **Abort** (the connection is closed) for anything malformed or out of
|
||||
order: an invalid frame or packet, a packet type that isn't expected at
|
||||
that point, an answer to a different request, a timeout during the
|
||||
@@ -187,12 +199,12 @@ the client's), and keeps that time on every server it's replicated to.
|
||||
```
|
||||
client: knows the server's Ed25519 public key (ServerPublicKey),
|
||||
makes a key pair for this connection
|
||||
C -> S ClientHello identity (topic and node refs) + Base64 public key
|
||||
C -> S ClientHello node (ref, the one it writes as) + Base64 public key
|
||||
+ the public half of the client's pair,
|
||||
sealed for the server's public key
|
||||
server: opens it (or aborts: not for this server), the refs must
|
||||
resolve to its ids, the key must decode to 32 bytes, and one
|
||||
[BakaShrot.Client.<name>] must list both this key and this identity
|
||||
server: opens it (or aborts: not for this server), the node must
|
||||
resolve to its id, the key must decode to 32 bytes, and one
|
||||
[BakaShrot.Client.<name>] must have this Node and list this key
|
||||
S -> C ChallengeRequest fresh random challenge + nonce, the public half of
|
||||
the server's pair, and the server's signature of
|
||||
the transcript (in plain text)
|
||||
@@ -215,14 +227,16 @@ server's session halves, the challenge, the nonce.
|
||||
connection:
|
||||
- Its **permissions**, from the matching client section: `AllowRead`,
|
||||
`AllowWrite`, `AllowQuery`, and the `PushTopics` / `ReadTopics` filters
|
||||
(default: the topics of its `Identities`).
|
||||
- Whether it's a **peer**: its key and identity match a
|
||||
(default: its `DefaultTopic`, nothing without one), and that
|
||||
`DefaultTopic`: the topic of its pushes that don't name one.
|
||||
- Whether it's a **peer**: its key and node match a
|
||||
`[BakaShrot.Peer.<name>]`, and then its `AcceptTopics`.
|
||||
|
||||
### Client requests
|
||||
|
||||
```
|
||||
PushMessage(t, json) AllowWrite, t in PushTopics ("" = own topic), at most
|
||||
PushMessage(t, json) AllowWrite, t in PushTopics ("" = its DefaultTopic,
|
||||
refused without one), at most
|
||||
#BakaShrot_MaxMessageSize. JSON or not: stored as
|
||||
is, SQLite flags it in is_json
|
||||
-> stored under t and the authenticated node with the
|
||||
|
||||
+16
-13
@@ -18,14 +18,14 @@ warning, not an error).
|
||||
Its smoke test, from the release folder, on one server with a throwaway
|
||||
database:
|
||||
|
||||
- generates keys with `KeyGen.exe`, writes a server and a client config;
|
||||
- generates keys with `BakaShrotGenerateKeyPairs.exe`, writes a server and a client config;
|
||||
- pushes two messages, reads the latest back by name, reads both with
|
||||
`GetMessages.exe`, resolves a name, queries them through the `messages`
|
||||
`BakaShrotGetMessages.exe`, resolves a name, queries them through the `messages`
|
||||
view with `is_json = 1`;
|
||||
- if `python` is on the PATH, reads them and pushes one with
|
||||
`python\bakashrot.py`;
|
||||
- pushes a 3 MB attachment with `PushMessage.exe -a` and reads it back
|
||||
identical with `GetAttachment.exe`;
|
||||
- pushes a 3 MB attachment with `BakaShrotPushMessage.exe -a` and reads it back
|
||||
identical with `BakaShrotGetAttachment.exe`;
|
||||
- then force-kills the server and deletes everything.
|
||||
|
||||
The end-to-end tests in `Tests/` cover much more (names, replication, big
|
||||
@@ -79,10 +79,12 @@ in `Tests/` already, to be pointed at the release instead.
|
||||
first time a pair is pushed to (`Writer.pbi`), `node_heads` is kept by a
|
||||
trigger in the same transaction as the messages, and every check-in
|
||||
with a peer starts from both sync states, read from the databases. A
|
||||
killed process loses nothing committed, even with `synchronous =
|
||||
NORMAL` (only a power loss or an OS crash can). **Not tested against
|
||||
the release yet**, `Names-Test.ps1` restarts a server but doesn't check
|
||||
these.
|
||||
killed process loses nothing committed, whatever `Synchronous` says
|
||||
(with `NORMAL`, a power loss or an OS crash can lose the last second). **Tested** by
|
||||
`Tests/Restart-Test.ps1` (2026-11-09): kills with traffic in flight,
|
||||
once in the middle of a catch-up, both directions, all hold. With
|
||||
`BenchServer.exe` (the same server code plus a stop file), not the
|
||||
release's exe itself.
|
||||
4. **A clean shutdown**: the release server only stops from its console
|
||||
(`quit`), so the test force-kills it, and the clean path never runs.
|
||||
Needs a way to stop it without a console: a stop file like
|
||||
@@ -108,12 +110,12 @@ in `Tests/` already, to be pointed at the release instead.
|
||||
- a 1 MB message reads back whole, on both servers;
|
||||
- a JSON query over non-JSON rows without `is_json = 1` is refused with
|
||||
SQLite's error, not answered with no rows (fixed, see below).
|
||||
9. **Every shipped tool runs once**: `ListNames`, `GetMessages --follow`
|
||||
9. **Every shipped tool runs once**: `BakaShrotList`, `BakaShrotGetMessages --follow`
|
||||
(picks up a new push, exits 1 once the server is gone) aren't yet.
|
||||
10. **Version hygiene**:
|
||||
- `-Version 1.0.0` refuses a dirty tree instead of appending `-dirty`;
|
||||
- the release commit is tagged (`v1.0.0`), the version comes from it;
|
||||
- `VERSION.txt` gives the protocol version (4) and the runtime needed;
|
||||
- `VERSION.txt` gives the protocol version (5 now) and the runtime needed;
|
||||
- the Python client is checked on the oldest version it claims (3.8),
|
||||
not only on the latest (3.14 here).
|
||||
|
||||
@@ -189,8 +191,9 @@ Not smoke-test items, but what the "1.0" label would promise. From
|
||||
Fixed (protocol 3).
|
||||
- Messages aren't signed by the node that first wrote them: a peer is
|
||||
trusted with what it replicates (`Design/ReplicationIssues.md` #3).
|
||||
- `synchronous = NORMAL`: the last commits can be lost on a power loss,
|
||||
decide if that's fine (`Design/StorageConcurrency.md`).
|
||||
- ~~`synchronous = NORMAL`: the last commits can be lost on a power loss.~~
|
||||
Decided: `[BakaShrot.Server] Synchronous`, `FULL` by default
|
||||
(`Design/StorageConcurrency.md`).
|
||||
|
||||
Either they're fixed, or they're documented limits of 1.0 (or it's a 0.9).
|
||||
|
||||
@@ -213,7 +216,7 @@ Notes for when the builds move to a pipeline.
|
||||
- `Build.ps1` ends by running the server, which waits on its console:
|
||||
needs a `-NoRun` switch. It also writes private keys into `Build\`,
|
||||
which must never be published as an artifact.
|
||||
- The tests use fixed ports (12399 for the release, 12401-12414 for
|
||||
- The tests use fixed ports (12399 for the release, 12401-12416 for
|
||||
`Tests/`): parallel jobs on one runner collide, make them parameters
|
||||
or pick free ones.
|
||||
- One entry point that runs every test (`Tests/*.ps1`, the handshake
|
||||
|
||||
@@ -7,12 +7,18 @@ behind on, with their original ids. Each peer does the same over its own link.
|
||||
|
||||
Issues below are roughly ordered by how much they matter.
|
||||
|
||||
## 1. Drift: the same message id with different content (accepted for now)
|
||||
## 1. Drift: the same message id with different content (ruled out by config)
|
||||
|
||||
**When:** the same topic/node id is written to on two servers, for example
|
||||
when a client identity is registered on both and pushes to each while they
|
||||
can't reach each other. This is a configuration issue that """shouldn't"""
|
||||
happen in real use.
|
||||
**The rule: a node pushes to one server.** Each client node has its
|
||||
`[BakaShrot.Client.<name>]` section (its `Node`) on one server only, the
|
||||
one it pushes to; the other servers get its messages by replication. Then
|
||||
every topic/node pair has a single writer and this can't happen. Reading
|
||||
from any server is fine, only pushing matters. Breaking the rule isn't
|
||||
detected: it's the config's to keep.
|
||||
|
||||
**When it would happen:** the same topic/node id written to on two
|
||||
servers, for example a client node registered on both, pushing to each
|
||||
while they can't reach each other.
|
||||
|
||||
**What happens:** both servers are at `1:2#1`, the link drops, then:
|
||||
|
||||
|
||||
@@ -37,15 +37,47 @@ not done yet: `Design/Suggestions.md`.
|
||||
## WAL and the write mutex (2026-11-07)
|
||||
|
||||
- **WAL mode,** set by `SetupStorageDatabase()` (stored in the file), with
|
||||
`synchronous = NORMAL` on every connection (`#BakaShrot_Storage_Synchronous`
|
||||
in `Storage.pbi`). Readers no longer block the writer: a 0.5 s raw query
|
||||
used to stall pushes for seconds and once made one fail with "database is
|
||||
locked", now pushes run next to it at full speed.
|
||||
- **The tradeoff of NORMAL:** commits are only synced at checkpoints. The
|
||||
file can't get corrupted, but the last commits before a power loss or an
|
||||
OS crash can be lost. Those messages were acknowledged and maybe already
|
||||
replicated, so their ids could be handed out again: drift
|
||||
(`ReplicationIssues.md` #1). Set it to `FULL` to sync every commit again.
|
||||
the config's `synchronous` on every connection (see below). Readers no
|
||||
longer block the writer: a 0.5 s raw query used to stall pushes for
|
||||
seconds and once made one fail with "database is locked", now pushes run
|
||||
next to it at full speed.
|
||||
- **`synchronous` is `[BakaShrot.Server] Synchronous`** since 2026-11-09,
|
||||
`FULL` by default (it was `NORMAL`, fixed). The root sets
|
||||
`BakaShrot_Storage_Synchronous` (`Storage.pbi`) before it opens any
|
||||
connection. `OFF` is refused (a power loss could corrupt the file),
|
||||
`EXTRA` too (the same as `FULL` in WAL mode, it only adds a directory
|
||||
sync for the other journal modes).
|
||||
- `FULL`: every commit flushes the WAL. An acknowledged push survives a
|
||||
power loss or an OS crash. The flush is per transaction, so a group
|
||||
commit's pushes share it.
|
||||
- `NORMAL`: the WAL is only flushed at checkpoints (about every second,
|
||||
`Writer.pbi`). The file can't get corrupted, but the last second or so
|
||||
of commits before a power loss or an OS crash can be lost. Those
|
||||
messages were acknowledged and maybe already replicated, so their ids
|
||||
could be handed out again: drift (`ReplicationIssues.md` #1).
|
||||
|
||||
### Measured (2026-11-09)
|
||||
|
||||
`Bench-Replication.ps1 -Ramp "1x0,10x0,10x20" -Parts Ramp -Synchronous ...`,
|
||||
4 servers in a Y, totals of the 4, one run each (±5-10%). On a VM whose
|
||||
virtual disk flushes in 0.60 ms (p99 0.78 ms).
|
||||
|
||||
| | OFF | NORMAL | FULL | EXTRA |
|
||||
|---|---|---|---|---|
|
||||
| 1 pusher per server, flat out: msg/s | 28,785 | 22,595 | 5,100 | 5,026 |
|
||||
| ... push p50 / p99 | 0.1 / 0.8 ms | 0.1 / 0.8 ms | 0.7 / 5.3 ms | 0.7 / 3.3 ms |
|
||||
| 10 pushers per server, flat out: msg/s | 42,854 | 33,870 | 17,207 | 17,763 |
|
||||
| ... push p50 / p99 / max | 0.6 / 4.8 / 95 ms | 0.5 / 3.3 / 1,113 ms | 1.6 / 9.3 / 123 ms | 1.6 / 8.7 / 129 ms |
|
||||
| 800 msg/s steady: push p50 / p99 | 0.2 / 0.5 ms | 0.2 / 0.9 ms | 0.9 / 5.0 ms | 0.8 / 4.6 ms |
|
||||
| Lost on a power loss / OS crash | the file may be corrupted | ~1 s of acknowledged pushes | nothing acknowledged | same as FULL |
|
||||
|
||||
No failed pushes, replication kept up in every case. `FULL`'s cost is the
|
||||
disk's flush time: one client pushing one message at a time gets about
|
||||
1 / (flush + 0.15 ms) pushes/s, ~1,300/s here; many clients share flushes
|
||||
through the group commit, so the total drops much less (half here). On a
|
||||
server SSD with power-loss protection a flush is far under 0.1 ms (close
|
||||
to `NORMAL`), on a consumer SSD 1-5 ms, on a hard disk ~10 ms (~100/s for
|
||||
one sequential client): time one on the target machine to know.
|
||||
- **`BakaShrot_Storage_WriteMutex`** around every write. A connection that
|
||||
finds the database locked sleeps in SQLite's busy handler (1, 2, 5, 10...
|
||||
ms) and retries; with 10+ threads pushing, that's where the time went, and
|
||||
@@ -137,12 +169,11 @@ ids exactly 1-800 on both servers.
|
||||
the push or batch is refused and retried at the next check-in for
|
||||
replication. Fine at current loads; decide later whether pushes should
|
||||
retry.
|
||||
- **Whether PureBasic's `DatabaseError()` is per thread** in thread-safe
|
||||
mode. If it's shared by the whole program, an error message could show up
|
||||
in the wrong thread's log or refusal. The data isn't affected.
|
||||
`RunReadOnlyQuery()` only checks it after reading the rows on Linux, where
|
||||
it could refuse a valid query because of another thread's error. On
|
||||
Windows it asks SQLite instead (`sqlite3_errcode()` on its own
|
||||
connection), see `Design/Release.md`.
|
||||
- ~~**Whether PureBasic's `DatabaseError()` is per thread**~~: it is, in
|
||||
thread-safe mode (`/THREAD`), checked 2026-11-09 with 5.73 and 6.40: two
|
||||
threads failing on their own connections 20,000 times each never saw the
|
||||
other's message. `sqlite3_errmsg16()` on the connection gives the same
|
||||
text. (`RunReadOnlyQuery()` still asks SQLite on Windows, for the errors
|
||||
`DatabaseError()` doesn't report at all, see `Design/Release.md`.)
|
||||
- **A single storage thread with a job queue,** only if writes ever become
|
||||
the bottleneck. SQLite only has one writer anyway.
|
||||
|
||||
@@ -104,11 +104,9 @@ protocol change).
|
||||
|
||||
## 3. Smaller ones
|
||||
|
||||
- **Decide on `synchronous = NORMAL`** (`#BakaShrot_Storage_Synchronous`):
|
||||
the last commits before a power loss or an OS crash can be lost, and their
|
||||
ids handed out again (drift). With group commit, `FULL` costs one sync per
|
||||
transaction, not per push, so it may cost much less than it used to: worth
|
||||
one benchmark run before deciding.
|
||||
- ~~**Decide on `synchronous = NORMAL`**~~: done 2026-11-09, a config
|
||||
option (`Synchronous`), `FULL` by default, measured in
|
||||
`Design/StorageConcurrency.md`.
|
||||
- **`Build.ps1`:** the compiler path and `-Compiler` are fixed (2026-11-07),
|
||||
but the `Libs\` zips for libsodium and SQLite are gone: it only works while
|
||||
the extracted DLLs are still in `Libs\*d`.
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# Examples
|
||||
|
||||
Ready-to-run setups, each in its own folder with its configs, scripts to
|
||||
start it, and a README. Build first (`Build.ps1` at the root): the scripts
|
||||
take the exes from `Build\`, or from a release folder with `-BinDir`.
|
||||
|
||||
| Example | What it shows |
|
||||
|---|---|
|
||||
| [`SingleServer`](SingleServer/README.md) | One server, one client: pushing, reading, attachments, names, SQL, with the tools. |
|
||||
|
||||
Their keys are in the repository, so public: they're only for trying the
|
||||
examples locally, never reuse them.
|
||||
@@ -0,0 +1,136 @@
|
||||
# One server, one client
|
||||
|
||||
The smallest BakaShrot setup: one server on `127.0.0.1:12360`, one client
|
||||
that pushes and reads messages with the tools.
|
||||
|
||||
> **The keys in `server.ini` and `client.ini` are public, they're in the
|
||||
> repository.** They're only for trying this example on your own machine
|
||||
> (the server only listens on 127.0.0.1). Never reuse them: make your own
|
||||
> with `BakaShrotGenerateKeyPairs.exe`.
|
||||
|
||||
## Running it
|
||||
|
||||
Build first, `Build.ps1` at the root, or use a release folder (`-BinDir
|
||||
Release\<version>` on both scripts). Then, from this folder:
|
||||
|
||||
```powershell
|
||||
powershell -ExecutionPolicy Bypass -File Start-Server.ps1
|
||||
powershell -ExecutionPolicy Bypass -File Run-Client.ps1
|
||||
```
|
||||
|
||||
- `Start-Server.ps1` opens the server in its own window and waits until it
|
||||
listens. Type `quit` in that window to stop it (`help` lists the other
|
||||
commands). `-Here` runs it in the current console instead, `-Reset`
|
||||
deletes its database first, so the ids start from 1 again.
|
||||
- `Run-Client.ps1` goes through what a client does, printing each command
|
||||
before its output. The commands can be pasted as they are from this
|
||||
folder:
|
||||
|
||||
```text
|
||||
== Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo
|
||||
> ..\..\Build\BakaShrotPushMessage.exe @messages\hello.json client.ini
|
||||
Pushed as message #1
|
||||
...
|
||||
== Read the latest message of logs:demo (topic:node, by name)
|
||||
> ..\..\Build\BakaShrotGetLatestMessage.exe logs demo client.ini
|
||||
Message logs:demo#2 (ids 1:2), pushed 2026-11-08T21:23:53.590Z
|
||||
Attachment: 159 bytes
|
||||
{"level":"info","text":"Daily report, attached"}
|
||||
```
|
||||
|
||||
The server's database (`example.sqlite`) and what the client saves
|
||||
(`out\`) stay in this folder, git ignores them.
|
||||
|
||||
## What's in here
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `server.ini` | The server: its key, its names, where it listens, the one client it accepts and what that client may do. Every option is documented in `Server/Config/schema.ini`. |
|
||||
| `client.ini` | The client: its key pair, the node it writes as (`demo`), and the server's address and public key. Every tool takes it as its last argument. |
|
||||
| `Start-Server.ps1` | Starts the server with `server.ini`. |
|
||||
| `Run-Client.ps1` | The client's steps, below. |
|
||||
| `messages\` | What the client pushes (`hello.json`, `reading.json`, `report.json` with `report.txt` attached) and the SQL it runs (`query.sql`). |
|
||||
|
||||
## How the two configs fit together
|
||||
|
||||
- **Keys:** each side has a key pair. The server lists the client's public
|
||||
key in `[BakaShrot.Client.demo] PublicKeys`; the client has the server's
|
||||
in `ServerPublicKey`. Every connection is encrypted, and only reaches the
|
||||
server holding the matching private key.
|
||||
- **Names:** messages are filed under a topic and a node. The topics are
|
||||
listed in `[BakaShrot.Topics]`, the nodes come from the sections that
|
||||
define them (`server`, `demo`). The server gives each name an id of its
|
||||
own; clients use the names.
|
||||
- **Who the client is:** its node, `demo`, in both configs (`Node`).
|
||||
Every message it pushes is stored under it. That's why the server
|
||||
checks it: the key proves who's connecting, the server's `Node` for that
|
||||
key says which node it may write as, so no client can push as another's
|
||||
node.
|
||||
- **Where its pushes go:** the server's `DefaultTopic = logs`, unless a
|
||||
push names another topic in `PushTopics` (`-t sensors`). Only the server
|
||||
has it: `client.ini` has no topic.
|
||||
- **What it may do:** read every topic (`ReadTopics = *`, `AllowRead`),
|
||||
push (`AllowWrite`), run read-only SQL (`AllowQuery`).
|
||||
- **Retention:** `sensors` messages are kept a day, `logs` ones forever.
|
||||
- **Durability:** `Synchronous = FULL` (the default): every message the
|
||||
server acknowledges is flushed to disk first, so it survives a power cut.
|
||||
`NORMAL` pushes faster but can lose the last second or so of messages
|
||||
then; see `Server/Config/schema.ini`.
|
||||
|
||||
## What the client does
|
||||
|
||||
`Run-Client.ps1`, step by step:
|
||||
|
||||
1. **Pushes** `hello.json` to `logs`, its default topic: `BakaShrotPushMessage @messages\hello.json`.
|
||||
JSON goes in a file (`@file`): PowerShell drops the double quotes of an
|
||||
argument.
|
||||
2. **Pushes** `reading.json` to `sensors`: `-t sensors`.
|
||||
3. **Pushes** `report.json` with `report.txt` attached: `-a messages\report.txt`.
|
||||
4. **Reads the latest** message of `logs:demo`: `BakaShrotGetLatestMessage logs demo`.
|
||||
5. **Saves the attachment** back to `out\report-copy.txt` and checks it's
|
||||
the same: `BakaShrotGetAttachment logs demo <id> out\report-copy.txt`.
|
||||
6. **Reads every** message of `logs:demo`, one per line (id, time, data):
|
||||
`BakaShrotGetMessages logs demo --time`.
|
||||
7. **Reads** `sensors:demo`'s latest.
|
||||
8. **Shows the ids** the server has for the names: `BakaShrotResolveIds topic sensors`, `BakaShrotList`.
|
||||
9. **Queries** with SQL: `BakaShrotQuery @messages\query.sql`, on the
|
||||
`messages` view, which has the names.
|
||||
|
||||
To watch messages arrive, leave this running and push from another
|
||||
terminal:
|
||||
|
||||
```powershell
|
||||
..\..\Build\BakaShrotGetMessages.exe logs demo --after latest --follow client.ini
|
||||
```
|
||||
|
||||
## Looking at the database
|
||||
|
||||
`example.sqlite` is a plain SQLite file, the `messages` view has the
|
||||
names. To browse one topic in a tool like SQLiteStudio:
|
||||
|
||||
1. Open the `browse` table: one row. Pick a topic in its `topic` cell (a
|
||||
dropdown of the topics, from its foreign key), and a node in `node` to
|
||||
narrow it, or leave it NULL for every node. Commit.
|
||||
2. Open the `browse_messages` view: that topic's messages, newest first,
|
||||
with their node, id, time (UTC), data and attachment size.
|
||||
|
||||
The server never writes `browse`, so it's safe to change while it runs.
|
||||
Close the tool when done: an open grid keeps the server from finishing
|
||||
its checkpoints, and its WAL file grows meanwhile.
|
||||
|
||||
## From Python
|
||||
|
||||
The same `client.ini` works with the Python client
|
||||
(`Interactors/Python/bakashrot.py`, over the DLL). From the repository's
|
||||
root:
|
||||
|
||||
```python
|
||||
import sys
|
||||
sys.path.insert(0, r"Interactors\Python")
|
||||
from bakashrot import Client
|
||||
|
||||
with Client.from_ini(r"Examples\SingleServer\client.ini", r"Build\BakaShrot_Client.dll") as client:
|
||||
print("pushed", client.push({"from": "python"}))
|
||||
for message in client.get_messages("logs", "demo").messages:
|
||||
print(message.id, message.json())
|
||||
```
|
||||
@@ -0,0 +1,101 @@
|
||||
# ============================================================================
|
||||
# BakaShrot example: what a client does, with the tools and client.ini.
|
||||
#
|
||||
# Start the server first (Start-Server.ps1). Each step prints the command
|
||||
# it runs, then its output: run from this folder, the commands can be
|
||||
# pasted as they are. Every run pushes 3 more messages, the ids go on from
|
||||
# the last run's (Start-Server.ps1 -Reset starts over).
|
||||
#
|
||||
# Usage: powershell -ExecutionPolicy Bypass -File Run-Client.ps1 [-BinDir <dir>]
|
||||
# -BinDir Where the tools are, with BakaShrot_Client.dll next to them:
|
||||
# Build\ by default (Build.ps1), or a Release\<v>\.
|
||||
# ============================================================================
|
||||
|
||||
param(
|
||||
[string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build")
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$Port = 12360
|
||||
|
||||
function Test-Port($Port) {
|
||||
$Client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
|
||||
return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected)
|
||||
} catch { return $false }
|
||||
finally { $Client.Close() }
|
||||
}
|
||||
|
||||
function Write-Step($Text) {
|
||||
Write-Host ""
|
||||
Write-Host "== $Text" -ForegroundColor Cyan
|
||||
}
|
||||
|
||||
# Runs a tool, shows the command and what it printed, stops if it failed.
|
||||
# client.ini is always the last argument.
|
||||
function Invoke-Tool($Name, [string[]]$Arguments) {
|
||||
$Arguments += "client.ini"
|
||||
$Shown = $Arguments | ForEach-Object { if ($_ -match " ") { "`"$_`"" } else { $_ } }
|
||||
Write-Host ("> " + (Join-Path $Bin "$Name.exe") + " " + ($Shown -join " ")) -ForegroundColor DarkGray
|
||||
$Output = & (Join-Path $Bin "$Name.exe") @Arguments 2>&1
|
||||
$Code = $LASTEXITCODE
|
||||
$Output | ForEach-Object { Write-Host " $_" }
|
||||
if ($Code -ne 0) { throw "$Name failed with code $Code" }
|
||||
return ($Output -join "`n")
|
||||
}
|
||||
|
||||
if (-not (Test-Path (Join-Path $BinDir "BakaShrot_Client.dll"))) {
|
||||
throw "No BakaShrot_Client.dll in ${BinDir}: build it first (Build.ps1), or pass -BinDir"
|
||||
}
|
||||
if (-not (Test-Port $Port)) {
|
||||
throw "Nothing listens on port ${Port}: start the server first (Start-Server.ps1)"
|
||||
}
|
||||
|
||||
# From this folder, so every path is short: client.ini, messages\...
|
||||
Push-Location $PSScriptRoot
|
||||
try {
|
||||
$Bin = Resolve-Path -Relative $BinDir
|
||||
New-Item -ItemType Directory -Force "out" | Out-Null
|
||||
|
||||
Write-Step "Push a message to the client's default topic (logs, the server's DefaultTopic for it), as node demo"
|
||||
# JSON goes in a file (@file): PowerShell drops the double quotes of an argument.
|
||||
$null = Invoke-Tool "BakaShrotPushMessage" @("@messages\hello.json")
|
||||
|
||||
Write-Step "Push one to another topic it may push to (sensors)"
|
||||
$null = Invoke-Tool "BakaShrotPushMessage" @("-t", "sensors", "@messages\reading.json")
|
||||
|
||||
Write-Step "Push one with a file attached"
|
||||
$Pushed = Invoke-Tool "BakaShrotPushMessage" @("-a", "messages\report.txt", "@messages\report.json")
|
||||
if ($Pushed -notmatch "message #(\d+)") { throw "Unexpected answer: $Pushed" }
|
||||
$ReportId = $Matches[1]
|
||||
|
||||
Write-Step "Read the latest message of logs:demo (topic:node, by name)"
|
||||
$null = Invoke-Tool "BakaShrotGetLatestMessage" @("logs", "demo")
|
||||
|
||||
Write-Step "Read the attachment back"
|
||||
$null = Invoke-Tool "BakaShrotGetAttachment" @("logs", "demo", $ReportId, "out\report-copy.txt")
|
||||
if ((Get-FileHash "out\report-copy.txt").Hash -ne (Get-FileHash "messages\report.txt").Hash) { throw "The attachment came back different" }
|
||||
Write-Host " Same bytes as messages\report.txt"
|
||||
|
||||
Write-Step "Read every message of logs:demo, with when they were pushed (UTC)"
|
||||
$null = Invoke-Tool "BakaShrotGetMessages" @("logs", "demo", "--time")
|
||||
|
||||
Write-Step "Read the sensors one"
|
||||
$null = Invoke-Tool "BakaShrotGetLatestMessage" @("sensors", "demo")
|
||||
|
||||
Write-Step "What the server calls the names: their ids there"
|
||||
$null = Invoke-Tool "BakaShrotResolveIds" @("topic", "sensors")
|
||||
$null = Invoke-Tool "BakaShrotList" @()
|
||||
|
||||
Write-Step "A raw SQL query (needs AllowQuery = 1), from messages\query.sql"
|
||||
$null = Invoke-Tool "BakaShrotQuery" @("@messages\query.sql")
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Done. To follow new messages as they come, from this folder:" -ForegroundColor Green
|
||||
Write-Host " $(Join-Path $Bin 'BakaShrotGetMessages.exe') logs demo --after latest --follow client.ini"
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
# ============================================================================
|
||||
# BakaShrot example: starts the server with server.ini.
|
||||
#
|
||||
# In a window of its own by default (the server needs a console: it reads
|
||||
# its commands there, and stops at once without one), then waits until it
|
||||
# listens. Type "quit" in that window to stop it, "help" for the others.
|
||||
#
|
||||
# Usage: powershell -ExecutionPolicy Bypass -File Start-Server.ps1 [-BinDir <dir>] [-Here] [-Reset]
|
||||
# -BinDir Where BakaShrot_Server.exe is, with libsodium.dll and
|
||||
# sqlite3.dll: Build\ by default (Build.ps1), or a Release\<v>\.
|
||||
# -Here Runs it in this console instead, until "quit".
|
||||
# -Reset Deletes the example's database first: no messages, ids from 1.
|
||||
#
|
||||
# Its database, example.sqlite, goes next to this script.
|
||||
# ============================================================================
|
||||
|
||||
param(
|
||||
[string]$BinDir = (Join-Path $PSScriptRoot "..\..\Build"),
|
||||
[switch]$Here,
|
||||
[switch]$Reset
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$Server = Join-Path $BinDir "BakaShrot_Server.exe"
|
||||
$Ini = Join-Path $PSScriptRoot "server.ini"
|
||||
$Port = 12360
|
||||
|
||||
function Test-Port($Port) {
|
||||
$Client = New-Object System.Net.Sockets.TcpClient
|
||||
try {
|
||||
$Async = $Client.BeginConnect("127.0.0.1", $Port, $null, $null)
|
||||
return ($Async.AsyncWaitHandle.WaitOne(200) -and $Client.Connected)
|
||||
} catch { return $false }
|
||||
finally { $Client.Close() }
|
||||
}
|
||||
|
||||
if (-not (Test-Path $Server)) {
|
||||
throw "No ${Server}: build it first (Build.ps1), or pass -BinDir"
|
||||
}
|
||||
if (Test-Port $Port) {
|
||||
throw "Something already listens on port $Port, the example server may already run"
|
||||
}
|
||||
|
||||
if ($Reset) {
|
||||
Get-ChildItem $PSScriptRoot -Filter "example.sqlite*" | Remove-Item -Confirm:$false
|
||||
Write-Host "Deleted the example's database"
|
||||
}
|
||||
|
||||
if ($Here) {
|
||||
Push-Location $PSScriptRoot
|
||||
try { & $Server $Ini }
|
||||
finally { Pop-Location }
|
||||
exit $LASTEXITCODE
|
||||
}
|
||||
|
||||
$Process = Start-Process -FilePath $Server -ArgumentList "`"$Ini`"" -WorkingDirectory $PSScriptRoot -PassThru
|
||||
$Deadline = (Get-Date).AddSeconds(15)
|
||||
while (-not (Test-Port $Port)) {
|
||||
if ($Process.HasExited) { throw "The server stopped with code $($Process.ExitCode), see its log above" }
|
||||
if ((Get-Date) -gt $Deadline) { throw "The server isn't listening on $Port after 15 s" }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
|
||||
Write-Host "The server runs in its own window (process $($Process.Id)), on 127.0.0.1:$Port."
|
||||
Write-Host "Try it with: powershell -ExecutionPolicy Bypass -File `"$(Join-Path $PSScriptRoot 'Run-Client.ps1')`""
|
||||
Write-Host "Stop it by typing quit in its window."
|
||||
@@ -0,0 +1,26 @@
|
||||
; ============================================================================
|
||||
; BakaShrot example: the client's config, read by every tool (their last
|
||||
; argument), the client DLL and the Python client.
|
||||
;
|
||||
; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real.
|
||||
; Make your own with BakaShrotGenerateKeyPairs.exe.
|
||||
; ============================================================================
|
||||
|
||||
[BakaShrot]
|
||||
; This client's key pair. The server lists the public key in
|
||||
; [BakaShrot.Client.demo] PublicKeys.
|
||||
PrivateKey = zDA8o6hp7zkIatlumOKFWqV8j3yYON8QFpIkMAEnpJnKv4FbbX4SmshWDRJp9ds5qpEDVYRHSnE7exw2pkQK1w==
|
||||
PublicKey = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc=
|
||||
|
||||
; The node it writes as: the server checks its section for this key says
|
||||
; Node = demo. Every message it pushes is stored as "demo".
|
||||
; No topic here: where its pushes go when they don't name one is the
|
||||
; server's DefaultTopic, which topics it may push to and read its
|
||||
; PushTopics and ReadTopics.
|
||||
Node = demo
|
||||
|
||||
; Where the server is, and its public key: the client only talks to the
|
||||
; server holding the matching private key.
|
||||
ServerHost = 127.0.0.1
|
||||
ServerPort = 12360
|
||||
ServerPublicKey = k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4=
|
||||
@@ -0,0 +1 @@
|
||||
{"level":"info","text":"Hello from the example client"}
|
||||
@@ -0,0 +1 @@
|
||||
SELECT topic, node, message_id, pushed_utc, message_data ->> '$.text' FROM messages WHERE topic = 'logs' AND is_json = 1 ORDER BY message_id
|
||||
@@ -0,0 +1 @@
|
||||
{"sensor":"kitchen-temperature","celsius":21.5}
|
||||
@@ -0,0 +1 @@
|
||||
{"level":"info","text":"Daily report, attached"}
|
||||
@@ -0,0 +1,5 @@
|
||||
Daily report
|
||||
============
|
||||
|
||||
Any file can be attached to a message: bytes of any kind, up to the
|
||||
server's MaxAttachmentSize. The message's JSON says what it is.
|
||||
@@ -0,0 +1,67 @@
|
||||
; ============================================================================
|
||||
; BakaShrot example: the server's config (one server, one client).
|
||||
;
|
||||
; EXAMPLE KEYS, PUBLIC IN THE REPOSITORY: never use them for anything real.
|
||||
; Make your own with BakaShrotGenerateKeyPairs.exe.
|
||||
;
|
||||
; Every option is documented in Server/Config/schema.ini.
|
||||
; ============================================================================
|
||||
|
||||
[BakaShrot]
|
||||
; This server's private key. Its public key, which the client needs, is
|
||||
; k32QNiTXL9lA7DhdwBQv9jQXouADujciaOWVZuA3JE4= (the server logs it too).
|
||||
PrivateKey = KymGH/iJFcqE0JtGmRmWIsQnKTEl49Zq+qYEsfLHtWOTfZA2JNcv2UDsOF3AFC/2NBei4AO6NyJo5ZVm4DckTg==
|
||||
|
||||
; The node this server authenticates as when it links to peers. It has
|
||||
; none here.
|
||||
Node = server
|
||||
|
||||
|
||||
; The topics this server has. It gives each an id of its own (they keep it
|
||||
; across restarts); clients and other servers use the names.
|
||||
[BakaShrot.Topics]
|
||||
logs
|
||||
sensors
|
||||
|
||||
; No [BakaShrot.Nodes]: the nodes come from the sections that define them,
|
||||
; "server" above and "demo" below (and the ones peers send, as they come).
|
||||
|
||||
|
||||
; Sensor readings are kept a day, logs forever (no line for them).
|
||||
[BakaShrot.Retention]
|
||||
sensors = 1d
|
||||
|
||||
|
||||
[BakaShrot.Server]
|
||||
; Only reachable from this machine.
|
||||
Host = 127.0.0.1
|
||||
Port = 12360
|
||||
ReplicatingTopics = logs;sensors
|
||||
NetThreadPoolSize = 4
|
||||
; Next to this file: Start-Server.ps1 runs the server from this folder.
|
||||
DatabasePath = ./example.sqlite
|
||||
MaxAttachmentSize = 64M
|
||||
; Every acknowledged push is on disk, even through a power loss (the
|
||||
; default). NORMAL is faster but can lose the last second of messages then.
|
||||
Synchronous = FULL
|
||||
|
||||
|
||||
; The one client: Run-Client.ps1's tools, with client.ini.
|
||||
[BakaShrot.Client.demo]
|
||||
; client.ini's PublicKey.
|
||||
PublicKeys = yr+BW21+EprIVg0SafXbOaqRA1WER0pxO3scNqZECtc=
|
||||
; The node this key writes as, fixed: every message it pushes is stored
|
||||
; under it, so no client can push as another's node. client.ini's Node
|
||||
; must say the same.
|
||||
Node = demo
|
||||
; Where its pushes go when they don't name a topic (BakaShrotPushMessage
|
||||
; without -t). Only a default: it may push to any topic in PushTopics.
|
||||
DefaultTopic = logs
|
||||
; The topics it may push to (always as "demo"), and read from. Without
|
||||
; these two lines: only its DefaultTopic.
|
||||
PushTopics = logs;sensors
|
||||
ReadTopics = *
|
||||
AllowRead = 1
|
||||
AllowWrite = 1
|
||||
; Raw read-only SQL, for BakaShrotQuery.exe.
|
||||
AllowQuery = 1
|
||||
+128
-38
@@ -27,6 +27,18 @@ The connection only goes through to the server holding the private key of
|
||||
server_public_key (client.ini's ServerPublicKey, the server logs it when it
|
||||
starts), and everything on it is encrypted.
|
||||
|
||||
Errors are exceptions with a code (`error.code`, an ErrorCode, the same
|
||||
numbers as the DLL's BakaShrot_GetLastError(), see
|
||||
Client/BakaShrot_ErrorCodes.pbi):
|
||||
RefusedError the server refused (codes 1-99), still connected
|
||||
ConnectionLostError not connected, unreachable, the connection lost or
|
||||
broken: connect() again (nothing reconnects by itself)
|
||||
AuthError the server rejected the handshake or couldn't prove
|
||||
its key: fix the config, retrying won't help
|
||||
BakaShrotError the rest: a bad argument, a file, the DLL itself
|
||||
A push whose answer was lost (ConnectionLostError) may have been stored all
|
||||
the same: pushed again, it's stored twice. Delivery is at least once.
|
||||
|
||||
The DLL holds a single connection per process: only one Client may be
|
||||
connected at a time. Calls are serialized with a lock, so a Client can be
|
||||
shared between threads, one request at a time.
|
||||
@@ -40,6 +52,7 @@ from __future__ import annotations
|
||||
|
||||
import configparser
|
||||
import ctypes
|
||||
import enum
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
@@ -50,7 +63,7 @@ from typing import Any, Iterator, Optional, Union
|
||||
|
||||
__all__ = [
|
||||
"Client", "Message", "MessagesPage", "NameEntry", "NamesList",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError",
|
||||
"BakaShrotError", "RefusedError", "ConnectionLostError", "AuthError", "ErrorCode",
|
||||
"MAX_GET_MESSAGES", "MAX_MESSAGE_SIZE",
|
||||
]
|
||||
|
||||
@@ -61,20 +74,75 @@ MAX_MESSAGE_SIZE = 16 * 1024 * 1024 - 4096
|
||||
Ref = Union[str, int]
|
||||
|
||||
|
||||
class ErrorCode(enum.IntEnum):
|
||||
"""What failed: Client/BakaShrot_ErrorCodes.pbi, the same numbers.
|
||||
1-99: refused by the server, 100+: the client's own."""
|
||||
NONE = 0
|
||||
# Refused by the server, the connection still open.
|
||||
NOT_ALLOWED = 1 # AllowRead/Write/Query, PushTopics/ReadTopics
|
||||
UNKNOWN_NAME = 2 # a topic or node this server doesn't know
|
||||
NOT_FOUND = 3 # no such message, attachment or upload
|
||||
NOT_READY = 4 # the attachment isn't on this server yet: retry later
|
||||
TOO_BIG = 5 # over a limit, or more than this server keeps
|
||||
NO_DEFAULT_TOPIC = 6 # a push without a topic, and no DefaultTopic
|
||||
INVALID_REQUEST = 7 # parts out of order, an upload for another topic...
|
||||
DATA_MISMATCH = 8 # an upload that doesn't match its SHA-256
|
||||
QUERY_FAILED = 9 # the SQL failed
|
||||
SERVER_ERROR = 10 # the server's database failed: retry later
|
||||
# The client's own.
|
||||
NOT_CONNECTED = 100 # never connected, or closed or lost before
|
||||
CONNECT_FAILED = 101 # nothing answers at that host and port
|
||||
AUTH_REJECTED = 102 # the server closed the handshake: wrong ServerPublicKey,
|
||||
# a key or node it doesn't allow, another version
|
||||
SERVER_NOT_VERIFIED = 103 # the server couldn't prove its key
|
||||
CONNECTION_LOST = 104 # broke during a request (a push may still be stored)
|
||||
PROTOCOL_ERROR = 105 # an unexpected answer, the connection is closed
|
||||
INVALID_ARGUMENT = 106
|
||||
FILE_ERROR = 107
|
||||
ATTACHMENT_MISMATCH = 108 # a downloaded attachment that doesn't match its SHA-256
|
||||
ALREADY_CONNECTED = 109
|
||||
INTERNAL = 110 # out of memory, the DLL missing or too old...
|
||||
|
||||
@property
|
||||
def is_refusal(self) -> bool:
|
||||
return 1 <= self.value <= 99
|
||||
|
||||
|
||||
def _error_code(value: int):
|
||||
"""An ErrorCode, or the int itself if this module doesn't know it."""
|
||||
try:
|
||||
return ErrorCode(value)
|
||||
except ValueError:
|
||||
return value
|
||||
|
||||
|
||||
class BakaShrotError(Exception):
|
||||
"""Something failed: the DLL couldn't be loaded, a bad argument, ..."""
|
||||
"""Something failed: code (an ErrorCode) tells what, see ErrorCode."""
|
||||
|
||||
def __init__(self, message: str, code: int = ErrorCode.INTERNAL):
|
||||
super().__init__(message)
|
||||
self.code = _error_code(code)
|
||||
|
||||
|
||||
class RefusedError(BakaShrotError):
|
||||
"""The server refused the request, the connection is still open."""
|
||||
"""The server refused the request, the connection is still open. code
|
||||
says why (1-99, e.g. ErrorCode.NOT_FOUND), reason in the server's words."""
|
||||
|
||||
def __init__(self, reason: str):
|
||||
super().__init__(reason or "Refused")
|
||||
def __init__(self, reason: str, code: int):
|
||||
super().__init__(reason or "Refused", code)
|
||||
self.reason = reason
|
||||
|
||||
|
||||
class ConnectionLostError(BakaShrotError):
|
||||
"""The connection failed or was closed, connect() again to go on."""
|
||||
"""Not connected, or the connection failed or was closed (code:
|
||||
NOT_CONNECTED, CONNECT_FAILED, CONNECTION_LOST, PROTOCOL_ERROR):
|
||||
connect() again to go on."""
|
||||
|
||||
|
||||
class AuthError(BakaShrotError):
|
||||
"""The server rejected the handshake (AUTH_REJECTED) or couldn't prove it
|
||||
holds server_public_key's private key (SERVER_NOT_VERIFIED): a config to
|
||||
fix, connecting again won't help."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -186,10 +254,10 @@ class _Dll:
|
||||
|
||||
I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p
|
||||
signatures = {
|
||||
"BakaShrot_GetLastError": (L, []),
|
||||
"BakaShrot_SetPrivateKeyA": (I, [P]),
|
||||
"BakaShrot_SetPublicKeyA": (I, [P]),
|
||||
"BakaShrot_SetServerPublicKeyA": (I, [P]),
|
||||
"BakaShrot_SetTopicA": (I, [P]),
|
||||
"BakaShrot_SetNodeA": (I, [P]),
|
||||
"BakaShrot_ConnectA": (I, [P, L]),
|
||||
"BakaShrot_IsConnected": (I, []),
|
||||
@@ -229,7 +297,7 @@ class _Dll:
|
||||
try:
|
||||
function = getattr(self.lib, name)
|
||||
except AttributeError as error:
|
||||
raise BakaShrotError(f"{path} has no {name}, is it an older build?") from error
|
||||
raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error
|
||||
function.restype = restype
|
||||
function.argtypes = argtypes
|
||||
setattr(self, name[len("BakaShrot_"):], function)
|
||||
@@ -247,23 +315,24 @@ class _Dll:
|
||||
class Client:
|
||||
"""A connection to a BakaShrot server, through the DLL.
|
||||
|
||||
private_key, public_key: the client's Ed25519 keys in Base64 (KeyGen.exe).
|
||||
private_key, public_key: the client's Ed25519 keys in Base64 (BakaShrotGenerateKeyPairs.exe).
|
||||
server_public_key: the server's Ed25519 public key in Base64, it must
|
||||
prove it holds the matching private key.
|
||||
topic, node: who the client is, names or ids, as the server's
|
||||
[BakaShrot.Client.<name>] Identities lists them.
|
||||
node: the node the client writes as, a name or an id, which the
|
||||
server's [BakaShrot.Client.<name>] must give its key (Node). Its
|
||||
default topic, for pushes that don't name one, is the server's to say
|
||||
(that section's DefaultTopic).
|
||||
"""
|
||||
|
||||
_connected_client: Optional["Client"] = None
|
||||
|
||||
def __init__(self, private_key: str, public_key: str, server_public_key: str, topic: Ref, node: Ref,
|
||||
def __init__(self, private_key: str, public_key: str, server_public_key: str, node: Ref,
|
||||
host: str = "127.0.0.1", port: int = 12345, dll_path: Optional[str] = None):
|
||||
self._dll = _Dll.get(dll_path)
|
||||
self._lock = threading.RLock()
|
||||
self.private_key = private_key
|
||||
self.public_key = public_key
|
||||
self.server_public_key = server_public_key
|
||||
self.topic = topic
|
||||
self.node = node
|
||||
self.host = host
|
||||
self.port = int(port)
|
||||
@@ -271,45 +340,48 @@ class Client:
|
||||
@classmethod
|
||||
def from_ini(cls, path: str, dll_path: Optional[str] = None) -> "Client":
|
||||
"""From a client.ini as the tools read it: [BakaShrot] PrivateKey,
|
||||
PublicKey, ServerPublicKey, Topic, Node, ServerHost, ServerPort."""
|
||||
PublicKey, ServerPublicKey, Node, ServerHost, ServerPort (a Topic
|
||||
left in it is ignored)."""
|
||||
parser = configparser.ConfigParser(interpolation=None)
|
||||
if not parser.read(path, encoding="utf-8-sig"):
|
||||
raise BakaShrotError(f"Failed to open '{path}'")
|
||||
raise BakaShrotError(f"Failed to open '{path}'", ErrorCode.FILE_ERROR)
|
||||
section = parser["BakaShrot"] if parser.has_section("BakaShrot") else {}
|
||||
|
||||
def get(key, fallback=None):
|
||||
value = section.get(key, fallback)
|
||||
if value is None:
|
||||
raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}")
|
||||
raise BakaShrotError(f"'{path}' has no [BakaShrot] {key}", ErrorCode.INVALID_ARGUMENT)
|
||||
return value.strip()
|
||||
|
||||
return cls(get("PrivateKey"), get("PublicKey"), get("ServerPublicKey"),
|
||||
get("Topic", section.get("TopicId")), get("Node", section.get("NodeId")),
|
||||
get("Node", section.get("NodeId")),
|
||||
get("ServerHost"), int(get("ServerPort")), dll_path)
|
||||
|
||||
# --- Connection --------------------------------------------------------
|
||||
|
||||
def connect(self) -> "Client":
|
||||
"""Connects and authenticates, raises BakaShrotError on failure."""
|
||||
"""Connects and authenticates. Raises ConnectionLostError when the
|
||||
server can't be reached (CONNECT_FAILED), AuthError when it rejects
|
||||
the handshake or can't prove its key, BakaShrotError on a bad setting
|
||||
(INVALID_ARGUMENT) or another Client holding the DLL's connection
|
||||
(ALREADY_CONNECTED)."""
|
||||
with self._lock:
|
||||
owner = Client._connected_client
|
||||
if owner is not None and owner is not self and owner.connected:
|
||||
raise BakaShrotError("The DLL holds one connection, another Client is connected")
|
||||
raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED)
|
||||
if self.connected:
|
||||
return self
|
||||
dll = self._dll
|
||||
if not dll.SetPrivateKeyA(self.private_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid private key")
|
||||
raise BakaShrotError("Invalid private key", dll.GetLastError())
|
||||
if not dll.SetPublicKeyA(self.public_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid public key")
|
||||
raise BakaShrotError("Invalid public key", dll.GetLastError())
|
||||
if not dll.SetServerPublicKeyA(self.server_public_key.encode("ascii")):
|
||||
raise BakaShrotError("Invalid server public key")
|
||||
if not dll.SetTopicA(_ref(self.topic)):
|
||||
raise BakaShrotError(f"Invalid topic {self.topic!r}")
|
||||
raise BakaShrotError("Invalid server public key", dll.GetLastError())
|
||||
if not dll.SetNodeA(_ref(self.node)):
|
||||
raise BakaShrotError(f"Invalid node {self.node!r}")
|
||||
raise BakaShrotError(f"Invalid node {self.node!r}", dll.GetLastError())
|
||||
if not dll.ConnectA(self.host.encode("utf-8"), self.port):
|
||||
raise ConnectionLostError(f"Failed to connect and authenticate to {self.host}:{self.port}")
|
||||
raise self._failed(f"Connect to {self.host}:{self.port}")
|
||||
Client._connected_client = self
|
||||
return self
|
||||
|
||||
@@ -331,22 +403,39 @@ class Client:
|
||||
|
||||
def _check_connected(self) -> None:
|
||||
if not self.connected:
|
||||
raise ConnectionLostError("Not connected")
|
||||
raise ConnectionLostError("Not connected", ErrorCode.NOT_CONNECTED)
|
||||
|
||||
_MESSAGES = {
|
||||
ErrorCode.NOT_CONNECTED: "not connected",
|
||||
ErrorCode.CONNECT_FAILED: "nothing answers there",
|
||||
ErrorCode.AUTH_REJECTED: "the server closed the connection during the handshake: wrong server public key, "
|
||||
"a key or node it doesn't allow, or another version (its log says which)",
|
||||
ErrorCode.SERVER_NOT_VERIFIED: "the server couldn't prove it holds the server public key's private key",
|
||||
ErrorCode.CONNECTION_LOST: "the connection to the server failed",
|
||||
ErrorCode.PROTOCOL_ERROR: "the server answered something unexpected, the connection is closed",
|
||||
}
|
||||
|
||||
def _failed(self, what: str) -> BakaShrotError:
|
||||
"""The error for a failed request: refused, or the connection is gone."""
|
||||
if self._dll.IsConnected():
|
||||
"""The error for a failed call, by the DLL's BakaShrot_GetLastError()."""
|
||||
code = _error_code(self._dll.GetLastError())
|
||||
reason = self._dll.string(self._dll.GetRefusalReasonA)
|
||||
return RefusedError(reason) if reason else BakaShrotError(f"{what} failed")
|
||||
if Client._connected_client is self:
|
||||
if isinstance(code, int) and 1 <= int(code) <= 99:
|
||||
return RefusedError(reason, code)
|
||||
if not self._dll.IsConnected() and Client._connected_client is self:
|
||||
Client._connected_client = None
|
||||
return ConnectionLostError(f"{what}: the connection to the server failed")
|
||||
name = code.name if isinstance(code, ErrorCode) else str(code)
|
||||
message = f"{what} ({name}): {reason or self._MESSAGES.get(code, 'failed')}"
|
||||
if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR):
|
||||
return ConnectionLostError(message, code)
|
||||
if code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED):
|
||||
return AuthError(message, code)
|
||||
return BakaShrotError(message, code if code else ErrorCode.INTERNAL)
|
||||
|
||||
# --- Requests ----------------------------------------------------------
|
||||
|
||||
def push(self, data: Any, topic: Optional[Ref] = None,
|
||||
attachment: Union[None, bytes, bytearray, memoryview, str, os.PathLike] = None) -> int:
|
||||
"""Pushes a message into topic (default: the client's own), under
|
||||
"""Pushes a message into topic (default: the client's default one, its server's DefaultTopic), under
|
||||
the client's node. data is stored as is if it's a str (JSON or not),
|
||||
anything else is turned into JSON first. Returns its message id.
|
||||
|
||||
@@ -357,7 +446,7 @@ class Client:
|
||||
data = json.dumps(data, separators=(",", ":"), ensure_ascii=False)
|
||||
encoded = data.encode("utf-8")
|
||||
if len(encoded) > MAX_MESSAGE_SIZE:
|
||||
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}")
|
||||
raise BakaShrotError(f"The message is too big: {len(encoded)} bytes, at most {MAX_MESSAGE_SIZE}", ErrorCode.INVALID_ARGUMENT)
|
||||
topic_ref = b"" if topic is None else _ref(topic)
|
||||
with self._lock:
|
||||
self._check_connected()
|
||||
@@ -366,13 +455,13 @@ class Client:
|
||||
elif isinstance(attachment, (bytes, bytearray, memoryview)):
|
||||
raw = bytes(attachment)
|
||||
if not raw:
|
||||
raise BakaShrotError("The attachment is empty")
|
||||
raise BakaShrotError("The attachment is empty", ErrorCode.INVALID_ARGUMENT)
|
||||
buffer = ctypes.create_string_buffer(raw, len(raw))
|
||||
message_id = self._dll.PushMessageWithDataA(topic_ref, encoded, ctypes.cast(buffer, ctypes.c_void_p), len(raw))
|
||||
else:
|
||||
path = os.fspath(attachment)
|
||||
if not os.path.isfile(path) or os.path.getsize(path) == 0:
|
||||
raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty")
|
||||
raise BakaShrotError(f"Can't attach {path!r}: no such file, or empty", ErrorCode.FILE_ERROR)
|
||||
message_id = self._dll.PushMessageWithFileA(topic_ref, encoded, path.encode("utf-8"))
|
||||
if message_id < 1:
|
||||
raise self._failed("Push")
|
||||
@@ -418,7 +507,7 @@ class Client:
|
||||
self._check_connected()
|
||||
if not self._dll.GetLatestMessageOfA(_ref(topic), _ref(node)):
|
||||
error = self._failed("Latest message")
|
||||
if isinstance(error, RefusedError) and error.reason.startswith("No message for"):
|
||||
if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND:
|
||||
return None
|
||||
raise error
|
||||
return self._current()
|
||||
@@ -460,7 +549,8 @@ class Client:
|
||||
"""Every message of topic/node after `after`, then new ones as they
|
||||
come, checking every `interval` seconds once caught up. Forever:
|
||||
stop iterating to stop. after="latest" starts with the next new one.
|
||||
Raises ConnectionLostError if the connection fails."""
|
||||
Raises ConnectionLostError if the connection fails: nothing
|
||||
reconnects by itself, connect() again and follow from the last id."""
|
||||
if after == "latest":
|
||||
latest = self.latest(topic, node)
|
||||
after = latest.id if latest else 0
|
||||
|
||||
@@ -14,7 +14,7 @@ import threading
|
||||
import time
|
||||
|
||||
import bakashrot
|
||||
from bakashrot import BakaShrotError, Client, ConnectionLostError, RefusedError
|
||||
from bakashrot import AuthError, BakaShrotError, Client, ConnectionLostError, ErrorCode, RefusedError
|
||||
|
||||
dll_path, kitchen_ini, lounge_ini = sys.argv[1:4]
|
||||
fails = 0
|
||||
@@ -30,11 +30,12 @@ def check(what, ok, detail=""):
|
||||
print(f"{'PASS' if ok else 'FAIL'} {what}\n -> {detail}", flush=True)
|
||||
|
||||
|
||||
def raises(function, error_type, contains=""):
|
||||
def raises(function, error_type, contains="", code=None):
|
||||
try:
|
||||
function()
|
||||
except error_type as error:
|
||||
return contains in str(error), f"{type(error).__name__}: {error}"
|
||||
got = getattr(error, "code", None)
|
||||
return contains in str(error) and (code is None or got == code), f"{type(error).__name__} [{got!r}]: {error}"
|
||||
except Exception as error: # noqa: BLE001 - reported as a failure
|
||||
return False, f"{type(error).__name__}: {error}"
|
||||
return False, "didn't raise"
|
||||
@@ -111,6 +112,8 @@ with kitchen:
|
||||
|
||||
rows = kitchen.query("SELECT is_json, COUNT(*) AS n FROM data GROUP BY is_json ORDER BY is_json")
|
||||
check("query(): is_json flags 3 non-JSON, 250 JSON", rows == [{"is_json": "0", "n": "3"}, {"is_json": "1", "n": "250"}], rows)
|
||||
ok, detail = raises(lambda: kitchen.query("SELECT nope FROM data"), RefusedError, "nope", ErrorCode.QUERY_FAILED)
|
||||
check("A query that fails: RefusedError, QUERY_FAILED", ok, detail)
|
||||
|
||||
# --- Answers split at ~1 MB ----------------------------------------------
|
||||
big = "x" * (700 * 1024)
|
||||
@@ -123,18 +126,18 @@ with kitchen:
|
||||
[len(m.data) for m in every])
|
||||
|
||||
# --- Refusals ------------------------------------------------------------
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'")
|
||||
check("Unknown node: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "nobody"), RefusedError, "Unknown node 'nobody'", ErrorCode.UNKNOWN_NAME)
|
||||
check("Unknown node: RefusedError, UNKNOWN_NAME", ok, detail)
|
||||
check("Still connected after a refusal", kitchen.connected and kitchen.latest("logs", "kitchen").id == big_ids[-1])
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", limit=0), ValueError)
|
||||
check("limit 0: ValueError, before asking", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.get_messages("logs", "kitchen", after=-1), ValueError)
|
||||
check("after -1: ValueError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic")
|
||||
check("Push to an unknown topic: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="nothing"), RefusedError, "Unknown topic", ErrorCode.UNKNOWN_NAME)
|
||||
check("Push to an unknown topic: RefusedError, UNKNOWN_NAME", ok, detail)
|
||||
secret_id = kitchen.push({"s": 1}, topic="secret")
|
||||
check("Push to another allowed topic", secret_id == 1, secret_id)
|
||||
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection")
|
||||
ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED)
|
||||
check("A second Client can't connect while one is", ok and not lounge.connected, detail)
|
||||
|
||||
topics = kitchen.list_topics()
|
||||
@@ -192,26 +195,34 @@ with kitchen:
|
||||
sizes = [(m.id, m.attachment_size, m.attachment_ready) for m in page]
|
||||
check("get_messages(): each message's attachment",
|
||||
sizes == [(blob_id, len(blob), True), (file_id, os.path.getsize(source), True), (plain_id, 0, False)], sizes)
|
||||
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment")
|
||||
check("get_attachment() of a message without: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty")
|
||||
ok, detail = raises(lambda: kitchen.get_attachment("secret", "kitchen", plain_id), RefusedError, "No attachment", ErrorCode.NOT_FOUND)
|
||||
check("get_attachment() of a message without: RefusedError, NOT_FOUND", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=b""), BakaShrotError, "empty", ErrorCode.INVALID_ARGUMENT)
|
||||
check("An empty attachment: refused before sending", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file")
|
||||
ok, detail = raises(lambda: kitchen.push("x", topic="secret", attachment=os.path.join(folder, "missing.bin")), BakaShrotError, "no such file", ErrorCode.FILE_ERROR)
|
||||
check("A missing file: refused before sending", ok, detail)
|
||||
check("Still connected", kitchen.connected)
|
||||
|
||||
check("close(): disconnected", not kitchen.connected)
|
||||
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError)
|
||||
check("A request once closed: ConnectionLostError", ok, detail)
|
||||
ok, detail = raises(lambda: kitchen.push("x"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED)
|
||||
check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail)
|
||||
|
||||
# --- Connecting: unreachable, rejected ---------------------------------------
|
||||
nowhere = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, kitchen.node, "127.0.0.1", 1, dll_path)
|
||||
ok, detail = raises(nowhere.connect, ConnectionLostError, code=ErrorCode.CONNECT_FAILED)
|
||||
check("Nothing listening: ConnectionLostError, CONNECT_FAILED", ok, detail)
|
||||
stranger = Client(kitchen.private_key, kitchen.public_key, kitchen.server_public_key, "nobody", kitchen.host, kitchen.port, dll_path)
|
||||
ok, detail = raises(stranger.connect, AuthError, code=ErrorCode.AUTH_REJECTED)
|
||||
check("A node the server doesn't give this key: AuthError, AUTH_REJECTED", ok, detail)
|
||||
|
||||
with lounge:
|
||||
page = lounge.get_messages("logs", "kitchen", after=245, limit=3)
|
||||
check("Another identity once the first closed: reads logs", [m.id for m in page] == [246, 247, 248] and page.more,
|
||||
f"{[m.id for m in page]}, more={page.more}")
|
||||
ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'")
|
||||
check("A topic not in its ReadTopics: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query")
|
||||
check("Not allowed to query: RefusedError", ok, detail)
|
||||
ok, detail = raises(lambda: lounge.get_messages("secret", "kitchen"), RefusedError, "Not allowed to read topic 'secret'", ErrorCode.NOT_ALLOWED)
|
||||
check("A topic not in its ReadTopics: RefusedError, NOT_ALLOWED", ok, detail)
|
||||
ok, detail = raises(lambda: lounge.query("SELECT 1"), RefusedError, "Not allowed to query", ErrorCode.NOT_ALLOWED)
|
||||
check("Not allowed to query: RefusedError, NOT_ALLOWED", ok, detail)
|
||||
|
||||
print()
|
||||
print("All checks passed" if fails == 0 else f"{fails} check(s) failed")
|
||||
|
||||
@@ -4,7 +4,7 @@ Usage: python example.py <ClientIni> <Topic> <Node> [--from-start]
|
||||
Run it from Build\\ (Build.ps1) while BakaShrot_Server.exe runs, e.g.:
|
||||
python ..\\Interactors\\Python\\example.py client.ini logs local
|
||||
and push from another terminal:
|
||||
.\\PushMessage.exe @msg.json client.ini
|
||||
.\\BakaShrotPushMessage.exe @msg.json client.ini
|
||||
Ctrl+C to stop.
|
||||
"""
|
||||
|
||||
@@ -27,7 +27,7 @@ dll = os.environ.get("BAKASHROT_DLL") or os.path.join(os.path.dirname(os.path.ab
|
||||
|
||||
try:
|
||||
with Client.from_ini(ini, dll) as client:
|
||||
print(f"Connected to {client.host}:{client.port} as {client.topic}:{client.node}, following {topic}:{node}")
|
||||
print(f"Connected to {client.host}:{client.port} as node {client.node}, following {topic}:{node}")
|
||||
for message in client.follow(topic, node, after=after):
|
||||
# Parsing is the app's business: the server stores anything.
|
||||
try:
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
# BakaShrot - working notes
|
||||
|
||||
Where things stand and what's next, as of 2026-11-08. A new session: read
|
||||
`CLAUDE.md` first (how to build, test, and the traps), then "Open items"
|
||||
below. The detailed docs are in `Design/`:
|
||||
Where things stand and what's next, as of 2026-11-09. A new session: read
|
||||
`CLAUDE.md` first (how to build, test, and the traps), then "Right now" and
|
||||
"Open items" below. The detailed docs are in `Design/`:
|
||||
|
||||
| Doc | About |
|
||||
|---|---|
|
||||
@@ -14,6 +14,21 @@ below. The detailed docs are in `Design/`:
|
||||
| `Design/Suggestions.md` | Improvements not done yet: pipelined pushes, faster replication, smaller ones. |
|
||||
| `Design/Release.md` | The release smoke test, what's missing for 1.0.0, the (fixed) silent query failure, notes for CI/CD. |
|
||||
|
||||
## Right now (2026-11-09)
|
||||
|
||||
- **Nothing since `df61ef9` is committed**, on `timestamps-retention`: the
|
||||
tool renames, protocols 5 and 6 (node identities, error codes), names-only
|
||||
configs, `Synchronous`, schema v8 (`browse`), `Examples/`,
|
||||
`Restart-Test.ps1`. Every suite passes on it (8, see `CLAUDE.md`), it
|
||||
compiles with 5.73 and 6.40, the push bench gives ~17,000 msg/s for 4
|
||||
servers with `Synchronous = FULL`.
|
||||
- **`Release\20261109-df61ef9-dirty\` is out of date** (before
|
||||
`Synchronous`, `browse` and the error codes): commit, then
|
||||
`Release.ps1` again.
|
||||
- **Suggested next** (not decided by the owner): the server without a
|
||||
console (item 1), then whatever the real-world test shows. The run on a
|
||||
clean Windows is the owner's, not an item here.
|
||||
|
||||
## Where things stand
|
||||
|
||||
- **Build:** `powershell -ExecutionPolicy Bypass -File Build.ps1`
|
||||
@@ -27,7 +42,18 @@ below. The detailed docs are in `Design/`:
|
||||
- Every connection is encrypted, and both ends prove who they are: the
|
||||
client with an Ed25519 challenge, the server by signing the handshake
|
||||
with the key its clients know (since protocol 3, `Design/Cryptography.md`;
|
||||
the protocol is at 4, with attachments).
|
||||
the protocol is at 6: attachments in 4, node-only identities in 5,
|
||||
refusal codes in 6).
|
||||
- A client authenticates as a node (`[BakaShrot.Client.<name>] Node`,
|
||||
one per section, a key may be in several); its pushes go to that
|
||||
section's `DefaultTopic` unless they name one.
|
||||
- Topics are listed by name (`[BakaShrot.Topics]`), the server gives the
|
||||
ids and keeps them; nodes come from the sections that use them,
|
||||
`[BakaShrot.Nodes]` is optional, peers' nodes are taken as they come
|
||||
(`AcceptNodes = *` by default).
|
||||
- `[BakaShrot.Server] Synchronous = FULL` (default, every acknowledged
|
||||
push on disk) or `NORMAL` (faster, a power loss can lose the last
|
||||
second).
|
||||
- Clients can push messages (usually JSON, anything is stored, flagged
|
||||
in `is_json`), read the latest one of a topic/node pair or a run of
|
||||
them after an id, resolve names, and run raw read-only SQL, each depending on
|
||||
@@ -43,11 +69,20 @@ below. The detailed docs are in `Design/`:
|
||||
(`Design/Attachments.md`).
|
||||
- One thread per client and per peer, each with its own SQLite connection.
|
||||
- The root thread can stop every worker (restart, vacuum).
|
||||
- **Errors:** every refusal carries a code, every client failure too
|
||||
(`Client/BakaShrot_ErrorCodes.pbi`): `BakaShrot_GetLastError()` in the
|
||||
DLL, `error.code` in Python, the name in the tools' messages. Nothing
|
||||
reconnects by itself; delivery is at least once.
|
||||
- **Database tools:** the `messages` view (by names), and `browse` /
|
||||
`browse_messages` to pick a topic from a dropdown in SQLiteStudio.
|
||||
- **Example:** `Examples/SingleServer/`, a server and a client with scripts
|
||||
(its keys committed on purpose, public).
|
||||
- **Client:** a DLL with A/W string exports, PureBasic prototypes in
|
||||
`Client/BakaShrot_Client_Prototypes.pbi`, and tools in `Tools/`:
|
||||
`PushMessage` (`-a` to attach a file), `GetLatestMessage`, `GetMessages`
|
||||
(with `--follow`), `GetAttachment`, `Resolve`, `ListNames`, `Query`,
|
||||
`KeyGen`.
|
||||
`BakaShrotPushMessage` (`-a` to attach a file),
|
||||
`BakaShrotGetLatestMessage`, `BakaShrotGetMessages` (with `--follow`),
|
||||
`BakaShrotGetAttachment`, `BakaShrotResolveIds`, `BakaShrotList`,
|
||||
`BakaShrotQuery`, `BakaShrotGenerateKeyPairs`.
|
||||
- **Python:** `Interactors/Python/bakashrot.py`, over the DLL with ctypes,
|
||||
no dependencies, and `example.py`.
|
||||
- **Release:** `Release.ps1` builds with PB 6.40's C backend into
|
||||
@@ -88,8 +123,9 @@ below. The detailed docs are in `Design/`:
|
||||
(`BakaShrot_Names_Ingest()`): highest free id counting down from 65535,
|
||||
origin "peer". So `AcceptNodes = kitchen-*` saves listing every kitchen
|
||||
node on every server. Clients still can't create topics by name.
|
||||
- **A peer authenticates by name:** its own topic and node must be named the
|
||||
same on the servers it links to (it sends its name when it has one).
|
||||
- **A peer authenticates by name:** its own node must be named the same
|
||||
on the servers it links to (it sends its name when it has one). It sent
|
||||
a topic too before protocol 5.
|
||||
- **Everywhere a topic or node goes, a name or an id:** config, the Hello,
|
||||
requests, tools, client.ini. Keys: `Topic`, `Node`, `ReplicatingTopics`
|
||||
(`TopicId`, `NodeId`, `ReplicatingTopicIds` still read when the new ones
|
||||
@@ -97,13 +133,13 @@ below. The detailed docs are in `Design/`:
|
||||
- **Filters:** per client `PushTopics` / `ReadTopics` (default: its
|
||||
identities' topics, as before), per peer `SendTopics` / `AcceptTopics`
|
||||
(default: `ReplicatingTopics`). `*` = every topic. A push picks its topic
|
||||
(`PushMessage -t sensors`), never its node.
|
||||
(`BakaShrotPushMessage -t sensors`), never its node.
|
||||
- **The config wins at start,** except when it would move a name to another
|
||||
id than the one its messages are under: the server then refuses to start
|
||||
and says which id to use (`Server/Storage/Names.pbi`).
|
||||
- **Seeing the names:** the server's `names` console command, the
|
||||
`ListNames` tool (`BakaShrot_ListTopics/Nodes()` + `BakaShrot_GetNamesList()`
|
||||
as JSON, request `ListNames`), `Resolve` for one.
|
||||
`BakaShrotList` tool (`BakaShrot_ListTopics/Nodes()` + `BakaShrot_GetNamesList()`
|
||||
as JSON, request `ListNames`), `BakaShrotResolveIds` for one.
|
||||
- **Clients:** `BakaShrot_ResolveTopic/Node()`, `BakaShrot_PushMessageTo()`,
|
||||
`BakaShrot_GetLatestMessageOf()`, the answer's names and ids. Raw
|
||||
queries: `SELECT * FROM messages WHERE topic = 'logs' AND node =
|
||||
@@ -204,8 +240,8 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs.
|
||||
`BakaShrot_HasMoreMessages()`. GetLatestMessage fills the same list (one
|
||||
message). The DLL checks the answer is about what it asked, no more than
|
||||
asked, after the asked id.
|
||||
- **Tool:** `GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>]
|
||||
[--follow] [--interval <Ms>] [ClientIni]`: one line per message, id, tab,
|
||||
- **Tool:** `BakaShrotGetMessages <Topic> <Node> [--after <Id|latest>]
|
||||
[--limit <N>] [--follow] [--interval <Ms>] [ClientIni]`: one line per message, id, tab,
|
||||
data as stored. `--follow` polls every 500 ms once caught up, exits 1 when
|
||||
the connection fails. Polling, not pushed by the server: fine for a few
|
||||
followers, a subscription would be the next step if many follow.
|
||||
@@ -217,8 +253,8 @@ existing `data` means rebuilding the table. So: name tables, joined, no FKs.
|
||||
`ConnectionLostError`. Uses the DLL's UTF-8 exports, a lock serializes
|
||||
calls. **One connection per process** (the DLL's globals): a second
|
||||
Client can't connect while one is. ~9,600 pushes/s on one connection,
|
||||
against ~75/s launching `PushMessage.exe` each time.
|
||||
- **Released:** `GetMessages.exe` and `python\` (bakashrot.py, example.py),
|
||||
against ~75/s launching `BakaShrotPushMessage.exe` each time.
|
||||
- **Released:** `BakaShrotGetMessages.exe` and `python\` (bakashrot.py, example.py),
|
||||
the smoke test reads both messages back with the tool and with Python
|
||||
(if `python` is on the PATH).
|
||||
- **Tested:** `Tests/GetMessages-Test.ps1` (27 checks: limits, after an id /
|
||||
@@ -316,7 +352,7 @@ runner, then CI.
|
||||
to (`ReplicateMessages` carries it). Clients get it in `LatestMessage`
|
||||
and `Messages`: `BakaShrot_GetMessagePushedAt()` in the DLL,
|
||||
`Message.pushed_at` / `.pushed` (a UTC datetime) in Python,
|
||||
`GetMessages --time`, and `GetLatestMessage` shows it. In SQL:
|
||||
`BakaShrotGetMessages --time`, and `BakaShrotGetLatestMessage` shows it. In SQL:
|
||||
`data.pushed_at`, and `pushed_at` / `pushed_utc` (text) in the
|
||||
`messages` view.
|
||||
- **Upgrade:** a database from before gets the column, every message
|
||||
@@ -377,7 +413,7 @@ runner, then CI.
|
||||
`_GetMessageAttachmentSize()`, `_IsMessageAttachmentReady()`; Python
|
||||
`push(..., attachment=bytes or path)`, `get_attachment()`,
|
||||
`save_attachment()`, `Message.attachment_size/_ready`; tools
|
||||
`PushMessage -a`, `GetAttachment`.
|
||||
`BakaShrotPushMessage -a`, `BakaShrotGetAttachment`.
|
||||
- **Measured:** 512 MB up in 8.5 s, down in 3.9 s, identical, the server
|
||||
peaking at 15 MB of memory. The push benchmark isn't affected (messages
|
||||
without attachments only gain a LEFT JOIN on reads).
|
||||
@@ -395,6 +431,219 @@ runner, then CI.
|
||||
does resume); several parts in flight for high-latency links.
|
||||
See `Design/Attachments.md`.
|
||||
|
||||
## Renamed: the tools (2026-11-08)
|
||||
|
||||
Every tool is prefixed with `BakaShrot` (no `_`, the server keeps
|
||||
`BakaShrot_Server`), folder, source and exe alike, three renamed too:
|
||||
|
||||
| Before | Now |
|
||||
|---|---|
|
||||
| KeyGen | BakaShrotGenerateKeyPairs |
|
||||
| ListNames | BakaShrotList |
|
||||
| Resolve | BakaShrotResolveIds |
|
||||
| PushMessage, GetLatestMessage, GetMessages, GetAttachment, Query | BakaShrotPushMessage, BakaShrotGetLatestMessage, ... |
|
||||
|
||||
The packets and DLL functions keep their names (`ListNames`,
|
||||
`GetMessages`, `BakaShrot_ResolveTopic()`...). Older sections below
|
||||
still say the old names where they tell what was done then.
|
||||
|
||||
## Done: tools wait for Enter when started from Explorer (2026-11-08)
|
||||
|
||||
- **Every tool** ends through `ToolConsole_End()` (`Tools/Common/ToolConsole.pbi`,
|
||||
included by `ToolClient.pbi`, and by BakaShrotGenerateKeyPairs directly): started directly
|
||||
(a double-click, a shortcut), it prints "Press Enter to close..." and
|
||||
waits, so what it printed (the usage, BakaShrotGenerateKeyPairs' keys) can be read before
|
||||
its console closes.
|
||||
- **Started directly** = alone on its console (`GetConsoleProcessList`, as
|
||||
[PB-Template-Win32-CliApp](https://github.com/aziascreations/PB-Template-Win32-CliApp)
|
||||
does it) **and** its input and output are a console: a redirected tool
|
||||
never waits, even alone on a new hidden console (the `--follow` test's
|
||||
`Start-Process -WindowStyle Hidden -RedirectStandardOutput`). Never
|
||||
waits outside of Windows.
|
||||
- **Checked:** from a shell, from Python's `subprocess`, hidden and
|
||||
redirected: no wait; `Start-Process` in a new window: waits. Every suite
|
||||
still passes; compiles with 5.73 and 6.40.
|
||||
|
||||
## Done: error codes, protocol 6 (2026-11-09)
|
||||
|
||||
- **Every failure has a code**, in `Client/BakaShrot_ErrorCodes.pbi`
|
||||
(shipped next to the prototypes, which include it), with what to do about
|
||||
each in its header:
|
||||
- 1-99, sent by the server with each refusal (`RequestRefused` got a
|
||||
`Code`, protocol 5 -> 6): NotAllowed, UnknownName, NotFound, NotReady,
|
||||
TooBig, NoDefaultTopic, InvalidRequest, DataMismatch, QueryFailed,
|
||||
ServerError. Each of the server's 64 refusals has one.
|
||||
- 100+, the client's own: NotConnected, ConnectFailed, AuthRejected,
|
||||
ServerNotVerified, ConnectionLost, ProtocolError, InvalidArgument,
|
||||
FileError, AttachmentMismatch, AlreadyConnected, Internal. The
|
||||
handshake (`Outbound.pbi`) tells where it failed: unreachable, closed
|
||||
by the server (wrong ServerPublicKey, key or node not allowed, another
|
||||
version), the server's signature wrong.
|
||||
- **DLL:** `BakaShrot_GetLastError()` after any call that can fail (0 when
|
||||
it succeeded); `BakaShrot_ErrorName()` names a code. Set where it
|
||||
happens (`BakaShrot_Fail()`), the lost connection, refusals and
|
||||
unexpected answers in one place each.
|
||||
- **Python:** `ErrorCode` (IntEnum, the same numbers), `error.code` on every
|
||||
exception; `RefusedError` (1-99), `ConnectionLostError` (not connected,
|
||||
unreachable, lost, protocol error: connect again), the new `AuthError`
|
||||
(rejected or unverified: fix the config). `latest()` tells "no message"
|
||||
by its code, not its text.
|
||||
- **Tools:** failures print the code's name, "Refused by the server
|
||||
(UnknownName): Unknown topic 'nope'", "Failed to connect and
|
||||
authenticate to host:port (AuthRejected): ..."; exit codes unchanged (1).
|
||||
`BakaShrotGetMessages --after latest` only starts from the start on
|
||||
NotFound, any other refusal is told.
|
||||
- **Nothing reconnects by itself**, decided: apps act on the codes. A push
|
||||
whose answer was lost may be stored twice if retried: at least once,
|
||||
accepted (11b).
|
||||
- **Tested:** the Python client's checks (UNKNOWN_NAME, NOT_FOUND,
|
||||
NOT_ALLOWED, QUERY_FAILED, INVALID_ARGUMENT, FILE_ERROR,
|
||||
ALREADY_CONNECTED, NOT_CONNECTED, CONNECT_FAILED, AUTH_REJECTED),
|
||||
`Names-Test.ps1` (the tools' code names), `Restart-Test.ps1` (a killed
|
||||
server gives the pushers CONNECTION_LOST).
|
||||
|
||||
## Done: restart catch-up tested (2026-11-09)
|
||||
|
||||
- **`Tests/Restart-Test.ps1`** (15 checks, ports 12415-12416, 26 s): two
|
||||
servers, a client node pushing on each through `Tests/restart_pusher.py`
|
||||
(as fast as answers come, logging every acknowledged id), servers killed
|
||||
with `Stop-Process -Force` (TerminateProcess, like a crash):
|
||||
1. B killed while both push, A goes on alone for 3 s, B restarted.
|
||||
2. B killed again partway through catching up (9,376 -> 10,806 of 22,064
|
||||
kitchen messages when killed), restarted.
|
||||
3. A killed while both push (the other direction), restarted.
|
||||
- **All hold:** every acknowledged push survived, ids 1..n without a gap
|
||||
on both servers, the last acknowledged message is the one pushed, the
|
||||
next push gets the next id, and both servers end with the same messages
|
||||
(counts, ids, data and pushed_at sums equal), each catching up on what
|
||||
the other got meanwhile. The logs show nothing but the links lost and
|
||||
retried while a server was down.
|
||||
- **Found:** a push committed but not answered before the kill (#26272
|
||||
stored, #26271 the last answered): a client retrying it stores it twice
|
||||
(open item 11b).
|
||||
- With `Synchronous = FULL`, the default; a killed process loses nothing
|
||||
committed with `NORMAL` either (only a power loss or an OS crash would).
|
||||
|
||||
## Done: browsing a topic from a database tool, schema v8 (2026-11-09)
|
||||
|
||||
- **A view can't take a parameter**, and SQLiteStudio has no dropdown for
|
||||
one. It does show a dropdown for a column with a foreign key (its
|
||||
`FkComboBox`, in the installed copy), so:
|
||||
- **`browse`**: one row (`id = 1`), `topic` referencing `topics(name)` and
|
||||
`node` referencing `nodes(name)` (NULL: every node). Set them from the
|
||||
dropdowns, commit, open **`browse_messages`**: that topic's messages,
|
||||
newest first, with `node`, `message_id`, `pushed_utc`, `message_data`,
|
||||
`is_json`, `attachment_size`. Index searches all the way (by name, then
|
||||
`(topic_id, pushed_at)`).
|
||||
- **The server never writes `browse`** nor turns foreign keys on, so the
|
||||
references never get in its way; a topic renamed in the config only
|
||||
leaves a stale name there. Made by `SetupStorageDatabase()`, so every
|
||||
database gets them at its next start (`db_schema_v8.dbml`).
|
||||
- **Writing to it while the server runs** is a short write next to the
|
||||
server's (it waits up to its 5 s busy timeout). A database tool left
|
||||
open on a table holds a read snapshot, which keeps checkpoints from
|
||||
finishing: the WAL grows until it's closed.
|
||||
- **Tested:** `Names-Test.ps1` sets it with Python's `sqlite3` (foreign
|
||||
keys on, like SQLiteStudio): a topic lists its messages, a node narrows
|
||||
them, a name that isn't a topic is refused. Not tested by hand in
|
||||
SQLiteStudio itself.
|
||||
|
||||
## Done: Synchronous, FULL by default (2026-11-09)
|
||||
|
||||
- **`[BakaShrot.Server] Synchronous`**: `FULL` (default, every commit
|
||||
flushed: an acknowledged push survives a power loss) or `NORMAL`
|
||||
(flushed at checkpoints, about every second: faster, but a power loss
|
||||
can lose the last second and hand its ids out again). `OFF` and `EXTRA`
|
||||
are refused, saying why. The server logs it ("ready (synchronous FULL)").
|
||||
- **Measured** (`Design/StorageConcurrency.md`): `FULL` halves the push
|
||||
ceiling here (17,200 msg/s for 4 servers instead of 33,900), a single
|
||||
sequential client gets ~1/flush pushes/s (1,300/s on this VM's 0.6 ms
|
||||
flush), and a steady load only gets ~0.7 ms more per push.
|
||||
- **The bench takes `-Synchronous`** (`FULL` by default, like the server),
|
||||
`-Synchronous NORMAL` to compare with the numbers from before.
|
||||
- **Before:** the release smoke test passed on the release built with
|
||||
protocol 5 and names-only configs, and the example ran from its
|
||||
extracted zip (2026-11-09). Not done: a run on a clean Windows.
|
||||
- **Tested:** `Names-Test.ps1` checks the C server starts with `NORMAL`
|
||||
and logs it, and that `OFF` is refused; every suite passes with the
|
||||
`FULL` default.
|
||||
|
||||
## Done: the server picks the ids, nodes come from their sections (2026-11-08)
|
||||
|
||||
- **`[BakaShrot.Topics]` is a list of names**, one per line. The server
|
||||
gives each its id: the one its database already has for the name, else
|
||||
the lowest free one (`AssignConfigId()`, `Config.pbi`), so the order
|
||||
doesn't matter and ids never move. `name = id` still pins one: every
|
||||
existing config works as it is (the tests and `Build.ps1` keep their
|
||||
pinned ids, they check the translation between servers).
|
||||
- **`[BakaShrot.Nodes]` is optional:** `[BakaShrot] Node`, every peer's and
|
||||
client's `Node` name their node by themselves (`DeclareConfigNode()`),
|
||||
before any node list is read. List only the others to know by name.
|
||||
- **The root reads the database's names before the config**
|
||||
(`BakaShrot_Names_ReadKnown()`, `Root.pbi`), from `DatabasePath` read
|
||||
ahead. `BakaShrot_Names_Load()` then reconciles as before.
|
||||
- **A peer's `AcceptNodes` defaults to `*`** (was: the named ones only):
|
||||
other servers' clients come as they come, under ids of this server's
|
||||
counting down from 65535. `AcceptNodes` still narrows it per peer.
|
||||
- **Found: the Preferences library misreads LF files** with keys without
|
||||
`=`: it takes the next line for the value, a section header too, losing
|
||||
that whole section. The config is now opened through a CRLF copy in the
|
||||
temporary folder when it has LF line endings (`OpenConfigPreferences()`),
|
||||
deleted once read.
|
||||
- **Tested:** `Names-Test.ps1` (55 checks): two servers with names-only
|
||||
topics and no nodes listed (C's in an LF file), ids in order, the nodes
|
||||
from the sections, D taking a node it never named, C restarted with its
|
||||
topics reordered and a new one: same ids. Every suite and the push bench
|
||||
(35,600 msg/s) pass; compiles with 5.73 and 6.40. The example's
|
||||
`server.ini` lists names only.
|
||||
|
||||
## Done: protocol 5, a client's node and default topic apart (2026-11-08)
|
||||
|
||||
- **Client sections** (`[BakaShrot.Client.<name>]`): `Node` (required, the
|
||||
node that key writes as) and `DefaultTopic` (optional, where its pushes
|
||||
go when they don't name a topic) instead of `Identities = Topic:Node;...`.
|
||||
`PushTopics` / `ReadTopics` default to `DefaultTopic`, nothing without
|
||||
one. A key that writes as several nodes is in a section per node.
|
||||
- **Why the node:** every push is stored under the authenticated node, so
|
||||
the server decides which node each key writes as. The topic was only
|
||||
ever the default one, and mixing the two made it look like more.
|
||||
- **The Hello carries the node only** (protocol 4 -> 5): `client.ini`,
|
||||
the DLL (`BakaShrot_SetTopic*()` removed), the tools and Python
|
||||
(`Client(...)` lost its `topic` argument) have no topic any more. A push
|
||||
without one and no `DefaultTopic` is refused ("No default topic for this
|
||||
client").
|
||||
- **Servers too:** `[BakaShrot] Topic` and peers' `Topic` aren't read any
|
||||
more (ignored if left), a server links to its peers by node only.
|
||||
- **Old configs:** `Identities` makes the server refuse to start, saying
|
||||
what to write (`Node = garage and DefaultTopic = logs instead of
|
||||
Identities = logs:garage`).
|
||||
- **Tested:** `Names-Test.ps1` (now 49 checks): no `DefaultTopic` means a
|
||||
push must name its topic, a key can't write as another section's node
|
||||
(and the log says why), the old `Identities` refused. Every suite and
|
||||
the push bench (36,400 msg/s, no failures) pass; compiles with 5.73 and
|
||||
6.40.
|
||||
|
||||
## Done: examples, one server and one client (2026-11-08)
|
||||
|
||||
- **`Examples/`**, one folder per setup with its README, indexed in
|
||||
`Examples/README.md`. The first, `Examples/SingleServer/`: one server on
|
||||
127.0.0.1:12360, one client (`logs:demo`, may push to logs and sensors,
|
||||
read all, query), retention on sensors.
|
||||
- **Its configs are committed, keys included** (a fixed key pair each,
|
||||
marked as public and example-only in the files and the README). Every
|
||||
other config with keys stays out of git.
|
||||
- **`Start-Server.ps1`** opens the server in its own window and waits until
|
||||
it listens (`-Here` in the current console, `-Reset` deletes its
|
||||
database). **`Run-Client.ps1`** pushes (to its topic, another topic, with
|
||||
an attachment), reads back (latest, every message with `--time`, the
|
||||
attachment, checked), resolves and lists names, runs a SQL query; it
|
||||
prints each command, pasteable from the example's folder. Both take
|
||||
`-BinDir`, `Build\` by default.
|
||||
- **Git ignores** what they write: `Examples/**/*.sqlite*`, `Examples/**/out/`.
|
||||
- **Checked:** both scripts, twice in a row (the ids go on), the
|
||||
double-start guard, the README's Python snippet. `Start-Server.ps1 -Here`
|
||||
wasn't (it needs an interactive console).
|
||||
|
||||
## Threat model (2026-11-08)
|
||||
|
||||
BakaShrot is an **internal tool, on trusted machines and a trusted
|
||||
@@ -420,11 +669,12 @@ network**, not exposed to the internet. So:
|
||||
no clean stop from a script (tests force-kill it). Fix: a stop file like
|
||||
`BenchServer.exe`'s, and/or a local admin connection, then a way to run
|
||||
it as a service. (`Design/Release.md` smoke test #4)
|
||||
2. **The 1.0.0 smoke test isn't done:** a run from the extracted zip on a
|
||||
clean Windows (the shipped runtime has never been checked there),
|
||||
replication between two release servers, restart catch-up (designed to
|
||||
work, never tested: kill a server, check ids continue and peers catch
|
||||
up). (`Design/Release.md`, items 1-3)
|
||||
2. **The 1.0.0 smoke test, what's left:** replication between two servers
|
||||
built by `Release.ps1` (the suites use `BenchServer.exe`, the same server
|
||||
code). Done: the release's own smoke test and the example from its zip
|
||||
(2026-11-09), restart catch-up (`Restart-Test.ps1`, 2026-11-09). The run
|
||||
on a clean Windows is the owner's, as needed: not an open item here.
|
||||
(`Design/Release.md`, items 1-3)
|
||||
3. **A corrupted stored attachment is re-sent to peers forever.** Found
|
||||
by `Tests/AttachmentEdges-Test.ps1` part 4 (a byte flipped in the
|
||||
sender's `blob_chunks`, `flip.py`).
|
||||
@@ -447,31 +697,31 @@ network**, not exposed to the internet. So:
|
||||
its own peers for a good copy (`MissingAttachments`), and stops
|
||||
serving it. Log it loudly. If its copy is fine (the damage was in
|
||||
transit), sending again is right.
|
||||
- Better than matching the refusal's text: a distinct answer for "the
|
||||
data doesn't match", e.g. a `ChunkStored` with `Complete = 0` and
|
||||
`Received = 0` after the last part, or a new field.
|
||||
- The refusal now has its own code (DataMismatch, protocol 6): match
|
||||
that rather than the text.
|
||||
- The origin (where it was pushed) has no other source: its attachment
|
||||
then stays missing ("isn't here yet"), better than serving bad data;
|
||||
maybe a "lost" state (4) so `GetAttachment` says so.
|
||||
maybe a "lost" state (4) so `BakaShrotGetAttachment` says so.
|
||||
- Optional, to catch it on reads too: a SHA-256 per part in
|
||||
`blob_chunks`, checked by `ReadStorageBlobChunk()`, at ~3 s/GB.
|
||||
- Test: part 4 of `AttachmentEdges-Test.ps1` then expects the sender to
|
||||
log its copy as damaged and the re-sends to stop (today it only prints
|
||||
an INFO line with the count); its own `attachments` row goes to 0.
|
||||
4. **`synchronous = NORMAL`:** the last commits can be lost on a power loss
|
||||
or OS crash (not on a killed process). Decide, or switch to `FULL`.
|
||||
(`Design/StorageConcurrency.md`)
|
||||
5. **Drift between servers** when one topic/node pair is written to on two
|
||||
servers: only partially resynced. Accepted while each pair has a single
|
||||
writer; document that as the rule. (`Design/ReplicationIssues.md` #1)
|
||||
4. ~~**`synchronous = NORMAL`**~~: done, `[BakaShrot.Server] Synchronous`,
|
||||
`FULL` by default (see "Done: Synchronous" above).
|
||||
5. ~~**Drift between servers**~~: ruled out by config, a node pushes to
|
||||
one server (written in `schema.ini` and `Design/ReplicationIssues.md`
|
||||
#1). Not an open item: nothing to do unless that rule has to go.
|
||||
6. **Gaps in a pair's ids aren't detected** on replication.
|
||||
(`Design/ReplicationIssues.md` #5)
|
||||
7. **No single test runner**, and fixed ports (12399, 12401-12414): every
|
||||
7. **No single test runner**, and fixed ports (12399, 12401-12416): every
|
||||
`Tests/*.ps1` and the two `.pb` tests are run by hand. Needed for CI.
|
||||
(`Design/Release.md`, "For CI/CD")
|
||||
8. **Is `DatabaseError()` per thread?** Messages could land in the wrong
|
||||
thread's log or refusal; Windows queries no longer depend on it.
|
||||
(`Design/StorageConcurrency.md`)
|
||||
8. ~~**Is `DatabaseError()` per thread?**~~ Yes, checked (2026-11-09):
|
||||
two threads failing on their own connections 20,000 times each, never
|
||||
once the other's message, with 5.73 and 6.40 (`/THREAD`).
|
||||
`sqlite3_errmsg16()` on the connection gives the same messages, kept as
|
||||
is. Linux untested (item 18).
|
||||
9. **Limits:** the sync state must fit in one packet (65536 topic/node
|
||||
pairs); `ReplicatingTopicIds` ranges are expanded to every id they cover.
|
||||
(`Design/ReplicationIssues.md` #7)
|
||||
@@ -479,13 +729,19 @@ network**, not exposed to the internet. So:
|
||||
### Client side
|
||||
|
||||
10. **One connection per process** (the DLL's globals): a handle-based API
|
||||
for several. No reconnect in `GetMessages --follow` / `follow()`, polling
|
||||
rather than server-pushed subscriptions.
|
||||
11. **Breaking with protocols 3 and 4:** every client config needs
|
||||
`ServerPublicKey`; older clients and servers can't connect (any
|
||||
version difference refuses the connection). Fine while it's all
|
||||
built from this repo, worth a line in the release notes of the first
|
||||
real release.
|
||||
for several. Polling rather than server-pushed subscriptions. Nothing
|
||||
reconnects by itself, on purpose: the error codes tell the app when to
|
||||
(see "Done: error codes" above).
|
||||
11. ~~**Breaking with protocols 3 to 6**~~: in the release notes now
|
||||
(`VERSION.txt`, "Compatibility", written by `Release.ps1`): servers and
|
||||
clients from the same release only, what old configs need.
|
||||
11b. ~~**A push whose answer was lost can be stored twice if retried.**~~
|
||||
Accepted, the way it is: delivery is at least once. A server killed
|
||||
between committing a push and answering it keeps it (`Restart-Test.ps1`
|
||||
saw #26272 stored, #26271 the last answered), the client gets
|
||||
ConnectionLost; pushing it again stores it twice. Documented in
|
||||
`BakaShrot_ErrorCodes.pbi`, the DLL's header and `bakashrot.py`; a
|
||||
client that minds checks the latest message before retrying.
|
||||
|
||||
### Security, low priority under the threat model
|
||||
|
||||
@@ -525,6 +781,17 @@ network**, not exposed to the internet. So:
|
||||
server, skipping on arrival what's past its age (2026-11-08).
|
||||
- Attachments, protocol 4: one per message, in 1 MB parts, replicated after
|
||||
their message, resumable; edge cases tested (2026-11-08).
|
||||
- Tools renamed `BakaShrot<Name>`, waiting for Enter when started from
|
||||
Explorer; `Examples/SingleServer/` (2026-11-08).
|
||||
- Protocol 5: a client is a node, its default topic the server's
|
||||
(`Node`, `DefaultTopic`); names-only topics, ids picked by the server,
|
||||
nodes from their sections, `AcceptNodes = *` (2026-11-08).
|
||||
- `Synchronous`, `FULL` by default, measured (2026-11-09).
|
||||
- Schema v8: `browse` / `browse_messages` for database tools (2026-11-09).
|
||||
- Restart catch-up tested: kills mid-traffic and mid-catch-up, nothing
|
||||
acknowledged lost (`Restart-Test.ps1`, 2026-11-09).
|
||||
- Protocol 6: error codes everywhere, at-least-once delivery accepted
|
||||
(2026-11-09).
|
||||
|
||||
## To check against Review.md
|
||||
|
||||
@@ -556,6 +823,12 @@ network**, not exposed to the internet. So:
|
||||
- **Things only a raw client can do** (a wrong SHA-256, abandoned uploads):
|
||||
`Tests/AttachmentEdgeClient.pb`, over `Commons/Networking/Outbound.pbi`.
|
||||
Copy its `Exchange()` / `Refusal()` helpers for new protocol tests.
|
||||
- **Log scans in the tests skip "Refused a request" lines:** refusals are
|
||||
expected, and their codes' names (`InvalidRequest`, `QueryFailed`) hold
|
||||
the words the scans look for. PowerShell's `-match` ignores case.
|
||||
- **Traffic while a server is killed:** `Tests/restart_pusher.py` pushes as
|
||||
fast as answers come and logs every acknowledged id, then the error's
|
||||
code; `Restart-Test.ps1` shows how to read it back.
|
||||
- **Corrupting or seeding a database** from a test: Python's `sqlite3`,
|
||||
with the server stopped through its stop file (its WAL is checkpointed
|
||||
then), see `Retention-Test.ps1` (an old schema) and
|
||||
|
||||
+60
-36
@@ -5,9 +5,12 @@
|
||||
# Release\<version>\, ready to copy to a server or hand to a client:
|
||||
# BakaShrot_Server.exe the server
|
||||
# BakaShrot_Client.dll the client DLL, with
|
||||
# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes
|
||||
# PushMessage.exe, GetLatestMessage.exe, GetMessages.exe, GetAttachment.exe,
|
||||
# Query.exe, Resolve.exe, ListNames.exe, KeyGen.exe the tools
|
||||
# BakaShrot_Client_Prototypes.pbi its PureBasic prototypes, and
|
||||
# BakaShrot_ErrorCodes.pbi the error codes they include
|
||||
# BakaShrotPushMessage.exe, BakaShrotGetLatestMessage.exe,
|
||||
# BakaShrotGetMessages.exe, BakaShrotGetAttachment.exe, BakaShrotQuery.exe,
|
||||
# BakaShrotResolveIds.exe, BakaShrotList.exe,
|
||||
# BakaShrotGenerateKeyPairs.exe the tools
|
||||
# libsodium.dll, sqlite3.dll what they need next to them
|
||||
# vcruntime140.dll what libsodium.dll needs (Libs\redist)
|
||||
# python\bakashrot.py, example.py the Python client, over the DLL
|
||||
@@ -15,7 +18,7 @@
|
||||
# VERSION.txt commit, date, compiler, libraries
|
||||
# and Release\BakaShrot-<version>.zip of it, unless -NoZip.
|
||||
#
|
||||
# No keys and no configs with keys in it: generate them with KeyGen.exe.
|
||||
# No keys and no configs with keys in it: generate them with BakaShrotGenerateKeyPairs.exe.
|
||||
#
|
||||
# Then checks the build works, unless -SkipTest: generates keys, runs the
|
||||
# server from the release folder on a spare port with a throwaway database,
|
||||
@@ -112,14 +115,14 @@ if (-not $NoOptimizer) { $Common += "/OPTIMIZER" }
|
||||
$Targets = @(
|
||||
@("Server\BakaShrot_Server.pb", "BakaShrot_Server.exe", @("/CONSOLE", "/THREAD")),
|
||||
@("Client\BakaShrot_Client.pbi", "BakaShrot_Client.dll", @("/DLL", "/THREAD")),
|
||||
@("Tools\PushMessage\PushMessage.pb", "PushMessage.exe", @("/CONSOLE")),
|
||||
@("Tools\GetLatestMessage\GetLatestMessage.pb", "GetLatestMessage.exe", @("/CONSOLE")),
|
||||
@("Tools\GetMessages\GetMessages.pb", "GetMessages.exe", @("/CONSOLE")),
|
||||
@("Tools\GetAttachment\GetAttachment.pb", "GetAttachment.exe", @("/CONSOLE")),
|
||||
@("Tools\Query\Query.pb", "Query.exe", @("/CONSOLE")),
|
||||
@("Tools\Resolve\Resolve.pb", "Resolve.exe", @("/CONSOLE")),
|
||||
@("Tools\ListNames\ListNames.pb", "ListNames.exe", @("/CONSOLE")),
|
||||
@("Tools\KeyGen\KeyGen.pb", "KeyGen.exe", @("/CONSOLE"))
|
||||
@("Tools\BakaShrotPushMessage\BakaShrotPushMessage.pb", "BakaShrotPushMessage.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotGetLatestMessage\BakaShrotGetLatestMessage.pb", "BakaShrotGetLatestMessage.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotGetMessages\BakaShrotGetMessages.pb", "BakaShrotGetMessages.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotGetAttachment\BakaShrotGetAttachment.pb", "BakaShrotGetAttachment.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotQuery\BakaShrotQuery.pb", "BakaShrotQuery.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotResolveIds\BakaShrotResolveIds.pb", "BakaShrotResolveIds.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotList\BakaShrotList.pb", "BakaShrotList.exe", @("/CONSOLE")),
|
||||
@("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE"))
|
||||
)
|
||||
|
||||
Push-Location $Root
|
||||
@@ -142,6 +145,7 @@ Copy-Item $Sodium $OutDir
|
||||
foreach ($File in $Redist) { Copy-Item $File.FullName $OutDir }
|
||||
Copy-Item $SqliteDll (Join-Path $OutDir "sqlite3.dll")
|
||||
Copy-Item (Join-Path $Root "Client\BakaShrot_Client_Prototypes.pbi") $OutDir
|
||||
Copy-Item (Join-Path $Root "Client\BakaShrot_ErrorCodes.pbi") $OutDir
|
||||
New-Item -ItemType Directory -Force (Join-Path $OutDir "python") | Out-Null
|
||||
foreach ($File in @("bakashrot.py", "example.py")) {
|
||||
Copy-Item (Join-Path $Root "Interactors\Python\$File") (Join-Path $OutDir "python")
|
||||
@@ -160,8 +164,8 @@ VC++ runtime: $RedistVersion (vcruntime140.dll, for libsodium.dll)
|
||||
Needs Windows 10 or later, 64-bit. Keep the DLLs next to the exes.
|
||||
|
||||
Run the server: BakaShrot_Server.exe config.ini
|
||||
Its config: config.example.ini. Keys: KeyGen.exe, the private key goes in
|
||||
[BakaShrot] PrivateKey, the public key in the configs that trust it, and
|
||||
Its config: config.example.ini. Keys: BakaShrotGenerateKeyPairs.exe, the
|
||||
private key goes in [BakaShrot] PrivateKey, the public key in the configs that trust it, and
|
||||
in its clients' client.ini as ServerPublicKey (it logs it when it starts).
|
||||
Every connection is encrypted, and only reaches the server holding the
|
||||
private key of the ServerPublicKey (or peer PublicKey) it was given.
|
||||
@@ -169,19 +173,40 @@ Run the server: BakaShrot_Server.exe config.ini
|
||||
needs one: it stops right away without console input.
|
||||
Topics and nodes go by name ([BakaShrot.Topics], [BakaShrot.Nodes]) or id,
|
||||
each server has its own ids for the same names.
|
||||
[BakaShrot.Server] Synchronous = FULL (default) flushes every push to disk
|
||||
before answering it; NORMAL is faster but a power loss can lose the last
|
||||
second of messages. See config.example.ini.
|
||||
Tools, next to BakaShrot_Client.dll, with a client.ini:
|
||||
PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||
GetLatestMessage <Topic> <Node> [ClientIni]
|
||||
GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--time] [ClientIni]
|
||||
GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||
Resolve <topic|node> <NameOrId> [ClientIni]
|
||||
ListNames [topics|nodes|all] [ClientIni] [--json]
|
||||
Query <Sql|@SqlFile> [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs'
|
||||
client.ini: [BakaShrot] PrivateKey, PublicKey, Topic, Node (names or
|
||||
ids), ServerHost, ServerPort, ServerPublicKey.
|
||||
BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||
BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]
|
||||
BakaShrotGetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--time] [ClientIni]
|
||||
BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||
BakaShrotResolveIds <topic|node> <NameOrId> [ClientIni]
|
||||
BakaShrotList [topics|nodes|all] [ClientIni] [--json]
|
||||
BakaShrotQuery <Sql|@SqlFile> [ClientIni] e.g. SELECT * FROM messages WHERE topic = 'logs'
|
||||
client.ini: [BakaShrot] PrivateKey, PublicKey, Node (the node it writes
|
||||
as, a name or an id), ServerHost, ServerPort, ServerPublicKey. Where its
|
||||
pushes go by default is the server's DefaultTopic for it.
|
||||
Python (3.8+, 64-bit): python\bakashrot.py, no dependencies, uses
|
||||
BakaShrot_Client.dll (set BAKASHROT_DLL, or pass dll_path). See its
|
||||
docstring, and python\example.py <ClientIni> <Topic> <Node>.
|
||||
Compatibility: protocol 6. Servers and clients (the DLL, the tools, the
|
||||
Python client) must come from the same release: any other version
|
||||
refuses the connection, there's no mixing. From an older release:
|
||||
- server configs: [BakaShrot.Client.<name>] Identities = topic:node is
|
||||
refused at start, write Node = node and DefaultTopic = topic (the
|
||||
server's message says which); [BakaShrot] and peer sections' Topic is
|
||||
ignored; [BakaShrot.Topics] can be names alone, [BakaShrot.Nodes] can
|
||||
go; Synchronous = FULL is the default now (NORMAL was);
|
||||
- client.ini: Topic is ignored, ServerPublicKey is required;
|
||||
- apps: BakaShrot_ErrorCodes.pbi next to the prototypes, SetTopic() is
|
||||
gone, and a database made before is upgraded in place at the first
|
||||
start (keep a copy).
|
||||
Errors: every failure has a code, BakaShrot_GetLastError() in the DLL,
|
||||
error.code in Python (bakashrot.ErrorCode), the name in the tools'
|
||||
messages. BakaShrot_ErrorCodes.pbi lists them, and what to do about each.
|
||||
Nothing reconnects by itself. A push whose answer was lost may have been
|
||||
stored: pushed again, it's stored twice (at least once delivery).
|
||||
"@
|
||||
Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encoding UTF8
|
||||
|
||||
@@ -189,8 +214,8 @@ Set-Content -Path (Join-Path $OutDir "VERSION.txt") -Value $VersionText -Encodin
|
||||
# --- Test -------------------------------------------------------------------
|
||||
|
||||
function New-KeyPair {
|
||||
$Lines = & (Join-Path $OutDir "KeyGen.exe")
|
||||
if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" }
|
||||
$Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe")
|
||||
if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" }
|
||||
return @{
|
||||
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
|
||||
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
|
||||
@@ -229,7 +254,6 @@ if (-not $SkipTest) {
|
||||
Set-Content -Path (Join-Path $TestDir "server.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($ServerKeys.PrivateKey)
|
||||
Topic = releasetest
|
||||
Node = server
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -247,7 +271,8 @@ DatabasePath = $(Join-Path $TestDir "test.sqlite")
|
||||
|
||||
[BakaShrot.Client.test]
|
||||
PublicKeys = $($ClientKeys.PublicKey)
|
||||
Identities = releasetest:tester
|
||||
Node = tester
|
||||
DefaultTopic = releasetest
|
||||
AllowRead = 1
|
||||
AllowWrite = 1
|
||||
AllowQuery = 1
|
||||
@@ -256,7 +281,6 @@ AllowQuery = 1
|
||||
[BakaShrot]
|
||||
PrivateKey = $($ClientKeys.PrivateKey)
|
||||
PublicKey = $($ClientKeys.PublicKey)
|
||||
Topic = releasetest
|
||||
Node = tester
|
||||
ServerHost = 127.0.0.1
|
||||
ServerPort = $TestPort
|
||||
@@ -276,26 +300,26 @@ ServerPublicKey = $($ServerKeys.PublicKey)
|
||||
}
|
||||
|
||||
$ClientIni = Join-Path $TestDir "client.ini"
|
||||
$Pushed = Invoke-Tool "PushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||
$Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||
if ($Pushed -notmatch "message #1") { throw "Unexpected push answer: $Pushed" }
|
||||
|
||||
$Latest = Invoke-Tool "GetLatestMessage.exe" @("releasetest", "tester", $ClientIni)
|
||||
$Latest = Invoke-Tool "BakaShrotGetLatestMessage.exe" @("releasetest", "tester", $ClientIni)
|
||||
if ($Latest -notmatch '"release"\s*:\s*"test"' -or $Latest -notmatch '\(ids 7:2\)') { throw "Unexpected latest message: $Latest" }
|
||||
|
||||
$Pushed = Invoke-Tool "PushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||
$Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||
if ($Pushed -notmatch "message #2") { throw "Unexpected second push answer: $Pushed" }
|
||||
# message.json ends with a line break, kept in the data: one empty line after each.
|
||||
$Messages = @(& (Join-Path $OutDir "GetMessages.exe") "releasetest" "tester" $ClientIni | Where-Object { $_ -ne "" })
|
||||
$Messages = @(& (Join-Path $OutDir "BakaShrotGetMessages.exe") "releasetest" "tester" $ClientIni | Where-Object { $_ -ne "" })
|
||||
if ($LASTEXITCODE -ne 0 -or $Messages.Count -ne 2 -or $Messages[0] -notmatch '^1\t\{"release"' -or $Messages[1] -notmatch '^2\t') {
|
||||
throw "Unexpected messages: $($Messages -join ' | ')"
|
||||
}
|
||||
|
||||
$Resolved = Invoke-Tool "Resolve.exe" @("topic", "releasetest", $ClientIni)
|
||||
$Resolved = Invoke-Tool "BakaShrotResolveIds.exe" @("topic", "releasetest", $ClientIni)
|
||||
if ($Resolved -notmatch "topic releasetest = 7") { throw "Unexpected resolved topic: $Resolved" }
|
||||
|
||||
$Sql = Join-Path $TestDir "query.sql"
|
||||
Set-Content -Path $Sql -Encoding Ascii -Value "SELECT message_data ->> '$.value', is_json, topic_id FROM messages WHERE topic = 'releasetest' AND node = 'tester' AND is_json = 1"
|
||||
$Queried = Invoke-Tool "Query.exe" @("@$Sql", $ClientIni)
|
||||
$Queried = Invoke-Tool "BakaShrotQuery.exe" @("@$Sql", $ClientIni)
|
||||
if ($Queried -notmatch '\[\["42","1","7"\],\["42","1","7"\]\]') { throw "Unexpected query result: $Queried" }
|
||||
|
||||
Write-Host " Pushed, read back by name, resolved and queried messages: OK"
|
||||
@@ -318,11 +342,11 @@ ServerPublicKey = $($ServerKeys.PublicKey)
|
||||
$Bytes = New-Object byte[] (3 * 1024 * 1024 + 17)
|
||||
(New-Object System.Random 5).NextBytes($Bytes)
|
||||
[IO.File]::WriteAllBytes($Attach, $Bytes)
|
||||
$Pushed = Invoke-Tool "PushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||
$Pushed = Invoke-Tool "BakaShrotPushMessage.exe" @("-a", $Attach, "@$(Join-Path $TestDir 'message.json')", $ClientIni)
|
||||
if ($Pushed -notmatch "message #(\d+), with an attachment of 3145745 bytes") { throw "Unexpected push with an attachment: $Pushed" }
|
||||
$AttachedId = $Matches[1]
|
||||
$Copy = Join-Path $TestDir "attach-copy.bin"
|
||||
$Saved = Invoke-Tool "GetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni)
|
||||
$Saved = Invoke-Tool "BakaShrotGetAttachment.exe" @("releasetest", "tester", $AttachedId, $Copy, $ClientIni)
|
||||
if ($Saved -notmatch "Saved 3145745 bytes" -or (Get-FileHash $Attach).Hash -ne (Get-FileHash $Copy).Hash) { throw "Unexpected attachment read back: $Saved" }
|
||||
Write-Host " Pushed and read back an attachment: OK"
|
||||
}
|
||||
|
||||
+335
-167
@@ -7,8 +7,11 @@
|
||||
; Section layout:
|
||||
; [BakaShrot] -> BakaShrot_CoreConfig
|
||||
; [BakaShrot.Server] -> BakaShrot_CoreConfig\Server
|
||||
; [BakaShrot.Topics] -> topic names, "name = id" lines
|
||||
; [BakaShrot.Nodes] -> node names, "name = id" lines
|
||||
; [BakaShrot.Topics] -> topic names, one per line, this server
|
||||
; gives them their ids ("name = id" pins one)
|
||||
; [BakaShrot.Nodes] -> node names, the same, optional: the nodes of
|
||||
; [BakaShrot], the peers and the clients are
|
||||
; named by their sections
|
||||
; [BakaShrot.Retention] -> how long each topic's messages are kept
|
||||
; here, "topic = max age" lines, see
|
||||
; BakaShrot_RetentionRule
|
||||
@@ -44,7 +47,7 @@ Structure BakaShrot_NameSet
|
||||
; Every one, named or not, known or not ("*").
|
||||
All.i
|
||||
|
||||
; Every one that has a name on this server: the default of AcceptNodes.
|
||||
; Every one that has a name on this server.
|
||||
Known.i
|
||||
|
||||
; Str(Id) -> #True, from ids, ranges and names in the list.
|
||||
@@ -61,7 +64,7 @@ EndStructure
|
||||
; The peer must register this server in one of its [BakaShrot.Client.<name>].
|
||||
; PublicKey is the peer's: a link to it only goes through if the peer
|
||||
; proves it holds the matching private key (Commons/Networking/Connections.pbi).
|
||||
; Topic and Node are only checked when the peer links to here.
|
||||
; Node is only checked when the peer links to here.
|
||||
Structure BakaShrot_PeerConfig
|
||||
|
||||
; Remote address of the peer
|
||||
@@ -72,9 +75,8 @@ Structure BakaShrot_PeerConfig
|
||||
; 0-65535
|
||||
Port.u
|
||||
|
||||
; Topic, Node: the remote node's topic and node, refs, resolved to this
|
||||
; server's ids. The peer authenticates with them when it links to here.
|
||||
TopicId.u
|
||||
; Node: the remote server's node, a ref resolved to this server's id.
|
||||
; The peer authenticates as it when it links to here.
|
||||
NodeId.u
|
||||
|
||||
; This peer's Ed25519 public key (Base64): the Hello of a link to it is
|
||||
@@ -90,7 +92,8 @@ Structure BakaShrot_PeerConfig
|
||||
|
||||
; SendNodes: the nodes whose messages this server sends to the peer.
|
||||
; Default: every one (*). AcceptNodes: the nodes whose messages it takes
|
||||
; from the peer. Default: every one named here, no other.
|
||||
; from the peer. Default: every one (*), the ones it doesn't name yet
|
||||
; are added as they come (Server/Storage/Names.pbi).
|
||||
SendNodes.BakaShrot_NameSet
|
||||
AcceptNodes.BakaShrot_NameSet
|
||||
|
||||
@@ -99,19 +102,11 @@ Structure BakaShrot_PeerConfig
|
||||
AcceptTopicsText.s
|
||||
SendNodesText.s
|
||||
AcceptNodesText.s
|
||||
TopicText.s
|
||||
NodeText.s
|
||||
|
||||
EndStructure
|
||||
|
||||
|
||||
; One "Topic:Node" entry of BakaShrot_ClientConfig\Identities().
|
||||
Structure BakaShrot_ClientIdentity
|
||||
TopicId.u
|
||||
NodeId.u
|
||||
EndStructure
|
||||
|
||||
|
||||
; What a client is allowed to do once authenticated.
|
||||
; Ini keys of [BakaShrot.Client.<name>], 1 to allow, 0 to deny.
|
||||
Structure BakaShrot_ClientPermissions
|
||||
@@ -140,22 +135,27 @@ Structure BakaShrot_ClientConfig
|
||||
; Format: Key;Key;...
|
||||
List PublicKeys.s()
|
||||
|
||||
; Topic and node pairs the client is allowed to authenticate as, once it
|
||||
; has authenticated with one of its PublicKeys.
|
||||
; Format: Topic:Node;Topic:Node;... each a name or an id.
|
||||
List Identities.BakaShrot_ClientIdentity()
|
||||
; Node: the node it writes as, a ref, required. It sends it in its
|
||||
; Hello, which must come with one of PublicKeys. A key listed in several
|
||||
; sections may write as each of their nodes.
|
||||
NodeId.u
|
||||
|
||||
; DefaultTopic: the topic of its pushes that don't name one, a ref, -1
|
||||
; without one (they're refused then).
|
||||
DefaultTopicId.l
|
||||
|
||||
; AllowRead, AllowWrite, AllowQuery
|
||||
Permissions.BakaShrot_ClientPermissions
|
||||
|
||||
; PushTopics: the topics it may push to, under its own node.
|
||||
; ReadTopics: the topics it may read the latest messages of.
|
||||
; Both default to the topics of its Identities.
|
||||
; Both default to its DefaultTopic, nothing without one.
|
||||
PushTopics.BakaShrot_NameSet
|
||||
ReadTopics.BakaShrot_NameSet
|
||||
|
||||
; As written in the ini, for SaveConfig(). Chr(1) when missing.
|
||||
IdentitiesText.s
|
||||
NodeText.s
|
||||
DefaultTopicText.s
|
||||
PushTopicsText.s
|
||||
ReadTopicsText.s
|
||||
|
||||
@@ -240,6 +240,10 @@ Structure BakaShrot_ServerConfig
|
||||
; that it's deleted. Default 3600.
|
||||
UploadTimeout.i
|
||||
|
||||
; PRAGMA synchronous, FULL (default) or NORMAL, see
|
||||
; BakaShrot_Storage_Synchronous in Server/Storage/Storage.pbi.
|
||||
Synchronous.s
|
||||
|
||||
EndStructure
|
||||
|
||||
|
||||
@@ -252,18 +256,17 @@ Structure BakaShrot_CoreConfig
|
||||
; own config. See Commons/Cryptography/Libsodium.pbi.
|
||||
PrivateKey.s
|
||||
|
||||
; Topic, Node: the topic and node this server authenticates as when it
|
||||
; links to its peers, refs. Peers must know them by the same names.
|
||||
TopicId.u
|
||||
; Node: the node this server authenticates as when it links to its
|
||||
; peers, a ref. Peers must know it by the same name.
|
||||
NodeId.u
|
||||
TopicText.s
|
||||
NodeText.s
|
||||
|
||||
; [BakaShrot.Server]
|
||||
Server.BakaShrot_ServerConfig
|
||||
|
||||
; [BakaShrot.Topics] and [BakaShrot.Nodes]:
|
||||
; LCase(name) -> id, and Str(id) -> name as written.
|
||||
; [BakaShrot.Topics] and [BakaShrot.Nodes], plus the nodes the other
|
||||
; sections define: LCase(name) -> id, and Str(id) -> name as written.
|
||||
; Ids pinned in the config, or given by LoadConfig() (AssignConfigId()).
|
||||
Map TopicIds.i()
|
||||
Map TopicNames.s()
|
||||
Map NodeIds.i()
|
||||
@@ -297,18 +300,34 @@ Macro Ptr_BakaShrot_CoreConfig : i : EndMacro
|
||||
#BakaShrot_Config_DefaultRetentionInterval = 60
|
||||
#BakaShrot_Config_DefaultMaxAttachmentSize = "1G"
|
||||
#BakaShrot_Config_DefaultUploadTimeout = 3600
|
||||
#BakaShrot_Config_DefaultSynchronous = "FULL"
|
||||
|
||||
; What ReadPreferenceString() returns for a missing key, to tell it from an
|
||||
; empty one: an empty PushTopics allows nothing, a missing one the default.
|
||||
#BakaShrot_Config_Missing = Chr(1)
|
||||
|
||||
|
||||
; What the database already has (BakaShrot_Names_ReadKnown(), Storage/
|
||||
; Names.pbi), for LoadConfig() to give a name listed without an id the id
|
||||
; it already has: LCase(name) -> id, and Str(id) -> #True for every id it
|
||||
; has a row or messages for, named or not.
|
||||
Structure BakaShrot_KnownNames
|
||||
Map TopicIds.i()
|
||||
Map TopicUsed.i()
|
||||
Map NodeIds.i()
|
||||
Map NodeUsed.i()
|
||||
EndStructure
|
||||
|
||||
; The one LoadConfig() was given, while it runs.
|
||||
Global *BakaShrot_ConfigKnown.BakaShrot_KnownNames
|
||||
|
||||
|
||||
; Why the last LoadConfig() failed.
|
||||
Global BakaShrot_ConfigError.s = ""
|
||||
|
||||
|
||||
; Reads Key, or OldKey if Key is missing: Topic, Node and ReplicatingTopics
|
||||
; were TopicId, NodeId and ReplicatingTopicIds before they took names, and
|
||||
; Reads Key, or OldKey if Key is missing: Node and ReplicatingTopics were
|
||||
; NodeId and ReplicatingTopicIds before they took names, and
|
||||
; configs written then still work.
|
||||
Procedure.s ReadConfigKey(Key.s, OldKey.s, DefaultValue.s)
|
||||
Protected Value.s = ReadPreferenceString(Key, #BakaShrot_Config_Missing)
|
||||
@@ -389,6 +408,50 @@ Procedure.i ResolveConfigNode(*Config.BakaShrot_CoreConfig, Ref.s)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Gives Name an id in Ids() / Names(): the one the database already has for
|
||||
; it (KnownIds()), unless another of the config's names has it, else the
|
||||
; lowest free one, used neither by the config nor by the database
|
||||
; (KnownUsed()). Names a peer adds get theirs counting down from 65535.
|
||||
; Returns the id, -1 if none is left.
|
||||
Procedure.i AssignConfigId(Name.s, Map Ids.i(), Map Names.s(), Map KnownIds.i(), Map KnownUsed.i())
|
||||
Protected Id.i = -1
|
||||
|
||||
If FindMapElement(KnownIds(), LCase(Name))
|
||||
Id = KnownIds()
|
||||
If FindMapElement(Names(), Str(Id))
|
||||
Id = -1
|
||||
EndIf
|
||||
EndIf
|
||||
If Id < 0
|
||||
For Id = 1 To #BakaShrot_MaxId
|
||||
If Not FindMapElement(Names(), Str(Id)) And Not FindMapElement(KnownUsed(), Str(Id))
|
||||
Break
|
||||
EndIf
|
||||
Next
|
||||
If Id > #BakaShrot_MaxId
|
||||
ProcedureReturn -1
|
||||
EndIf
|
||||
EndIf
|
||||
|
||||
Ids(LCase(Name)) = Id
|
||||
Names(Str(Id)) = Name
|
||||
ProcedureReturn Id
|
||||
EndProcedure
|
||||
|
||||
; A node ref that defines a node: [BakaShrot] Node, a peer's or a client's.
|
||||
; Resolved like ResolveConfigNode(), and a name [BakaShrot.Nodes] doesn't
|
||||
; list is named all the same, its id given like one listed without an id.
|
||||
; -1 if it's neither an id nor a valid name.
|
||||
Procedure.i DeclareConfigNode(*Config.BakaShrot_CoreConfig, Ref.s)
|
||||
Protected Id.i = ResolveConfigNode(*Config, Ref)
|
||||
|
||||
If Id >= 0 Or Not BakaShrot_IsValidName(Ref)
|
||||
ProcedureReturn Id
|
||||
EndIf
|
||||
ProcedureReturn AssignConfigId(Ref, *Config\NodeIds(), *Config\NodeNames(), *BakaShrot_ConfigKnown\NodeIds(), *BakaShrot_ConfigKnown\NodeUsed())
|
||||
EndProcedure
|
||||
|
||||
|
||||
; An age as [BakaShrot.Retention] writes it ("30d", "1d12h", "forever") in
|
||||
; milliseconds, 0 for forever, -1 if it isn't one.
|
||||
Procedure.q ParseRetentionAge(Text.s)
|
||||
@@ -560,17 +623,20 @@ Procedure.q RetentionMaxAgeMs(List Rules.BakaShrot_RetentionRule(), TopicId.i, N
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Reads a "name = id" section into Ids() (LCase(name) -> id) and Names()
|
||||
; (Str(id) -> name). Kind is "topic" or "node", for the errors.
|
||||
; Reads a names section into Ids() (LCase(name) -> id) and Names() (Str(id)
|
||||
; -> name). A line is a name, its id given by AssignConfigId() once the
|
||||
; pinned ones are known (the database's for it, else a free one), or
|
||||
; "name = id" to pin it. Kind is "topic" or "node", for the errors.
|
||||
; The file must be open with OpenConfigPreferences(), see why there.
|
||||
; Returns #False on an invalid name or id, or one given twice.
|
||||
Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s())
|
||||
Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s(), Map KnownIds.i(), Map KnownUsed.i())
|
||||
Protected Name.s, Value.s, Id.i
|
||||
Protected NewList Unpinned.s()
|
||||
|
||||
If Not PreferenceGroup(Section)
|
||||
If Not PreferenceGroup(Section) Or Not ExaminePreferenceKeys()
|
||||
ProcedureReturn #True
|
||||
EndIf
|
||||
|
||||
If ExaminePreferenceKeys()
|
||||
While NextPreferenceKey()
|
||||
Name = Trim(PreferenceKeyName())
|
||||
Value = Trim(PreferenceKeyValue())
|
||||
@@ -578,15 +644,21 @@ Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s())
|
||||
BakaShrot_ConfigError = "[" + Section + "] '" + Name + "' isn't a valid " + Kind + " name: 1-" + Str(#BakaShrot_MaxNameLength) + " of A-Z a-z 0-9 _ . -, not only digits"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Id = BakaShrot_RefToId(Value)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If FindMapElement(Ids(), LCase(Name))
|
||||
BakaShrot_ConfigError = "[" + Section + "] " + Kind + " '" + Name + "' is given twice"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If Value = ""
|
||||
; Its id once every pinned one is known, -1 until then.
|
||||
Ids(LCase(Name)) = -1
|
||||
AddElement(Unpinned()) : Unpinned() = Name
|
||||
Continue
|
||||
EndIf
|
||||
Id = BakaShrot_RefToId(Value)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[" + Section + "] " + Name + " = '" + Value + "' isn't an id, 0-" + Str(#BakaShrot_MaxId) + " (or leave it out, the server gives it one)"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If FindMapElement(Names(), Str(Id))
|
||||
BakaShrot_ConfigError = "[" + Section + "] " + Kind + " id " + Str(Id) + " is given to both '" + Names() + "' and '" + Name + "'"
|
||||
ProcedureReturn #False
|
||||
@@ -594,7 +666,14 @@ Procedure.i ParseNameSection(Section.s, Kind.s, Map Ids.i(), Map Names.s())
|
||||
Ids(LCase(Name)) = Id
|
||||
Names(Str(Id)) = Name
|
||||
Wend
|
||||
|
||||
ForEach Unpinned()
|
||||
DeleteMapElement(Ids(), LCase(Unpinned()))
|
||||
If AssignConfigId(Unpinned(), Ids(), Names(), KnownIds(), KnownUsed()) < 0
|
||||
BakaShrot_ConfigError = "[" + Section + "] no " + Kind + " id left for '" + Unpinned() + "'"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Next
|
||||
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
@@ -717,92 +796,81 @@ Procedure.s FormatPublicKeyList(List Keys.s())
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Parses a "Topic:Node;Topic:Node;..." list into a list of identities.
|
||||
; Returns #False if an entry isn't exactly "Topic:Node" with known refs,
|
||||
; since silently turning a typo into a 0:0 identity would grant an identity
|
||||
; nobody asked for.
|
||||
Procedure.i ParseIdentityList(*Config.BakaShrot_CoreConfig, IdentitiesString.s, List Identities.BakaShrot_ClientIdentity(), Where.s)
|
||||
Protected i, Part.s, TopicPart.s, NodePart.s, TopicId.i, NodeId.i
|
||||
; Reads a client section's Node and DefaultTopic into *Client, in the
|
||||
; current preference group. Where: "[BakaShrot.Client.<name>]".
|
||||
; Returns #False with BakaShrot_ConfigError set: Node missing or unknown,
|
||||
; DefaultTopic unknown, or the old Identities still there. That one is
|
||||
; refused rather than guessed at: a "Topic:Node" list could grant several
|
||||
; nodes, and the topic was only ever the default one.
|
||||
Procedure.i ParseClientIdentity(*Config.BakaShrot_CoreConfig, *Client.BakaShrot_ClientConfig, Where.s)
|
||||
Protected Old.s, Pair.s, Id.i
|
||||
|
||||
ClearList(Identities())
|
||||
|
||||
For i = 1 To CountString(IdentitiesString, ";") + 1
|
||||
Part = Trim(StringField(IdentitiesString, i, ";"))
|
||||
If Part = ""
|
||||
Continue
|
||||
Old = Trim(ReadPreferenceString("Identities", #BakaShrot_Config_Missing))
|
||||
If Old <> #BakaShrot_Config_Missing
|
||||
Pair = Trim(StringField(Old, 1, ";"))
|
||||
If CountString(Old, ";") = 0 And CountString(Pair, ":") = 1
|
||||
BakaShrot_ConfigError = Where + " Identities isn't used any more (protocol 5): write Node = " + Trim(StringField(Pair, 2, ":")) +
|
||||
" and DefaultTopic = " + Trim(StringField(Pair, 1, ":")) + " instead of Identities = " + Old
|
||||
Else
|
||||
BakaShrot_ConfigError = Where + " Identities isn't used any more (protocol 5): write the node it writes as in Node, and the topic of its pushes that don't name one in DefaultTopic, one section per node (a key may be in several)"
|
||||
EndIf
|
||||
|
||||
If CountString(Part, ":") <> 1
|
||||
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
TopicPart = Trim(StringField(Part, 1, ":"))
|
||||
NodePart = Trim(StringField(Part, 2, ":"))
|
||||
If TopicPart = "" Or NodePart = ""
|
||||
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node"
|
||||
*Client\NodeText = Trim(ReadPreferenceString("Node", ""))
|
||||
If *Client\NodeText = ""
|
||||
BakaShrot_ConfigError = Where + " Node is missing: the node this client writes as, a name or an id"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
TopicId = ResolveConfigTopic(*Config, TopicPart)
|
||||
NodeId = ResolveConfigNode(*Config, NodePart)
|
||||
If TopicId < 0
|
||||
BakaShrot_ConfigError = Where + ": unknown topic '" + TopicPart + "', not an id nor in [BakaShrot.Topics]"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If NodeId < 0
|
||||
BakaShrot_ConfigError = Where + ": unknown node '" + NodePart + "', not an id nor in [BakaShrot.Nodes]"
|
||||
Id = DeclareConfigNode(*Config, *Client\NodeText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = Where + " Node: '" + *Client\NodeText + "' isn't a node name or an id"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
*Client\NodeId = Id
|
||||
*Config\UsedNodeIds(Str(Id)) = #True
|
||||
|
||||
AddElement(Identities())
|
||||
Identities()\TopicId = TopicId
|
||||
Identities()\NodeId = NodeId
|
||||
*Config\UsedTopicIds(Str(TopicId)) = #True
|
||||
*Config\UsedNodeIds(Str(NodeId)) = #True
|
||||
Next
|
||||
*Client\DefaultTopicId = -1
|
||||
*Client\DefaultTopicText = ReadPreferenceString("DefaultTopic", #BakaShrot_Config_Missing)
|
||||
If *Client\DefaultTopicText <> #BakaShrot_Config_Missing And Trim(*Client\DefaultTopicText) <> ""
|
||||
*Client\DefaultTopicText = Trim(*Client\DefaultTopicText)
|
||||
Id = ResolveConfigTopic(*Config, *Client\DefaultTopicText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = Where + " DefaultTopic: unknown topic '" + *Client\DefaultTopicText + "', not an id nor in [BakaShrot.Topics]"
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
*Client\DefaultTopicId = Id
|
||||
*Config\UsedTopicIds(Str(Id)) = #True
|
||||
EndIf
|
||||
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Returns the name of the [BakaShrot.Client.<name>] section allowing both
|
||||
; PublicKey and the TopicId:NodeId identity, or "" if none does.
|
||||
; Returns the name of the [BakaShrot.Client.<name>] section with this Node
|
||||
; and PublicKey in its PublicKeys, or "" if none has.
|
||||
; Not thread-safe, it moves *Config\Clients()' current element.
|
||||
Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i)
|
||||
Protected KeyAllowed.i, IdentityAllowed.i
|
||||
|
||||
Procedure.s FindClientName(*Config.BakaShrot_CoreConfig, PublicKey.s, NodeId.i)
|
||||
ForEach *Config\Clients()
|
||||
KeyAllowed = #False
|
||||
If *Config\Clients()\NodeId = NodeId
|
||||
ForEach *Config\Clients()\PublicKeys()
|
||||
If *Config\Clients()\PublicKeys() = PublicKey
|
||||
KeyAllowed = #True
|
||||
Break
|
||||
EndIf
|
||||
Next
|
||||
|
||||
IdentityAllowed = #False
|
||||
ForEach *Config\Clients()\Identities()
|
||||
If *Config\Clients()\Identities()\TopicId = TopicId And *Config\Clients()\Identities()\NodeId = NodeId
|
||||
IdentityAllowed = #True
|
||||
Break
|
||||
EndIf
|
||||
Next
|
||||
|
||||
If KeyAllowed And IdentityAllowed
|
||||
ProcedureReturn MapKey(*Config\Clients())
|
||||
EndIf
|
||||
Next
|
||||
EndIf
|
||||
Next
|
||||
|
||||
ProcedureReturn ""
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Returns the name of the [BakaShrot.Peer.<name>] section with exactly this
|
||||
; public key and TopicId:NodeId identity, or "" if none has.
|
||||
; public key and node, or "" if none has.
|
||||
; Not thread-safe, it moves *Config\Peers()' current element.
|
||||
Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, TopicId.i, NodeId.i)
|
||||
Procedure.s FindPeerName(*Config.BakaShrot_CoreConfig, PublicKey.s, NodeId.i)
|
||||
ForEach *Config\Peers()
|
||||
If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\TopicId = TopicId And *Config\Peers()\NodeId = NodeId
|
||||
If *Config\Peers()\PublicKey = PublicKey And *Config\Peers()\NodeId = NodeId
|
||||
ProcedureReturn MapKey(*Config\Peers())
|
||||
EndIf
|
||||
Next
|
||||
@@ -816,32 +884,167 @@ Procedure FreeConfig(*Config.BakaShrot_CoreConfig)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Where OpenConfigPreferences() put its copy, "" when it opened the file.
|
||||
Global BakaShrot_ConfigCopyPath.s
|
||||
|
||||
; OpenPreferences(IniFilePath), through a copy with CRLF line endings when
|
||||
; the file has LF ones: there, the Preferences library takes the line after
|
||||
; a key without "=" for its value, a section header too ("logs" then
|
||||
; "[BakaShrot.Server]" loses that whole section), and names are listed
|
||||
; without "=". The copy goes in the temporary folder, CloseConfigPreferences()
|
||||
; deletes it. Returns OpenPreferences()' result.
|
||||
Procedure.i OpenConfigPreferences(IniFilePath.s)
|
||||
Protected FileId.i, Format.i, HadBom.i, Size.q, *Data, Text.s, Copy.s, Opened.i
|
||||
|
||||
BakaShrot_ConfigCopyPath = ""
|
||||
FileId = ReadFile(#PB_Any, IniFilePath)
|
||||
If Not FileId
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
Format = ReadStringFormat(FileId)
|
||||
HadBom = Bool(Format <> #PB_Ascii)
|
||||
If Not HadBom
|
||||
Format = #PB_UTF8
|
||||
EndIf
|
||||
Size = Lof(FileId) - Loc(FileId)
|
||||
*Data = AllocateMemory(Size + 2)
|
||||
If Not *Data
|
||||
CloseFile(FileId)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ReadData(FileId, *Data, Size)
|
||||
CloseFile(FileId)
|
||||
Text = PeekS(*Data, Size, Format | #PB_ByteLength)
|
||||
FreeMemory(*Data)
|
||||
|
||||
If Not FindString(ReplaceString(Text, #CRLF$, ""), #LF$)
|
||||
ProcedureReturn OpenPreferences(IniFilePath)
|
||||
EndIf
|
||||
|
||||
Text = ReplaceString(ReplaceString(Text, #CRLF$, #LF$), #LF$, #CRLF$)
|
||||
Copy = GetTemporaryDirectory() + "BakaShrot-config-" + Str(Date()) + "-" + Str(Random(999999)) + ".ini"
|
||||
FileId = CreateFile(#PB_Any, Copy)
|
||||
If Not FileId
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If HadBom
|
||||
WriteStringFormat(FileId, Format)
|
||||
EndIf
|
||||
WriteString(FileId, Text, Format)
|
||||
CloseFile(FileId)
|
||||
|
||||
Opened = OpenPreferences(Copy)
|
||||
If Opened
|
||||
BakaShrot_ConfigCopyPath = Copy
|
||||
Else
|
||||
DeleteFile(Copy)
|
||||
EndIf
|
||||
ProcedureReturn Opened
|
||||
EndProcedure
|
||||
|
||||
; ClosePreferences(), and deletes OpenConfigPreferences()' copy if it made one.
|
||||
Procedure CloseConfigPreferences()
|
||||
ClosePreferences()
|
||||
If BakaShrot_ConfigCopyPath <> ""
|
||||
DeleteFile(BakaShrot_ConfigCopyPath)
|
||||
BakaShrot_ConfigCopyPath = ""
|
||||
EndIf
|
||||
EndProcedure
|
||||
|
||||
|
||||
; [BakaShrot.Server] DatabasePath of IniFilePath, "" if it can't be opened:
|
||||
; where the root reads the names it already has from, before LoadConfig().
|
||||
Procedure.s ReadConfigDatabasePath(IniFilePath.s)
|
||||
Protected Path.s
|
||||
|
||||
If OpenConfigPreferences(IniFilePath)
|
||||
PreferenceGroup("BakaShrot.Server")
|
||||
Path = ReadPreferenceString("DatabasePath", #BakaShrot_Config_DefaultDatabasePath)
|
||||
CloseConfigPreferences()
|
||||
EndIf
|
||||
ProcedureReturn Path
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Loads IniFilePath. Returns 0 on failure, with the reason in BakaShrot_ConfigError.
|
||||
Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
; *Known: the names the database already has, so the ones listed without an
|
||||
; id keep theirs (0: none, a new database).
|
||||
Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s, *Known.BakaShrot_KnownNames = 0)
|
||||
Protected *Config.BakaShrot_CoreConfig
|
||||
Protected GroupName.s, PeerName.s, ClientName.s, Text.s, Id.i
|
||||
Protected NewList PeerNames.s(), NewList ClientNames.s()
|
||||
Protected Failed.i = #False
|
||||
Protected NoneKnown.BakaShrot_KnownNames
|
||||
|
||||
BakaShrot_ConfigError = ""
|
||||
If Not *Known
|
||||
*Known = @NoneKnown
|
||||
EndIf
|
||||
*BakaShrot_ConfigKnown = *Known
|
||||
|
||||
If Not OpenPreferences(IniFilePath)
|
||||
If Not OpenConfigPreferences(IniFilePath)
|
||||
BakaShrot_ConfigError = "can't open '" + IniFilePath + "'"
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
*Config = AllocateStructure(BakaShrot_CoreConfig)
|
||||
If Not *Config
|
||||
ClosePreferences()
|
||||
CloseConfigPreferences()
|
||||
BakaShrot_ConfigError = "out of memory"
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
; Names first, everything else can refer to them.
|
||||
If Not ParseNameSection("BakaShrot.Topics", "topic", *Config\TopicIds(), *Config\TopicNames()) Or
|
||||
Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames())
|
||||
If Not ParseNameSection("BakaShrot.Topics", "topic", *Config\TopicIds(), *Config\TopicNames(), *Known\TopicIds(), *Known\TopicUsed()) Or
|
||||
Not ParseNameSection("BakaShrot.Nodes", "node", *Config\NodeIds(), *Config\NodeNames(), *Known\NodeIds(), *Known\NodeUsed())
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
|
||||
PreferenceGroup("BakaShrot")
|
||||
*Config\PrivateKey = ReadPreferenceString("PrivateKey", "")
|
||||
; Topic (TopicId) isn't read any more: a server authenticates by node.
|
||||
*Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0"))
|
||||
Id = DeclareConfigNode(*Config, *Config\NodeText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[BakaShrot] Node: '" + *Config\NodeText + "' isn't a node name or an id"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\NodeId = Id
|
||||
*Config\UsedNodeIds(Str(*Config\NodeId)) = #True
|
||||
|
||||
; Every [BakaShrot.Peer.<name>] and [BakaShrot.Client.<name>], found
|
||||
; dynamically so adding one never needs a second "list of names" kept in
|
||||
; sync by hand. Read once the walk is done: PreferenceGroup() inside it
|
||||
; would lose the walk's place.
|
||||
If ExaminePreferenceGroups()
|
||||
While NextPreferenceGroup()
|
||||
GroupName = PreferenceGroupName()
|
||||
If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.")
|
||||
AddElement(PeerNames())
|
||||
PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1)
|
||||
EndIf
|
||||
If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.")
|
||||
AddElement(ClientNames())
|
||||
ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1)
|
||||
EndIf
|
||||
Wend
|
||||
EndIf
|
||||
|
||||
; The nodes the peer and client sections define are named before any
|
||||
; node list (SendNodes, AcceptNodes) can refer to them. A bad one is
|
||||
; reported when its section is read below.
|
||||
ForEach PeerNames()
|
||||
PreferenceGroup("BakaShrot.Peer." + PeerNames())
|
||||
DeclareConfigNode(*Config, Trim(ReadConfigKey("Node", "NodeId", "0")))
|
||||
Next
|
||||
ForEach ClientNames()
|
||||
PreferenceGroup("BakaShrot.Client." + ClientNames())
|
||||
Text = Trim(ReadPreferenceString("Node", ""))
|
||||
If Text <> ""
|
||||
DeclareConfigNode(*Config, Text)
|
||||
EndIf
|
||||
Next
|
||||
|
||||
ForEach *Config\TopicNames()
|
||||
*Config\UsedTopicIds(MapKey(*Config\TopicNames())) = #True
|
||||
Next
|
||||
@@ -849,25 +1052,6 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
*Config\UsedNodeIds(MapKey(*Config\NodeNames())) = #True
|
||||
Next
|
||||
|
||||
PreferenceGroup("BakaShrot")
|
||||
*Config\PrivateKey = ReadPreferenceString("PrivateKey", "")
|
||||
*Config\TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0"))
|
||||
*Config\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0"))
|
||||
Id = ResolveConfigTopic(*Config, *Config\TopicText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[BakaShrot] Topic: unknown topic '" + *Config\TopicText + "'"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\TopicId = Id
|
||||
Id = ResolveConfigNode(*Config, *Config\NodeText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[BakaShrot] Node: unknown node '" + *Config\NodeText + "'"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\NodeId = Id
|
||||
*Config\UsedTopicIds(Str(*Config\TopicId)) = #True
|
||||
*Config\UsedNodeIds(Str(*Config\NodeId)) = #True
|
||||
|
||||
PreferenceGroup("BakaShrot.Server")
|
||||
*Config\Server\Host = ReadPreferenceString("Host", "")
|
||||
*Config\Server\Port = ReadPreferenceLong("Port", 0)
|
||||
@@ -892,6 +1076,19 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] UploadTimeout must be 10 seconds or more"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\Server\Synchronous = UCase(Trim(ReadPreferenceString("Synchronous", #BakaShrot_Config_DefaultSynchronous)))
|
||||
; An If chain, not a Select: a Goto out of a Select corrupts the stack
|
||||
; with 5.73's ASM backend (it keeps the value there).
|
||||
If *Config\Server\Synchronous = "OFF"
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = OFF isn't allowed: a power loss could corrupt the database. FULL, or NORMAL to only risk the last second of messages"
|
||||
Goto LoadFailed
|
||||
ElseIf *Config\Server\Synchronous = "EXTRA"
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = EXTRA does nothing more than FULL in WAL mode: write FULL"
|
||||
Goto LoadFailed
|
||||
ElseIf *Config\Server\Synchronous <> "FULL" And *Config\Server\Synchronous <> "NORMAL"
|
||||
BakaShrot_ConfigError = "[BakaShrot.Server] Synchronous = '" + *Config\Server\Synchronous + "' isn't FULL or NORMAL"
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
*Config\Server\ReplicatingTopicsText = ReadConfigKey("ReplicatingTopics", "ReplicatingTopicIds", "")
|
||||
If Not ParseTopicSet(*Config, *Config\Server\ReplicatingTopicsText, @*Config\Server\ReplicatingTopics, "[BakaShrot.Server] ReplicatingTopics")
|
||||
Goto LoadFailed
|
||||
@@ -901,24 +1098,6 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
|
||||
; Every [BakaShrot.Peer.<name>] and [BakaShrot.Client.<name>], found
|
||||
; dynamically so adding one never needs a second "list of names" kept in
|
||||
; sync by hand. Read once the walk is done: PreferenceGroup() inside it
|
||||
; would lose the walk's place.
|
||||
If ExaminePreferenceGroups()
|
||||
While NextPreferenceGroup()
|
||||
GroupName = PreferenceGroupName()
|
||||
If Left(GroupName, Len("BakaShrot.Peer.")) = "BakaShrot.Peer." And Len(GroupName) > Len("BakaShrot.Peer.")
|
||||
AddElement(PeerNames())
|
||||
PeerNames() = Mid(GroupName, Len("BakaShrot.Peer.") + 1)
|
||||
EndIf
|
||||
If Left(GroupName, Len("BakaShrot.Client.")) = "BakaShrot.Client." And Len(GroupName) > Len("BakaShrot.Client.")
|
||||
AddElement(ClientNames())
|
||||
ClientNames() = Mid(GroupName, Len("BakaShrot.Client.") + 1)
|
||||
EndIf
|
||||
Wend
|
||||
EndIf
|
||||
|
||||
ForEach PeerNames()
|
||||
PeerName = PeerNames()
|
||||
PreferenceGroup("BakaShrot.Peer." + PeerName)
|
||||
@@ -927,21 +1106,14 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
\Host = ReadPreferenceString("Host", "")
|
||||
\Port = ReadPreferenceLong("Port", 0)
|
||||
\PublicKey = ReadPreferenceString("PublicKey", "")
|
||||
\TopicText = Trim(ReadConfigKey("Topic", "TopicId", "0"))
|
||||
; Topic (TopicId) isn't read any more: a peer authenticates by node.
|
||||
\NodeText = Trim(ReadConfigKey("Node", "NodeId", "0"))
|
||||
Id = ResolveConfigTopic(*Config, \TopicText)
|
||||
Id = DeclareConfigNode(*Config, \NodeText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Topic: unknown topic '" + \TopicText + "'"
|
||||
Failed = #True : Break
|
||||
EndIf
|
||||
\TopicId = Id
|
||||
Id = ResolveConfigNode(*Config, \NodeText)
|
||||
If Id < 0
|
||||
BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: unknown node '" + \NodeText + "'"
|
||||
BakaShrot_ConfigError = "[BakaShrot.Peer." + PeerName + "] Node: '" + \NodeText + "' isn't a node name or an id"
|
||||
Failed = #True : Break
|
||||
EndIf
|
||||
\NodeId = Id
|
||||
*Config\UsedTopicIds(Str(\TopicId)) = #True
|
||||
*Config\UsedNodeIds(Str(\NodeId)) = #True
|
||||
|
||||
\SendTopicsText = ReadPreferenceString("SendTopics", #BakaShrot_Config_Missing)
|
||||
@@ -967,7 +1139,7 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
|
||||
\AcceptNodesText = ReadPreferenceString("AcceptNodes", #BakaShrot_Config_Missing)
|
||||
If \AcceptNodesText = #BakaShrot_Config_Missing
|
||||
\AcceptNodes\Known = #True
|
||||
\AcceptNodes\All = #True
|
||||
ElseIf Not ParseNameSet(*Config, \AcceptNodesText, @\AcceptNodes, #True, "[BakaShrot.Peer." + PeerName + "] AcceptNodes")
|
||||
Failed = #True : Break
|
||||
EndIf
|
||||
@@ -983,28 +1155,27 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
AddMapElement(*Config\Clients(), ClientName)
|
||||
With *Config\Clients()
|
||||
ParsePublicKeyList(ReadPreferenceString("PublicKeys", ""), \PublicKeys())
|
||||
\IdentitiesText = ReadPreferenceString("Identities", "")
|
||||
If Not ParseIdentityList(*Config, \IdentitiesText, \Identities(), "[BakaShrot.Client." + ClientName + "] Identities")
|
||||
If Not ParseClientIdentity(*Config, @*Config\Clients(), "[BakaShrot.Client." + ClientName + "]")
|
||||
Failed = #True : Break
|
||||
EndIf
|
||||
\Permissions\Read = Bool(ReadPreferenceLong("AllowRead", #BakaShrot_Config_DefaultAllowRead) <> 0)
|
||||
\Permissions\Write = Bool(ReadPreferenceLong("AllowWrite", #BakaShrot_Config_DefaultAllowWrite) <> 0)
|
||||
\Permissions\Query = Bool(ReadPreferenceLong("AllowQuery", #BakaShrot_Config_DefaultAllowQuery) <> 0)
|
||||
|
||||
; By default, only the topics it authenticates in, like before.
|
||||
; By default, only its default topic, nothing without one.
|
||||
\PushTopicsText = ReadPreferenceString("PushTopics", #BakaShrot_Config_Missing)
|
||||
\ReadTopicsText = ReadPreferenceString("ReadTopics", #BakaShrot_Config_Missing)
|
||||
If \PushTopicsText = #BakaShrot_Config_Missing
|
||||
ForEach \Identities()
|
||||
\PushTopics\Ids(Str(\Identities()\TopicId)) = #True
|
||||
Next
|
||||
If \DefaultTopicId >= 0
|
||||
\PushTopics\Ids(Str(\DefaultTopicId)) = #True
|
||||
EndIf
|
||||
ElseIf Not ParseTopicSet(*Config, \PushTopicsText, @\PushTopics, "[BakaShrot.Client." + ClientName + "] PushTopics")
|
||||
Failed = #True : Break
|
||||
EndIf
|
||||
If \ReadTopicsText = #BakaShrot_Config_Missing
|
||||
ForEach \Identities()
|
||||
\ReadTopics\Ids(Str(\Identities()\TopicId)) = #True
|
||||
Next
|
||||
If \DefaultTopicId >= 0
|
||||
\ReadTopics\Ids(Str(\DefaultTopicId)) = #True
|
||||
EndIf
|
||||
ElseIf Not ParseTopicSet(*Config, \ReadTopicsText, @\ReadTopics, "[BakaShrot.Client." + ClientName + "] ReadTopics")
|
||||
Failed = #True : Break
|
||||
EndIf
|
||||
@@ -1014,11 +1185,11 @@ Procedure.Ptr_BakaShrot_CoreConfig LoadConfig(IniFilePath.s)
|
||||
Goto LoadFailed
|
||||
EndIf
|
||||
|
||||
ClosePreferences()
|
||||
CloseConfigPreferences()
|
||||
ProcedureReturn *Config
|
||||
|
||||
LoadFailed:
|
||||
ClosePreferences()
|
||||
CloseConfigPreferences()
|
||||
FreeConfig(*Config)
|
||||
ProcedureReturn 0
|
||||
EndProcedure
|
||||
@@ -1041,7 +1212,6 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
|
||||
|
||||
PreferenceGroup("BakaShrot")
|
||||
WritePreferenceString("PrivateKey", *Config\PrivateKey)
|
||||
WritePreferenceString("Topic", *Config\TopicText)
|
||||
WritePreferenceString("Node", *Config\NodeText)
|
||||
|
||||
PreferenceGroup("BakaShrot.Server")
|
||||
@@ -1056,6 +1226,7 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
|
||||
WritePreferenceLong("RetentionInterval", *Config\Server\RetentionInterval)
|
||||
WritePreferenceString("MaxAttachmentSize", *Config\Server\MaxAttachmentSizeText)
|
||||
WritePreferenceLong("UploadTimeout", *Config\Server\UploadTimeout)
|
||||
WritePreferenceString("Synchronous", *Config\Server\Synchronous)
|
||||
|
||||
PreferenceGroup("BakaShrot.Topics")
|
||||
ForEach *Config\TopicNames()
|
||||
@@ -1078,7 +1249,6 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
|
||||
PreferenceGroup("BakaShrot.Peer." + MapKey(*Config\Peers()))
|
||||
WritePreferenceString("Host", *Config\Peers()\Host)
|
||||
WritePreferenceLong("Port", *Config\Peers()\Port)
|
||||
WritePreferenceString("Topic", *Config\Peers()\TopicText)
|
||||
WritePreferenceString("Node", *Config\Peers()\NodeText)
|
||||
WritePreferenceString("PublicKey", *Config\Peers()\PublicKey)
|
||||
WriteConfigText("SendTopics", *Config\Peers()\SendTopicsText)
|
||||
@@ -1090,7 +1260,8 @@ Procedure.i SaveConfig(IniFilePath.s, *Config.BakaShrot_CoreConfig)
|
||||
ForEach *Config\Clients()
|
||||
PreferenceGroup("BakaShrot.Client." + MapKey(*Config\Clients()))
|
||||
WritePreferenceString("PublicKeys", FormatPublicKeyList(*Config\Clients()\PublicKeys()))
|
||||
WritePreferenceString("Identities", *Config\Clients()\IdentitiesText)
|
||||
WritePreferenceString("Node", *Config\Clients()\NodeText)
|
||||
WriteConfigText("DefaultTopic", *Config\Clients()\DefaultTopicText)
|
||||
WritePreferenceLong("AllowRead", *Config\Clients()\Permissions\Read)
|
||||
WritePreferenceLong("AllowWrite", *Config\Clients()\Permissions\Write)
|
||||
WritePreferenceLong("AllowQuery", *Config\Clients()\Permissions\Query)
|
||||
@@ -1112,7 +1283,6 @@ CompilerIf #PB_Compiler_IsMainFile
|
||||
|
||||
If *Config
|
||||
Debug "PrivateKey: " + *Config\PrivateKey
|
||||
Debug "TopicId: " + Str(*Config\TopicId)
|
||||
Debug "NodeId: " + Str(*Config\NodeId)
|
||||
|
||||
Debug "Server: " + *Config\Server\Host + ":" + Str(*Config\Server\Port)
|
||||
@@ -1135,9 +1305,7 @@ CompilerIf #PB_Compiler_IsMainFile
|
||||
ForEach *Config\Clients()\PublicKeys()
|
||||
Debug " PublicKey: " + *Config\Clients()\PublicKeys()
|
||||
Next
|
||||
ForEach *Config\Clients()\Identities()
|
||||
Debug " Identity: " + Str(*Config\Clients()\Identities()\TopicId) + ":" + Str(*Config\Clients()\Identities()\NodeId)
|
||||
Next
|
||||
Debug " Node: " + Str(*Config\Clients()\NodeId) + ", DefaultTopic: " + Str(*Config\Clients()\DefaultTopicId)
|
||||
Next
|
||||
|
||||
SaveConfig("schema_out.ini", *Config)
|
||||
|
||||
+67
-28
@@ -3,15 +3,17 @@
|
||||
; library is concerned — the dots below are just part of the name.
|
||||
;
|
||||
; Topics and nodes: each has an id (0-65535) on this server, and can have a
|
||||
; name, in [BakaShrot.Topics] and [BakaShrot.Nodes]. Names are what's shared
|
||||
; between servers: replication sends them, and each server stores the
|
||||
; messages under its own ids for them ("logs" can be 1 here and 200 on a
|
||||
; peer).
|
||||
; name. Topics are named in [BakaShrot.Topics]; nodes by the sections that
|
||||
; define them ([BakaShrot] Node, a peer's, a client's), [BakaShrot.Nodes]
|
||||
; only names the others. The server gives every name its id, and keeps it.
|
||||
; Names are what's shared between servers: replication sends them, and
|
||||
; each server stores the messages under its own ids for them ("logs" can be
|
||||
; 1 here and 200 on a peer).
|
||||
; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a
|
||||
; name, or whose name the other server doesn't have, is dropped. Unnamed
|
||||
; ones still work locally, by id.
|
||||
; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter.
|
||||
; The server's "names" command and the ListNames tool list them all.
|
||||
; The server's "names" command and the BakaShrotList tool list them all.
|
||||
;
|
||||
; Topic, Node and ReplicatingTopics were TopicId, NodeId and
|
||||
; ReplicatingTopicIds before: the old names are still read.
|
||||
@@ -27,31 +29,37 @@
|
||||
[BakaShrot]
|
||||
; Config shared by every type of config.
|
||||
|
||||
; This node's Ed25519 private key (Base64), from KeyGen.exe. It proves who
|
||||
; This node's Ed25519 private key (Base64), from BakaShrotGenerateKeyPairs.exe. It proves who
|
||||
; this server is: clients seal their Hello for its public key and check
|
||||
; that it signed the handshake, so they need that public key (client.ini's
|
||||
; ServerPublicKey, peers' PublicKey below in THEIR own config). The server
|
||||
; logs it when it starts. See Commons/Networking/Connections.pbi.
|
||||
PrivateKey =
|
||||
|
||||
; The topic and node this server authenticates as when it links to its
|
||||
; peers, a name or an id. Its peers must register it under the same names.
|
||||
Topic =
|
||||
; The node this server authenticates as when it links to its peers, a name
|
||||
; or an id. Its peers must register it under the same name: a client
|
||||
; section with this Node and this server's public key. (A Topic left here
|
||||
; from before protocol 5 is ignored.)
|
||||
Node =
|
||||
|
||||
|
||||
[BakaShrot.Topics]
|
||||
; One line per named topic: name = this server's id for it.
|
||||
; logs = 1
|
||||
; sensors = 2
|
||||
; One topic name per line. This server gives each its id: the one its
|
||||
; database already has for it, or the lowest free one for a new one, so the
|
||||
; order doesn't matter and they keep their ids.
|
||||
; "name = id" pins one instead (configs from before work as they are). Once
|
||||
; a name has messages, its id can't change: the server refuses to start if
|
||||
; a pin moves it, and says which id to use.
|
||||
; logs
|
||||
; sensors
|
||||
|
||||
|
||||
[BakaShrot.Nodes]
|
||||
; One line per named node (a client's or a server's), same as topics. Every
|
||||
; server that should get a node's messages must name it too.
|
||||
; Once a name has messages, keep its id: the server refuses to start if the
|
||||
; config moves it to another one, and says which id to use.
|
||||
; kitchen = 2
|
||||
; Optional. The nodes [BakaShrot] Node, the peers' and the clients' Node
|
||||
; define are named already. List the others this server should know by name
|
||||
; up front, like topics; peers add the ones they send as they come
|
||||
; (AcceptNodes, below).
|
||||
; kitchen
|
||||
|
||||
|
||||
[BakaShrot.Retention]
|
||||
@@ -114,6 +122,21 @@ MaxAttachmentSize = 1G
|
||||
; after which the upload is deleted.
|
||||
UploadTimeout = 3600
|
||||
|
||||
; How hard the database makes sure a push is on disk before answering it.
|
||||
; FULL (default) every commit is flushed to disk: a message the server
|
||||
; acknowledged survives a power loss or an OS crash.
|
||||
; NORMAL flushed about once a second only (at the checkpoints): faster
|
||||
; (twice the pushes under full load, measured), but a power loss
|
||||
; or an OS crash loses the last second or so of acknowledged
|
||||
; messages, and their ids are handed out again, which peers that
|
||||
; already got them can't tell (Design/ReplicationIssues.md #1).
|
||||
; A crash of the server alone loses nothing either way.
|
||||
; The cost of FULL is the disk's flush time, once per group of pushes: well
|
||||
; under a millisecond on a server SSD, ~10 ms on a hard disk, which then
|
||||
; caps one client pushing one message at a time to ~100/s.
|
||||
; See Design/StorageConcurrency.md for the numbers.
|
||||
Synchronous = FULL
|
||||
|
||||
|
||||
; One [BakaShrot.Peer.<name>] section per peer this node talks to.
|
||||
; <name> is only a key for this file; it is never sent on the wire.
|
||||
@@ -129,9 +152,8 @@ Port =
|
||||
; The link only goes through if the peer proves it holds the private key
|
||||
; of PublicKey below, and it's encrypted.
|
||||
|
||||
; Remote node's topic and node, names or ids. The peer authenticates with
|
||||
; them when it links to here.
|
||||
Topic =
|
||||
; The peer's node, a name or an id: the one in its own [BakaShrot] Node.
|
||||
; It authenticates as it when it links to here.
|
||||
Node =
|
||||
|
||||
; The topics sent to this peer (if it takes them), and the topics taken
|
||||
@@ -140,9 +162,9 @@ Node =
|
||||
; AcceptTopics = logs;sensors.*
|
||||
|
||||
; The nodes whose messages are sent to this peer (default: every one), and
|
||||
; the nodes whose messages are taken from it (default: the ones named in
|
||||
; [BakaShrot.Nodes], no other). AcceptNodes = kitchen-* takes every
|
||||
; kitchen-something the peer sends, named here or not.
|
||||
; the nodes whose messages are taken from it (default: every one, the names
|
||||
; this server doesn't have yet are added as they come). AcceptNodes =
|
||||
; kitchen-*;garage only takes those, named here or not.
|
||||
; SendNodes = *
|
||||
; AcceptNodes = kitchen-*;garage
|
||||
|
||||
@@ -159,13 +181,30 @@ PublicKey =
|
||||
; Format: Key;Key;...
|
||||
PublicKeys =
|
||||
|
||||
; Topic and node pairs this client is allowed to authenticate as, names or ids.
|
||||
; Format: Topic:Node;Topic:Node;...
|
||||
Identities =
|
||||
; The node this client writes as, a name or an id, required. Every message
|
||||
; it pushes is stored under it, so the server decides which node each key
|
||||
; writes as, and no client can push as another's node (or as a peer's).
|
||||
; Its client.ini's Node must say the same. A key that writes as several
|
||||
; nodes is listed in a section per node.
|
||||
; ONE SERVER PER NODE: give a node a client section on the one server it
|
||||
; pushes to, the others get its messages by replication. Two servers taking
|
||||
; pushes for the same node end up with different messages under the same
|
||||
; ids, which nothing detects (Design/ReplicationIssues.md #1). To read from
|
||||
; another server, give the client another node there (or no write access:
|
||||
; AllowWrite = 0).
|
||||
Node =
|
||||
|
||||
; Where its pushes go when they don't name a topic, a name or an id.
|
||||
; Optional: without it, every push must name its topic. Only a default, it
|
||||
; may push to any topic in PushTopics.
|
||||
; DefaultTopic = logs
|
||||
|
||||
; (Identities, the Topic:Node pairs before protocol 5, isn't read any more:
|
||||
; the server refuses to start with it, saying what to write instead.)
|
||||
|
||||
; The topics it may push to (always under its own node), and the topics it
|
||||
; may read the latest messages of. Both default to the topics of its
|
||||
; Identities, empty allows none.
|
||||
; may read the latest messages of. Both default to its DefaultTopic,
|
||||
; nothing without one; empty allows none.
|
||||
; PushTopics = logs;sensors
|
||||
; ReadTopics = *
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
Protected Accepted.BakaShrot_AuthAccepted
|
||||
Protected Proof.BakaShrot_ChallengeProof
|
||||
Protected KeyPair.BakaShrot_SessionKeyPair
|
||||
Protected TopicId.i, NodeId.i, PublicKey.s, ClientName.s, TopicRef.s, NodeRef.s
|
||||
Protected NodeId.i, DefaultTopicId.i, PublicKey.s, ClientName.s, NodeRef.s
|
||||
Protected NonceMatches.i, SignatureDecoded.i, Sent.i, CipherReady.i
|
||||
|
||||
*Client\Metadata\Status = #BakaShrot_ConnectionStatus_New
|
||||
@@ -235,16 +235,14 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
TopicRef = *Hello\ClientTopic
|
||||
NodeRef = *Hello\ClientNode
|
||||
PublicKey = *Hello\ClientPubKeyB64
|
||||
CopyMemory(@*Hello\ClientSessionKey[0], @*Client\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize)
|
||||
FreeStructure(*Hello)
|
||||
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If TopicId < 0 Or NodeId < 0
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown identity '" + Left(TopicRef, 80) + "':'" + Left(NodeRef, 80) + "'")
|
||||
If NodeId < 0
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
@@ -254,9 +252,11 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
EndIf
|
||||
|
||||
LockMutex(*Server\Mutex)
|
||||
ClientName = FindClientName(*Server\Config, PublicKey, TopicId, NodeId)
|
||||
*Client\PeerName = FindPeerName(*Server\Config, PublicKey, TopicId, NodeId)
|
||||
ClientName = FindClientName(*Server\Config, PublicKey, NodeId)
|
||||
*Client\PeerName = FindPeerName(*Server\Config, PublicKey, NodeId)
|
||||
DefaultTopicId = -1
|
||||
If ClientName <> "" And FindMapElement(*Server\Config\Clients(), ClientName)
|
||||
DefaultTopicId = *Server\Config\Clients()\DefaultTopicId
|
||||
*Client\Permissions\Read = *Server\Config\Clients()\Permissions\Read
|
||||
*Client\Permissions\Write = *Server\Config\Clients()\Permissions\Write
|
||||
*Client\Permissions\Query = *Server\Config\Clients()\Permissions\Query
|
||||
@@ -270,11 +270,11 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
EndIf
|
||||
UnlockMutex(*Server\Mutex)
|
||||
If ClientName = ""
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to use " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + " with its public key")
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to write as node " + BakaShrot_Names_NodeRef(NodeId) + " with its public key")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
*Client\Metadata\TopicId = TopicId
|
||||
*Client\Metadata\DefaultTopicId = DefaultTopicId
|
||||
*Client\Metadata\NodeId = NodeId
|
||||
|
||||
|
||||
@@ -386,9 +386,9 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
|
||||
*Client\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated
|
||||
If *Client\PeerName = ""
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId))
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId))
|
||||
Else
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'")
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'")
|
||||
EndIf
|
||||
|
||||
ProcedureReturn #True
|
||||
@@ -397,12 +397,13 @@ EndProcedure
|
||||
|
||||
; Encodes and sends a RequestRefused.
|
||||
; Returns #False if it couldn't be sent, the client must then be aborted.
|
||||
Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Reason.s)
|
||||
Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Code.l, Reason.s)
|
||||
Protected Refused.BakaShrot_RequestRefused
|
||||
Protected *Packet, PacketSize.Integer, Sent.i
|
||||
|
||||
PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + ": " + Reason)
|
||||
PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + " (" + BakaShrot_ErrorName(Code) + "): " + Reason)
|
||||
|
||||
Refused\Code = Code
|
||||
Refused\Reason = Reason
|
||||
*Packet = BakaShrot_RequestRefusedPacket_Encode(@Refused, @PacketSize)
|
||||
If Not *Packet
|
||||
@@ -449,51 +450,54 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *
|
||||
EndIf
|
||||
|
||||
If Not *Client\Permissions\Write
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write")
|
||||
EndIf
|
||||
|
||||
If TopicRef = ""
|
||||
TopicId = *Client\Metadata\TopicId
|
||||
TopicId = *Client\Metadata\DefaultTopicId
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic")
|
||||
EndIf
|
||||
Else
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
|
||||
; So it fits in every packet that carries it later, see Packets.pbi.
|
||||
JsonSize = StringByteLength(JsonData, #PB_UTF8)
|
||||
If JsonSize > #BakaShrot_MaxMessageSize
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize))
|
||||
EndIf
|
||||
|
||||
; A topic allowed by "*" may be new here, it needs its row for the
|
||||
; "messages" view.
|
||||
If Not BakaShrot_Names_EnsureTopicId(TopicId, @StoreError)
|
||||
PrintN("[Net] Failed to register topic " + Str(TopicId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored")
|
||||
EndIf
|
||||
|
||||
; Its attachment: one of this client's complete uploads, for that topic.
|
||||
If UploadId
|
||||
If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload")
|
||||
EndIf
|
||||
If Blob\State <> #BakaShrot_Blob_Complete
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload isn't complete, or is attached already")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload isn't complete, or is attached already")
|
||||
EndIf
|
||||
If Blob\TopicId <> TopicId
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
|
||||
MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId)
|
||||
If MessageId < 1
|
||||
PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored")
|
||||
EndIf
|
||||
|
||||
Pushed\MessageId = MessageId
|
||||
@@ -542,23 +546,23 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie
|
||||
EndIf
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read")
|
||||
EndIf
|
||||
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
If Not GetLatestMessage(*Client\DbId, TopicId, NodeId, @Message)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId))
|
||||
EndIf
|
||||
|
||||
Latest\TopicId = TopicId
|
||||
@@ -619,24 +623,24 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, *
|
||||
EndIf
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read")
|
||||
EndIf
|
||||
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
; In characters, the bytes are counted below: never less than that.
|
||||
If Not GetMessagesAfter(*Client\DbId, TopicId, NodeId, AfterMessageId, Limit, #BakaShrot_MessagesBatchBytes, Messages(), @More)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be read")
|
||||
EndIf
|
||||
|
||||
; As many as fit in #BakaShrot_MessagesBatchBytes, the rest is for the
|
||||
@@ -702,16 +706,16 @@ Procedure.i BakaShrot_NetClient_HandleQuery(*Client.BakaShrot_NetClient, *Packet
|
||||
FreeStructure(*Request)
|
||||
|
||||
If Not *Client\Permissions\Query
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to query")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to query")
|
||||
EndIf
|
||||
|
||||
If Not RunReadOnlyQuery(*Client\Server\DatabasePath, Sql, @JsonResult, @QueryError)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Query failed: " + QueryError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_QueryFailed, "Query failed: " + QueryError\s)
|
||||
EndIf
|
||||
|
||||
; Leaves room for the packet's own fields.
|
||||
If StringByteLength(JsonResult\s, #PB_UTF8) > #BakaShrot_MaxPacketSize - 64
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The result is too big for one packet, add a LIMIT")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The result is too big for one packet, add a LIMIT")
|
||||
EndIf
|
||||
|
||||
Result\JsonResult = JsonResult\s
|
||||
@@ -755,16 +759,16 @@ Procedure.i BakaShrot_NetClient_HandleResolveName(*Client.BakaShrot_NetClient, *
|
||||
If Kind = #BakaShrot_NameKind_Topic
|
||||
Id = BakaShrot_Names_ResolveTopic(Ref)
|
||||
If Id < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
EndIf
|
||||
If Not *Client\Permissions\Query And Not NameSetHas(@*Client\PushTopics, Id, BakaShrot_Names_TopicName(Id)) And Not NameSetHas(@*Client\ReadTopics, Id, BakaShrot_Names_TopicName(Id))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
EndIf
|
||||
Resolved\Name = BakaShrot_Names_TopicName(Id)
|
||||
Else
|
||||
Id = BakaShrot_Names_ResolveNode(Ref)
|
||||
If Id < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(Ref, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(Ref, 80) + "'")
|
||||
EndIf
|
||||
Resolved\Name = BakaShrot_Names_NodeName(Id)
|
||||
EndIf
|
||||
@@ -878,12 +882,12 @@ Procedure.i BakaShrot_NetClient_HandleSyncStateRequest(*Client.BakaShrot_NetClie
|
||||
FreeStructure(*Request)
|
||||
|
||||
If *Client\PeerName = ""
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
If Not GetSyncState(*Client\DbId, AllPairs())
|
||||
PrintN("[Net] Failed to read the sync state for peer '" + *Client\PeerName + "': " + DatabaseError())
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The sync state couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The sync state couldn't be read")
|
||||
EndIf
|
||||
|
||||
; Every name this server knows, the peer only sends those.
|
||||
@@ -963,20 +967,20 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
|
||||
If *Client\PeerName = ""
|
||||
FreeStructure(*Batch)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
TopicId = BakaShrot_Names_TopicByName(TopicRef)
|
||||
If Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef)
|
||||
FreeStructure(*Batch)
|
||||
BakaShrot_Names_NoteDropped(*Client\PeerName, "topic", TopicRef, "not taken here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Topic '" + TopicRef + "' isn't replicated here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Topic '" + TopicRef + "' isn't replicated here")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_NodeByName(NodeRef)
|
||||
If Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef)
|
||||
FreeStructure(*Batch)
|
||||
BakaShrot_Names_NoteDropped(*Client\PeerName, "node", NodeRef, "not taken here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Node '" + NodeRef + "' isn't replicated here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Node '" + NodeRef + "' isn't replicated here")
|
||||
EndIf
|
||||
|
||||
; Taken by a wildcard, new here.
|
||||
@@ -989,7 +993,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
If TopicId < 0 Or NodeId < 0
|
||||
FreeStructure(*Batch)
|
||||
PrintN("[Net] Failed to add '" + TopicRef + "':'" + NodeRef + "' from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored")
|
||||
EndIf
|
||||
|
||||
MaxAge = RetentionMaxAgeMs(*Client\Retention(), TopicId, TopicRef)
|
||||
@@ -1003,7 +1007,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
EndIf
|
||||
If Not IsStored
|
||||
PrintN("[Net] Failed to store messages from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored")
|
||||
EndIf
|
||||
|
||||
Pushed\MessageId = LastMessageId
|
||||
@@ -1062,29 +1066,32 @@ Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, *
|
||||
FreeStructure(*Start)
|
||||
|
||||
If Not *Client\Permissions\Write
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write")
|
||||
EndIf
|
||||
If TopicRef = ""
|
||||
TopicId = *Client\Metadata\TopicId
|
||||
TopicId = *Client\Metadata\DefaultTopicId
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic")
|
||||
EndIf
|
||||
Else
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
|
||||
MaxSize = *Client\Server\Config\Server\MaxAttachmentSize
|
||||
If Size > MaxSize
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here")
|
||||
EndIf
|
||||
|
||||
BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError)
|
||||
If Not BlobId
|
||||
PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be started")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be started")
|
||||
EndIf
|
||||
|
||||
Started\UploadId = BlobId
|
||||
@@ -1120,23 +1127,23 @@ Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *
|
||||
; Only its own uploads: same node, a topic it may still push to.
|
||||
If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload in progress")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload in progress")
|
||||
EndIf
|
||||
If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId))
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
EndIf
|
||||
Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex)
|
||||
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes")
|
||||
EndIf
|
||||
|
||||
Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError)
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
If Received < 0
|
||||
PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored")
|
||||
EndIf
|
||||
|
||||
If Received < Blob\Size
|
||||
@@ -1146,10 +1153,10 @@ Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *
|
||||
; All of it: the SHA-256 given at the start must match.
|
||||
If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0])
|
||||
SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload doesn't match its SHA-256, it's dropped")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The upload doesn't match its SHA-256, it's dropped")
|
||||
EndIf
|
||||
If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be stored")
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||
EndProcedure
|
||||
@@ -1181,36 +1188,36 @@ Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient,
|
||||
FreeStructure(*Request)
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read")
|
||||
EndIf
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId))
|
||||
EndIf
|
||||
Select Attachment\State
|
||||
Case #BakaShrot_Attachment_NotKept
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize")
|
||||
Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotReady, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes")
|
||||
EndSelect
|
||||
If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts")
|
||||
EndIf
|
||||
|
||||
Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize)
|
||||
If Not Chunk\Data
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be read")
|
||||
EndIf
|
||||
Chunk\DataSize = DataSize\i
|
||||
Chunk\TopicId = TopicId
|
||||
@@ -1252,12 +1259,12 @@ Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShro
|
||||
FreeStructure(*Request)
|
||||
|
||||
If *Client\PeerName = ""
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
; More than one answer holds, some of them may be someone else's.
|
||||
If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing())
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The missing attachments couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The missing attachments couldn't be read")
|
||||
EndIf
|
||||
ForEach Missing()
|
||||
If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments
|
||||
@@ -1312,18 +1319,18 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
|
||||
If *Client\PeerName = ""
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
TopicId = BakaShrot_Names_TopicByName(TopicRef)
|
||||
NodeId = BakaShrot_Names_NodeByName(NodeRef)
|
||||
If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here")
|
||||
EndIf
|
||||
|
||||
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId))
|
||||
EndIf
|
||||
If Attachment\State = #BakaShrot_Attachment_Ready
|
||||
; Someone else's link was faster: done.
|
||||
@@ -1332,11 +1339,11 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
EndIf
|
||||
If Attachment\State = #BakaShrot_Attachment_NotKept
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here")
|
||||
EndIf
|
||||
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize))
|
||||
EndIf
|
||||
|
||||
BlobId = Attachment\BlobId
|
||||
@@ -1351,7 +1358,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
If Received < 0
|
||||
PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored")
|
||||
EndIf
|
||||
|
||||
If Received < Attachment\Size
|
||||
@@ -1360,11 +1367,11 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
|
||||
IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0])
|
||||
If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be stored")
|
||||
EndIf
|
||||
If Not IsValid
|
||||
PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment doesn't match its SHA-256, send it again")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The attachment doesn't match its SHA-256, send it again")
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||
EndProcedure
|
||||
|
||||
@@ -141,7 +141,7 @@ Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, Ans
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
PrintN("[Peer] '" + *Link\Name + "' refused: " + *Refused\Reason)
|
||||
PrintN("[Peer] '" + *Link\Name + "' refused (" + BakaShrot_ErrorName(*Refused\Code) + "): " + *Refused\Reason)
|
||||
FreeStructure(*Refused)
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
@@ -665,7 +665,6 @@ Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig)
|
||||
GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0])
|
||||
|
||||
; By name: the peer has its own ids for them.
|
||||
*Links\Identity\Topic = BakaShrot_Names_TopicRef(*Config\TopicId)
|
||||
*Links\Identity\Node = BakaShrot_Names_NodeRef(*Config\NodeId)
|
||||
*Links\Identity\PublicKey = EncodeKeyToString(@*Links\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
|
||||
*Links\Identity\PrivateKey = @*Links\PrivateKey[0]
|
||||
|
||||
+23
-3
@@ -52,8 +52,24 @@ EndStructure
|
||||
; Only while the workers are stopped, they use the config.
|
||||
Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root)
|
||||
Protected *Config.BakaShrot_CoreConfig
|
||||
Protected Known.BakaShrot_KnownNames, KnownError.String, DatabasePath.s, DbId.i
|
||||
|
||||
*Config = LoadConfig(*Root\ConfigPath)
|
||||
; The names the database has first, so the ones the config lists without
|
||||
; an id keep theirs (Storage/Names.pbi). Nothing to read on a new one.
|
||||
DatabasePath = ReadConfigDatabasePath(*Root\ConfigPath)
|
||||
If DatabasePath <> "" And FileSize(DatabasePath) > 0
|
||||
DbId = OpenStorageDatabase(DatabasePath)
|
||||
If Not DbId Or Not SetupStorageDatabase(DbId) Or Not BakaShrot_Names_ReadKnown(DbId, @Known, @KnownError)
|
||||
PrintN("[Root] Failed to read the names of the database '" + DatabasePath + "': " + KnownError\s + DatabaseError())
|
||||
If DbId
|
||||
CloseDatabase(DbId)
|
||||
EndIf
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
CloseDatabase(DbId)
|
||||
EndIf
|
||||
|
||||
*Config = LoadConfig(*Root\ConfigPath, @Known)
|
||||
If Not *Config
|
||||
PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError)
|
||||
ProcedureReturn #False
|
||||
@@ -64,7 +80,7 @@ Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root)
|
||||
EndIf
|
||||
*Root\Config = *Config
|
||||
|
||||
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Topic=" + *Config\TopicText + ", Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
|
||||
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
|
||||
Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)")
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
@@ -77,6 +93,10 @@ Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root)
|
||||
Protected DatabasePath.s = *Root\Config\Server\DatabasePath
|
||||
Protected NamesError.String
|
||||
|
||||
; Every connection opened from here on, the workers' included (they're
|
||||
; stopped meanwhile), takes it.
|
||||
BakaShrot_Storage_Synchronous = *Root\Config\Server\Synchronous
|
||||
|
||||
*Root\DbId = OpenStorageDatabase(DatabasePath)
|
||||
If Not *Root\DbId
|
||||
PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError())
|
||||
@@ -97,7 +117,7 @@ Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
PrintN("[Root] Database '" + DatabasePath + "' is ready")
|
||||
PrintN("[Root] Database '" + DatabasePath + "' is ready (synchronous " + BakaShrot_Storage_Synchronous + ")")
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
@@ -21,10 +21,16 @@
|
||||
; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can
|
||||
; join on them (the "messages" view), and in memory for the server, guarded
|
||||
; by BakaShrot_Names_Mutex. Every id in "data" has a row:
|
||||
; origin "config" named in [BakaShrot.Topics] / [BakaShrot.Nodes]
|
||||
; origin "config" named by the config: in [BakaShrot.Topics] /
|
||||
; [BakaShrot.Nodes], or a peer's or client's Node
|
||||
; origin "id" unnamed, its name is its id in digits
|
||||
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
|
||||
;
|
||||
; Ids are this server's to pick: a name the config lists without one keeps
|
||||
; the one these tables have for it, a new one gets the lowest free one
|
||||
; (LoadConfig(), after BakaShrot_Names_ReadKnown()). The config may still
|
||||
; pin one ("logs = 1").
|
||||
;
|
||||
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
|
||||
; on restart). The config wins, except when it would give a name to another
|
||||
; id than the one the database has it under (or rename a "peer" one): that
|
||||
@@ -219,6 +225,47 @@ Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.St
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Fills *Known with what the database has, for LoadConfig() (Config.pbi):
|
||||
; the id of every name, and every id with a row or messages. Before the
|
||||
; config is loaded, on a connection of its own, the database set up.
|
||||
; Returns #False with the reason in *Error\s.
|
||||
Procedure.i BakaShrot_Names_ReadKnown(DbId.i, *Known.BakaShrot_KnownNames, *Error.String)
|
||||
Protected Name.s, Id.i
|
||||
|
||||
; Topics
|
||||
If Not DatabaseQuery(DbId, "SELECT topic_id, name FROM topics UNION SELECT DISTINCT topic_id, '' FROM node_heads")
|
||||
*Error\s = "can't read the topics: " + DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
While NextDatabaseRow(DbId)
|
||||
Id = GetDatabaseLong(DbId, 0)
|
||||
Name = GetDatabaseString(DbId, 1)
|
||||
*Known\TopicUsed(Str(Id)) = #True
|
||||
If Name <> "" And Not BakaShrot_IsDigits(Name)
|
||||
*Known\TopicIds(LCase(Name)) = Id
|
||||
EndIf
|
||||
Wend
|
||||
FinishDatabaseQuery(DbId)
|
||||
|
||||
; Nodes
|
||||
If Not DatabaseQuery(DbId, "SELECT node_id, name FROM nodes UNION SELECT DISTINCT node_id, '' FROM node_heads")
|
||||
*Error\s = "can't read the nodes: " + DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
While NextDatabaseRow(DbId)
|
||||
Id = GetDatabaseLong(DbId, 0)
|
||||
Name = GetDatabaseString(DbId, 1)
|
||||
*Known\NodeUsed(Str(Id)) = #True
|
||||
If Name <> "" And Not BakaShrot_IsDigits(Name)
|
||||
*Known\NodeIds(LCase(Name)) = Id
|
||||
EndIf
|
||||
Wend
|
||||
FinishDatabaseQuery(DbId)
|
||||
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
; --- Lookups -----------------------------------------------------------------
|
||||
|
||||
; The id Ref stands for: an id in digits is that id, a name must be known.
|
||||
|
||||
+44
-14
@@ -3,7 +3,7 @@
|
||||
;
|
||||
; Opens the SQLite database file that backs the node's local storage, and
|
||||
; provides the basic read/write operations on top of it.
|
||||
; Schema: see db_schema_v7.dbml in this same folder. Attachments: see
|
||||
; Schema: see db_schema_v8.dbml in this same folder. Attachments: see
|
||||
; Attachments.pbi and Design/Attachments.md.
|
||||
;
|
||||
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
|
||||
@@ -37,7 +37,7 @@ CompilerElse
|
||||
CompilerEndIf
|
||||
|
||||
|
||||
; One row of the "data" table (see db_schema_v7.dbml).
|
||||
; One row of the "data" table (see db_schema_v8.dbml).
|
||||
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
|
||||
; AttachmentSize: its attachment's size, 0 for none (the "attachments"
|
||||
; table), AttachmentReady #True once all of it is here, AttachmentSha256 its
|
||||
@@ -82,15 +82,18 @@ EndProcedure
|
||||
; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in
|
||||
; the file): readers and the writer don't block each other anymore, so a
|
||||
; long raw query no longer stalls every push.
|
||||
; With WAL, NORMAL only syncs to disk at checkpoints instead of on every
|
||||
; commit, which is most of what a push used to cost. The database can't get
|
||||
; corrupted, but the last commits before a power loss or an OS crash (not a
|
||||
; crash of the server itself) can be lost. Those messages were acknowledged,
|
||||
; and maybe replicated already, so their ids could then be handed out again
|
||||
; for other messages: drift, see Design/ReplicationIssues.md #1.
|
||||
; FULL syncs every commit, like before, but still lets reads and writes run
|
||||
; side by side.
|
||||
#BakaShrot_Storage_Synchronous = "NORMAL"
|
||||
; PRAGMA synchronous of every connection: [BakaShrot.Server] Synchronous,
|
||||
; set by the root before it opens any (Server/Root.pbi). FULL by default.
|
||||
; FULL syncs the WAL on every commit: an acknowledged push is on disk. It
|
||||
; costs one flush per transaction, shared by a group commit's pushes.
|
||||
; NORMAL only syncs at checkpoints (about every second, Writer.pbi): the
|
||||
; database can't get corrupted, but the last commits before a power loss or
|
||||
; an OS crash (not a crash of the server itself) can be lost. Those messages
|
||||
; were acknowledged, and maybe replicated already, so their ids could then
|
||||
; be handed out again for other messages: drift, see
|
||||
; Design/ReplicationIssues.md #1. Measured: Design/StorageConcurrency.md.
|
||||
#BakaShrot_Storage_DefaultSynchronous = "FULL"
|
||||
Global BakaShrot_Storage_Synchronous.s = #BakaShrot_Storage_DefaultSynchronous
|
||||
|
||||
|
||||
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
|
||||
@@ -120,8 +123,8 @@ Procedure.i OpenStorageDatabase(DatabasePath.s)
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
; Per connection, see #BakaShrot_Storage_Synchronous.
|
||||
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + #BakaShrot_Storage_Synchronous)
|
||||
; Per connection, see BakaShrot_Storage_Synchronous.
|
||||
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + BakaShrot_Storage_Synchronous)
|
||||
CloseDatabase(DbId)
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
@@ -232,7 +235,7 @@ Procedure.i MigrateStoragePushedAt(DbId.i)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Creates the tables and indexes described by db_schema_v7.dbml, if they
|
||||
; Creates the tables and indexes described by db_schema_v8.dbml, if they
|
||||
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
|
||||
; upgrade mechanism (DbUpdater) will replace this later.
|
||||
; Fails on a database made with an older schema, since it would be left as is.
|
||||
@@ -430,6 +433,33 @@ Procedure.i SetupStorageDatabase(DbId.i)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; For browsing with a database tool: set browse's one row to a topic
|
||||
; (and optionally a node), open browse_messages. The foreign keys are
|
||||
; only there for the tools: SQLiteStudio shows a dropdown of the names
|
||||
; for a column that references them. The server never turns foreign keys
|
||||
; on, so they never get in its way (a topic renamed in the config only
|
||||
; leaves a stale name here). The server never writes to browse either.
|
||||
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS browse (" +
|
||||
"id INTEGER PRIMARY KEY CHECK (id = 1), " +
|
||||
"topic TEXT COLLATE NOCASE REFERENCES topics (name), " +
|
||||
"node TEXT COLLATE NOCASE REFERENCES nodes (name))") Or
|
||||
Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO browse (id) VALUES (1)")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; Newest first, by the (topic_id, pushed_at) index. Made again on every
|
||||
; start, like messages.
|
||||
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS browse_messages") Or
|
||||
Not DatabaseUpdate(DbId, "CREATE VIEW browse_messages AS " +
|
||||
"SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, " +
|
||||
"a.size AS attachment_size, m.topic " +
|
||||
"FROM browse b JOIN messages m ON m.topic = b.topic " +
|
||||
"LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id AND a.message_id = m.message_id " +
|
||||
"WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) " +
|
||||
"ORDER BY m.pushed_at DESC, m.node, m.message_id DESC")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Changes from v7:
|
||||
// - browse: one row (id 1), the topic and optionally the node to browse,
|
||||
// referencing topics and nodes by name so database tools (SQLiteStudio)
|
||||
// show a dropdown of them. Never written by the server, its foreign keys
|
||||
// never turned on by it.
|
||||
// - browse_messages: the view of what browse selects, newest first.
|
||||
// - The origins of topics and nodes: "config" also covers the nodes the
|
||||
// config's sections define, "peer" the names peers sent (AcceptTopics /
|
||||
// AcceptNodes wildcards).
|
||||
//
|
||||
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
|
||||
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
|
||||
|
||||
table data {
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
message_id integer [not null]
|
||||
message_data text [not null]
|
||||
|
||||
// 1 if message_data is well-formed JSON, 0 otherwise.
|
||||
// Can't be written, SQLite computes it on insert and stores it.
|
||||
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
|
||||
|
||||
// When it was pushed to its origin, ms since 1970-01-01 UTC.
|
||||
pushed_at integer [not null, default: 0]
|
||||
|
||||
indexes {
|
||||
(topic_id, node_id, message_id) [unique]
|
||||
message_id
|
||||
(topic_id, pushed_at)
|
||||
}
|
||||
}
|
||||
|
||||
// One row per topic/node id that has ever had messages: deleting messages
|
||||
// (the retention) leaves it as is, so ids never go back.
|
||||
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
|
||||
// max_message_id = MAX(max_message_id, excluded.max_message_id)
|
||||
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
|
||||
table node_heads [note: 'WITHOUT ROWID'] {
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
max_message_id integer [not null]
|
||||
|
||||
indexes {
|
||||
(topic_id, node_id) [pk]
|
||||
}
|
||||
}
|
||||
|
||||
// A message's attachment (Design/Attachments.md). Its size and SHA-256 come
|
||||
// with it (pushed, or replicated), its data in blob_id once any is here.
|
||||
// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready,
|
||||
// 3 not kept (bigger than this server's MaxAttachmentSize).
|
||||
// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its
|
||||
// blob to delete (state 3).
|
||||
table attachments [note: 'WITHOUT ROWID'] {
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
message_id integer [not null]
|
||||
size integer [not null]
|
||||
sha256 blob [not null]
|
||||
blob_id integer
|
||||
state integer [not null]
|
||||
|
||||
indexes {
|
||||
(topic_id, node_id, message_id) [pk]
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
// The data of one attachment, being received (an upload, or replicated) or
|
||||
// stored. topic_id, node_id: an upload's owner, or the message's pair.
|
||||
// received: bytes stored so far. created_at: ms since 1970 UTC, an upload
|
||||
// not pushed with its message within UploadTimeout is deleted.
|
||||
// state: 0 receiving, 1 complete (an upload waiting for its message),
|
||||
// 2 attached, 3 to delete.
|
||||
table blobs {
|
||||
blob_id integer [pk]
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
size integer [not null]
|
||||
sha256 blob [not null]
|
||||
received integer [not null, default: 0]
|
||||
state integer [not null]
|
||||
created_at integer [not null]
|
||||
|
||||
indexes {
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one
|
||||
// what's left.
|
||||
table blob_chunks {
|
||||
blob_id integer [not null]
|
||||
chunk_index integer [not null]
|
||||
chunk_data blob [not null]
|
||||
|
||||
indexes {
|
||||
(blob_id, chunk_index) [pk]
|
||||
}
|
||||
}
|
||||
|
||||
// origin: "config" (named in [BakaShrot.Topics]), "peer" (taken from a
|
||||
// peer by a wildcard), "id" (unnamed, name is the id in digits).
|
||||
table topics {
|
||||
topic_id integer [pk]
|
||||
name text [not null, unique, note: 'COLLATE NOCASE']
|
||||
origin text [not null]
|
||||
}
|
||||
|
||||
// origin: "config" (named in [BakaShrot.Nodes], or a node the config's
|
||||
// [BakaShrot], peer or client sections define), "peer" (taken from a peer:
|
||||
// AcceptNodes is * by default), "id" (unnamed).
|
||||
table nodes {
|
||||
node_id integer [pk]
|
||||
name text [not null, unique, note: 'COLLATE NOCASE']
|
||||
origin text [not null]
|
||||
}
|
||||
|
||||
// View messages:
|
||||
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
|
||||
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
|
||||
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
|
||||
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
|
||||
// JOIN nodes n ON n.node_id = d.node_id
|
||||
// WHERE topic = ... AND node = ... goes through the name indexes, then
|
||||
// data's (topic_id, node_id, message_id) one.
|
||||
|
||||
// What to browse with a database tool: set topic (and node, NULL for every
|
||||
// one) in its one row, open browse_messages. The references are for the
|
||||
// tools' dropdowns only: the server doesn't turn foreign keys on.
|
||||
table browse {
|
||||
id integer [pk, note: 'CHECK (id = 1)']
|
||||
topic text [ref: > topics.name, note: 'COLLATE NOCASE']
|
||||
node text [ref: > nodes.name, note: 'COLLATE NOCASE']
|
||||
}
|
||||
|
||||
// View browse_messages:
|
||||
// SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json,
|
||||
// a.size AS attachment_size, m.topic
|
||||
// FROM browse b JOIN messages m ON m.topic = b.topic
|
||||
// LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id
|
||||
// AND a.message_id = m.message_id
|
||||
// WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node)
|
||||
// ORDER BY m.pushed_at DESC, m.node, m.message_id DESC
|
||||
|
||||
// Note, ignore it
|
||||
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
|
||||
@@ -51,7 +51,6 @@ Procedure.i ConnectIni(*Client.EdgeClient, IniPath.s)
|
||||
Ok = DecodeKeyFromString(ReadPreferenceString("PrivateKey", ""), @*Client\PrivateKey[0], #BakaShrot_Ed25519_PrivateKeySize)
|
||||
Ok = Bool(Ok And DecodeKeyFromString(ReadPreferenceString("ServerPublicKey", ""), @*Client\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize))
|
||||
*Client\Identity\PublicKey = ReadPreferenceString("PublicKey", "")
|
||||
*Client\Identity\Topic = ReadPreferenceString("Topic", "")
|
||||
*Client\Identity\Node = ReadPreferenceString("Node", "")
|
||||
*Client\Identity\PrivateKey = @*Client\PrivateKey[0]
|
||||
Host = ReadPreferenceString("ServerHost", "127.0.0.1")
|
||||
|
||||
@@ -26,7 +26,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||
$Fails = 0
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -71,7 +71,7 @@ function Wait-Port($Port, $S) {
|
||||
}
|
||||
function Query($Sql, $Ini) {
|
||||
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||
Tool "Query.exe" @("@$F", $Ini)
|
||||
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
|
||||
}
|
||||
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
|
||||
$D = (Get-Date).AddSeconds($Seconds)
|
||||
@@ -87,7 +87,7 @@ function Push($Data, $Ini, [string]$Attach = "") {
|
||||
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
|
||||
$A = @()
|
||||
if ($Attach) { $A += @("-a", $Attach) }
|
||||
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
|
||||
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
|
||||
}
|
||||
function New-File($Name, [int64]$Size, [int]$Seed) {
|
||||
$P = Join-Path $Dir $Name
|
||||
@@ -112,7 +112,6 @@ foreach ($Name in "a", "b") {
|
||||
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($Me.Priv)
|
||||
Topic = logs
|
||||
Node = server$Name
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -140,24 +139,26 @@ UploadTimeout = 10
|
||||
[BakaShrot.Peer.$PeerName]
|
||||
Host = 127.0.0.1
|
||||
Port = $PeerPort
|
||||
Topic = logs
|
||||
Node = server$PeerName
|
||||
PublicKey = $($Peer.Pub)
|
||||
|
||||
[BakaShrot.Client.$PeerName]
|
||||
PublicKeys = $($Peer.Pub)
|
||||
Identities = logs:server$PeerName
|
||||
Node = server$PeerName
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;other;secret
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
|
||||
[BakaShrot.Client.garage]
|
||||
PublicKeys = $($G.Pub)
|
||||
Identities = logs:garage
|
||||
Node = garage
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs
|
||||
ReadTopics = logs
|
||||
"@
|
||||
@@ -165,7 +166,7 @@ ReadTopics = logs
|
||||
$ServerKeys = @{ 12413 = $A.Pub; 12414 = $B.Pub }
|
||||
function Client-Ini($Name, $Keys, $Node, $Port) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
$P
|
||||
}
|
||||
$KitchenA = Client-Ini "kitchen-a" $K "kitchen" 12413
|
||||
@@ -223,7 +224,7 @@ try {
|
||||
$Copy = Join-Path $Dir "big-from-b.bin"
|
||||
$D = (Get-Date).AddSeconds(90)
|
||||
do {
|
||||
$R = Tool "GetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
|
||||
$R = Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BigId, $Copy, $KitchenB)
|
||||
if ($R.Code -eq 0) { break }
|
||||
Start-Sleep -Milliseconds 500
|
||||
} while ((Get-Date) -lt $D)
|
||||
@@ -260,7 +261,7 @@ db.commit(); print("flipped")
|
||||
$SA = Start-Srv "a"
|
||||
Wait-Port 12413 $SA
|
||||
$Copy = Join-Path $Dir "bad-from-a.bin"
|
||||
Expect "reading it from A: the client refuses it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1
|
||||
Expect "reading it from A: the client refuses it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenA)) "doesn't match its SHA-256" 1
|
||||
Check " and leaves no file" (-not (Test-Path $Copy)) "checked"
|
||||
$SB = Start-Srv "b"
|
||||
Wait-Port 12414 $SB
|
||||
@@ -268,7 +269,7 @@ db.commit(); print("flipped")
|
||||
$LogB = Get-Content $SB.Log -Raw
|
||||
$Drops = [regex]::Matches($LogB, "attachment of logs:kitchen#$BadId from peer 'a' doesn't match its SHA-256, dropped").Count
|
||||
Check "B drops it: doesn't match" ($Drops -ge 1) "$Drops times in 6 s"
|
||||
Expect "B doesn't serve it" (Tool "GetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1
|
||||
Expect "B doesn't serve it" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", $BadId, $Copy, $KitchenB)) "isn't here yet" 1
|
||||
$R = Query "SELECT a.state, COALESCE(a.blob_id, 0) FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' AND a.message_id = $BadId" $KitchenB
|
||||
Check "B's attachment is back to missing (0), no blob" ($R.Out -match '\[\["0","0"\]\]') $R.Out
|
||||
Expect "B: no blob left behind, once cleaned" (Wait-Query "SELECT COUNT(*) FROM blobs WHERE state <> 2" $KitchenB '\[\["0"\]\]' 5) '\[\["0"\]\]'
|
||||
@@ -280,7 +281,9 @@ finally {
|
||||
}
|
||||
|
||||
"--- Logs"
|
||||
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -match "invalid|unexpected|doesn't decrypt" }
|
||||
# Refusals are what this test asks for, their codes' names (InvalidRequest)
|
||||
# aren't bad packets.
|
||||
$All = (Get-ChildItem $Dir -Filter "*.log" | ForEach-Object { Get-Content $_.FullName }) | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|doesn't decrypt" }
|
||||
Check "no invalid or unexpected packets in any log" ($All.Count -eq 0) ($All -join " / ")
|
||||
|
||||
""
|
||||
|
||||
+22
-22
@@ -1,5 +1,5 @@
|
||||
# End-to-end test of attachments (Design/Attachments.md), through the tools
|
||||
# (PushMessage -a, GetAttachment, GetLatestMessage):
|
||||
# (BakaShrotPushMessage -a, BakaShrotGetAttachment, BakaShrotGetLatestMessage):
|
||||
# - pushed with a message, read back identical (100 KB, 5 MB + a bit,
|
||||
# exactly 2 MB: one part, several, a whole number of them);
|
||||
# - a message without one: refused when asked for it;
|
||||
@@ -21,7 +21,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||
$Fails = 0
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -62,7 +62,7 @@ function Wait-Port($Port, $S) {
|
||||
}
|
||||
function Query($Sql, $Ini) {
|
||||
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||
Tool "Query.exe" @("@$F", $Ini)
|
||||
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
|
||||
}
|
||||
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
|
||||
$D = (Get-Date).AddSeconds($Seconds)
|
||||
@@ -79,7 +79,7 @@ function Push($Data, $Ini, [string]$Topic = "", [string]$Attach = "") {
|
||||
$A = @()
|
||||
if ($Topic) { $A += @("-t", $Topic) }
|
||||
if ($Attach) { $A += @("-a", $Attach) }
|
||||
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
|
||||
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
|
||||
}
|
||||
# A file of Size random bytes.
|
||||
function New-File($Name, [int]$Size, [int]$Seed) {
|
||||
@@ -93,16 +93,16 @@ function Hash($Path) { if (Test-Path $Path) { (Get-FileHash $Path -Algorithm SHA
|
||||
# Saves an attachment and compares it with the original.
|
||||
function Expect-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini) {
|
||||
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
|
||||
$R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
|
||||
$R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
|
||||
$Same = ($R.Code -eq 0) -and ((Hash $Out) -eq (Hash $Original))
|
||||
Check $What $Same ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
}
|
||||
# Retries GetAttachment until it works: replicated ones come after their message.
|
||||
# Retries BakaShrotGetAttachment until it works: replicated ones come after their message.
|
||||
function Wait-Same([string]$What, $Topic, $Node, $Id, $Original, $Ini, $Seconds = 20) {
|
||||
$Out = Join-Path $Dir ("got-" + [guid]::NewGuid().ToString("N") + ".bin")
|
||||
$D = (Get-Date).AddSeconds($Seconds)
|
||||
do {
|
||||
$R = Tool "GetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
|
||||
$R = Tool "BakaShrotGetAttachment.exe" @($Topic, $Node, "$Id", $Out, $Ini)
|
||||
if ($R.Code -eq 0) { break }
|
||||
Start-Sleep -Milliseconds 250
|
||||
} while ((Get-Date) -lt $D)
|
||||
@@ -114,7 +114,6 @@ $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
|
||||
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($A.Priv)
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -144,17 +143,18 @@ MaxAttachmentSize = 64M
|
||||
[BakaShrot.Peer.b]
|
||||
Host = 127.0.0.1
|
||||
Port = 12411
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
PublicKey = $($B.Pub)
|
||||
|
||||
[BakaShrot.Client.b]
|
||||
PublicKeys = $($B.Pub)
|
||||
Identities = logs:serverB
|
||||
Node = serverB
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;short
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
@@ -163,7 +163,6 @@ AllowQuery = 1
|
||||
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($B.Priv)
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -190,17 +189,18 @@ MaxAttachmentSize = 3M
|
||||
[BakaShrot.Peer.a]
|
||||
Host = 127.0.0.1
|
||||
Port = 12410
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
PublicKey = $($A.Pub)
|
||||
|
||||
[BakaShrot.Client.a]
|
||||
PublicKeys = $($A.Pub)
|
||||
Identities = logs:serverA
|
||||
Node = serverA
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.garage]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = photos:garage
|
||||
Node = garage
|
||||
DefaultTopic = photos
|
||||
PushTopics = photos
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
@@ -209,7 +209,7 @@ AllowQuery = 1
|
||||
$ServerKeys = @{ 12410 = $A.Pub; 12411 = $B.Pub }
|
||||
function Client-Ini($Name, $Topic, $Node, $Port) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = $Topic`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
$P
|
||||
}
|
||||
$OnA = Client-Ini "kitchen-a" "logs" "kitchen" 12410
|
||||
@@ -241,10 +241,10 @@ try {
|
||||
Check "5 MB up and down, tool start included" $true ("{0:N0} ms up, {1:N0} ms down" -f $UploadMs, $DownloadMs)
|
||||
Expect-Same "#3 read back identical" "logs" "kitchen" 3 $Exact $OnA
|
||||
Expect-Same "#4 read back identical" "logs" "kitchen" 4 $Tiny $OnA
|
||||
Expect "#5 has none: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1
|
||||
Expect "#5 has none: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "5", (Join-Path $Dir "none.bin"), $OnA)) "No attachment for logs:kitchen#5" 1
|
||||
Check "a refused one leaves no file" (-not (Test-Path (Join-Path $Dir "none.bin"))) "checked"
|
||||
Expect "a message that doesn't exist: refused" (Tool "GetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1
|
||||
Expect "GetLatestMessage: #5, no attachment line" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$"
|
||||
Expect "a message that doesn't exist: refused" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "99", (Join-Path $Dir "none.bin"), $OnA)) "No attachment" 1
|
||||
Expect "BakaShrotGetLatestMessage: #5, no attachment line" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) "#5 \(ids 1:2\), pushed [^|]+\| \{`"n`":5\}$"
|
||||
$R = Query "SELECT message_id, size, state FROM attachments WHERE topic_id = 1 AND node_id = 2 ORDER BY message_id" $OnA
|
||||
Check "A's attachments: 4, all ready (2)" ($R.Out -match '\[\["1","102400","2"\],\["2","5243003","2"\],\["3","2097152","2"\],\["4","1","2"\]\]') $R.Out
|
||||
Expect "A stores 6 + 2 + 1 + 1 parts" (Query "SELECT COUNT(*) FROM blob_chunks" $OnA) '\[\["10"\]\]'
|
||||
@@ -255,16 +255,16 @@ try {
|
||||
Wait-Same "B: #1 identical" "logs" "kitchen" 1 $Small $OnB
|
||||
Wait-Same "B: #3 identical (2 MB)" "logs" "kitchen" 3 $Exact $OnB
|
||||
Wait-Same "B: #4 identical (1 byte)" "logs" "kitchen" 4 $Tiny $OnB
|
||||
Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "GetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1
|
||||
Expect "B: #2 isn't kept (5 MB > 3M)" (Tool "BakaShrotGetAttachment.exe" @("logs", "kitchen", "2", (Join-Path $Dir "none.bin"), $OnB)) "isn't kept here" 1
|
||||
$R = Query "SELECT a.message_id, a.state FROM attachments a JOIN topics t ON t.topic_id = a.topic_id WHERE t.name = 'logs' ORDER BY a.message_id" $OnB
|
||||
Check "B's attachments: ready, not kept (3), ready, ready" ($R.Out -match '\[\["1","2"\],\["2","3"\],\["3","2"\],\["4","2"\]\]') $R.Out
|
||||
Expect "B: GetLatestMessage logs:kitchen, #5 has none" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}"
|
||||
Expect "B: BakaShrotGetLatestMessage logs:kitchen, #5 has none" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) "#5 \(ids 300:30\), pushed [^|]+\| \{`"n`":5\}"
|
||||
|
||||
"--- Pushed on B, too big there, then replicated to A"
|
||||
Expect "B refuses 5 MB (more than 3M)" (Push '{"photo":0}' $OnB "" $Mid) "too big: 5243003 bytes, at most 3145728" 1
|
||||
Expect "the message wasn't stored: the next is #1" (Push '{"photo":1}' $OnB "" $Small) "message #1, with an attachment"
|
||||
Wait-Same "A got B's photos:garage#1 identical" "photos" "garage" 1 $Small $OnA
|
||||
Expect "A: the latest of photos:garage" (Tool "GetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}"
|
||||
Expect "A: the latest of photos:garage" (Tool "BakaShrotGetLatestMessage.exe" @("photos", "garage", $OnA)) "Attachment: 102400 bytes \| \{`"photo`":1\}"
|
||||
|
||||
"--- Deleted with their message (A: short = 4s)"
|
||||
$Before = (Query "SELECT COUNT(*) FROM blob_chunks" $OnA).Out
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
# powershell -ExecutionPolicy Bypass -File Tests\Bench\Bench-Replication.ps1
|
||||
# ... -Ramp "5x20,10x50" -SeedTotals @() -PushSeconds 10 quick run
|
||||
# ... -Topology Mesh -PeerSyncInterval 1 variations
|
||||
# ... -Synchronous NORMAL the servers' Synchronous (FULL by default)
|
||||
# ... -Names Wildcard each server only names its own nodes, and
|
||||
# takes the others' by AcceptNodes = n*
|
||||
# ... -Parts Ramp only part 1
|
||||
@@ -62,6 +63,10 @@ param(
|
||||
[int]$PushSeconds = 30,
|
||||
[int]$PeerSyncInterval = 5,
|
||||
[int]$PeerBatchSize = 100,
|
||||
# The servers' [BakaShrot.Server] Synchronous: FULL like their default,
|
||||
# NORMAL to compare with the runs from before 2026-11-09.
|
||||
[ValidateSet("FULL", "NORMAL")]
|
||||
[string]$Synchronous = "FULL",
|
||||
[int]$PortBase = 13001,
|
||||
[string]$Ramp = "5x5,5x20,5x50,5x100,5x0,10x20,10x50,10x100,10x0",
|
||||
[int[]]$SeedTotals = @(250000, 1000000),
|
||||
@@ -138,7 +143,7 @@ function Invoke-Build {
|
||||
@("Tests\Bench\BenchServer.pb", "BenchServer.exe", @("/CONSOLE", "/THREAD")),
|
||||
@("Tests\Bench\BenchClient.pb", "BenchClient.exe", @("/CONSOLE", "/THREAD")),
|
||||
@("Tests\Bench\BenchSeed.pb", "BenchSeed.exe", @("/CONSOLE")),
|
||||
@("Tools\KeyGen\KeyGen.pb", "KeyGen.exe", @("/CONSOLE")))) {
|
||||
@("Tools\BakaShrotGenerateKeyPairs\BakaShrotGenerateKeyPairs.pb", "BakaShrotGenerateKeyPairs.exe", @("/CONSOLE")))) {
|
||||
Write-Host "Compiling $($Item[0])"
|
||||
$Flags = $Item[2] + $Extra
|
||||
& $Pb (Join-Path $Root $Item[0]) @Flags /QUIET $OutputFlag (Join-Path $OutDir $Item[1])
|
||||
@@ -147,8 +152,8 @@ function Invoke-Build {
|
||||
}
|
||||
|
||||
function New-KeyPair {
|
||||
$Lines = & (Join-Path $OutDir "KeyGen.exe")
|
||||
if ($LASTEXITCODE -ne 0) { throw "KeyGen failed: $Lines" }
|
||||
$Lines = & (Join-Path $OutDir "BakaShrotGenerateKeyPairs.exe")
|
||||
if ($LASTEXITCODE -ne 0) { throw "BakaShrotGenerateKeyPairs failed: $Lines" }
|
||||
return @{
|
||||
PrivateKey = $Lines[0] -replace "^PrivateKey = ", ""
|
||||
PublicKey = $Lines[1] -replace "^PublicKey = ", ""
|
||||
@@ -203,7 +208,17 @@ function New-Servers {
|
||||
|
||||
function Write-ServerConfig($Server, $Servers, $ClientKeys) {
|
||||
$LastNode = $Server.FirstNode + $MaxNodesPerServer - 1
|
||||
$Identities = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { "${TopicId}:$_" }) -join ";"
|
||||
# The bench's one key writes as every node: a client section per node.
|
||||
$ClientSections = (@($Server.FirstNode..$LastNode) + @($Server.MonitorNode, $Server.QueryNode) | ForEach-Object { @"
|
||||
[BakaShrot.Client.bench$_]
|
||||
PublicKeys = $($ClientKeys.PublicKey)
|
||||
Node = $_
|
||||
DefaultTopic = $TopicId
|
||||
AllowRead = 1
|
||||
AllowWrite = 1
|
||||
AllowQuery = 1
|
||||
|
||||
"@ }) -join "`r`n"
|
||||
|
||||
# Only named topics and nodes replicate, and they must be named on both
|
||||
# ends (Declared): every server names every node of every server, with
|
||||
@@ -224,7 +239,6 @@ function Write-ServerConfig($Server, $Servers, $ClientKeys) {
|
||||
$Text = @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($Server.PrivateKey)
|
||||
Topic = $TopicId
|
||||
Node = $($Server.NodeId)
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -241,14 +255,9 @@ DatabasePath = $($Server.DatabasePath)
|
||||
PeerRetryDelay = 2
|
||||
PeerSyncInterval = $PeerSyncInterval
|
||||
PeerBatchSize = $PeerBatchSize
|
||||
Synchronous = $Synchronous
|
||||
|
||||
[BakaShrot.Client.bench]
|
||||
PublicKeys = $($ClientKeys.PublicKey)
|
||||
Identities = $Identities
|
||||
AllowRead = 1
|
||||
AllowWrite = 1
|
||||
AllowQuery = 1
|
||||
|
||||
$ClientSections
|
||||
"@
|
||||
foreach ($PeerIndex in $Server.Peers) {
|
||||
$Peer = $Servers[$PeerIndex]
|
||||
@@ -256,14 +265,13 @@ AllowQuery = 1
|
||||
[BakaShrot.Peer.$($Peer.Name)]
|
||||
Host = 127.0.0.1
|
||||
Port = $($Peer.Port)
|
||||
Topic = $TopicId
|
||||
Node = $($Peer.NodeId)
|
||||
PublicKey = $($Peer.PublicKey)
|
||||
$(if ($Names -eq "Wildcard") { "AcceptNodes = n*" })
|
||||
|
||||
[BakaShrot.Client.$($Peer.Name)]
|
||||
PublicKeys = $($Peer.PublicKey)
|
||||
Identities = ${TopicId}:$($Peer.NodeId)
|
||||
Node = $($Peer.NodeId)
|
||||
AllowRead = 0
|
||||
AllowWrite = 0
|
||||
AllowQuery = 0
|
||||
|
||||
@@ -35,7 +35,7 @@
|
||||
; FirstNode, MaxNodes Its nodes are FirstNode to FirstNode+MaxNodes-1,
|
||||
; all of them are monitored.
|
||||
; NodeCount How many of them push in this stage, from FirstNode.
|
||||
; MonitorNode, QueryNode Identities used by the sampler and the queries.
|
||||
; MonitorNode, QueryNode Nodes used by the sampler and the queries.
|
||||
; QueryLoad, Query 0/1, see above.
|
||||
;
|
||||
; Query file: one query per line, "Name | SQL", # starts a comment.
|
||||
@@ -312,7 +312,6 @@ EndProcedure
|
||||
Procedure.i Bench_Connect(*Outbound.BakaShrot_Outbound, *Server.BenchServer, NodeId.i)
|
||||
Protected Identity.BakaShrot_OutboundIdentity
|
||||
|
||||
Identity\Topic = Str(Bench_TopicId)
|
||||
Identity\Node = Str(NodeId)
|
||||
Identity\PublicKey = Bench_PublicKey
|
||||
Identity\PrivateKey = @Bench_PrivateKey(0)
|
||||
|
||||
+25
-25
@@ -21,7 +21,7 @@ $MaxPacketSize = 16 * 1024 * 1024
|
||||
$MaxMessageSize = $MaxPacketSize - 4096
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -63,7 +63,7 @@ function Wait-Port($Port, $S) {
|
||||
}
|
||||
function Query($Sql, $Ini) {
|
||||
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||
Tool "Query.exe" @("@$F", $Ini)
|
||||
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
|
||||
}
|
||||
# Waits until Sql answers something matching Pattern, for up to Seconds.
|
||||
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) {
|
||||
@@ -75,7 +75,7 @@ function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 30) {
|
||||
} while ((Get-Date) -lt $D)
|
||||
$R
|
||||
}
|
||||
# A JSON message of exactly Size bytes, in a file, as PushMessage's @File.
|
||||
# A JSON message of exactly Size bytes, in a file, as BakaShrotPushMessage's @File.
|
||||
function New-Message($Name, [int]$Size) {
|
||||
$P = Join-Path $Dir "$Name.json"
|
||||
$Head = '{"n":"' + $Name + '","pad":"'
|
||||
@@ -112,7 +112,6 @@ $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
|
||||
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($A.Priv)
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -134,17 +133,18 @@ PeerRetryDelay = 1
|
||||
[BakaShrot.Peer.b]
|
||||
Host = 127.0.0.1
|
||||
Port = 12404
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
PublicKey = $($B.Pub)
|
||||
|
||||
[BakaShrot.Client.b]
|
||||
PublicKeys = $($B.Pub)
|
||||
Identities = logs:serverB
|
||||
Node = serverB
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
"@
|
||||
@@ -152,7 +152,6 @@ AllowQuery = 1
|
||||
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($B.Priv)
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -174,17 +173,18 @@ PeerRetryDelay = 1
|
||||
[BakaShrot.Peer.a]
|
||||
Host = 127.0.0.1
|
||||
Port = 12403
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
PublicKey = $($A.Pub)
|
||||
|
||||
[BakaShrot.Client.a]
|
||||
PublicKeys = $($A.Pub)
|
||||
Identities = logs:serverA
|
||||
Node = serverA
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
"@
|
||||
@@ -192,7 +192,7 @@ AllowQuery = 1
|
||||
$ServerKeys = @{ 12403 = $A.Pub; 12404 = $B.Pub }
|
||||
function Client-Ini($Name, $Port) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
$P
|
||||
}
|
||||
$OnA = Client-Ini "kitchen-a" 12403
|
||||
@@ -222,15 +222,15 @@ try {
|
||||
$Id = 0
|
||||
foreach ($N in $Sizes.Keys) {
|
||||
$Id++
|
||||
$T = Measure-Command { $R = Tool "PushMessage.exe" @($Files[$N], $OnA) }
|
||||
$T = Measure-Command { $R = Tool "BakaShrotPushMessage.exe" @($Files[$N], $OnA) }
|
||||
Expect ("push of {0:N0} bytes ({1:N0} ms)" -f $Sizes[$N], $T.TotalMilliseconds) $R "message #$Id"
|
||||
}
|
||||
Expect "a push 1 byte over the cap is refused" (Tool "PushMessage.exe" @($Over, $OnA)) "too big" 1
|
||||
Expect "a push 1 byte over the cap is refused" (Tool "BakaShrotPushMessage.exe" @($Over, $OnA)) "too big" 1
|
||||
$Id++
|
||||
Expect "a small push after them" (Tool "PushMessage.exe" @($Small, $OnA)) "message #$Id"
|
||||
Expect "a small push after them" (Tool "BakaShrotPushMessage.exe" @($Small, $OnA)) "message #$Id"
|
||||
|
||||
"--- Read back"
|
||||
$T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 }
|
||||
$T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnA 2>&1 }
|
||||
$Code = $LASTEXITCODE
|
||||
Check "latest is the small one" ($Code -eq 0 -and ($O -join "") -match '"n":"small"') ($O -join " | ")
|
||||
$R = Query "SELECT message_id, length(message_data) FROM data WHERE node_id = 2 ORDER BY message_id" $OnA
|
||||
@@ -245,25 +245,25 @@ try {
|
||||
"--- Read back the biggest, from B"
|
||||
# Pushed after the small one, so it's the latest.
|
||||
$Id++
|
||||
Expect "push the biggest again" (Tool "PushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id"
|
||||
Expect "push the biggest again" (Tool "BakaShrotPushMessage.exe" @($Files["mmax"], $OnA)) "message #$Id"
|
||||
$null = Wait-Query "SELECT max(message_id) FROM data WHERE node_id = 30" $OnB "`"$Id`"" 60
|
||||
$T = Measure-Command { $O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 }
|
||||
$T = Measure-Command { $O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1 }
|
||||
$Code = $LASTEXITCODE
|
||||
$Json = if ($O.Count -ge 2) { [string]$O[1] } else { "" }
|
||||
Check ("GetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars")
|
||||
Check ("BakaShrotGetLatestMessage of {0:N0} bytes from B ({1:N0} ms)" -f $MaxMessageSize, $T.TotalMilliseconds) ($Code -eq 0 -and $Json.Length -eq $MaxMessageSize -and $Json -eq [IO.File]::ReadAllText($Files["mmax"].Substring(1))) ("[$Code] " + [string]$O[0] + ", " + $Json.Length + " chars")
|
||||
|
||||
"--- Many small ones still go in batches"
|
||||
1..30 | ForEach-Object { $null = Tool "PushMessage.exe" @($Small, $OnA) }
|
||||
1..30 | ForEach-Object { $null = Tool "BakaShrotPushMessage.exe" @($Small, $OnA) }
|
||||
$R = Wait-Query "SELECT count(*) FROM data WHERE node_id = 30" $OnB '"35"' 30
|
||||
Expect "35 on B" $R '\[\["35"\]\]'
|
||||
|
||||
"--- Not JSON: stored as is, flagged"
|
||||
Expect "1 MB of broken JSON is stored" (Tool "PushMessage.exe" @("@$Broken", $OnA)) "message #36"
|
||||
Expect "plain text is stored" (Tool "PushMessage.exe" @("@$Text", $OnA)) "message #37"
|
||||
Expect "1 MB of broken JSON is stored" (Tool "BakaShrotPushMessage.exe" @("@$Broken", $OnA)) "message #36"
|
||||
Expect "plain text is stored" (Tool "BakaShrotPushMessage.exe" @("@$Text", $OnA)) "message #37"
|
||||
Expect "flagged is_json = 0 on A, the rest 1" (Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 2 AND message_id >= 35 ORDER BY message_id" $OnA) '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]'
|
||||
$R = Wait-Query "SELECT message_id, is_json, length(message_data) FROM data WHERE node_id = 30 AND message_id >= 35 ORDER BY message_id" $OnB '"37"' 30
|
||||
Expect "replicated and flagged the same on B" $R '\[\["35","1","40"\],\["36","0","1000000"\],\["37","0","24"\]\]'
|
||||
$O = & (Join-Path $Build "GetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1
|
||||
$O = & (Join-Path $Build "BakaShrotGetLatestMessage.exe") "logs" "kitchen" $OnB 2>&1
|
||||
Check "read back as is from B" ($LASTEXITCODE -eq 0 -and [string]$O[1] -eq "just some text, not JSON") ($O -join " | ")
|
||||
|
||||
"--- is_json for the edge cases (SQLite's json_valid(), RFC 8259)"
|
||||
@@ -275,7 +275,7 @@ try {
|
||||
$Id++
|
||||
$F = Join-Path $Dir "case$Id.txt"
|
||||
[IO.File]::WriteAllText($F, $C[0])
|
||||
$R = Tool "PushMessage.exe" @("@$F", $OnA)
|
||||
$R = Tool "BakaShrotPushMessage.exe" @("@$F", $OnA)
|
||||
$Q = Query "SELECT is_json FROM data WHERE node_id = 2 AND message_id = $Id" $OnA
|
||||
Check ("'{0}' stored, is_json = {1}" -f $C[0], $C[1]) ($R.Out -match "message #$Id" -and $Q.Out -match ('"rows":\[\["{0}"\]\]' -f $C[1])) ($R.Out + " / " + $Q.Out)
|
||||
}
|
||||
@@ -303,7 +303,7 @@ function Read-Log($Name) {
|
||||
$L = @(Get-Content (Join-Path $Dir "$Name.log"))
|
||||
$End = [array]::IndexOf($L, "Stopping...")
|
||||
if ($End -lt 0) { $End = $L.Count }
|
||||
while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Retrying|disconnected|aborted|didn't answer") { $End-- }
|
||||
while ($End -gt 0 -and $L[$End - 1] -match "Lost the link|Dropping the link|Retrying|disconnected|aborted|didn't answer") { $End-- }
|
||||
($L[0..([math]::Max($End - 1, 0))]) -join "`n"
|
||||
}
|
||||
$LogA = Read-Log "a"
|
||||
|
||||
+30
-29
@@ -1,6 +1,6 @@
|
||||
# End-to-end test of reading runs of messages: the GetMessages request
|
||||
# (Commons/Networking/Packets/GetMessagesPacket.pbi), through the client DLL
|
||||
# and Tools\GetMessages: from the start, after an id, after the latest one,
|
||||
# and Tools\BakaShrotGetMessages: from the start, after an id, after the latest one,
|
||||
# with a limit, answers split at ~1 MB, data that isn't JSON or spans lines,
|
||||
# refusals, and --follow picking up new pushes.
|
||||
# Needs Build\ (Build.ps1) and Build\Bench\BenchServer.exe (Bench-Replication.ps1,
|
||||
@@ -17,7 +17,7 @@ $Port = 12405
|
||||
$Fails = 0
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -37,7 +37,7 @@ function Check([string]$What, [bool]$Ok, [string]$Detail) {
|
||||
function Expect([string]$What, $Result, [string]$Pattern, [int]$Code = 0) {
|
||||
Check $What (($Result.Code -eq $Code) -and ($Result.Out -match $Pattern)) ("[{0}] {1}" -f $Result.Code, $Result.Out)
|
||||
}
|
||||
# The ids GetMessages printed, in order.
|
||||
# The ids BakaShrotGetMessages printed, in order.
|
||||
function Ids($Result) {
|
||||
@($Result.Lines | Where-Object { $_ -match "^\d+`t" } | ForEach-Object { [long]($_ -split "`t", 2)[0] })
|
||||
}
|
||||
@@ -51,7 +51,7 @@ function Push($Data, $Ini, [string]$Topic = "") {
|
||||
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
|
||||
$A = @()
|
||||
if ($Topic) { $A += @("-t", $Topic) }
|
||||
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
|
||||
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
|
||||
}
|
||||
|
||||
$S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
|
||||
@@ -59,7 +59,6 @@ $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
|
||||
Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($S.Priv)
|
||||
Topic = logs
|
||||
Node = server
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -79,20 +78,22 @@ DatabasePath = $(Join-Path $Dir "server.sqlite")
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;secret
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
|
||||
[BakaShrot.Client.lounge]
|
||||
PublicKeys = $($L.Pub)
|
||||
Identities = logs:lounge
|
||||
Node = lounge
|
||||
DefaultTopic = logs
|
||||
ReadTopics = logs
|
||||
"@
|
||||
|
||||
function Client-Ini($Name, $Keys) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
|
||||
$P
|
||||
}
|
||||
$Kitchen = Client-Ini "kitchen" $K
|
||||
@@ -114,10 +115,10 @@ try {
|
||||
|
||||
# --- Nothing yet ----------------------------------------------------------
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen)
|
||||
Check "No messages yet: nothing printed, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
|
||||
Check "--after latest with no messages yet: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
# --- 120 small ones -------------------------------------------------------
|
||||
@@ -130,50 +131,50 @@ try {
|
||||
}
|
||||
Check "120 pushes" ($Pushed -eq 120) ("{0} pushed in {1:N1} s" -f $Pushed, ((Get-Date) - $Started).TotalSeconds)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", $Kitchen)
|
||||
$Ids = Ids $R
|
||||
Check "Default: the first 100, in order" ($R.Code -eq 0 -and (Is-Run $Ids 1 100)) ("[{0}] {1} ids, {2}..{3}" -f $R.Code, $Ids.Count, $Ids[0], $Ids[-1])
|
||||
Check "Each line is the id, a tab and the data as stored" ($R.Lines[0] -eq "1`t{`"i`":1}" -and $R.Lines[99] -eq "100`t{`"i`":100}") ("'{0}' / '{1}'" -f $R.Lines[0], $R.Lines[99])
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--limit", "0", $Kitchen)
|
||||
Check "--limit 0: all 120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "115", $Kitchen)
|
||||
Check "--after 115: 116-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 116 120)) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "10", "--limit", "7", $Kitchen)
|
||||
Check "--after 10 --limit 7: 11-17" ($R.Code -eq 0 -and (Is-Run (Ids $R) 11 17)) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
|
||||
Check "--after the last one: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "latest", $Kitchen)
|
||||
Check "--after latest: nothing" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("1", "5", "--after", "118", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("1", "5", "--after", "118", $Kitchen)
|
||||
Check "By ids (1, 5): 119-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 119 120)) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "100", $Lounge)
|
||||
Check "Another client allowed to read logs: 101-120" ($R.Code -eq 0 -and (Is-Run (Ids $R) 101 120)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
|
||||
|
||||
# --- Refusals -------------------------------------------------------------
|
||||
|
||||
$null = Push '{"s":1}' $Kitchen "secret"
|
||||
$R = Tool "GetMessages.exe" @("secret", "kitchen", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Kitchen)
|
||||
Check "A topic in ReadTopics (*): read" ($R.Code -eq 0 -and (Is-Run (Ids $R) 1 1)) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
Expect "A topic not in ReadTopics: refused" (Tool "GetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1
|
||||
Expect "Unknown node: refused" (Tool "GetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1
|
||||
Expect "Unknown topic: refused" (Tool "GetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1
|
||||
$R = Tool "GetMessages.exe" @("logs", "empty", $Kitchen)
|
||||
Expect "A topic not in ReadTopics: refused" (Tool "BakaShrotGetMessages.exe" @("secret", "kitchen", $Lounge)) "Not allowed to read topic 'secret'" 1
|
||||
Expect "Unknown node: refused" (Tool "BakaShrotGetMessages.exe" @("logs", "nobody", $Kitchen)) "Unknown node 'nobody'" 1
|
||||
Expect "Unknown topic: refused" (Tool "BakaShrotGetMessages.exe" @("nothing", "kitchen", $Kitchen)) "Unknown topic 'nothing'" 1
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "empty", $Kitchen)
|
||||
Check "A known node with no messages: nothing, not a failure" ($R.Code -eq 0 -and $R.Lines.Count -eq 0) ("[{0}] {1}" -f $R.Code, $R.Out)
|
||||
Expect "Bad --after: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1
|
||||
Expect "Unknown option: refused by the tool" (Tool "GetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1
|
||||
Expect "Bad --after: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "-3", $Kitchen)) "Invalid --after" 1
|
||||
Expect "Unknown option: refused by the tool" (Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--nope", $Kitchen)) "Unknown option" 1
|
||||
|
||||
# --- Data that isn't one line of JSON -------------------------------------
|
||||
|
||||
$null = Push "plain text, not JSON" $Kitchen
|
||||
$null = Push "two`nlines" $Kitchen
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "120", $Kitchen)
|
||||
Check "Non-JSON data printed as stored, a line break spans lines" (
|
||||
$R.Code -eq 0 -and $R.Lines.Count -eq 3 -and $R.Lines[0] -eq "121`tplain text, not JSON" -and $R.Lines[1] -eq "122`ttwo" -and $R.Lines[2] -eq "lines"
|
||||
) ($R.Lines -join " / ")
|
||||
@@ -189,7 +190,7 @@ try {
|
||||
}
|
||||
Check "6 big pushes (5 x 600 KB, 3 MB)" ($BigOk -eq 6) "$BigOk pushed"
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", $Kitchen)
|
||||
$Ids = Ids $R
|
||||
$Lengths = @($R.Lines | ForEach-Object { (($_ -split "`t", 2)[1]).Length })
|
||||
$WantLengths = @($Sizes | ForEach-Object { $_ })
|
||||
@@ -197,13 +198,13 @@ try {
|
||||
$R.Code -eq 0 -and (Is-Run $Ids 123 128) -and (($Lengths -join ",") -eq ($WantLengths -join ","))
|
||||
) ("[{0}] ids {1}, lengths {2}" -f $R.Code, ($Ids -join ","), ($Lengths -join ","))
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen)
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "122", "--limit", "2", $Kitchen)
|
||||
Check "--limit 2 over big ones: 123-124" ($R.Code -eq 0 -and (Is-Run (Ids $R) 123 124)) ("[{0}] {1} lines" -f $R.Code, $R.Lines.Count)
|
||||
|
||||
# --- --follow ---------------------------------------------------------------
|
||||
|
||||
$FollowOut = Join-Path $Dir "follow.out"
|
||||
$Follower = Start-Process -FilePath (Join-Path $Build "GetMessages.exe") `
|
||||
$Follower = Start-Process -FilePath (Join-Path $Build "BakaShrotGetMessages.exe") `
|
||||
-ArgumentList "logs", "kitchen", "--after", "latest", "--follow", "--interval", "100", "`"$Kitchen`"" `
|
||||
-WorkingDirectory $Build -RedirectStandardOutput $FollowOut -WindowStyle Hidden -PassThru
|
||||
$null = $Follower.Handle
|
||||
|
||||
@@ -54,7 +54,6 @@ Check(Bool(OpenCryptRandom()), "Opened the secure random generator")
|
||||
|
||||
; --- 1. Client -> Server: Hello ---------------------------------------------
|
||||
|
||||
ClientHello\ClientTopic = "logs"
|
||||
ClientHello\ClientNode = "34"
|
||||
ClientHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"
|
||||
Check(Bool(CryptRandomData(@ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize)), "Client made a session key")
|
||||
@@ -69,7 +68,6 @@ MsgPackFree(*View, #False)
|
||||
FreeMemory(*Wire)
|
||||
|
||||
Check(Bool(*ServerHello), "Server decoded the hello")
|
||||
Check(Bool(*ServerHello\ClientTopic = "logs"), "Hello's ClientTopic survived")
|
||||
Check(Bool(*ServerHello\ClientNode = "34"), "Hello's ClientNode survived")
|
||||
Check(Bool(*ServerHello\ClientPubKeyB64 = "Q2xpZW50UHViS2V5"), "Hello's ClientPubKeyB64 survived")
|
||||
Check(CompareMemory(@*ServerHello\ClientSessionKey[0], @ClientHello\ClientSessionKey[0], #BakaShrot_SessionKeySize), "Hello's ClientSessionKey survived")
|
||||
|
||||
+252
-57
@@ -14,7 +14,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||
$Fails = 0
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -52,16 +52,15 @@ function Wait-Port($Port, $S) {
|
||||
}
|
||||
function Query($Sql, $Ini) {
|
||||
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||
Tool "Query.exe" @("@$F", $Ini)
|
||||
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
|
||||
}
|
||||
|
||||
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair
|
||||
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair; $BC = New-KeyPair; $K2 = New-KeyPair; $R = New-KeyPair
|
||||
|
||||
# --- Server A: new keys, logs = 1, sensors = 2 -----------------------------
|
||||
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($A.Priv)
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -78,6 +77,7 @@ garage = 5
|
||||
kitchen-2 = 6
|
||||
blocal = 20
|
||||
bsecret = 21
|
||||
reader = 30
|
||||
|
||||
[BakaShrot.Server]
|
||||
Host = 127.0.0.1
|
||||
@@ -90,30 +90,39 @@ PeerRetryDelay = 1
|
||||
[BakaShrot.Peer.b]
|
||||
Host = 127.0.0.1
|
||||
Port = 12402
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
PublicKey = $($B.Pub)
|
||||
AcceptTopics = logs
|
||||
|
||||
[BakaShrot.Client.b]
|
||||
PublicKeys = $($B.Pub)
|
||||
Identities = logs:serverB
|
||||
Node = serverB
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;sensors*
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
|
||||
[BakaShrot.Client.kitchen2]
|
||||
PublicKeys = $($K2.Pub)
|
||||
Identities = logs:kitchen-2
|
||||
Node = kitchen-2
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;sensors.temp
|
||||
|
||||
[BakaShrot.Client.garage]
|
||||
PublicKeys = $($G.Pub)
|
||||
Identities = logs:garage
|
||||
Node = garage
|
||||
DefaultTopic = logs
|
||||
|
||||
; No DefaultTopic: its pushes must name their topic.
|
||||
[BakaShrot.Client.reader]
|
||||
PublicKeys = $($R.Pub)
|
||||
Node = reader
|
||||
PushTopics = logs
|
||||
"@
|
||||
|
||||
# --- Server B: the old key names, logs = 200, sensors = 201 ----------------
|
||||
@@ -125,7 +134,6 @@ function Write-B([string]$Kitchen) {
|
||||
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($B.Priv)
|
||||
TopicId = logs
|
||||
NodeId = serverB
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -151,7 +159,6 @@ PeerRetryDelay = 1
|
||||
[BakaShrot.Peer.a]
|
||||
Host = 127.0.0.1
|
||||
Port = 12401
|
||||
TopicId = logs
|
||||
NodeId = serverA
|
||||
PublicKey = $($A.Pub)
|
||||
AcceptTopics = logs;sensors;sensors.*
|
||||
@@ -160,11 +167,30 @@ SendNodes = blocal;9
|
||||
|
||||
[BakaShrot.Client.a]
|
||||
PublicKeys = $($A.Pub)
|
||||
Identities = logs:serverA
|
||||
Node = serverA
|
||||
DefaultTopic = logs
|
||||
|
||||
; One key, three nodes: a section each.
|
||||
[BakaShrot.Client.local]
|
||||
PublicKeys = $($BC.Pub)
|
||||
Identities = sensors:blocal;logs:9;logs:bsecret
|
||||
Node = blocal
|
||||
DefaultTopic = sensors
|
||||
PushTopics = sensors;logs;extra
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
|
||||
[BakaShrot.Client.local9]
|
||||
PublicKeys = $($BC.Pub)
|
||||
Node = 9
|
||||
DefaultTopic = logs
|
||||
PushTopics = sensors;logs;extra
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
|
||||
[BakaShrot.Client.localsecret]
|
||||
PublicKeys = $($BC.Pub)
|
||||
Node = bsecret
|
||||
DefaultTopic = logs
|
||||
PushTopics = sensors;logs;extra
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
@@ -172,13 +198,14 @@ AllowQuery = 1
|
||||
}
|
||||
Write-B "7"
|
||||
|
||||
# New key names, except garage's (TopicId / NodeId, by ids).
|
||||
# New key names, except garage's (NodeId, by id). No Topic: the server's
|
||||
# DefaultTopic for each client says where its pushes go.
|
||||
$ServerKeys = @{ 12401 = $A.Pub; 12402 = $B.Pub }
|
||||
function Client-Ini($Name, $Keys, $Topic, $Node, $Port, [switch]$OldKeys) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
$TK = "Topic"; $NK = "Node"
|
||||
if ($OldKeys) { $TK = "TopicId"; $NK = "NodeId" }
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$TK = $Topic`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
$NK = "Node"
|
||||
if ($OldKeys) { $NK = "NodeId" }
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`n$NK = $Node`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
$P
|
||||
}
|
||||
$Kitchen = Client-Ini "kitchen" $K "logs" "kitchen" 12401
|
||||
@@ -187,6 +214,9 @@ $Local = Client-Ini "local" $BC "sensors" "blocal" 12402
|
||||
$Anon = Client-Ini "anon" $BC "logs" "9" 12402
|
||||
$BSecret = Client-Ini "bsecret" $BC "logs" "bsecret" 12402
|
||||
$Kitchen2 = Client-Ini "kitchen2" $K2 "logs" "kitchen-2" 12401
|
||||
$Reader = Client-Ini "reader" $R "logs" "reader" 12401
|
||||
# reader's key, but kitchen's node: its section only gives it reader.
|
||||
$Impostor = Client-Ini "impostor" $R "logs" "kitchen" 12401
|
||||
Set-Content (Join-Path $Dir "m1.json") -Encoding Ascii -Value '{"temp":21}'
|
||||
Set-Content (Join-Path $Dir "m2.json") -Encoding Ascii -Value '{"temp":22,"where":"kitchen"}'
|
||||
Set-Content (Join-Path $Dir "m3.json") -Encoding Ascii -Value '{"from":"b-local"}'
|
||||
@@ -196,59 +226,64 @@ $SA = Start-Srv "a"; $SB = Start-Srv "b"
|
||||
try {
|
||||
Wait-Port 12401 $SA; Wait-Port 12402 $SB
|
||||
"--- Server A: pushes and the push filter"
|
||||
Expect "kitchen pushes into its own topic (logs)" (Tool "PushMessage.exe" @($M1, $Kitchen)) "message #1"
|
||||
Expect "kitchen pushes into sensors by name" (Tool "PushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1"
|
||||
Expect "kitchen pushes into logs by id" (Tool "PushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2"
|
||||
Expect "kitchen can't push into secret" (Tool "PushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1
|
||||
Expect "unknown topic refused" (Tool "PushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "Unknown topic 'nope'" 1
|
||||
Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "PushMessage.exe" @($M1, $Garage)) "message #1"
|
||||
Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1"
|
||||
Expect "kitchen-2 pushes into logs" (Tool "PushMessage.exe" @($M1, $Kitchen2)) "message #1"
|
||||
Expect "kitchen-2 pushes into sensors.temp" (Tool "PushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1"
|
||||
Expect "kitchen-2 can't push into sensors" (Tool "PushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1
|
||||
Expect "kitchen pushes into its own topic (logs)" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen)) "message #1"
|
||||
Expect "kitchen pushes into sensors by name" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M2, $Kitchen)) "message #1"
|
||||
Expect "kitchen pushes into logs by id" (Tool "BakaShrotPushMessage.exe" @("-t", "1", $M2, $Kitchen)) "message #2"
|
||||
Expect "kitchen can't push into secret" (Tool "BakaShrotPushMessage.exe" @("-t", "secret", $M1, $Kitchen)) "Not allowed to push to topic 'secret'" 1
|
||||
Expect "unknown topic refused, with its code" (Tool "BakaShrotPushMessage.exe" @("-t", "nope", $M1, $Kitchen)) "\(UnknownName\): Unknown topic 'nope'" 1
|
||||
Expect "garage (old keys, by ids 1:5) pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Garage)) "message #1"
|
||||
Expect "kitchen pushes into sensors.temp (PushTopics sensors*)" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M2, $Kitchen)) "message #1"
|
||||
Expect "kitchen-2 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M1, $Kitchen2)) "message #1"
|
||||
Expect "kitchen-2 pushes into sensors.temp" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors.temp", $M1, $Kitchen2)) "message #1"
|
||||
Expect "kitchen-2 can't push into sensors" (Tool "BakaShrotPushMessage.exe" @("-t", "sensors", $M1, $Kitchen2)) "Not allowed to push to topic 'sensors'" 1
|
||||
|
||||
"--- Server A: identities (a node per key, the default topic the server's)"
|
||||
Expect "reader (no DefaultTopic) can't push without naming a topic" (Tool "BakaShrotPushMessage.exe" @($M1, $Reader)) "\(NoDefaultTopic\): No default topic for this client" 1
|
||||
Expect "reader pushes when it names one" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Reader)) "message #1"
|
||||
Expect "reader's key can't write as kitchen" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M1, $Impostor)) "Failed to connect and authenticate to [^ ]+ \(AuthRejected\)" 1
|
||||
|
||||
"--- Server A: reads and the read filter"
|
||||
Expect "garage reads logs:kitchen by name" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)"
|
||||
Expect "garage reads it by ids, case-insensitive name" (Tool "GetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2"
|
||||
Expect "garage can't read sensors (default ReadTopics)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1
|
||||
Expect "kitchen reads sensors (ReadTopics = *)" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)"
|
||||
Expect "garage reads logs:kitchen by name" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Garage)) "logs:kitchen#2 \(ids 1:2\)"
|
||||
Expect "garage reads it by ids, case-insensitive name" (Tool "BakaShrotGetLatestMessage.exe" @("1", "KITCHEN", $Garage)) "logs:kitchen#2"
|
||||
Expect "garage can't read sensors (default ReadTopics)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Garage)) "Not allowed to read topic 'sensors'" 1
|
||||
Expect "kitchen reads sensors (ReadTopics = *)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Kitchen)) "sensors:kitchen#1 \(ids 2:2\)"
|
||||
|
||||
"--- Server A: resolving and listing"
|
||||
Expect "kitchen resolves topic sensors" (Tool "Resolve.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2"
|
||||
Expect "kitchen resolves topic id 1" (Tool "Resolve.exe" @("topic", "1", $Kitchen)) "topic logs = 1"
|
||||
Expect "kitchen resolves node garage" (Tool "Resolve.exe" @("node", "garage", $Kitchen)) "node garage = 5"
|
||||
Expect "garage can't resolve sensors (no access)" (Tool "Resolve.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1
|
||||
Expect "kitchen can resolve secret (it may query)" (Tool "Resolve.exe" @("topic", "secret", $Kitchen)) "topic secret = 3"
|
||||
Expect "kitchen lists every topic (it may query)" (Tool "ListNames.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config"
|
||||
Expect "garage lists only the topics it can use" (Tool "ListNames.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs"
|
||||
Expect "the nodes, as JSON" (Tool "ListNames.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])'
|
||||
Expect "kitchen resolves topic sensors" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Kitchen)) "topic sensors = 2"
|
||||
Expect "kitchen resolves topic id 1" (Tool "BakaShrotResolveIds.exe" @("topic", "1", $Kitchen)) "topic logs = 1"
|
||||
Expect "kitchen resolves node garage" (Tool "BakaShrotResolveIds.exe" @("node", "garage", $Kitchen)) "node garage = 5"
|
||||
Expect "garage can't resolve sensors (no access)" (Tool "BakaShrotResolveIds.exe" @("topic", "sensors", $Garage)) "Unknown topic" 1
|
||||
Expect "kitchen can resolve secret (it may query)" (Tool "BakaShrotResolveIds.exe" @("topic", "secret", $Kitchen)) "topic secret = 3"
|
||||
Expect "kitchen lists every topic (it may query)" (Tool "BakaShrotList.exe" @("topics", $Kitchen)) "Topics \(4\): \|\s+1 logs\s+config \|\s+2 sensors\s+config \|\s+3 secret\s+config \|\s+4 sensors.temp\s+config"
|
||||
Expect "garage lists only the topics it can use" (Tool "BakaShrotList.exe" @("topics", $Garage)) "Topics \(1\): \|\s+1 logs"
|
||||
Expect "the nodes, as JSON" (Tool "BakaShrotList.exe" @("nodes", "--json", $Kitchen)) '(?=.*"kind":"node")(?=.*\{[^}]*"name":"kitchen"[^}]*\})(?=.*\{[^}]*"id":2[,}])'
|
||||
|
||||
"--- Server A: queries by name through the view"
|
||||
Expect "messages view, by names" (Query "SELECT topic, node, message_id FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id" $Kitchen) '\[\["logs","kitchen","1"\],\["logs","kitchen","2"\]\]'
|
||||
|
||||
"--- Replication, A -> B, translated (logs 1 -> 200, kitchen 2 -> 7)"
|
||||
Start-Sleep -Seconds 4
|
||||
Expect "B has logs:kitchen, under its own ids" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)"
|
||||
Expect "B has sensors:kitchen" (Tool "GetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)"
|
||||
Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "GetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1
|
||||
Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)"
|
||||
Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "GetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)"
|
||||
Expect "B: both new ones" (Tool "GetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)"
|
||||
Expect "B has logs:kitchen, under its own ids" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Local)) "logs:kitchen#2 \(ids 200:7\)"
|
||||
Expect "B has sensors:kitchen" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "kitchen", $Local)) "sensors:kitchen#1 \(ids 201:7\)"
|
||||
Expect "B didn't get logs:garage (garage isn't named on B)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "garage", $Local)) "Unknown node 'garage'" 1
|
||||
Expect "B took sensors.temp by AcceptTopics sensors.* (new topic id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen", $Local)) "sensors.temp:kitchen#1 \(ids 65535:7\)"
|
||||
Expect "B took kitchen-2 by AcceptNodes kitchen-* (new node id 65535)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen-2", $Local)) "logs:kitchen-2#1 \(ids 200:65535\)"
|
||||
Expect "B: both new ones" (Tool "BakaShrotGetLatestMessage.exe" @("sensors.temp", "kitchen-2", $Local)) "sensors.temp:kitchen-2#1 \(ids 65535:65535\)"
|
||||
Expect "B: added from the peer, nothing else" (Query "SELECT 'topic', name, topic_id FROM topics WHERE origin = 'peer' UNION ALL SELECT 'node', name, node_id FROM nodes WHERE origin = 'peer'" $Local) '\[\["topic","sensors.temp","65535"\],\["node","kitchen-2","65535"\]\]'
|
||||
Expect "B's view: same messages by name" (Query "SELECT topic, node, message_id, topic_id, node_id FROM messages WHERE topic = 'sensors'" $Local) '\[\["sensors","kitchen","1","201","7"\]\]'
|
||||
|
||||
"--- Replication, B -> A: only what A names and takes (AcceptTopics = logs)"
|
||||
Expect "B's local pushes into sensors" (Tool "PushMessage.exe" @($M3, $Local)) "message #1"
|
||||
Expect "B's local pushes into logs" (Tool "PushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1"
|
||||
Expect "B's local pushes into extra" (Tool "PushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1"
|
||||
Expect "B's unnamed node 9 pushes into logs" (Tool "PushMessage.exe" @($M3, $Anon)) "message #1"
|
||||
Expect "B's bsecret pushes into logs" (Tool "PushMessage.exe" @($M3, $BSecret)) "message #1"
|
||||
Expect "B's local pushes into sensors" (Tool "BakaShrotPushMessage.exe" @($M3, $Local)) "message #1"
|
||||
Expect "B's local pushes into logs" (Tool "BakaShrotPushMessage.exe" @("-t", "logs", $M3, $Local)) "message #1"
|
||||
Expect "B's local pushes into extra" (Tool "BakaShrotPushMessage.exe" @("-t", "extra", $M3, $Local)) "message #1"
|
||||
Expect "B's unnamed node 9 pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $Anon)) "message #1"
|
||||
Expect "B's bsecret pushes into logs" (Tool "BakaShrotPushMessage.exe" @($M3, $BSecret)) "message #1"
|
||||
Start-Sleep -Seconds 4
|
||||
Expect "A got logs:blocal (ids 1:20)" (Tool "GetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}'
|
||||
Expect "A didn't get sensors:blocal (not accepted)" (Tool "GetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1
|
||||
Expect "A didn't get logs:9 (unnamed)" (Tool "GetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1
|
||||
Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "GetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1
|
||||
Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]'
|
||||
Expect "A got logs:blocal (ids 1:20)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "blocal", $Kitchen)) 'logs:blocal#1 \(ids 1:20\), pushed \d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \| \{"from":"b-local"\}'
|
||||
Expect "A didn't get sensors:blocal (not accepted)" (Tool "BakaShrotGetLatestMessage.exe" @("sensors", "blocal", $Kitchen)) "No message" 1
|
||||
Expect "A didn't get logs:9 (unnamed)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "9", $Kitchen)) "No message" 1
|
||||
Expect "A didn't get logs:bsecret (B's SendNodes)" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "bsecret", $Kitchen)) "No message" 1
|
||||
Expect "A's pairs, nothing more, nothing twice" (Query "SELECT topic, node, COUNT(*) FROM messages GROUP BY 1, 2 ORDER BY 1, 2" $Kitchen) '\[\["logs","blocal","1"\],\["logs","garage","1"\],\["logs","kitchen","2"\],\["logs","kitchen-2","1"\],\["logs","reader","1"\],\["sensors","kitchen","1"\],\["sensors.temp","kitchen","1"\],\["sensors.temp","kitchen-2","1"\]\]'
|
||||
} finally {
|
||||
Stop-Srv $SA; Stop-Srv $SB
|
||||
}
|
||||
@@ -258,6 +293,9 @@ $Refusals = @(Get-Content (Join-Path $Dir "a.log"), (Join-Path $Dir "b.log") | S
|
||||
$Ok = $Refusals.Count -eq 0
|
||||
if (-not $Ok) { $Fails++ }
|
||||
"{0} no replication refusals in either log`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $(if ($Ok) { "none" } else { $Refusals -join " | " })
|
||||
$Ok = (Get-Content (Join-Path $Dir "a.log") -Raw) -match "isn't allowed to write as node kitchen with its public key"
|
||||
if (-not $Ok) { $Fails++ }
|
||||
"{0} A logged why the impostor was refused" -f $(if ($Ok) { "PASS" } else { "FAIL" })
|
||||
"A:"; Get-Content (Join-Path $Dir "a.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" }
|
||||
"B:"; Get-Content (Join-Path $Dir "b.log") | Select-String "\[Peer\] Sent|Names" | % { " $_" }
|
||||
|
||||
@@ -276,8 +314,165 @@ Write-B "7"
|
||||
$SB = Start-Srv "b"
|
||||
try {
|
||||
Wait-Port 12402 $SB
|
||||
Expect "B starts, kitchen still 7" (Tool "ListNames.exe" @("nodes", $Local)) "\s+7 kitchen\s+config"
|
||||
Expect "B starts, kitchen still 7" (Tool "BakaShrotList.exe" @("nodes", $Local)) "\s+7 kitchen\s+config"
|
||||
} finally { Stop-Srv $SB }
|
||||
|
||||
"--- The old Identities (before protocol 5): refused at start, saying what to write"
|
||||
(Get-Content (Join-Path $Dir "a.ini") -Raw) -replace "Node = garage\r?\nDefaultTopic = logs", "Identities = logs:garage" | Set-Content (Join-Path $Dir "old.ini") -Encoding Ascii
|
||||
$SO = Start-Srv "old"
|
||||
$Exited = $SO.P.WaitForExit(10000)
|
||||
if (-not $Exited) { Stop-Srv $SO }
|
||||
$Log = Get-Content (Join-Path $Dir "old.log") -Raw
|
||||
$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "write Node = garage and DefaultTopic = logs instead of Identities = logs:garage"
|
||||
if (-not $Ok) { $Fails++ }
|
||||
"{0} refused, with what to write instead`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Identities" | Select-Object -First 1)
|
||||
|
||||
# --- C and D: topics listed without ids, no nodes listed at all ------------
|
||||
# The servers pick the ids, the nodes come from the sections (C's own, its
|
||||
# peer's, its client's), D takes the client's node from C as it comes.
|
||||
$C = New-KeyPair; $D = New-KeyPair; $KC = New-KeyPair
|
||||
# LF line endings on purpose: the names sections are read by hand, the
|
||||
# Preferences library misreads a bare name there (Config.pbi).
|
||||
function Write-C([string]$Topics, [string]$Sync = "NORMAL") {
|
||||
$Text = @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($C.Priv)
|
||||
Node = serverC
|
||||
|
||||
[BakaShrot.Topics]
|
||||
$Topics
|
||||
|
||||
[BakaShrot.Server]
|
||||
Host = 127.0.0.1
|
||||
Port = 12401
|
||||
ReplicatingTopics = logs
|
||||
DatabasePath = $(Join-Path $Dir "c.sqlite")
|
||||
PeerSyncInterval = 1
|
||||
PeerRetryDelay = 1
|
||||
Synchronous = $Sync
|
||||
|
||||
[BakaShrot.Peer.d]
|
||||
Host = 127.0.0.1
|
||||
Port = 12402
|
||||
Node = serverD
|
||||
PublicKey = $($D.Pub)
|
||||
|
||||
[BakaShrot.Client.d]
|
||||
PublicKeys = $($D.Pub)
|
||||
Node = serverD
|
||||
AllowWrite = 0
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($KC.Pub)
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
ReadTopics = *
|
||||
"@
|
||||
[IO.File]::WriteAllText((Join-Path $Dir "c.ini"), ($Text -replace "`r`n", "`n"))
|
||||
}
|
||||
Write-C "logs`nsensors"
|
||||
Set-Content (Join-Path $Dir "d.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($D.Priv)
|
||||
Node = serverD
|
||||
|
||||
[BakaShrot.Topics]
|
||||
logs
|
||||
|
||||
[BakaShrot.Server]
|
||||
Host = 127.0.0.1
|
||||
Port = 12402
|
||||
ReplicatingTopics = logs
|
||||
DatabasePath = $(Join-Path $Dir "d.sqlite")
|
||||
PeerSyncInterval = 1
|
||||
PeerRetryDelay = 1
|
||||
|
||||
[BakaShrot.Peer.c]
|
||||
Host = 127.0.0.1
|
||||
Port = 12401
|
||||
Node = serverC
|
||||
PublicKey = $($C.Pub)
|
||||
|
||||
[BakaShrot.Client.c]
|
||||
PublicKeys = $($C.Pub)
|
||||
Node = serverC
|
||||
AllowWrite = 0
|
||||
|
||||
[BakaShrot.Client.watcher]
|
||||
PublicKeys = $($KC.Pub)
|
||||
Node = watcher
|
||||
ReadTopics = *
|
||||
"@
|
||||
$ServerKeys[12401] = $C.Pub; $ServerKeys[12402] = $D.Pub
|
||||
$KitchenC = Client-Ini "kitchen-c" $KC "logs" "kitchen" 12401
|
||||
$Watcher = Client-Ini "watcher" $KC "logs" "watcher" 12402
|
||||
|
||||
"--- C and D: names without ids"
|
||||
$SC = Start-Srv "c"; $SD = Start-Srv "d"
|
||||
try {
|
||||
Wait-Port 12401 $SC; Wait-Port 12402 $SD
|
||||
Expect "C gives the listed topics ids, in order" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config"
|
||||
Expect "C names its own, its peer's and its client's nodes" (Tool "BakaShrotList.exe" @("nodes", $KitchenC)) "\s1 serverC\s+config.*\s2 serverD\s+config.*\s3 kitchen\s+config"
|
||||
Expect "kitchen pushes to its DefaultTopic" (Tool "BakaShrotPushMessage.exe" @($M1, $KitchenC)) "message #1"
|
||||
$Deadline = (Get-Date).AddSeconds(15)
|
||||
do {
|
||||
$R = Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $Watcher)
|
||||
if ($R.Code -eq 0) { break }
|
||||
Start-Sleep -Milliseconds 300
|
||||
} while ((Get-Date) -lt $Deadline)
|
||||
Expect "D took logs:kitchen though it never named kitchen (AcceptNodes = * by default)" $R "logs:kitchen#1 \(ids 1:65535\)"
|
||||
} finally {
|
||||
Stop-Srv $SC; Stop-Srv $SD
|
||||
}
|
||||
|
||||
"--- C again, its topics reordered and a new one first: the ids stay"
|
||||
Write-C "alpha`nsensors`nlogs"
|
||||
$SC = Start-Srv "c"
|
||||
try {
|
||||
Wait-Port 12401 $SC
|
||||
Expect "logs and sensors keep 1 and 2, alpha gets 3" (Tool "BakaShrotList.exe" @("topics", $KitchenC)) "\s1 logs\s+config.*\s2 sensors\s+config.*\s3 alpha\s+config"
|
||||
Expect "kitchen's message still under logs" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $KitchenC)) "logs:kitchen#1 \(ids 1:3\)"
|
||||
} finally { Stop-Srv $SC }
|
||||
|
||||
"--- Synchronous: C ran with NORMAL, D with the default FULL, OFF is refused"
|
||||
$Ok = ((Get-Content (Join-Path $Dir "c.log") -Raw) -match "is ready \(synchronous NORMAL\)") -and ((Get-Content (Join-Path $Dir "d.log") -Raw) -match "is ready \(synchronous FULL\)")
|
||||
if (-not $Ok) { $Fails++ }
|
||||
"{0} C logged NORMAL, D FULL" -f $(if ($Ok) { "PASS" } else { "FAIL" })
|
||||
Write-C "logs" "OFF"
|
||||
$SO = Start-Srv "c"
|
||||
$Exited = $SO.P.WaitForExit(10000)
|
||||
if (-not $Exited) { Stop-Srv $SO }
|
||||
$Log = Get-Content (Join-Path $Dir "c.log") -Raw
|
||||
$Ok = $Exited -and $SO.P.ExitCode -ne 0 -and $Log -match "Synchronous = OFF isn't allowed"
|
||||
if (-not $Ok) { $Fails++ }
|
||||
"{0} Synchronous = OFF refused at start`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), (($Log -split "`n") | Select-String "Synchronous" | Select-Object -First 1)
|
||||
|
||||
"--- browse / browse_messages, as a database tool uses them (C stopped)"
|
||||
$PythonExe = Get-Command python -ErrorAction SilentlyContinue
|
||||
if ($PythonExe) {
|
||||
Set-Content (Join-Path $Dir "browse.py") -Encoding Ascii -Value @'
|
||||
import sqlite3, sys
|
||||
db = sqlite3.connect(sys.argv[1])
|
||||
db.execute("PRAGMA foreign_keys = ON") # like SQLiteStudio
|
||||
print("rows", db.execute("SELECT COUNT(*) FROM browse").fetchone()[0])
|
||||
db.execute("UPDATE browse SET topic = 'logs', node = NULL"); db.commit()
|
||||
print("logs", db.execute("SELECT node, message_id, attachment_size FROM browse_messages").fetchall())
|
||||
db.execute("UPDATE browse SET topic = 'LOGS', node = 'kitchen'"); db.commit()
|
||||
print("kitchen", db.execute("SELECT node, message_id FROM browse_messages").fetchall())
|
||||
try:
|
||||
db.execute("UPDATE browse SET topic = 'nope'"); db.commit(); print("bad accepted")
|
||||
except sqlite3.IntegrityError:
|
||||
print("bad refused")
|
||||
db.execute("UPDATE browse SET topic = 'sensors', node = NULL"); db.commit()
|
||||
print("sensors", db.execute("SELECT COUNT(*) FROM browse_messages").fetchone()[0])
|
||||
'@
|
||||
$Out = (& $PythonExe.Source -B (Join-Path $Dir "browse.py") (Join-Path $Dir "c.sqlite") 2>&1) -join " | "
|
||||
$Ok = $Out -eq "rows 1 | logs [('kitchen', 1, None)] | kitchen [('kitchen', 1)] | bad refused | sensors 0"
|
||||
if (-not $Ok) { $Fails++ }
|
||||
"{0} one row, a topic shows its messages, a node narrows them, an unknown topic is refused`n -> {1}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $Out
|
||||
} else {
|
||||
"SKIP browse: no python on the PATH"
|
||||
}
|
||||
|
||||
""
|
||||
if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED" }
|
||||
if ($Fails -eq 0) { "ALL PASSED" } else { "$Fails FAILED"; exit 1 }
|
||||
|
||||
@@ -20,7 +20,7 @@ $Port = 12406
|
||||
$ProxyPort = 12407
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -33,7 +33,6 @@ $S = New-KeyPair; $K = New-KeyPair; $L = New-KeyPair
|
||||
Set-Content (Join-Path $Dir "server.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($S.Priv)
|
||||
Topic = logs
|
||||
Node = server
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -52,20 +51,22 @@ DatabasePath = $(Join-Path $Dir "server.sqlite")
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;secret
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
|
||||
[BakaShrot.Client.lounge]
|
||||
PublicKeys = $($L.Pub)
|
||||
Identities = logs:lounge
|
||||
Node = lounge
|
||||
DefaultTopic = logs
|
||||
ReadTopics = logs
|
||||
"@
|
||||
|
||||
function Client-Ini($Name, $Keys) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nTopic = logs`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($Keys.Priv)`r`nPublicKey = $($Keys.Pub)`r`nNode = $Name`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($S.Pub)"
|
||||
$P
|
||||
}
|
||||
$Kitchen = Client-Ini "kitchen" $K
|
||||
@@ -89,7 +90,9 @@ try {
|
||||
& $Python (Join-Path $PSScriptRoot "..\Interactors\Python\check_bakashrot.py") (Join-Path $Build "BakaShrot_Client.dll") $Kitchen $Lounge
|
||||
$Code = $LASTEXITCODE
|
||||
|
||||
$Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -match "invalid|unexpected|Failed|decrypt|sealed" })
|
||||
# Refusals are expected (the checks ask for them), their codes' names
|
||||
# (QueryFailed, InvalidRequest) aren't problems.
|
||||
$Bad = @(Get-Content (Join-Path $Dir "server.log") | Where-Object { $_ -notmatch "Refused a request" -and $_ -match "invalid|unexpected|Failed|decrypt|sealed" })
|
||||
if ($Bad.Count) { "FAIL Server log: $($Bad -join ' / ')"; $Code = 1 } else { "PASS Server log: no invalid or unexpected packets" }
|
||||
|
||||
# The wire: encrypted, tampering and a wrong server key refused. Another
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# End-to-end test of a server killed mid-traffic and restarted (a crash,
|
||||
# not a clean stop): what it acknowledged survives, its ids carry on where
|
||||
# they stopped, and the two servers catch up with each other both ways.
|
||||
#
|
||||
# Two linked servers, A and B, each with its own client node pushing
|
||||
# (kitchen on A, garage on B: one writer per topic/node pair) through
|
||||
# Tests/restart_pusher.py, as fast as acknowledgements come back:
|
||||
# 1. B killed while both push; A keeps pushing while B is down; B
|
||||
# restarted: every push it acknowledged is there, no gap, its next id
|
||||
# follows, and both servers end up with the same messages.
|
||||
# 2. B killed again a fraction of a second into that catch-up, restarted:
|
||||
# still converges.
|
||||
# 3. A killed while both push (the other direction), restarted: same.
|
||||
# The servers are killed with Stop-Process -Force (TerminateProcess), like
|
||||
# a crash. Synchronous is the default (FULL); a killed process loses
|
||||
# nothing committed with NORMAL either, only a power loss would.
|
||||
#
|
||||
# Needs Build\ (Build.ps1), Build\Bench\BenchServer.exe, and Python 3 on the
|
||||
# PATH (the pushers use Interactors/Python/bakashrot.py). Uses ports
|
||||
# 12415-12416.
|
||||
# Usage: powershell -ExecutionPolicy Bypass -File Tests\Restart-Test.ps1
|
||||
|
||||
param([string]$Build = (Join-Path $PSScriptRoot "..\Build"), [string]$Python = "python")
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
$Build = (Resolve-Path $Build).Path
|
||||
$Dir = Join-Path $Build "_restarttest"
|
||||
Remove-Item -Recurse -Force $Dir -ErrorAction SilentlyContinue
|
||||
New-Item -ItemType Directory $Dir | Out-Null
|
||||
$Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||
$Dll = Join-Path $Build "BakaShrot_Client.dll"
|
||||
$Pusher = Join-Path $PSScriptRoot "restart_pusher.py"
|
||||
$Fails = 0
|
||||
|
||||
$PythonExe = (Get-Command $Python -ErrorAction SilentlyContinue)
|
||||
if (-not $PythonExe) { "FAIL no Python ($Python), the pushers need it"; exit 1 }
|
||||
$PythonExe = $PythonExe.Source
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
$C = New-Object System.Net.Sockets.TcpClient
|
||||
try { $A = $C.BeginConnect("127.0.0.1", $P, $null, $null); $A.AsyncWaitHandle.WaitOne(200) -and $C.Connected } catch { $false } finally { $C.Close() }
|
||||
}
|
||||
function Tool([string]$Name, [string[]]$A) {
|
||||
$O = & (Join-Path $Build $Name) @A 2>&1
|
||||
@{ Code = $LASTEXITCODE; Out = ($O -join " | ") }
|
||||
}
|
||||
function Check([string]$What, [bool]$Ok, [string]$Detail) {
|
||||
if (-not $Ok) { $script:Fails++ }
|
||||
"{0} {1}`n -> {2}" -f $(if ($Ok) { "PASS" } else { "FAIL" }), $What, $Detail
|
||||
}
|
||||
function Start-Srv($Name) {
|
||||
$Stop = Join-Path $Dir "$Name.stop"
|
||||
Remove-Item $Stop -ErrorAction SilentlyContinue
|
||||
# Each run its own log, the previous ones are kept for a look.
|
||||
$script:Runs[$Name] = 1 + [int]$script:Runs[$Name]
|
||||
$P = Start-Process -FilePath $Server -ArgumentList "`"$(Join-Path $Dir "$Name.ini")`"", "`"$Stop`"" -WorkingDirectory $Dir `
|
||||
-RedirectStandardOutput (Join-Path $Dir ("{0}.{1}.log" -f $Name, $script:Runs[$Name])) -WindowStyle Hidden -PassThru
|
||||
$null = $P.Handle
|
||||
@{ P = $P; Stop = $Stop; Name = $Name }
|
||||
}
|
||||
function Stop-Srv($S) {
|
||||
if ($S.P.HasExited) { return }
|
||||
Set-Content $S.Stop "x"
|
||||
if (-not $S.P.WaitForExit(15000)) { Stop-Process -Id $S.P.Id -Force }
|
||||
}
|
||||
function Kill-Srv($S) {
|
||||
Stop-Process -Id $S.P.Id -Force
|
||||
$null = $S.P.WaitForExit(10000)
|
||||
}
|
||||
function Wait-Port($Port, $S) {
|
||||
$D = (Get-Date).AddSeconds(15)
|
||||
while (-not (Test-Port $Port)) {
|
||||
if ($S.P.HasExited) { throw "$($S.Name) exited" }
|
||||
if ((Get-Date) -gt $D) { throw "$($S.Name) not listening" }
|
||||
Start-Sleep -Milliseconds 100
|
||||
}
|
||||
}
|
||||
function Query($Sql, $Ini) {
|
||||
$F = Join-Path $Dir ("q-" + [guid]::NewGuid().ToString("N") + ".sql"); Set-Content $F -Encoding Ascii -Value $Sql
|
||||
$R = Tool "BakaShrotQuery.exe" @("@$F", $Ini)
|
||||
Remove-Item $F
|
||||
$R
|
||||
}
|
||||
|
||||
# A pusher in the background: Name's out file gets "<id> <seq>" per
|
||||
# acknowledged push, then STOPPED or ERR.
|
||||
function Start-Pusher($Name, $Ini) {
|
||||
$Out = Join-Path $Dir "$Name.out"; $Stop = Join-Path $Dir "$Name.stop"
|
||||
Remove-Item $Out, $Stop -ErrorAction SilentlyContinue
|
||||
$P = Start-Process -FilePath $PythonExe -ArgumentList "-B", "`"$Pusher`"", "`"$Dll`"", "`"$Ini`"", "`"$Stop`"", "`"$Out`"", $Name `
|
||||
-WorkingDirectory $Build -WindowStyle Hidden -PassThru
|
||||
$null = $P.Handle
|
||||
@{ P = $P; Out = $Out; Stop = $Stop; Name = $Name }
|
||||
}
|
||||
function Stop-Pusher($Pu) {
|
||||
Set-Content $Pu.Stop "x"
|
||||
if (-not $Pu.P.WaitForExit(15000)) { Stop-Process -Id $Pu.P.Id -Force }
|
||||
}
|
||||
# What a pusher saw: how many acknowledged, the last id and seq, how it ended.
|
||||
function Read-Pusher($Pu) {
|
||||
$Lines = @(Get-Content $Pu.Out -ErrorAction SilentlyContinue)
|
||||
$Acked = @($Lines | Where-Object { $_ -match "^\d+ \d+$" })
|
||||
$Last = if ($Acked.Count) { $Acked[-1] -split " " } else { @("0", "0") }
|
||||
@{ Count = $Acked.Count; LastId = [int64]$Last[0]; LastSeq = [int]$Last[1]; End = [string]($Lines | Select-Object -Last 1) }
|
||||
}
|
||||
|
||||
# Every node of logs on a server: count, first and last id, and sums over
|
||||
# the data and the push times, to compare two servers.
|
||||
$StatsSql = "SELECT node, COUNT(*), MIN(message_id), MAX(message_id), SUM(length(message_data)), SUM(pushed_at % 1000003), SUM(message_id * length(message_data)) FROM messages WHERE topic = 'logs' GROUP BY node ORDER BY node"
|
||||
function Stats($Ini) {
|
||||
$R = Query $StatsSql $Ini
|
||||
if ($R.Code -ne 0) { return "query failed: " + $R.Out }
|
||||
($R.Out -replace '^.*"rows":', '')
|
||||
}
|
||||
# The highest id and the count of a node on a server.
|
||||
function Head($Node, $Ini) {
|
||||
$R = Query "SELECT COUNT(*), COALESCE(MAX(message_id), 0) FROM messages WHERE topic = 'logs' AND node = '$Node'" $Ini
|
||||
if ($R.Out -match '\[\["(\d+)","(\d+)"\]\]') { @{ Count = [int64]$Matches[1]; Max = [int64]$Matches[2] } } else { @{ Count = -1; Max = -1; Out = $R.Out } }
|
||||
}
|
||||
# Waits until A and B have the same messages, and at least Kitchen and
|
||||
# Garage messages of each node. Returns the stats, and whether they matched.
|
||||
function Wait-Converged($Kitchen, $Garage, $Seconds = 60) {
|
||||
$D = (Get-Date).AddSeconds($Seconds)
|
||||
do {
|
||||
$SA = Stats $OnA; $SB = Stats $OnB
|
||||
$HK = Head "kitchen" $OnB; $HG = Head "garage" $OnA
|
||||
if ($SA -eq $SB -and $HK.Count -ge $Kitchen -and $HG.Count -ge $Garage) { return @{ Ok = $true; A = $SA; B = $SB } }
|
||||
Start-Sleep -Milliseconds 250
|
||||
} while ((Get-Date) -lt $D)
|
||||
@{ Ok = $false; A = $SA; B = $SB }
|
||||
}
|
||||
# What a restarted server must show for the node its pusher wrote to: every
|
||||
# acknowledged push there (ids 1..max without a gap, max at least the last
|
||||
# acknowledged one, its data the one acknowledged), and at most one more
|
||||
# (committed, the answer lost with the kill). Leaves the node's head in
|
||||
# $Survived: a function's return value would take its PASS/FAIL lines too.
|
||||
function Check-Survived($What, $Node, $Pu, $Ini) {
|
||||
$Seen = Read-Pusher $Pu
|
||||
$H = Head $Node $Ini
|
||||
Check "$What`: every acknowledged push survived, ids without a gap" `
|
||||
($Seen.LastId -gt 0 -and $H.Count -eq $H.Max -and $H.Max -ge $Seen.LastId -and $H.Max -le $Seen.LastId + 1) `
|
||||
("{0} acknowledged, last #{1}; stored {2}, last #{3}; pusher: {4}" -f $Seen.Count, $Seen.LastId, $H.Count, $H.Max, $Seen.End)
|
||||
$R = Query "SELECT message_data FROM messages WHERE topic = 'logs' AND node = '$Node' AND message_id = $($Seen.LastId)" $Ini
|
||||
Check "$What`: the last acknowledged one is the one pushed" ($R.Out -match ('\\"seq\\":' + $Seen.LastSeq + '[,}]')) $R.Out
|
||||
$script:Survived = $H
|
||||
}
|
||||
|
||||
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair; $G = New-KeyPair
|
||||
$Runs = @{}
|
||||
|
||||
# Topics listed by name, nodes from the sections: a restart must give every
|
||||
# name its id back, by the database.
|
||||
function Write-Config($Name, $Keys, $Port, $Node, $PeerName, $PeerPort, $PeerNode, $PeerKey, $ClientNode, $ClientKey) {
|
||||
Set-Content (Join-Path $Dir "$Name.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($Keys.Priv)
|
||||
Node = $Node
|
||||
|
||||
[BakaShrot.Topics]
|
||||
logs
|
||||
|
||||
[BakaShrot.Server]
|
||||
Host = 127.0.0.1
|
||||
Port = $Port
|
||||
ReplicatingTopics = logs
|
||||
DatabasePath = $(Join-Path $Dir "$Name.sqlite")
|
||||
PeerSyncInterval = 1
|
||||
PeerRetryDelay = 1
|
||||
PeerBatchSize = 10
|
||||
|
||||
[BakaShrot.Peer.$PeerName]
|
||||
Host = 127.0.0.1
|
||||
Port = $PeerPort
|
||||
Node = $PeerNode
|
||||
PublicKey = $PeerKey
|
||||
|
||||
[BakaShrot.Client.$PeerName]
|
||||
PublicKeys = $PeerKey
|
||||
Node = $PeerNode
|
||||
AllowWrite = 0
|
||||
|
||||
[BakaShrot.Client.$ClientNode]
|
||||
PublicKeys = $ClientKey
|
||||
Node = $ClientNode
|
||||
DefaultTopic = logs
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
"@
|
||||
}
|
||||
Write-Config "a" $A 12415 "serverA" "b" 12416 "serverB" $B.Pub "kitchen" $K.Pub
|
||||
Write-Config "b" $B 12416 "serverB" "a" 12415 "serverA" $A.Pub "garage" $G.Pub
|
||||
Set-Content (Join-Path $Dir "kitchen.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = 12415`r`nServerPublicKey = $($A.Pub)"
|
||||
Set-Content (Join-Path $Dir "garage.ini") -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($G.Priv)`r`nPublicKey = $($G.Pub)`r`nNode = garage`r`nServerHost = 127.0.0.1`r`nServerPort = 12416`r`nServerPublicKey = $($B.Pub)"
|
||||
$OnA = Join-Path $Dir "kitchen.ini"; $OnB = Join-Path $Dir "garage.ini"
|
||||
Set-Content (Join-Path $Dir "next.json") -Encoding Ascii -Value '{"after":"restart"}'
|
||||
$Next = "@" + (Join-Path $Dir "next.json")
|
||||
|
||||
$SA = Start-Srv "a"; $SB = Start-Srv "b"
|
||||
$Pushers = @()
|
||||
try {
|
||||
Wait-Port 12415 $SA; Wait-Port 12416 $SB
|
||||
|
||||
"--- 1. B killed while both push, A keeps pushing, B restarted"
|
||||
$PK = Start-Pusher "kitchen-1" $OnA; $PG = Start-Pusher "garage-1" $OnB; $Pushers += $PK, $PG
|
||||
Start-Sleep -Seconds 3
|
||||
Kill-Srv $SB
|
||||
$null = $PG.P.WaitForExit(15000)
|
||||
Start-Sleep -Seconds 3 # A goes on alone
|
||||
Stop-Pusher $PK
|
||||
$KSeen = Read-Pusher $PK
|
||||
Check "the garage pusher noticed B was gone: ConnectionLostError, code 104" ($PG.P.HasExited -and (Read-Pusher $PG).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PG).End
|
||||
Check "kitchen kept pushing on A meanwhile" ($KSeen.Count -gt 100 -and $KSeen.End -eq "STOPPED") ("{0} acknowledged" -f $KSeen.Count)
|
||||
|
||||
$SB = Start-Srv "b"; Wait-Port 12416 $SB
|
||||
Check-Survived "B" "garage" $PG $OnB
|
||||
$HG = $Survived
|
||||
$R = Tool "BakaShrotPushMessage.exe" @($Next, $OnB)
|
||||
Check "B: the next push carries on from the last id" ($R.Out -match "message #$($HG.Max + 1)\b") ("after #{0}: {1}" -f $HG.Max, $R.Out)
|
||||
$C = Wait-Converged $KSeen.LastId ($HG.Max + 1)
|
||||
Check "A and B converged (B caught up on kitchen, A on garage)" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
|
||||
|
||||
"--- 2. B killed again in the middle of its catch-up"
|
||||
$Before = (Head "kitchen" $OnB).Count
|
||||
$PK = Start-Pusher "kitchen-2" $OnA; $Pushers += $PK
|
||||
Start-Sleep -Seconds 1
|
||||
Kill-Srv $SB
|
||||
Start-Sleep -Seconds 6 # a backlog for B
|
||||
Stop-Pusher $PK
|
||||
$Total = (Head "kitchen" $OnA).Max
|
||||
$SB = Start-Srv "b"; Wait-Port 12416 $SB
|
||||
# Killed as soon as some of the backlog is in, not all of it.
|
||||
$D = (Get-Date).AddSeconds(30)
|
||||
do {
|
||||
$Mid = Head "kitchen" $OnB
|
||||
if ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) { Kill-Srv $SB; break }
|
||||
Start-Sleep -Milliseconds 20
|
||||
} while ($Mid.Count -lt $Total -and (Get-Date) -lt $D)
|
||||
Check "B killed partway through its catch-up" ($Mid.Count -gt $Before -and $Mid.Count -lt $Total) `
|
||||
("B had {0} kitchen messages before, {1} when killed, A {2}" -f $Before, $Mid.Count, $Total)
|
||||
if (-not $SB.P.HasExited) { Kill-Srv $SB }
|
||||
$SB = Start-Srv "b"; Wait-Port 12416 $SB
|
||||
$C = Wait-Converged $Total 0
|
||||
Check "B restarted, still converged" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
|
||||
$H = Head "kitchen" $OnB
|
||||
Check "B's copy of kitchen has no gap" ($H.Count -eq $H.Max -and $H.Max -eq $Total) ("{0} stored, last #{1}, A's last #{2}" -f $H.Count, $H.Max, $Total)
|
||||
|
||||
"--- 3. A killed while both push, B keeps pushing, A restarted"
|
||||
$PK = Start-Pusher "kitchen-3" $OnA; $PG = Start-Pusher "garage-3" $OnB; $Pushers += $PK, $PG
|
||||
Start-Sleep -Seconds 3
|
||||
Kill-Srv $SA
|
||||
$null = $PK.P.WaitForExit(15000)
|
||||
Start-Sleep -Seconds 3 # B goes on alone
|
||||
Stop-Pusher $PG
|
||||
$GSeen = Read-Pusher $PG
|
||||
Check "the kitchen pusher noticed A was gone: ConnectionLostError, code 104" ($PK.P.HasExited -and (Read-Pusher $PK).End -like "ERR 104 ConnectionLostError*") (Read-Pusher $PK).End
|
||||
|
||||
$SA = Start-Srv "a"; Wait-Port 12415 $SA
|
||||
Check-Survived "A" "kitchen" $PK $OnA
|
||||
$HK = $Survived
|
||||
$R = Tool "BakaShrotPushMessage.exe" @($Next, $OnA)
|
||||
Check "A: the next push carries on from the last id" ($R.Out -match "message #$($HK.Max + 1)\b") ("after #{0}: {1}" -f $HK.Max, $R.Out)
|
||||
$C = Wait-Converged ($HK.Max + 1) $GSeen.LastId
|
||||
Check "A and B converged again" $C.Ok ("A {0}`n B {1}" -f $C.A, $C.B)
|
||||
|
||||
"--- Logs"
|
||||
$Bad = @(Get-ChildItem $Dir -Filter "*.log" | Select-String "Failed|refused|corrupt|malformed" | Where-Object { $_.Line -notmatch "Failed to connect|Lost the link|link to .* failed" })
|
||||
Check "no failure in either server's logs, other than the links lost to the kills" ($Bad.Count -eq 0) $(if ($Bad.Count) { ($Bad | Select-Object -First 5 | ForEach-Object { "$($_.Filename): $($_.Line)" }) -join " | " } else { "none" })
|
||||
} finally {
|
||||
foreach ($Pu in $Pushers) { if (-not $Pu.P.HasExited) { Stop-Process -Id $Pu.P.Id -Force } }
|
||||
Stop-Srv $SA; Stop-Srv $SB
|
||||
}
|
||||
|
||||
""
|
||||
if ($Fails) { "$Fails FAILED"; exit 1 } else { "All passed" }
|
||||
+22
-22
@@ -1,8 +1,8 @@
|
||||
# End-to-end test of pushed_at and [BakaShrot.Retention]:
|
||||
# - a database from before pushed_at gets it (the time of the upgrade), and
|
||||
# its ids go on;
|
||||
# - a push is stamped with the time it arrived (UTC), GetMessages --time
|
||||
# and GetLatestMessage show it, replication carries it as is;
|
||||
# - a push is stamped with the time it arrived (UTC), BakaShrotGetMessages
|
||||
# --time and BakaShrotGetLatestMessage show it, replication carries it as is;
|
||||
# - each server deletes a topic's messages past its own max age (by name,
|
||||
# by pattern, "*"), only its own: the peer keeps its copies;
|
||||
# - after deleting, ids go on, and the peer doesn't send them again;
|
||||
@@ -27,7 +27,7 @@ $Server = Join-Path $Build "Bench\BenchServer.exe"
|
||||
$Fails = 0
|
||||
|
||||
function New-KeyPair {
|
||||
$L = & (Join-Path $Build "KeyGen.exe")
|
||||
$L = & (Join-Path $Build "BakaShrotGenerateKeyPairs.exe")
|
||||
@{ Priv = $L[0] -replace "^PrivateKey = ", ""; Pub = $L[1] -replace "^PublicKey = ", "" }
|
||||
}
|
||||
function Test-Port($P) {
|
||||
@@ -68,7 +68,7 @@ function Wait-Port($Port, $S) {
|
||||
}
|
||||
function Query($Sql, $Ini) {
|
||||
$F = Join-Path $Dir "q.sql"; Set-Content $F -Encoding Ascii -Value $Sql
|
||||
Tool "Query.exe" @("@$F", $Ini)
|
||||
Tool "BakaShrotQuery.exe" @("@$F", $Ini)
|
||||
}
|
||||
# Waits until Sql answers something matching Pattern, for up to Seconds.
|
||||
function Wait-Query($Sql, $Ini, $Pattern, $Seconds = 20) {
|
||||
@@ -90,7 +90,7 @@ function Push($Data, $Ini, [string]$Topic = "") {
|
||||
[IO.File]::WriteAllText($F, $Data, (New-Object System.Text.UTF8Encoding $false))
|
||||
$A = @()
|
||||
if ($Topic) { $A += @("-t", $Topic) }
|
||||
Tool "PushMessage.exe" ($A + @("@$F", $Ini))
|
||||
Tool "BakaShrotPushMessage.exe" ($A + @("@$F", $Ini))
|
||||
}
|
||||
|
||||
$A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
|
||||
@@ -99,7 +99,6 @@ $A = New-KeyPair; $B = New-KeyPair; $K = New-KeyPair
|
||||
Set-Content (Join-Path $Dir "a.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($A.Priv)
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -128,17 +127,18 @@ RetentionInterval = 1
|
||||
[BakaShrot.Peer.b]
|
||||
Host = 127.0.0.1
|
||||
Port = 12409
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
PublicKey = $($B.Pub)
|
||||
|
||||
[BakaShrot.Client.b]
|
||||
PublicKeys = $($B.Pub)
|
||||
Identities = logs:serverB
|
||||
Node = serverB
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
PushTopics = logs;short;keep;late
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
@@ -148,7 +148,6 @@ AllowQuery = 1
|
||||
Set-Content (Join-Path $Dir "b.ini") -Encoding Ascii -Value @"
|
||||
[BakaShrot]
|
||||
PrivateKey = $($B.Priv)
|
||||
Topic = logs
|
||||
Node = serverB
|
||||
|
||||
[BakaShrot.Topics]
|
||||
@@ -180,17 +179,18 @@ RetentionInterval = 1
|
||||
[BakaShrot.Peer.a]
|
||||
Host = 127.0.0.1
|
||||
Port = 12408
|
||||
Topic = logs
|
||||
Node = serverA
|
||||
PublicKey = $($A.Pub)
|
||||
|
||||
[BakaShrot.Client.a]
|
||||
PublicKeys = $($A.Pub)
|
||||
Identities = logs:serverA
|
||||
Node = serverA
|
||||
DefaultTopic = logs
|
||||
|
||||
[BakaShrot.Client.kitchen]
|
||||
PublicKeys = $($K.Pub)
|
||||
Identities = logs:kitchen
|
||||
Node = kitchen
|
||||
DefaultTopic = logs
|
||||
ReadTopics = *
|
||||
AllowQuery = 1
|
||||
"@
|
||||
@@ -198,7 +198,7 @@ AllowQuery = 1
|
||||
$ServerKeys = @{ 12408 = $A.Pub; 12409 = $B.Pub }
|
||||
function Client-Ini($Name, $Port) {
|
||||
$P = Join-Path $Dir "$Name.ini"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nTopic = logs`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
Set-Content $P -Encoding Ascii -Value "[BakaShrot]`r`nPrivateKey = $($K.Priv)`r`nPublicKey = $($K.Pub)`r`nNode = kitchen`r`nServerHost = 127.0.0.1`r`nServerPort = $Port`r`nServerPublicKey = $($ServerKeys[$Port])"
|
||||
$P
|
||||
}
|
||||
$OnA = Client-Ini "kitchen-a" 12408
|
||||
@@ -253,17 +253,17 @@ try {
|
||||
$Expected = [DateTimeOffset]::FromUnixTimeMilliseconds($Stamp).UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffZ")
|
||||
Check "the view's pushed_utc is the same, as text" ($Utc -eq $Expected) "$Utc, expected $Expected"
|
||||
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA)
|
||||
Check "GetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out
|
||||
$R = Tool "GetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA)
|
||||
Check "GetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out
|
||||
Expect "GetLatestMessage shows it" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected))
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", "--time", $OnA)
|
||||
Check "BakaShrotGetMessages --time: id, time, data" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t$Expected`t{`"n`":`"stamped`"}") $R.Out
|
||||
$R = Tool "BakaShrotGetMessages.exe" @("logs", "kitchen", "--after", "2", $OnA)
|
||||
Check "BakaShrotGetMessages without --time: as before" ($R.Code -eq 0 -and $R.Lines.Count -eq 1 -and $R.Lines[0] -eq "3`t{`"n`":`"stamped`"}") $R.Out
|
||||
Expect "BakaShrotGetLatestMessage shows it" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnA)) ("#3 \(ids 1:2\), pushed " + [regex]::Escape($Expected))
|
||||
|
||||
$Sql = "SELECT message_id, pushed_at FROM messages WHERE topic = 'logs' AND node = 'kitchen' ORDER BY message_id"
|
||||
$OnAStamps = (Query $Sql $OnA).Out
|
||||
$R = Wait-Query $Sql $OnB '"3","\d+"'
|
||||
Check "replicated with the same pushed_at, every one" ($R.Out -eq $OnAStamps) "A $OnAStamps | B $($R.Out)"
|
||||
Expect "GetLatestMessage on B: the same time" (Tool "GetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected))
|
||||
Expect "BakaShrotGetLatestMessage on B: the same time" (Tool "BakaShrotGetLatestMessage.exe" @("logs", "kitchen", $OnB)) ("#3 \(ids 300:30\), pushed " + [regex]::Escape($Expected))
|
||||
|
||||
"--- Retention on A (short = 3s), not on B (short = forever)"
|
||||
foreach ($i in 1..3) { Expect "push short #$i" (Push "{`"short`":$i}" $OnA "short") "message #$i" }
|
||||
@@ -273,7 +273,7 @@ try {
|
||||
Check "A deleted them past 3 s" ($R.Out -match '\[\["0"\]\]') $R.Out
|
||||
Expect "A kept logs (no max age)" (Query (Count "logs") $OnA) '\[\["3"\]\]'
|
||||
Expect "B kept them (its own rules)" (Query (Count "short") $OnB) '\[\["3"\]\]'
|
||||
Expect "A: no message left in short" (Tool "GetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1
|
||||
Expect "A: no message left in short" (Tool "BakaShrotGetLatestMessage.exe" @("short", "kitchen", $OnA)) "No message" 1
|
||||
Expect "A's ids go on after deleting: #4" (Push '{"short":4}' $OnA "short") "message #4"
|
||||
$R = Wait-Query (Count "short") $OnB '\[\["4"\]\]' 10
|
||||
Check "B got #4" ($R.Out -match '\[\["4"\]\]') $R.Out
|
||||
@@ -290,7 +290,7 @@ try {
|
||||
Expect "push keep #3" (Push '{"keep":3}' $OnA "keep") "message #3"
|
||||
$R = Wait-Query (Count "keep") $OnB '\[\["1"\]\]' 10
|
||||
Check "B only got #3, not #1 and #2 again" ($R.Out -match '\[\["1"\]\]') $R.Out
|
||||
Expect "B: it's #3" (Tool "GetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3"
|
||||
Expect "B: it's #3" (Tool "BakaShrotGetLatestMessage.exe" @("keep", "kitchen", $OnB)) "keep:kitchen#3"
|
||||
Expect "B's * = 1h keeps logs" (Query (Count "logs") $OnB) '\[\["3"\]\]'
|
||||
|
||||
"--- Replicated already past the max age (B: late = 3s)"
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Pushes as fast as the server acknowledges, for Tests/Restart-Test.ps1.
|
||||
|
||||
Usage: restart_pusher.py <BakaShrot_Client.dll> <client.ini> <stop file> <out file> <tag>
|
||||
Pushes {"by": tag, "seq": n} to the client's DefaultTopic until the stop
|
||||
file exists, writing "<message id> <seq>" to the out file once each push is
|
||||
acknowledged. Ends with "STOPPED", or "ERR <code> <why>" when the server
|
||||
goes away (the test kills it; code 104, ConnectionLost): what was
|
||||
acknowledged before is what must survive.
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "Interactors", "Python"))
|
||||
from bakashrot import BakaShrotError, Client # noqa: E402
|
||||
|
||||
dll_path, ini_path, stop_path, out_path, tag = sys.argv[1:6]
|
||||
|
||||
client = Client.from_ini(ini_path, dll_path)
|
||||
with open(out_path, "a", buffering=1) as out:
|
||||
try:
|
||||
client.connect()
|
||||
seq = 0
|
||||
while not os.path.exists(stop_path):
|
||||
seq += 1
|
||||
message_id = client.push({"by": tag, "seq": seq})
|
||||
out.write(f"{message_id} {seq}\n")
|
||||
out.write("STOPPED\n")
|
||||
except BakaShrotError as error:
|
||||
out.write(f"ERR {int(error.code)} {type(error).__name__}: {error}\n")
|
||||
finally:
|
||||
try:
|
||||
client.close()
|
||||
except BakaShrotError:
|
||||
pass
|
||||
+8
-5
@@ -84,18 +84,21 @@ class Proxy:
|
||||
base = Client.from_ini(ini_path, dll_path)
|
||||
proxy = Proxy(proxy_port, base.host, base.port)
|
||||
marker = "wire-marker-7f3a91"
|
||||
# The client's DefaultTopic in Python-Test.ps1's server config: its pushes
|
||||
# land there, and it reads them back from there.
|
||||
topic = "logs"
|
||||
|
||||
client = Client(base.private_key, base.public_key, base.server_public_key, base.topic, base.node,
|
||||
client = Client(base.private_key, base.public_key, base.server_public_key, base.node,
|
||||
"127.0.0.1", proxy_port, dll_path)
|
||||
|
||||
# Through the proxy, all of it recorded.
|
||||
try:
|
||||
client.connect()
|
||||
message_id = client.push({"note": marker})
|
||||
latest = client.latest(base.topic, base.node)
|
||||
latest = client.latest(topic, base.node)
|
||||
check("Pushed and read back through the proxy", latest is not None and marker in latest.data,
|
||||
latest.data if latest else "nothing")
|
||||
pages = client.get_messages(base.topic, base.node, after=message_id - 1, limit=10)
|
||||
pages = client.get_messages(topic, base.node, after=message_id - 1, limit=10)
|
||||
check("Read as a run of messages too", any(marker in m.data for m in pages.messages))
|
||||
client.close()
|
||||
except BakaShrotError as error:
|
||||
@@ -104,7 +107,7 @@ except BakaShrotError as error:
|
||||
wire_up, wire_down = bytes(proxy.to_server), bytes(proxy.to_client)
|
||||
check("Something went through both ways", len(wire_up) > 200 and len(wire_down) > 200,
|
||||
f"{len(wire_up)} bytes up, {len(wire_down)} down")
|
||||
for needle in (marker, str(base.node), str(base.topic), base.public_key):
|
||||
for needle in (marker, str(base.node), topic, base.public_key):
|
||||
shown = needle.encode("utf-8")
|
||||
check(f"'{needle[:20]}' never in plain text on the wire", shown not in wire_up and shown not in wire_down)
|
||||
|
||||
@@ -122,7 +125,7 @@ except BakaShrotError as error:
|
||||
check("A tampered request drops the connection", False, "couldn't connect: " + str(error))
|
||||
|
||||
# Another server's key: the server can't open the Hello, nor sign for it.
|
||||
impostor = Client(base.private_key, base.public_key, other_key, base.topic, base.node,
|
||||
impostor = Client(base.private_key, base.public_key, other_key, base.node,
|
||||
base.host, base.port, dll_path)
|
||||
try:
|
||||
impostor.connect()
|
||||
|
||||
+6
-5
@@ -1,5 +1,5 @@
|
||||
; ============================================================================
|
||||
; BakaShrot KeyGen
|
||||
; BakaShrotGenerateKeyPairs
|
||||
;
|
||||
; Generates a new Ed25519 keypair and prints it as two ini-style lines:
|
||||
; PrivateKey = <Base64>
|
||||
@@ -13,6 +13,7 @@
|
||||
|
||||
EnableExplicit
|
||||
|
||||
XIncludeFile "../Common/ToolConsole.pbi"
|
||||
XIncludeFile "../../Commons/Cryptography/Libsodium.pbi"
|
||||
|
||||
|
||||
@@ -22,19 +23,19 @@ OpenConsole()
|
||||
|
||||
If Not InitCryptography()
|
||||
PrintN("Failed to initialize libsodium")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
*PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
|
||||
If Not *PublicKey
|
||||
PrintN("Failed to allocate the public key")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
*PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
|
||||
If Not *PrivateKey
|
||||
PrintN("Failed to allocate the private key")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
GenerateKeyPair(*PublicKey, *PrivateKey)
|
||||
@@ -47,4 +48,4 @@ FillMemory(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize, 0)
|
||||
FreeMemory(*PrivateKey)
|
||||
FreeMemory(*PublicKey)
|
||||
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
+9
-9
@@ -1,7 +1,7 @@
|
||||
; ============================================================================
|
||||
; BakaShrot GetAttachment
|
||||
; BakaShrotGetAttachment
|
||||
;
|
||||
; Usage: GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||
; Usage: BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]
|
||||
; Topic, Node Whose message, each a name or an id.
|
||||
; MessageId Which message.
|
||||
; OutFile Where to save its attachment (replaced).
|
||||
@@ -26,22 +26,22 @@ Define Topic.s, Node.s, MessageText.s, OutFile.s, IniPath.s, MessageId.q, Size.q
|
||||
OpenConsole()
|
||||
|
||||
If CountProgramParameters() < 4
|
||||
PrintN("Usage: GetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]")
|
||||
PrintN("Usage: BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]")
|
||||
PrintN(" Topic and Node are names or ids.")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Topic = ProgramParameter(0)
|
||||
Node = ProgramParameter(1)
|
||||
If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node)
|
||||
PrintN("Invalid topic or node, expected names or ids 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
MessageText = ProgramParameter(2)
|
||||
MessageId = Val(MessageText)
|
||||
If MessageId < 1 Or Str(MessageId) <> MessageText
|
||||
PrintN("Invalid message id '" + MessageText + "'")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
OutFile = ProgramParameter(3)
|
||||
|
||||
@@ -51,7 +51,7 @@ If CountProgramParameters() > 4
|
||||
EndIf
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
StartTime = ElapsedMilliseconds()
|
||||
@@ -59,10 +59,10 @@ Size = BakaShrot_SaveAttachment(Topic, Node, MessageId, OutFile)
|
||||
If Size < 0
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
PrintN("Saved " + Str(Size) + " bytes to '" + OutFile + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
|
||||
|
||||
ToolClient_Close()
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
+10
-10
@@ -1,12 +1,12 @@
|
||||
; ============================================================================
|
||||
; BakaShrot GetLatestMessage
|
||||
; BakaShrotGetLatestMessage
|
||||
;
|
||||
; Usage: GetLatestMessage <Topic> <Node> [ClientIni]
|
||||
; Usage: BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]
|
||||
; Topic, Node Whose latest message to get, each a name or an id.
|
||||
; ClientIni Identity and server to use, defaults to "client.ini".
|
||||
;
|
||||
; Prints the latest message stored for that topic/node, and when it was
|
||||
; pushed (UTC), its attachment if it has one (GetAttachment saves it), then
|
||||
; pushed (UTC), its attachment if it has one (BakaShrotGetAttachment saves it), then
|
||||
; its data. The server refuses
|
||||
; if the client's ReadTopics don't allow the topic, if either is unknown, or
|
||||
; if there's no message.
|
||||
@@ -24,21 +24,21 @@ Define Topic.s, Node.s, IniPath.s
|
||||
OpenConsole()
|
||||
|
||||
If CountProgramParameters() < 2
|
||||
PrintN("Usage: GetLatestMessage <Topic> <Node> [ClientIni]")
|
||||
PrintN("Usage: BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]")
|
||||
PrintN(" Topic and Node are names or ids.")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Topic = ProgramParameter(0)
|
||||
If Not BakaShrot_IsValidRef(Topic)
|
||||
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Node = ProgramParameter(1)
|
||||
If Not BakaShrot_IsValidRef(Node)
|
||||
PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
IniPath = "client.ini"
|
||||
@@ -47,13 +47,13 @@ If CountProgramParameters() > 2
|
||||
EndIf
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_GetLatestMessageOf(Topic, Node)
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) +
|
||||
@@ -68,4 +68,4 @@ EndIf
|
||||
PrintN(BakaShrot_GetMessageDataString())
|
||||
|
||||
ToolClient_Close()
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
+16
-15
@@ -1,7 +1,7 @@
|
||||
; ============================================================================
|
||||
; BakaShrot GetMessages
|
||||
; BakaShrotGetMessages
|
||||
;
|
||||
; Usage: GetMessages <Topic> <Node> [options] [ClientIni]
|
||||
; Usage: BakaShrotGetMessages <Topic> <Node> [options] [ClientIni]
|
||||
; Topic, Node Whose messages to get, each a name or an id.
|
||||
; --after <Id> Starts after that message id, defaults to 0: from the
|
||||
; first one. "latest" starts after the latest one,
|
||||
@@ -41,10 +41,10 @@ OpenConsole()
|
||||
|
||||
; Prints the usage and exits.
|
||||
Procedure Usage()
|
||||
PrintN("Usage: GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--time] [ClientIni]")
|
||||
PrintN("Usage: BakaShrotGetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [--time] [ClientIni]")
|
||||
PrintN(" Topic and Node are names or ids. Prints each message as its id, a tab, and its data.")
|
||||
PrintN(" --time also prints when it was pushed (UTC) between them.")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndProcedure
|
||||
|
||||
; Whether Text is a whole number of digits, 0 or more.
|
||||
@@ -68,7 +68,7 @@ While i < CountProgramParameters()
|
||||
Case "--after", "--limit", "--interval"
|
||||
If i + 1 >= CountProgramParameters()
|
||||
PrintN("Missing the value of " + Argument)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
i + 1
|
||||
Value = ProgramParameter(i)
|
||||
@@ -76,19 +76,19 @@ While i < CountProgramParameters()
|
||||
Case "--after"
|
||||
If LCase(Value) <> "latest" And Not IsNumber(Value)
|
||||
PrintN("Invalid --after '" + Value + "', expected a message id or 'latest'")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
AfterText = LCase(Value)
|
||||
Case "--limit"
|
||||
If Not IsNumber(Value)
|
||||
PrintN("Invalid --limit '" + Value + "', expected a number")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
Limit = Val(Value)
|
||||
Case "--interval"
|
||||
If Not IsNumber(Value) Or Val(Value) < 10 Or Val(Value) > 3600000
|
||||
PrintN("Invalid --interval '" + Value + "', expected 10 to 3600000 ms")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
IntervalMs = Val(Value)
|
||||
EndSelect
|
||||
@@ -118,11 +118,11 @@ If Positional < 2
|
||||
EndIf
|
||||
If Not BakaShrot_IsValidRef(Topic)
|
||||
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
If Not BakaShrot_IsValidRef(Node)
|
||||
PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
If Limit < 0
|
||||
If Follow
|
||||
@@ -133,17 +133,18 @@ If Limit < 0
|
||||
EndIf
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
; "latest": after the latest message, or from the start if there's none yet.
|
||||
If AfterText = "latest"
|
||||
If BakaShrot_GetLatestMessageOf(Topic, Node)
|
||||
AfterMessageId = BakaShrot_GetMessageId()
|
||||
ElseIf Not BakaShrot_IsConnected()
|
||||
ElseIf BakaShrot_GetLastError() <> #BakaShrot_Refused_NotFound
|
||||
; Only "no message yet" starts from the start, anything else is told.
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
Else
|
||||
AfterMessageId = Val(AfterText)
|
||||
@@ -160,7 +161,7 @@ Repeat
|
||||
If Count < 0
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
For n = 0 To Count - 1
|
||||
@@ -186,4 +187,4 @@ Repeat
|
||||
ForEver
|
||||
|
||||
ToolClient_Close()
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
@@ -1,7 +1,7 @@
|
||||
; ============================================================================
|
||||
; BakaShrot ListNames
|
||||
; BakaShrotList
|
||||
;
|
||||
; Usage: ListNames [topics|nodes|all] [ClientIni] [--json]
|
||||
; Usage: BakaShrotList [topics|nodes|all] [ClientIni] [--json]
|
||||
; topics|nodes|all What to list, defaults to all.
|
||||
; ClientIni Identity and server to use, defaults to "client.ini".
|
||||
; --json Prints the DLL's JSON instead of a table.
|
||||
@@ -36,7 +36,7 @@ For i = 0 To CountProgramParameters() - 1
|
||||
Next
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
; Prints one list, from the DLL's JSON.
|
||||
@@ -91,6 +91,6 @@ EndIf
|
||||
|
||||
ToolClient_Close()
|
||||
If Failed
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
@@ -0,0 +1,6 @@
|
||||
IDE Options = PureBasic 6.41 (Windows - x64)
|
||||
CursorPosition = 7
|
||||
Folding = -
|
||||
EnableXP
|
||||
DPIAware
|
||||
CompileSourceDirectory
|
||||
+10
-10
@@ -1,7 +1,7 @@
|
||||
; ============================================================================
|
||||
; BakaShrot PushMessage
|
||||
; BakaShrotPushMessage
|
||||
;
|
||||
; Usage: PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||
; Usage: BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]
|
||||
; -t Topic The topic to push to, a name or an id. Defaults to the
|
||||
; client's own topic (its TopicId). The client's PushTopics on
|
||||
; the server must allow it.
|
||||
@@ -38,14 +38,14 @@ For i = 0 To CountProgramParameters() - 1
|
||||
Topic = ProgramParameter(i)
|
||||
If Not BakaShrot_IsValidRef(Topic)
|
||||
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
ElseIf (Argument = "-a" Or Argument = "--attach") And i < CountProgramParameters() - 1
|
||||
i + 1
|
||||
AttachPath = ProgramParameter(i)
|
||||
If FileSize(AttachPath) < 1
|
||||
PrintN("Can't attach '" + AttachPath + "': no such file, or empty")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
Else
|
||||
AddElement(Arguments())
|
||||
@@ -54,16 +54,16 @@ For i = 0 To CountProgramParameters() - 1
|
||||
Next
|
||||
|
||||
If ListSize(Arguments()) < 1
|
||||
PrintN("Usage: PushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]")
|
||||
PrintN("Usage: BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]")
|
||||
PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
FirstElement(Arguments())
|
||||
JsonData = Arguments()
|
||||
If Left(JsonData, 1) = "@"
|
||||
If Not ToolClient_ReadTextFile(Mid(JsonData, 2), @FileText)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
JsonData = FileText\s
|
||||
EndIf
|
||||
@@ -74,7 +74,7 @@ If NextElement(Arguments())
|
||||
EndIf
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
If AttachPath <> ""
|
||||
@@ -85,7 +85,7 @@ EndIf
|
||||
If MessageId < 1
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
If AttachPath <> ""
|
||||
@@ -95,4 +95,4 @@ Else
|
||||
EndIf
|
||||
|
||||
ToolClient_Close()
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
@@ -1,7 +1,7 @@
|
||||
; ============================================================================
|
||||
; BakaShrot Query
|
||||
; BakaShrotQuery
|
||||
;
|
||||
; Usage: Query <Sql|@SqlFile> [ClientIni]
|
||||
; Usage: BakaShrotQuery <Sql|@SqlFile> [ClientIni]
|
||||
; Sql A single read-only SELECT (or WITH ... SELECT), or @ followed
|
||||
; by a file holding it. Command-line arguments lose their
|
||||
; double quotes, use single quotes or @SqlFile.
|
||||
@@ -24,15 +24,15 @@ Define Sql.s, IniPath.s, FileText.String
|
||||
OpenConsole()
|
||||
|
||||
If CountProgramParameters() < 1
|
||||
PrintN("Usage: Query <Sql|@SqlFile> [ClientIni]")
|
||||
PrintN("Usage: BakaShrotQuery <Sql|@SqlFile> [ClientIni]")
|
||||
PrintN(" Command-line arguments lose their double quotes, use single quotes or @SqlFile.")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Sql = ProgramParameter(0)
|
||||
If Left(Sql, 1) = "@"
|
||||
If Not ToolClient_ReadTextFile(Mid(Sql, 2), @FileText)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
Sql = FileText\s
|
||||
EndIf
|
||||
@@ -43,16 +43,16 @@ If CountProgramParameters() > 1
|
||||
EndIf
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_Query(Sql)
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
PrintN(BakaShrot_GetQueryResultString())
|
||||
|
||||
ToolClient_Close()
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
@@ -1,7 +1,7 @@
|
||||
; ============================================================================
|
||||
; BakaShrot Resolve
|
||||
; BakaShrotResolveIds
|
||||
;
|
||||
; Usage: Resolve <topic|node> <NameOrId> [ClientIni]
|
||||
; Usage: BakaShrotResolveIds <topic|node> <NameOrId> [ClientIni]
|
||||
; topic|node What to look up.
|
||||
; NameOrId A name, to get its id on the server, or an id, to get its name.
|
||||
; ClientIni Identity and server to use, defaults to "client.ini".
|
||||
@@ -23,20 +23,20 @@ Define Kind.s, Ref.s, IniPath.s, Id.l, Name.s
|
||||
OpenConsole()
|
||||
|
||||
If CountProgramParameters() < 2
|
||||
PrintN("Usage: Resolve <topic|node> <NameOrId> [ClientIni]")
|
||||
End 1
|
||||
PrintN("Usage: BakaShrotResolveIds <topic|node> <NameOrId> [ClientIni]")
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Kind = LCase(ProgramParameter(0))
|
||||
If Kind <> "topic" And Kind <> "node"
|
||||
PrintN("Expected 'topic' or 'node', not '" + ProgramParameter(0) + "'")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Ref = ProgramParameter(1)
|
||||
If Not BakaShrot_IsValidRef(Ref)
|
||||
PrintN("Invalid " + Kind + " '" + Ref + "', expected a name or an id 0-65535")
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
IniPath = "client.ini"
|
||||
@@ -45,7 +45,7 @@ If CountProgramParameters() > 2
|
||||
EndIf
|
||||
|
||||
If Not ToolClient_Connect(IniPath)
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
If Kind = "topic"
|
||||
@@ -56,7 +56,7 @@ EndIf
|
||||
If Id < 0
|
||||
ToolClient_PrintFailure()
|
||||
ToolClient_Close()
|
||||
End 1
|
||||
ToolConsole_End(1)
|
||||
EndIf
|
||||
|
||||
Name = BakaShrot_GetResolvedNameString()
|
||||
@@ -66,4 +66,4 @@ EndIf
|
||||
PrintN(Kind + " " + Name + " = " + Str(Id))
|
||||
|
||||
ToolClient_Close()
|
||||
End 0
|
||||
ToolConsole_End(0)
|
||||
@@ -0,0 +1,5 @@
|
||||
IDE Options = PureBasic 6.41 (Windows - x64)
|
||||
CursorPosition = 7
|
||||
EnableXP
|
||||
DPIAware
|
||||
CompileSourceDirectory
|
||||
+36
-15
@@ -5,19 +5,41 @@
|
||||
; The DLL must be next to the tool, the identity and server come from an ini
|
||||
; file laid out like the client.ini Build.ps1 writes:
|
||||
; [BakaShrot]
|
||||
; PrivateKey, PublicKey, Topic, Node, ServerHost, ServerPort,
|
||||
; PrivateKey, PublicKey, Node, ServerHost, ServerPort,
|
||||
; ServerPublicKey (the server's, it logs it when it starts)
|
||||
; Topic and Node can be names or ids (Commons/Networking/Names.pbi). They
|
||||
; were TopicId and NodeId before, still read when Topic and Node are missing.
|
||||
; Node is the node the client writes as, a name or an id
|
||||
; (Commons/Networking/Names.pbi); NodeId before, still read when Node is
|
||||
; missing. A Topic (TopicId) left in it is ignored: the client's default
|
||||
; topic is in the server's config (DefaultTopic).
|
||||
; ============================================================================
|
||||
|
||||
XIncludeFile "../../Client/BakaShrot_Client_Prototypes.pbi"
|
||||
XIncludeFile "ToolConsole.pbi"
|
||||
|
||||
|
||||
; What a client error code (100+, BakaShrot_ErrorCodes.pbi) means, for the
|
||||
; tools' messages.
|
||||
Procedure.s ToolClient_Explain(Code.l)
|
||||
Select Code
|
||||
Case #BakaShrot_Error_NotConnected : ProcedureReturn "not connected"
|
||||
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "nothing answers there"
|
||||
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "the server closed the connection: wrong ServerPublicKey, a key or node it doesn't allow, or another version (its log says which)"
|
||||
Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "the server couldn't prove it holds ServerPublicKey's private key"
|
||||
Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "the connection to the server failed"
|
||||
Case #BakaShrot_Error_ProtocolError : ProcedureReturn "the server answered something unexpected, the connection is closed"
|
||||
Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "an invalid argument"
|
||||
Case #BakaShrot_Error_FileError : ProcedureReturn "a file couldn't be opened, read or written"
|
||||
Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "the attachment doesn't match its SHA-256"
|
||||
Case #BakaShrot_Error_Internal : ProcedureReturn "out of memory, or another failure in the client"
|
||||
EndSelect
|
||||
ProcedureReturn BakaShrot_ErrorName(Code)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Loads the DLL, reads IniPath and connects to its server with its identity.
|
||||
; Prints what failed and returns #False on failure, the DLL is then unloaded.
|
||||
Procedure.i ToolClient_Connect(IniPath.s)
|
||||
Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Topic.s, Node.s, ServerHost.s, ServerPort.l
|
||||
Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l
|
||||
|
||||
If Not OpenPreferences(IniPath)
|
||||
PrintN("Failed to open '" + IniPath + "'")
|
||||
@@ -27,7 +49,6 @@ Procedure.i ToolClient_Connect(IniPath.s)
|
||||
PrivateKey = ReadPreferenceString("PrivateKey", "")
|
||||
PublicKey = ReadPreferenceString("PublicKey", "")
|
||||
ServerPublicKey = ReadPreferenceString("ServerPublicKey", "")
|
||||
Topic = Trim(ReadPreferenceString("Topic", ReadPreferenceString("TopicId", "")))
|
||||
Node = Trim(ReadPreferenceString("Node", ReadPreferenceString("NodeId", "")))
|
||||
ServerHost = ReadPreferenceString("ServerHost", "")
|
||||
ServerPort = ReadPreferenceLong("ServerPort", 0)
|
||||
@@ -56,12 +77,6 @@ Procedure.i ToolClient_Connect(IniPath.s)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_SetTopic(Topic)
|
||||
PrintN("Invalid Topic '" + Topic + "' in '" + IniPath + "', expected a name or an id")
|
||||
BakaShrot_UnloadClient()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_SetNode(Node)
|
||||
PrintN("Invalid Node '" + Node + "' in '" + IniPath + "', expected a name or an id")
|
||||
BakaShrot_UnloadClient()
|
||||
@@ -69,7 +84,7 @@ Procedure.i ToolClient_Connect(IniPath.s)
|
||||
EndIf
|
||||
|
||||
If Not BakaShrot_Connect(ServerHost, ServerPort)
|
||||
PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort))
|
||||
PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort) + " (" + BakaShrot_ErrorName(BakaShrot_GetLastError()) + "): " + ToolClient_Explain(BakaShrot_GetLastError()))
|
||||
BakaShrot_UnloadClient()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
@@ -93,11 +108,17 @@ EndProcedure
|
||||
|
||||
|
||||
; Prints why the last request failed.
|
||||
; With its code's name (BakaShrot_ErrorCodes.pbi), for scripts to match on.
|
||||
Procedure ToolClient_PrintFailure()
|
||||
If BakaShrot_IsConnected()
|
||||
PrintN("Refused by the server: " + BakaShrot_GetRefusalReasonString())
|
||||
Protected Code.l = BakaShrot_GetLastError()
|
||||
|
||||
If BakaShrot_IsRefusalCode(Code)
|
||||
PrintN("Refused by the server (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString())
|
||||
ElseIf BakaShrot_GetRefusalReasonString() <> ""
|
||||
; The client's own refusals: a message or attachment over the limits...
|
||||
PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString())
|
||||
Else
|
||||
PrintN("The connection to the server failed")
|
||||
PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + ToolClient_Explain(Code))
|
||||
EndIf
|
||||
EndProcedure
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
; ============================================================================
|
||||
; BakaShrot Tools - Console
|
||||
;
|
||||
; Shared by every tool. Started from Explorer (a double-click, a shortcut),
|
||||
; a console program gets a console of its own that closes as soon as it
|
||||
; ends, before what it printed can be read: ToolConsole_End() waits for
|
||||
; Enter then, and ends at once otherwise.
|
||||
; As https://github.com/aziascreations/PB-Template-Win32-CliApp does it: a
|
||||
; program started from a shell shares the shell's console, one started
|
||||
; directly is alone in its own.
|
||||
; ============================================================================
|
||||
|
||||
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
|
||||
; Not in PureBasic 5.73's API functions, named so it can't clash with a
|
||||
; compiler that has it.
|
||||
Import "kernel32.lib"
|
||||
CompilerIf #PB_Compiler_Processor = #PB_Processor_x86
|
||||
ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "_GetConsoleProcessList@8"
|
||||
CompilerElse
|
||||
ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "GetConsoleProcessList"
|
||||
CompilerEndIf
|
||||
EndImport
|
||||
CompilerEndIf
|
||||
|
||||
|
||||
; #True if the tool was started directly rather than from a shell: it is the
|
||||
; only process on its console. Input or output redirected is #False, someone
|
||||
; else reads it (a test starting it with Start-Process gets a new hidden
|
||||
; console too, alone on it). Always #False outside of Windows.
|
||||
Procedure.i ToolConsole_IsRunDirectly()
|
||||
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
|
||||
Protected Mode.l, ProcessList.q ; ProcessList: room for 2 process ids
|
||||
|
||||
If Not GetConsoleMode_(GetStdHandle_(#STD_INPUT_HANDLE), @Mode)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
If Not GetConsoleMode_(GetStdHandle_(#STD_OUTPUT_HANDLE), @Mode)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
ProcedureReturn Bool(ToolConsole_GetConsoleProcessList(@ProcessList, 2) <= 1)
|
||||
CompilerElse
|
||||
ProcedureReturn #False
|
||||
CompilerEndIf
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Ends the tool with ExitCode, after waiting for Enter if it was started
|
||||
; directly (ToolConsole_IsRunDirectly()).
|
||||
Procedure ToolConsole_End(ExitCode.i)
|
||||
If ToolConsole_IsRunDirectly()
|
||||
PrintN("")
|
||||
Print("Press Enter to close...")
|
||||
Input()
|
||||
EndIf
|
||||
End ExitCode
|
||||
EndProcedure
|
||||
Reference in New Issue
Block a user