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
+363 -195
View File
@@ -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,41 +623,57 @@ 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())
If Not BakaShrot_IsValidName(Name)
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 FindMapElement(Names(), Str(Id))
BakaShrot_ConfigError = "[" + Section + "] " + Kind + " id " + Str(Id) + " is given to both '" + Names() + "' and '" + Name + "'"
ProcedureReturn #False
EndIf
Ids(LCase(Name)) = Id
Names(Str(Id)) = Name
Wend
EndIf
While NextPreferenceKey()
Name = Trim(PreferenceKeyName())
Value = Trim(PreferenceKeyValue())
If Not BakaShrot_IsValidName(Name)
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
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
EndIf
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,79 +796,68 @@ 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
ProcedureReturn #False
EndIf
If CountString(Part, ":") <> 1
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
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
*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
TopicPart = Trim(StringField(Part, 1, ":"))
NodePart = Trim(StringField(Part, 2, ":"))
If TopicPart = "" Or NodePart = ""
BakaShrot_ConfigError = Where + ": '" + Part + "' isn't Topic:Node"
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]"
ProcedureReturn #False
EndIf
AddElement(Identities())
Identities()\TopicId = TopicId
Identities()\NodeId = NodeId
*Config\UsedTopicIds(Str(TopicId)) = #True
*Config\UsedNodeIds(Str(NodeId)) = #True
Next
*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
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())
If *Config\Clients()\NodeId = NodeId
ForEach *Config\Clients()\PublicKeys()
If *Config\Clients()\PublicKeys() = PublicKey
ProcedureReturn MapKey(*Config\Clients())
EndIf
Next
EndIf
Next
@@ -798,11 +866,11 @@ 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,22 +1106,15 @@ 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
*Config\UsedNodeIds(Str(\NodeId)) = #True
\SendTopicsText = ReadPreferenceString("SendTopics", #BakaShrot_Config_Missing)
If \SendTopicsText = #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)