1
0
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:
2026-11-09 23:57:55 +01:00
parent df61ef9719
commit 488ffe4bc8
67 changed files with 3163 additions and 1029 deletions
@@ -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)
@@ -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)
@@ -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)
@@ -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)
+6
View File
@@ -0,0 +1,6 @@
IDE Options = PureBasic 6.41 (Windows - x64)
CursorPosition = 7
Folding = -
EnableXP
DPIAware
CompileSourceDirectory
@@ -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
View File
@@ -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
+56
View File
@@ -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