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

Moved the PureBasic version to OldSource/, Started the Rust rewrite in Source/

The rewrite's plan and decisions are in revamp.md. Steps 0 to 10 are done:
the workspace and checks, bakashrot-proto, bakashrot-pki and
bakashrot-cert, bakashrot-config, bakashrot-storage (schema v9), the
server and the client library (every request but replication's,
attachments and retention included), the C DLL with its C, PureBasic and
Python bindings, and the bakashrot tool. Step 11 (replication) is next.

OldSource/ is the old implementation, kept building and passing as the
reference.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
@@ -0,0 +1,68 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotGenerateKeyPairs.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotGenerateKeyPairs
;
; Generates a new Ed25519 keypair and prints it as two ini-style lines:
; PrivateKey = <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 "../Common/ToolConsole.pbi"
XIncludeFile "../../Commons/Cryptography/Libsodium.pbi"
Define *PublicKey, *PrivateKey
OpenConsole()
If Not InitCryptography()
PrintN("Failed to initialize libsodium")
ToolConsole_End(1)
EndIf
*PublicKey = AllocateMemory(#BakaShrot_Ed25519_PublicKeySize)
If Not *PublicKey
PrintN("Failed to allocate the public key")
ToolConsole_End(1)
EndIf
*PrivateKey = AllocateMemory(#BakaShrot_Ed25519_PrivateKeySize)
If Not *PrivateKey
PrintN("Failed to allocate the private key")
ToolConsole_End(1)
EndIf
GenerateKeyPair(*PublicKey, *PrivateKey)
PrintN("PrivateKey = " + EncodeKeyToString(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize))
PrintN("PublicKey = " + EncodeKeyToString(*PublicKey, #BakaShrot_Ed25519_PublicKeySize))
; Don't leave the private key lying around in freed memory.
FillMemory(*PrivateKey, #BakaShrot_Ed25519_PrivateKeySize, 0)
FreeMemory(*PrivateKey)
FreeMemory(*PublicKey)
ToolConsole_End(0)
@@ -0,0 +1,85 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotGetAttachment.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotGetAttachment
;
; Usage: BakaShrotGetAttachment <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).
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Saves the attachment of a message, read from the server a part at a time
; and checked with its SHA-256, and prints its size. The server refuses if
; the client's ReadTopics don't allow the topic, if the message has none, or
; if it isn't on that server yet (a replicated one comes after its message).
; A failed one leaves no file. See Design/Attachments.md.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
Define Topic.s, Node.s, MessageText.s, OutFile.s, IniPath.s, MessageId.q, Size.q, StartTime.i
OpenConsole()
If CountProgramParameters() < 4
PrintN("Usage: BakaShrotGetAttachment <Topic> <Node> <MessageId> <OutFile> [ClientIni]")
PrintN(" Topic and Node are names or ids.")
ToolConsole_End(1)
EndIf
Topic = ProgramParameter(0)
Node = ProgramParameter(1)
If Not BakaShrot_IsValidRef(Topic) Or Not BakaShrot_IsValidRef(Node)
PrintN("Invalid topic or node, expected names or ids 0-65535")
ToolConsole_End(1)
EndIf
MessageText = ProgramParameter(2)
MessageId = Val(MessageText)
If MessageId < 1 Or Str(MessageId) <> MessageText
PrintN("Invalid message id '" + MessageText + "'")
ToolConsole_End(1)
EndIf
OutFile = ProgramParameter(3)
IniPath = "client.ini"
If CountProgramParameters() > 4
IniPath = ProgramParameter(4)
EndIf
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
StartTime = ElapsedMilliseconds()
Size = BakaShrot_SaveAttachment(Topic, Node, MessageId, OutFile)
If Size < 0
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
PrintN("Saved " + Str(Size) + " bytes to '" + OutFile + "' in " + Str(ElapsedMilliseconds() - StartTime) + " ms")
ToolClient_Close()
ToolConsole_End(0)
@@ -0,0 +1,88 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotGetLatestMessage.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotGetLatestMessage
;
; Usage: BakaShrotGetLatestMessage <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 (BakaShrotGetAttachment saves it), then
; its data. The server refuses
; if the client's ReadTopics don't allow the topic, if either is unknown, or
; if there's no message.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
Define Topic.s, Node.s, IniPath.s
OpenConsole()
If CountProgramParameters() < 2
PrintN("Usage: BakaShrotGetLatestMessage <Topic> <Node> [ClientIni]")
PrintN(" Topic and Node are names or ids.")
ToolConsole_End(1)
EndIf
Topic = ProgramParameter(0)
If Not BakaShrot_IsValidRef(Topic)
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
ToolConsole_End(1)
EndIf
Node = ProgramParameter(1)
If Not BakaShrot_IsValidRef(Node)
PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535")
ToolConsole_End(1)
EndIf
IniPath = "client.ini"
If CountProgramParameters() > 2
IniPath = ProgramParameter(2)
EndIf
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
If Not BakaShrot_GetLatestMessageOf(Topic, Node)
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
PrintN("Message " + BakaShrot_GetMessageTopicString() + ":" + BakaShrot_GetMessageNodeString() + "#" + Str(BakaShrot_GetMessageId()) +
" (ids " + Str(BakaShrot_GetMessageTopicId()) + ":" + Str(BakaShrot_GetMessageNodeId()) + "), pushed " + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()))
If BakaShrot_GetMessageAttachmentSize() > 0
If BakaShrot_IsMessageAttachmentReady()
PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes")
Else
PrintN("Attachment: " + Str(BakaShrot_GetMessageAttachmentSize()) + " bytes, not on this server yet")
EndIf
EndIf
PrintN(BakaShrot_GetMessageDataString())
ToolClient_Close()
ToolConsole_End(0)
@@ -0,0 +1,207 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotGetMessages.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotGetMessages
;
; Usage: BakaShrotGetMessages <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.
; --time, -t Also prints when each message was pushed, in UTC.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Prints each message on its own line, in message id order, as its id, a
; tab (with --time: when it was pushed, "2026-11-08T14:03:59.123Z", and
; another tab), and its data as stored (JSON or not, a message with line breaks spans
; several lines). The server refuses if the client's ReadTopics don't allow
; the topic, or if either is unknown.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
; Most messages asked for at once, the server's maximum.
#GetMessages_BatchLimit = 10000
Define Topic.s, Node.s, IniPath.s = "client.ini", AfterText.s = "0"
Define Limit.q = -1, Follow.i = #False, IntervalMs.i = 500, ShowTime.i = #False
Define i.i, Argument.s, Value.s, Positional.i
Define AfterMessageId.q, Printed.q, Asked.l, Count.l, n.l
OpenConsole()
; Prints the usage and exits.
Procedure Usage()
PrintN("Usage: BakaShrotGetMessages <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.")
ToolConsole_End(1)
EndProcedure
; Whether Text is a whole number of digits, 0 or more.
Procedure.i IsNumber(Text.s)
Protected i.i
If Text = "" Or Len(Text) > 18
ProcedureReturn #False
EndIf
For i = 1 To Len(Text)
If Mid(Text, i, 1) < "0" Or Mid(Text, i, 1) > "9"
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
i = 0
While i < CountProgramParameters()
Argument = ProgramParameter(i)
Select LCase(Argument)
Case "--after", "--limit", "--interval"
If i + 1 >= CountProgramParameters()
PrintN("Missing the value of " + Argument)
ToolConsole_End(1)
EndIf
i + 1
Value = ProgramParameter(i)
Select LCase(Argument)
Case "--after"
If LCase(Value) <> "latest" And Not IsNumber(Value)
PrintN("Invalid --after '" + Value + "', expected a message id or 'latest'")
ToolConsole_End(1)
EndIf
AfterText = LCase(Value)
Case "--limit"
If Not IsNumber(Value)
PrintN("Invalid --limit '" + Value + "', expected a number")
ToolConsole_End(1)
EndIf
Limit = Val(Value)
Case "--interval"
If Not IsNumber(Value) Or Val(Value) < 10 Or Val(Value) > 3600000
PrintN("Invalid --interval '" + Value + "', expected 10 to 3600000 ms")
ToolConsole_End(1)
EndIf
IntervalMs = Val(Value)
EndSelect
Case "--time", "-t"
ShowTime = #True
Case "--follow", "-f"
Follow = #True
Default
If Left(Argument, 2) = "--"
PrintN("Unknown option '" + Argument + "'")
Usage()
EndIf
Select Positional
Case 0 : Topic = Argument
Case 1 : Node = Argument
Case 2 : IniPath = Argument
Default
Usage()
EndSelect
Positional + 1
EndSelect
i + 1
Wend
If Positional < 2
Usage()
EndIf
If Not BakaShrot_IsValidRef(Topic)
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
ToolConsole_End(1)
EndIf
If Not BakaShrot_IsValidRef(Node)
PrintN("Invalid node '" + Node + "', expected a name or an id 0-65535")
ToolConsole_End(1)
EndIf
If Limit < 0
If Follow
Limit = 0
Else
Limit = 100
EndIf
EndIf
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
; "latest": after the latest message, or from the start if there's none yet.
If AfterText = "latest"
If BakaShrot_GetLatestMessageOf(Topic, Node)
AfterMessageId = BakaShrot_GetMessageId()
ElseIf BakaShrot_GetLastError() <> #BakaShrot_Refused_NotFound
; Only "no message yet" starts from the start, anything else is told.
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
Else
AfterMessageId = Val(AfterText)
EndIf
Printed = 0
Repeat
Asked = #GetMessages_BatchLimit
If Limit > 0 And Limit - Printed < Asked
Asked = Limit - Printed
EndIf
Count = BakaShrot_GetMessages(Topic, Node, AfterMessageId, Asked)
If Count < 0
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
For n = 0 To Count - 1
BakaShrot_SelectMessage(n)
AfterMessageId = BakaShrot_GetMessageId()
If ShowTime
PrintN(Str(AfterMessageId) + #TAB$ + ToolClient_FormatUtc(BakaShrot_GetMessagePushedAt()) + #TAB$ + BakaShrot_GetMessageDataString())
Else
PrintN(Str(AfterMessageId) + #TAB$ + BakaShrot_GetMessageDataString())
EndIf
Next
Printed + Count
If Limit > 0 And Printed >= Limit
Break
EndIf
If Not BakaShrot_HasMoreMessages()
If Not Follow
Break
EndIf
Delay(IntervalMs)
EndIf
ForEver
ToolClient_Close()
ToolConsole_End(0)
@@ -0,0 +1,113 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotList.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotList
;
; Usage: BakaShrotList [topics|nodes|all] [ClientIni] [--json]
; topics|nodes|all What to list, defaults to all.
; ClientIni Identity and server to use, defaults to "client.ini".
; --json Prints the DLL's JSON instead of a table.
;
; Lists every topic and node the server has, with this server's id and its
; name: what the names in requests and queries stand for there. Unnamed ones
; aren't replicated. Topics: only those the client may push to or read,
; unless it may query.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
Define What.s = "all", IniPath.s = "client.ini", AsJson.i = #False
Define i.i, Argument.s, Count.l, Json.i, Items.i, Item.i, n.i, Name.s, Failed.i
OpenConsole()
For i = 0 To CountProgramParameters() - 1
Argument = ProgramParameter(i)
Select LCase(Argument)
Case "topics", "nodes", "all"
What = LCase(Argument)
Case "--json"
AsJson = #True
Default
IniPath = Argument
EndSelect
Next
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
; Prints one list, from the DLL's JSON.
Procedure.i PrintList(Label.s, AsJson.i)
Protected Json.i, Items.i, Item.i, n.i, Name.s, Text.s
Text = BakaShrot_GetNamesListString()
If AsJson
PrintN(Text)
ProcedureReturn #True
EndIf
Json = ParseJSON(#PB_Any, Text)
If Not Json
PrintN("The server's list couldn't be read")
ProcedureReturn #False
EndIf
Items = GetJSONMember(JSONValue(Json), "items")
PrintN(Label + " (" + Str(JSONArraySize(Items)) + "):")
For n = 0 To JSONArraySize(Items) - 1
Item = GetJSONElement(Items, n)
Name = GetJSONString(GetJSONMember(Item, "name"))
If Name = ""
Name = "(unnamed, not replicated)"
EndIf
PrintN(" " + RSet(Str(GetJSONInteger(GetJSONMember(Item, "id"))), 5) + " " + LSet(Name, 30) + " " + GetJSONString(GetJSONMember(Item, "origin")))
Next
If GetJSONBoolean(GetJSONMember(JSONValue(Json), "truncated"))
PrintN(" ... more than fit in one answer")
EndIf
FreeJSON(Json)
ProcedureReturn #True
EndProcedure
Failed = #False
If What = "topics" Or What = "all"
If BakaShrot_ListTopics() < 0
ToolClient_PrintFailure()
Failed = #True
ElseIf Not PrintList("Topics", AsJson)
Failed = #True
EndIf
EndIf
If Not Failed And (What = "nodes" Or What = "all")
If BakaShrot_ListNodes() < 0
ToolClient_PrintFailure()
Failed = #True
ElseIf Not PrintList("Nodes", AsJson)
Failed = #True
EndIf
EndIf
ToolClient_Close()
If Failed
ToolConsole_End(1)
EndIf
ToolConsole_End(0)
@@ -0,0 +1,6 @@
IDE Options = PureBasic 6.41 (Windows - x64)
CursorPosition = 7
Folding = -
EnableXP
DPIAware
CompileSourceDirectory
@@ -0,0 +1,115 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotPushMessage.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotPushMessage
;
; Usage: BakaShrotPushMessage [-t <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.
; -a File Attaches File to the message (any size up to the server's
; MaxAttachmentSize): uploaded first, the message is only
; stored once all of it is. See Design/Attachments.md.
; Json The message to push, or @ followed by a file holding it.
; Usually JSON, but anything goes: the server flags it in is_json.
; PureBasic's ProgramParameter() drops double quotes and
; doesn't understand \" escapes, so JSON with strings only
; gets through intact from a file: use @JsonFile.
; ClientIni Identity and server to use, defaults to "client.ini".
;
; Pushes one message under the client's node, and prints the message id the
; server stored it under.
; Compile as a console program, exits with 0 on success, 1 on failure.
; ============================================================================
EnableExplicit
XIncludeFile "../Common/ToolClient.pbi"
XIncludeFile "../../Commons/Networking/Names.pbi"
Define JsonData.s, IniPath.s, Topic.s, AttachPath.s, FileText.String, MessageId.q, i.i, Argument.s
Define NewList Arguments.s()
OpenConsole()
For i = 0 To CountProgramParameters() - 1
Argument = ProgramParameter(i)
If (Argument = "-t" Or Argument = "--topic") And i < CountProgramParameters() - 1
i + 1
Topic = ProgramParameter(i)
If Not BakaShrot_IsValidRef(Topic)
PrintN("Invalid topic '" + Topic + "', expected a name or an id 0-65535")
ToolConsole_End(1)
EndIf
ElseIf (Argument = "-a" Or Argument = "--attach") And i < CountProgramParameters() - 1
i + 1
AttachPath = ProgramParameter(i)
If FileSize(AttachPath) < 1
PrintN("Can't attach '" + AttachPath + "': no such file, or empty")
ToolConsole_End(1)
EndIf
Else
AddElement(Arguments())
Arguments() = Argument
EndIf
Next
If ListSize(Arguments()) < 1
PrintN("Usage: BakaShrotPushMessage [-t <Topic>] [-a <File>] <Json|@JsonFile> [ClientIni]")
PrintN(" Command-line arguments lose their double quotes, so use @JsonFile for JSON with strings.")
ToolConsole_End(1)
EndIf
FirstElement(Arguments())
JsonData = Arguments()
If Left(JsonData, 1) = "@"
If Not ToolClient_ReadTextFile(Mid(JsonData, 2), @FileText)
ToolConsole_End(1)
EndIf
JsonData = FileText\s
EndIf
IniPath = "client.ini"
If NextElement(Arguments())
IniPath = Arguments()
EndIf
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
If AttachPath <> ""
MessageId = BakaShrot_PushMessageWithFile(Topic, JsonData, AttachPath)
Else
MessageId = BakaShrot_PushMessageTo(Topic, JsonData)
EndIf
If MessageId < 1
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
If AttachPath <> ""
PrintN("Pushed as message #" + Str(MessageId) + ", with an attachment of " + Str(FileSize(AttachPath)) + " bytes")
Else
PrintN("Pushed as message #" + Str(MessageId))
EndIf
ToolClient_Close()
ToolConsole_End(0)
@@ -0,0 +1,75 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotQuery.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotQuery
;
; Usage: BakaShrotQuery <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: BakaShrotQuery <Sql|@SqlFile> [ClientIni]")
PrintN(" Command-line arguments lose their double quotes, use single quotes or @SqlFile.")
ToolConsole_End(1)
EndIf
Sql = ProgramParameter(0)
If Left(Sql, 1) = "@"
If Not ToolClient_ReadTextFile(Mid(Sql, 2), @FileText)
ToolConsole_End(1)
EndIf
Sql = FileText\s
EndIf
IniPath = "client.ini"
If CountProgramParameters() > 1
IniPath = ProgramParameter(1)
EndIf
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
If Not BakaShrot_Query(Sql)
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
PrintN(BakaShrot_GetQueryResultString())
ToolClient_Close()
ToolConsole_End(0)
@@ -0,0 +1,86 @@
;{- Code Header
; ==- Basic Info -================================
; Name: BakaShrotResolveIds.pb
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrotResolveIds
;
; Usage: BakaShrotResolveIds <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: 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) + "'")
ToolConsole_End(1)
EndIf
Ref = ProgramParameter(1)
If Not BakaShrot_IsValidRef(Ref)
PrintN("Invalid " + Kind + " '" + Ref + "', expected a name or an id 0-65535")
ToolConsole_End(1)
EndIf
IniPath = "client.ini"
If CountProgramParameters() > 2
IniPath = ProgramParameter(2)
EndIf
If Not ToolClient_Connect(IniPath)
ToolConsole_End(1)
EndIf
If Kind = "topic"
Id = BakaShrot_ResolveTopic(Ref)
Else
Id = BakaShrot_ResolveNode(Ref)
EndIf
If Id < 0
ToolClient_PrintFailure()
ToolClient_Close()
ToolConsole_End(1)
EndIf
Name = BakaShrot_GetResolvedNameString()
If Name = ""
Name = "(unnamed)"
EndIf
PrintN(Kind + " " + Name + " = " + Str(Id))
ToolClient_Close()
ToolConsole_End(0)
@@ -0,0 +1,5 @@
IDE Options = PureBasic 6.41 (Windows - x64)
CursorPosition = 7
EnableXP
DPIAware
CompileSourceDirectory
+178
View File
@@ -0,0 +1,178 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ToolClient.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Tools - Client connection
;
; Shared by the tools that talk to a server through BakaShrot_Client.dll.
; The DLL must be next to the tool, the identity and server come from an ini
; file laid out like the client.ini Build.ps1 writes:
; [BakaShrot]
; PrivateKey, PublicKey, Node, ServerHost, ServerPort,
; ServerPublicKey (the server's, it logs it when it starts)
; Node is the node the client writes as, a name or an id
; (Commons/Networking/Names.pbi); NodeId before, still read when Node is
; missing. A Topic (TopicId) left in it is ignored: the client's default
; topic is in the server's config (DefaultTopic).
; ============================================================================
XIncludeFile "../../Client/BakaShrot_Client_Prototypes.pbi"
XIncludeFile "ToolConsole.pbi"
; What a client error code (100+, BakaShrot_ErrorCodes.pbi) means, for the
; tools' messages.
Procedure.s ToolClient_Explain(Code.l)
Select Code
Case #BakaShrot_Error_NotConnected : ProcedureReturn "not connected"
Case #BakaShrot_Error_ConnectFailed : ProcedureReturn "nothing answers there"
Case #BakaShrot_Error_AuthRejected : ProcedureReturn "the server closed the connection: wrong ServerPublicKey, a key or node it doesn't allow, or another version (its log says which)"
Case #BakaShrot_Error_ServerNotVerified : ProcedureReturn "the server couldn't prove it holds ServerPublicKey's private key"
Case #BakaShrot_Error_ConnectionLost : ProcedureReturn "the connection to the server failed"
Case #BakaShrot_Error_ProtocolError : ProcedureReturn "the server answered something unexpected, the connection is closed"
Case #BakaShrot_Error_InvalidArgument : ProcedureReturn "an invalid argument"
Case #BakaShrot_Error_FileError : ProcedureReturn "a file couldn't be opened, read or written"
Case #BakaShrot_Error_AttachmentMismatch : ProcedureReturn "the attachment doesn't match its SHA-256"
Case #BakaShrot_Error_Internal : ProcedureReturn "out of memory, or another failure in the client"
EndSelect
ProcedureReturn BakaShrot_ErrorName(Code)
EndProcedure
; Loads the DLL, reads IniPath and connects to its server with its identity.
; Prints what failed and returns #False on failure, the DLL is then unloaded.
Procedure.i ToolClient_Connect(IniPath.s)
Protected PrivateKey.s, PublicKey.s, ServerPublicKey.s, Node.s, ServerHost.s, ServerPort.l
If Not OpenPreferences(IniPath)
PrintN("Failed to open '" + IniPath + "'")
ProcedureReturn #False
EndIf
PreferenceGroup("BakaShrot")
PrivateKey = ReadPreferenceString("PrivateKey", "")
PublicKey = ReadPreferenceString("PublicKey", "")
ServerPublicKey = ReadPreferenceString("ServerPublicKey", "")
Node = Trim(ReadPreferenceString("Node", ReadPreferenceString("NodeId", "")))
ServerHost = ReadPreferenceString("ServerHost", "")
ServerPort = ReadPreferenceLong("ServerPort", 0)
ClosePreferences()
If Not BakaShrot_LoadClient(GetPathPart(ProgramFilename()) + "BakaShrot_Client.dll")
PrintN("Failed to load BakaShrot_Client.dll")
ProcedureReturn #False
EndIf
If Not BakaShrot_SetPrivateKey(PrivateKey)
PrintN("Invalid PrivateKey in '" + IniPath + "'")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetPublicKey(PublicKey)
PrintN("Invalid PublicKey in '" + IniPath + "'")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetServerPublicKey(ServerPublicKey)
PrintN("Missing or invalid ServerPublicKey in '" + IniPath + "', the server logs it when it starts")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_SetNode(Node)
PrintN("Invalid Node '" + Node + "' in '" + IniPath + "', expected a name or an id")
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
If Not BakaShrot_Connect(ServerHost, ServerPort)
PrintN("Failed to connect and authenticate to " + ServerHost + ":" + Str(ServerPort) + " (" + BakaShrot_ErrorName(BakaShrot_GetLastError()) + "): " + ToolClient_Explain(BakaShrot_GetLastError()))
BakaShrot_UnloadClient()
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Ms (milliseconds since 1970 UTC, as BakaShrot_GetMessagePushedAt() gives
; it) as "2026-11-08T14:03:59.123Z".
Procedure.s ToolClient_FormatUtc(Ms.q)
ProcedureReturn FormatDate("%yyyy-%mm-%ddT%hh:%ii:%ss", Ms / 1000) + "." + RSet(Str(Ms % 1000), 3, "0") + "Z"
EndProcedure
; Disconnects and unloads the DLL.
Procedure ToolClient_Close()
BakaShrot_Disconnect()
BakaShrot_UnloadClient()
EndProcedure
; Prints why the last request failed.
; With its code's name (BakaShrot_ErrorCodes.pbi), for scripts to match on.
Procedure ToolClient_PrintFailure()
Protected Code.l = BakaShrot_GetLastError()
If BakaShrot_IsRefusalCode(Code)
PrintN("Refused by the server (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString())
ElseIf BakaShrot_GetRefusalReasonString() <> ""
; The client's own refusals: a message or attachment over the limits...
PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + BakaShrot_GetRefusalReasonString())
Else
PrintN("Failed (" + BakaShrot_ErrorName(Code) + "): " + ToolClient_Explain(Code))
EndIf
EndProcedure
; Reads a whole UTF-8 text file (a byte order mark is skipped) into *Text.
; In one go: ReadString() with #PB_File_IgnoreEOL takes seconds on a 16 MB
; line. Prints why and returns #False if it can't be read.
Procedure.i ToolClient_ReadTextFile(Path.s, *Text.String)
Protected FileId.i, Size.q, *Data, Offset.i
FileId = ReadFile(#PB_Any, Path)
If Not FileId
PrintN("Failed to open '" + Path + "'")
ProcedureReturn #False
EndIf
Size = Lof(FileId)
*Data = AllocateMemory(Size + 1)
If Not *Data
CloseFile(FileId)
PrintN("'" + Path + "' is too big to read")
ProcedureReturn #False
EndIf
If ReadData(FileId, *Data, Size) <> Size
FreeMemory(*Data)
CloseFile(FileId)
PrintN("Failed to read '" + Path + "'")
ProcedureReturn #False
EndIf
CloseFile(FileId)
If Size >= 3 And PeekA(*Data) = $EF And PeekA(*Data + 1) = $BB And PeekA(*Data + 2) = $BF
Offset = 3
EndIf
*Text\s = ""
If Size > Offset
*Text\s = PeekS(*Data + Offset, Size - Offset, #PB_UTF8 | #PB_ByteLength)
EndIf
FreeMemory(*Data)
ProcedureReturn #True
EndProcedure
+73
View File
@@ -0,0 +1,73 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ToolConsole.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Tools - Console
;
; Shared by every tool. Started from Explorer (a double-click, a shortcut),
; a console program gets a console of its own that closes as soon as it
; ends, before what it printed can be read: ToolConsole_End() waits for
; Enter then, and ends at once otherwise.
; As https://github.com/aziascreations/PB-Template-Win32-CliApp does it: a
; program started from a shell shares the shell's console, one started
; directly is alone in its own.
; ============================================================================
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; Not in PureBasic 5.73's API functions, named so it can't clash with a
; compiler that has it.
Import "kernel32.lib"
CompilerIf #PB_Compiler_Processor = #PB_Processor_x86
ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "_GetConsoleProcessList@8"
CompilerElse
ToolConsole_GetConsoleProcessList.l(*ProcessList, ProcessCount.l) As "GetConsoleProcessList"
CompilerEndIf
EndImport
CompilerEndIf
; #True if the tool was started directly rather than from a shell: it is the
; only process on its console. Input or output redirected is #False, someone
; else reads it (a test starting it with Start-Process gets a new hidden
; console too, alone on it). Always #False outside of Windows.
Procedure.i ToolConsole_IsRunDirectly()
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
Protected Mode.l, ProcessList.q ; ProcessList: room for 2 process ids
If Not GetConsoleMode_(GetStdHandle_(#STD_INPUT_HANDLE), @Mode)
ProcedureReturn #False
EndIf
If Not GetConsoleMode_(GetStdHandle_(#STD_OUTPUT_HANDLE), @Mode)
ProcedureReturn #False
EndIf
ProcedureReturn Bool(ToolConsole_GetConsoleProcessList(@ProcessList, 2) <= 1)
CompilerElse
ProcedureReturn #False
CompilerEndIf
EndProcedure
; Ends the tool with ExitCode, after waiting for Enter if it was started
; directly (ToolConsole_IsRunDirectly()).
Procedure ToolConsole_End(ExitCode.i)
If ToolConsole_IsRunDirectly()
PrintN("")
Print("Press Enter to close...")
Input()
EndIf
End ExitCode
EndProcedure