1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
+133
View File
@@ -0,0 +1,133 @@
; ============================================================================
; BakaShrot Tools - Client connection
;
; Shared by the tools that talk to a server through BakaShrot_Client.dll.
; The DLL must be next to the tool, the identity and server come from an ini
; file laid out like the client.ini Build.ps1 writes:
; [BakaShrot]
; PrivateKey, PublicKey, Topic, Node, ServerHost, ServerPort,
; ServerPublicKey (the server's, it logs it when it starts)
; Topic and Node can be names or ids (Commons/Networking/Names.pbi). They
; were TopicId and NodeId before, still read when Topic and Node are missing.
; ============================================================================
XIncludeFile "../../Client/BakaShrot_Client_Prototypes.pbi"
; Loads the DLL, reads IniPath and connects to its server with its identity.
; Prints what failed and returns #False on failure, the DLL is then unloaded.
Procedure.i ToolClient_Connect(IniPath.s)
Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Topic.s, Node.s, ServerHost.s, ServerPort.l
If Not OpenPreferences(IniPath)
PrintN("Failed to open '" + IniPath + "'")
ProcedureReturn #False
EndIf
PreferenceGroup("BakaShrot")
PrivateKey = ReadPreferenceString("PrivateKey", "")
PublicKey = ReadPreferenceString("PublicKey", "")
ServerPublicKey = ReadPreferenceString("ServerPublicKey", "")
Topic = Trim(ReadPreferenceString("Topic", ReadPreferenceString("TopicId", "")))
Node = Trim(ReadPreferenceString("Node", ReadPreferenceString("NodeId", "")))
ServerHost = ReadPreferenceString("ServerHost", "")
ServerPort = ReadPreferenceLong("ServerPort", 0)
ClosePreferences()
If Not BakaShrot_LoadClient(GetPathPart(ProgramFilename()) + "BakaShrot_Client.dll")
PrintN("Failed to load BakaShrot_Client.dll")
ProcedureReturn #False
EndIf
If Not BakaShrot_SetPrivateKey(PrivateKey)
PrintN("Invalid PrivateKey in '" + IniPath + "'")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetPublicKey(PublicKey)
PrintN("Invalid PublicKey in '" + IniPath + "'")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetServerPublicKey(ServerPublicKey)
PrintN("Missing or invalid ServerPublicKey in '" + IniPath + "', the server logs it when it starts")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetTopic(Topic)
PrintN("Invalid Topic '" + Topic + "' in '" + IniPath + "', expected a name or an id")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetNode(Node)
PrintN("Invalid Node '" + Node + "' in '" + IniPath + "', expected a name or an id")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_Connect(ServerHost, ServerPort)
PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort))
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Disconnects and unloads the DLL.
Procedure ToolClient_Close()
BakaShrot_Disconnect()
BakaShrot_UnloadClient()
EndProcedure
; Prints why the last request failed.
Procedure ToolClient_PrintFailure()
If BakaShrot_IsConnected()
PrintN("Refused by the server: " + BakaShrot_GetRefusalReasonString())
Else
PrintN("The connection to the server failed")
EndIf
EndProcedure
; Reads a whole UTF-8 text file (a byte order mark is skipped) into *Text.
; In one go: ReadString() with #PB_File_IgnoreEOL takes seconds on a 16 MB
; line. Prints why and returns #False if it can't be read.
Procedure.i ToolClient_ReadTextFile(Path.s, *Text.String)
Protected FileId.i, Size.q, *Data, Offset.i
FileId = ReadFile(#PB_Any, Path)
If Not FileId
PrintN("Failed to open '" + Path + "'")
ProcedureReturn #False
EndIf
Size = Lof(FileId)
*Data = AllocateMemory(Size + 1)
If Not *Data
CloseFile(FileId)
PrintN("'" + Path + "' is too big to read")
ProcedureReturn #False
EndIf
If ReadData(FileId, *Data, Size) <> Size
FreeMemory(*Data)
CloseFile(FileId)
PrintN("Failed to read '" + Path + "'")
ProcedureReturn #False
EndIf
CloseFile(FileId)
If Size >= 3 And PeekA(*Data) = $EF And PeekA(*Data + 1) = $BB And PeekA(*Data + 2) = $BF
Offset = 3
EndIf
*Text\s = ""
If Size > Offset
*Text\s = PeekS(*Data + Offset, Size - Offset, #PB_UTF8 | #PB_ByteLength)
EndIf
FreeMemory(*Data)
ProcedureReturn #True
EndProcedure
@@ -0,0 +1,62 @@
; ============================================================================
; BakaShrot GetLatestMessage
;
; Usage: GetLatestMessage <Topic> <Node> [ClientIni]
; Topic, Node Whose latest message to get, each a name or an id.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Prints the latest message stored for that topic/node, the server refuses
; if the client's ReadTopics don't allow the topic, if either is unknown, or
; if there's no message.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
Define Topic.s, Node.s, IniPath.s
OpenConsole()
If CountProgramParameters() < 2
PrintN("Usage: GetLatestMessage <Topic> <Node> [ClientIni]")
PrintN(" Topic and Node are names or ids.")
End 1
EndIf
Topic = ProgramParameter(0)
If Not BakaShrot_IsValidRef(Topic)
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
End 1
EndIf
Node = ProgramParameter(1)
If Not BakaShrot_IsValidRef(Node)
PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535")
End 1
EndIf
IniPath = "client.ini"
If CountProgramParameters() > 2
IniPath = ProgramParameter(2)
EndIf
If Not ToolClient_Connect(IniPath)
End 1
EndIf
If Not BakaShrot_GetLatestMessageOf(Topic, Node)
ToolClient_PrintFailure()
ToolClient_Close()
End 1
EndIf
PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) +
" (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + ")")
PrintN(BakaShrot_GetMessageDataString())
ToolClient_Close()
End 0
+180
View File
@@ -0,0 +1,180 @@
; ============================================================================
; BakaShrot GetMessages
;
; Usage: GetMessages <Topic> <Node> [options] [ClientIni]
; Topic, Node Whose messages to get, each a name or an id.
; --after <Id> Starts after that message id, defaults to 0: from the
; first one. "latest" starts after the latest one,
; only new messages then (with --follow).
; --limit <N> Stops after N messages, defaults to 100, or to no
; limit with --follow. 0 is no limit.
; --follow, -f Keeps going once caught up: checks for new messages
; every --interval ms, until stopped (Ctrl+C) or the
; connection fails.
; --interval <Ms> How often --follow checks, defaults to 500.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Prints each message on its own line, in message id order, as its id, a
; tab, and its data as stored (JSON or not, a message with line breaks spans
; several lines). The server refuses if the client's ReadTopics don't allow
; the topic, or if either is unknown.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
; Most messages asked for at once, the server's maximum.
#GetMessages_BatchLimit = 10000
Define Topic.s, Node.s, IniPath.s = "client.ini", AfterText.s = "0"
Define Limit.q = -1, Follow.i = #False, IntervalMs.i = 500
Define i.i, Argument.s, Value.s, Positional.i
Define AfterMessageId.q, Printed.q, Asked.l, Count.l, n.l
OpenConsole()
; Prints the usage and exits.
Procedure Usage()
PrintN("Usage: GetMessages <Topic> <Node> [--after <Id|latest>] [--limit <N>] [--follow] [--interval <Ms>] [ClientIni]")
PrintN(" Topic and Node are names or ids. Prints each message as its id, a tab, and its data.")
End 1
EndProcedure
; Whether Text is a whole number of digits, 0 or more.
Procedure.i IsNumber(Text.s)
Protected i.i
If Text = "" Or Len(Text) > 18
ProcedureReturn #False
EndIf
For i = 1 To Len(Text)
If Mid(Text, i, 1) < "0" Or Mid(Text, i, 1) > "9"
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
i = 0
While i < CountProgramParameters()
Argument = ProgramParameter(i)
Select LCase(Argument)
Case "--after", "--limit", "--interval"
If i + 1 >= CountProgramParameters()
PrintN("Missing the value of " + Argument)
End 1
EndIf
i + 1
Value = ProgramParameter(i)
Select LCase(Argument)
Case "--after"
If LCase(Value) <> "latest" And Not IsNumber(Value)
PrintN("Invalid --after '" + Value + "', expected a message id or 'latest'")
End 1
EndIf
AfterText = LCase(Value)
Case "--limit"
If Not IsNumber(Value)
PrintN("Invalid --limit '" + Value + "', expected a number")
End 1
EndIf
Limit = Val(Value)
Case "--interval"
If Not IsNumber(Value) Or Val(Value) < 10 Or Val(Value) > 3600000
PrintN("Invalid --interval '" + Value + "', expected 10 to 3600000 ms")
End 1
EndIf
IntervalMs = Val(Value)
EndSelect
Case "--follow", "-f"
Follow = #True
Default
If Left(Argument, 2) = "--"
PrintN("Unknown option '" + Argument + "'")
Usage()
EndIf
Select Positional
Case 0 : Topic = Argument
Case 1 : Node = Argument
Case 2 : IniPath = Argument
Default
Usage()
EndSelect
Positional + 1
EndSelect
i + 1
Wend
If Positional < 2
Usage()
EndIf
If Not BakaShrot_IsValidRef(Topic)
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
End 1
EndIf
If Not BakaShrot_IsValidRef(Node)
PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535")
End 1
EndIf
If Limit < 0
If Follow
Limit = 0
Else
Limit = 100
EndIf
EndIf
If Not ToolClient_Connect(IniPath)
End 1
EndIf
; "latest": after the latest message, or from the start if there's none yet.
If AfterText = "latest"
If BakaShrot_GetLatestMessageOf(Topic, Node)
AfterMessageId = BakaShrot_GetMessageId()
ElseIf Not BakaShrot_IsConnected()
ToolClient_PrintFailure()
ToolClient_Close()
End 1
EndIf
Else
AfterMessageId = Val(AfterText)
EndIf
Printed = 0
Repeat
Asked = #GetMessages_BatchLimit
If Limit > 0 And Limit - Printed < Asked
Asked = Limit - Printed
EndIf
Count = BakaShrot_GetMessages(Topic, Node, AfterMessageId, Asked)
If Count < 0
ToolClient_PrintFailure()
ToolClient_Close()
End 1
EndIf
For n = 0 To Count - 1
BakaShrot_SelectMessage(n)
AfterMessageId = BakaShrot_GetMessageId()
PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString())
Next
Printed + Count
If Limit > 0 And Printed >= Limit
Break
EndIf
If Not BakaShrot_HasMoreMessages()
If Not Follow
Break
EndIf
Delay(IntervalMs)
EndIf
ForEver
ToolClient_Close()
End 0
+50
View File
@@ -0,0 +1,50 @@
; ============================================================================
; BakaShrot KeyGen
;
; Generates a new Ed25519 keypair and prints it as two ini-style lines:
; PrivateKey = <Base64>
; PublicKey = <Base64>
;
; The private key goes in the node's own [BakaShrot] PrivateKey, the public
; key goes in the configs of whoever needs to trust that node.
;
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../../Commons/Cryptography/Libsodium.pbi"
Define *PublicKey, *PrivateKey
OpenConsole()
If Not InitCryptography()
PrintN("Failed to initialize libsodium")
End 1
EndIf
*PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
If Not *PublicKey
PrintN("Failed to allocate the public key")
End 1
EndIf
*PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
If Not *PrivateKey
PrintN("Failed to allocate the private key")
End 1
EndIf
GenerateKeyPair(*PublicKey, *PrivateKey)
PrintN("PrivateKey = " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize))
PrintN("PublicKey = " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize))
; Don't leave the private key lying around in freed memory.
FillMemory(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize, 0)
FreeMemory(*PrivateKey)
FreeMemory(*PublicKey)
End 0
+96
View File
@@ -0,0 +1,96 @@
; ============================================================================
; BakaShrot ListNames
;
; Usage: ListNames [topics|nodes|all] [ClientIni] [--json]
; topics|nodes|all What to list, defaults to all.
; ClientIni Identity and server to use, defaults to "client.ini".
; --json Prints the DLL's JSON instead of a table.
;
; Lists every topic and node the server has, with this server's id and its
; name: what the names in requests and queries stand for there. Unnamed ones
; aren't replicated. Topics: only those the client may push to or read,
; unless it may query.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
Define What.s = "all", IniPath.s = "client.ini", AsJson.i = #False
Define i.i, Argument.s, Count.l, Json.i, Items.i, Item.i, n.i, Name.s, Failed.i
OpenConsole()
For i = 0 To CountProgramParameters() - 1
Argument = ProgramParameter(i)
Select LCase(Argument)
Case "topics", "nodes", "all"
What = LCase(Argument)
Case "--json"
AsJson = #True
Default
IniPath = Argument
EndSelect
Next
If Not ToolClient_Connect(IniPath)
End 1
EndIf
; Prints one list, from the DLL's JSON.
Procedure.i PrintList(Label.s, AsJson.i)
Protected Json.i, Items.i, Item.i, n.i, Name.s, Text.s
Text = BakaShrot_GetNamesListString()
If AsJson
PrintN(Text)
ProcedureReturn #True
EndIf
Json = ParseJSON(#PB_Any, Text)
If Not Json
PrintN("The server's list couldn't be read")
ProcedureReturn #False
EndIf
Items = GetJSONMember(JSONValue(Json), "items")
PrintN(Label + " (" + Str(JSONArraySize(Items)) + "):")
For n = 0 To JSONArraySize(Items) - 1
Item = GetJSONElement(Items, n)
Name = GetJSONString(GetJSONMember(Item, "name"))
If Name = ""
Name = "(unnamed, not replicated)"
EndIf
PrintN(" " + RSet(Str(GetJSONInteger(GetJSONMember(Item, "id"))), 5) + " " + LSet(Name, 30) + " " + GetJSONString(GetJSONMember(Item, "origin")))
Next
If GetJSONBoolean(GetJSONMember(JSONValue(Json), "truncated"))
PrintN(" ... more than fit in one answer")
EndIf
FreeJSON(Json)
ProcedureReturn #True
EndProcedure
Failed = #False
If What = "topics" Or What = "all"
If BakaShrot_ListTopics() < 0
ToolClient_PrintFailure()
Failed = #True
ElseIf Not PrintList("Topics", AsJson)
Failed = #True
EndIf
EndIf
If Not Failed And (What = "nodes" Or What = "all")
If BakaShrot_ListNodes() < 0
ToolClient_PrintFailure()
Failed = #True
ElseIf Not PrintList("Nodes", AsJson)
Failed = #True
EndIf
EndIf
ToolClient_Close()
If Failed
End 1
EndIf
End 0
+80
View File
@@ -0,0 +1,80 @@
; ============================================================================
; BakaShrot PushMessage
;
; Usage: PushMessage [-t <Topic>] <Json|@JsonFile> [ClientIni]
; -t Topic The topic to push to, a name or an id. Defaults to the
; client's own topic (its TopicId). The client's PushTopics on
; the server must allow it.
; Json The message to push, or @ followed by a file holding it.
; Usually JSON, but anything goes: the server flags it in is_json.
; PureBasic's ProgramParameter() drops double quotes and
; doesn't understand \" escapes, so JSON with strings only
; gets through intact from a file: use @JsonFile.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Pushes one message under the client's node, and prints the message id the
; server stored it under.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
Define JsonData.s, IniPath.s, Topic.s, FileText.String, MessageId.q, i.i, Argument.s
Define NewList Arguments.s()
OpenConsole()
For i = 0 To CountProgramParameters() - 1
Argument = ProgramParameter(i)
If (Argument = "-t" Or Argument = "--topic") And i < CountProgramParameters() - 1
i + 1
Topic = ProgramParameter(i)
If Not BakaShrot_IsValidRef(Topic)
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
End 1
EndIf
Else
AddElement(Arguments())
Arguments() = Argument
EndIf
Next
If ListSize(Arguments()) < 1
PrintN("Usage: PushMessage [-t <Topic>] <Json|@JsonFile> [ClientIni]")
PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.")
End 1
EndIf
FirstElement(Arguments())
JsonData = Arguments()
If Left(JsonData, 1) = "@"
If Not ToolClient_ReadTextFile(Mid(JsonData, 2), @FileText)
End 1
EndIf
JsonData = FileText\s
EndIf
IniPath = "client.ini"
If NextElement(Arguments())
IniPath = Arguments()
EndIf
If Not ToolClient_Connect(IniPath)
End 1
EndIf
MessageId = BakaShrot_PushMessageTo(Topic, JsonData)
If MessageId < 1
ToolClient_PrintFailure()
ToolClient_Close()
End 1
EndIf
PrintN("Pushed as message #" + Str(MessageId))
ToolClient_Close()
End 0
+58
View File
@@ -0,0 +1,58 @@
; ============================================================================
; BakaShrot Query
;
; Usage: Query <Sql|@SqlFile> [ClientIni]
; Sql A single read-only SELECT (or WITH ... SELECT), or @ followed
; by a file holding it. Command-line arguments lose their
; double quotes, use single quotes or @SqlFile.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Runs a raw SQL query on the server and prints its result as JSON:
; {"columns": ["name", ...], "rows": [["value", ...], ...]}
; The client must be allowed to query: AllowQuery = 1 in its server-side
; [BakaShrot.Client.<name>].
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
Define Sql.s, IniPath.s, FileText.String
OpenConsole()
If CountProgramParameters() < 1
PrintN("Usage: Query <Sql|@SqlFile> [ClientIni]")
PrintN(" Command-line arguments lose their double quotes, use single quotes or @SqlFile.")
End 1
EndIf
Sql = ProgramParameter(0)
If Left(Sql, 1) = "@"
If Not ToolClient_ReadTextFile(Mid(Sql, 2), @FileText)
End 1
EndIf
Sql = FileText\s
EndIf
IniPath = "client.ini"
If CountProgramParameters() > 1
IniPath = ProgramParameter(1)
EndIf
If Not ToolClient_Connect(IniPath)
End 1
EndIf
If Not BakaShrot_Query(Sql)
ToolClient_PrintFailure()
ToolClient_Close()
End 1
EndIf
PrintN(BakaShrot_GetQueryResultString())
ToolClient_Close()
End 0
+69
View File
@@ -0,0 +1,69 @@
; ============================================================================
; BakaShrot Resolve
;
; Usage: Resolve <topic|node> <NameOrId> [ClientIni]
; topic|node What to look up.
; NameOrId A name, to get its id on the server, or an id, to get its name.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Prints the server's id and name for it, as "topic logs = 1". Each server
; can have different ids for the same names. The server only resolves the
; topics the client may push to or read, unless it may query.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
Define Kind.s, Ref.s, IniPath.s, Id.l, Name.s
OpenConsole()
If CountProgramParameters() < 2
PrintN("Usage: Resolve <topic|node> <NameOrId> [ClientIni]")
End 1
EndIf
Kind = LCase(ProgramParameter(0))
If Kind <> "topic" And Kind <> "node"
PrintN("Expected 'topic' or 'node', not '" + ProgramParameter(0) + "'")
End 1
EndIf
Ref = ProgramParameter(1)
If Not BakaShrot_IsValidRef(Ref)
PrintN("Invalid " + Kind + " '" + Ref + "', expected a name or an id 0-65535")
End 1
EndIf
IniPath = "client.ini"
If CountProgramParameters() > 2
IniPath = ProgramParameter(2)
EndIf
If Not ToolClient_Connect(IniPath)
End 1
EndIf
If Kind = "topic"
Id = BakaShrot_ResolveTopic(Ref)
Else
Id = BakaShrot_ResolveNode(Ref)
EndIf
If Id < 0
ToolClient_PrintFailure()
ToolClient_Close()
End 1
EndIf
Name = BakaShrot_GetResolvedNameString()
If Name = ""
Name = "(unnamed)"
EndIf
PrintN(Kind + " " + Name + " = " + Str(Id))
ToolClient_Close()
End 0