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:
+363
-195
@@ -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)
|
||||
|
||||
+67
-28
@@ -3,15 +3,17 @@
|
||||
; library is concerned — the dots below are just part of the name.
|
||||
;
|
||||
; Topics and nodes: each has an id (0-65535) on this server, and can have a
|
||||
; name, in [BakaShrot.Topics] and [BakaShrot.Nodes]. Names are what's shared
|
||||
; between servers: replication sends them, and each server stores the
|
||||
; messages under its own ids for them ("logs" can be 1 here and 200 on a
|
||||
; peer).
|
||||
; name. Topics are named in [BakaShrot.Topics]; nodes by the sections that
|
||||
; define them ([BakaShrot] Node, a peer's, a client's), [BakaShrot.Nodes]
|
||||
; only names the others. The server gives every name its id, and keeps it.
|
||||
; Names are what's shared between servers: replication sends them, and
|
||||
; each server stores the messages under its own ids for them ("logs" can be
|
||||
; 1 here and 200 on a peer).
|
||||
; ONLY WHAT'S NAMED ON BOTH SERVERS REPLICATES: a topic or node without a
|
||||
; name, or whose name the other server doesn't have, is dropped. Unnamed
|
||||
; ones still work locally, by id.
|
||||
; Names: 1-64 of A-Z a-z 0-9 _ . -, not only digits, case doesn't matter.
|
||||
; The server's "names" command and the ListNames tool list them all.
|
||||
; The server's "names" command and the BakaShrotList tool list them all.
|
||||
;
|
||||
; Topic, Node and ReplicatingTopics were TopicId, NodeId and
|
||||
; ReplicatingTopicIds before: the old names are still read.
|
||||
@@ -27,31 +29,37 @@
|
||||
[BakaShrot]
|
||||
; Config shared by every type of config.
|
||||
|
||||
; This node's Ed25519 private key (Base64), from KeyGen.exe. It proves who
|
||||
; This node's Ed25519 private key (Base64), from BakaShrotGenerateKeyPairs.exe. It proves who
|
||||
; this server is: clients seal their Hello for its public key and check
|
||||
; that it signed the handshake, so they need that public key (client.ini's
|
||||
; ServerPublicKey, peers' PublicKey below in THEIR own config). The server
|
||||
; logs it when it starts. See Commons/Networking/Connections.pbi.
|
||||
PrivateKey =
|
||||
|
||||
; The topic and node this server authenticates as when it links to its
|
||||
; peers, a name or an id. Its peers must register it under the same names.
|
||||
Topic =
|
||||
; The node this server authenticates as when it links to its peers, a name
|
||||
; or an id. Its peers must register it under the same name: a client
|
||||
; section with this Node and this server's public key. (A Topic left here
|
||||
; from before protocol 5 is ignored.)
|
||||
Node =
|
||||
|
||||
|
||||
[BakaShrot.Topics]
|
||||
; One line per named topic: name = this server's id for it.
|
||||
; logs = 1
|
||||
; sensors = 2
|
||||
; One topic name per line. This server gives each its id: the one its
|
||||
; database already has for it, or the lowest free one for a new one, so the
|
||||
; order doesn't matter and they keep their ids.
|
||||
; "name = id" pins one instead (configs from before work as they are). Once
|
||||
; a name has messages, its id can't change: the server refuses to start if
|
||||
; a pin moves it, and says which id to use.
|
||||
; logs
|
||||
; sensors
|
||||
|
||||
|
||||
[BakaShrot.Nodes]
|
||||
; One line per named node (a client's or a server's), same as topics. Every
|
||||
; server that should get a node's messages must name it too.
|
||||
; Once a name has messages, keep its id: the server refuses to start if the
|
||||
; config moves it to another one, and says which id to use.
|
||||
; kitchen = 2
|
||||
; Optional. The nodes [BakaShrot] Node, the peers' and the clients' Node
|
||||
; define are named already. List the others this server should know by name
|
||||
; up front, like topics; peers add the ones they send as they come
|
||||
; (AcceptNodes, below).
|
||||
; kitchen
|
||||
|
||||
|
||||
[BakaShrot.Retention]
|
||||
@@ -114,6 +122,21 @@ MaxAttachmentSize = 1G
|
||||
; after which the upload is deleted.
|
||||
UploadTimeout = 3600
|
||||
|
||||
; How hard the database makes sure a push is on disk before answering it.
|
||||
; FULL (default) every commit is flushed to disk: a message the server
|
||||
; acknowledged survives a power loss or an OS crash.
|
||||
; NORMAL flushed about once a second only (at the checkpoints): faster
|
||||
; (twice the pushes under full load, measured), but a power loss
|
||||
; or an OS crash loses the last second or so of acknowledged
|
||||
; messages, and their ids are handed out again, which peers that
|
||||
; already got them can't tell (Design/ReplicationIssues.md #1).
|
||||
; A crash of the server alone loses nothing either way.
|
||||
; The cost of FULL is the disk's flush time, once per group of pushes: well
|
||||
; under a millisecond on a server SSD, ~10 ms on a hard disk, which then
|
||||
; caps one client pushing one message at a time to ~100/s.
|
||||
; See Design/StorageConcurrency.md for the numbers.
|
||||
Synchronous = FULL
|
||||
|
||||
|
||||
; One [BakaShrot.Peer.<name>] section per peer this node talks to.
|
||||
; <name> is only a key for this file; it is never sent on the wire.
|
||||
@@ -129,9 +152,8 @@ Port =
|
||||
; The link only goes through if the peer proves it holds the private key
|
||||
; of PublicKey below, and it's encrypted.
|
||||
|
||||
; Remote node's topic and node, names or ids. The peer authenticates with
|
||||
; them when it links to here.
|
||||
Topic =
|
||||
; The peer's node, a name or an id: the one in its own [BakaShrot] Node.
|
||||
; It authenticates as it when it links to here.
|
||||
Node =
|
||||
|
||||
; The topics sent to this peer (if it takes them), and the topics taken
|
||||
@@ -140,9 +162,9 @@ Node =
|
||||
; AcceptTopics = logs;sensors.*
|
||||
|
||||
; The nodes whose messages are sent to this peer (default: every one), and
|
||||
; the nodes whose messages are taken from it (default: the ones named in
|
||||
; [BakaShrot.Nodes], no other). AcceptNodes = kitchen-* takes every
|
||||
; kitchen-something the peer sends, named here or not.
|
||||
; the nodes whose messages are taken from it (default: every one, the names
|
||||
; this server doesn't have yet are added as they come). AcceptNodes =
|
||||
; kitchen-*;garage only takes those, named here or not.
|
||||
; SendNodes = *
|
||||
; AcceptNodes = kitchen-*;garage
|
||||
|
||||
@@ -159,13 +181,30 @@ PublicKey =
|
||||
; Format: Key;Key;...
|
||||
PublicKeys =
|
||||
|
||||
; Topic and node pairs this client is allowed to authenticate as, names or ids.
|
||||
; Format: Topic:Node;Topic:Node;...
|
||||
Identities =
|
||||
; The node this client writes as, a name or an id, required. Every message
|
||||
; it pushes is stored under it, so the server decides which node each key
|
||||
; writes as, and no client can push as another's node (or as a peer's).
|
||||
; Its client.ini's Node must say the same. A key that writes as several
|
||||
; nodes is listed in a section per node.
|
||||
; ONE SERVER PER NODE: give a node a client section on the one server it
|
||||
; pushes to, the others get its messages by replication. Two servers taking
|
||||
; pushes for the same node end up with different messages under the same
|
||||
; ids, which nothing detects (Design/ReplicationIssues.md #1). To read from
|
||||
; another server, give the client another node there (or no write access:
|
||||
; AllowWrite = 0).
|
||||
Node =
|
||||
|
||||
; Where its pushes go when they don't name a topic, a name or an id.
|
||||
; Optional: without it, every push must name its topic. Only a default, it
|
||||
; may push to any topic in PushTopics.
|
||||
; DefaultTopic = logs
|
||||
|
||||
; (Identities, the Topic:Node pairs before protocol 5, isn't read any more:
|
||||
; the server refuses to start with it, saying what to write instead.)
|
||||
|
||||
; The topics it may push to (always under its own node), and the topics it
|
||||
; may read the latest messages of. Both default to the topics of its
|
||||
; Identities, empty allows none.
|
||||
; may read the latest messages of. Both default to its DefaultTopic,
|
||||
; nothing without one; empty allows none.
|
||||
; PushTopics = logs;sensors
|
||||
; ReadTopics = *
|
||||
|
||||
|
||||
@@ -204,7 +204,7 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
Protected Accepted.BakaShrot_AuthAccepted
|
||||
Protected Proof.BakaShrot_ChallengeProof
|
||||
Protected KeyPair.BakaShrot_SessionKeyPair
|
||||
Protected TopicId.i, NodeId.i, PublicKey.s, ClientName.s, TopicRef.s, NodeRef.s
|
||||
Protected NodeId.i, DefaultTopicId.i, PublicKey.s, ClientName.s, NodeRef.s
|
||||
Protected NonceMatches.i, SignatureDecoded.i, Sent.i, CipherReady.i
|
||||
|
||||
*Client\Metadata\Status = #BakaShrot_ConnectionStatus_New
|
||||
@@ -235,16 +235,14 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
TopicRef = *Hello\ClientTopic
|
||||
NodeRef = *Hello\ClientNode
|
||||
PublicKey = *Hello\ClientPubKeyB64
|
||||
CopyMemory(@*Hello\ClientSessionKey[0], @*Client\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize)
|
||||
FreeStructure(*Hello)
|
||||
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If TopicId < 0 Or NodeId < 0
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown identity '" + Left(TopicRef, 80) + "':'" + Left(NodeRef, 80) + "'")
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " sent an unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
@@ -254,9 +252,11 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
EndIf
|
||||
|
||||
LockMutex(*Server\Mutex)
|
||||
ClientName = FindClientName(*Server\Config, PublicKey, TopicId, NodeId)
|
||||
*Client\PeerName = FindPeerName(*Server\Config, PublicKey, TopicId, NodeId)
|
||||
ClientName = FindClientName(*Server\Config, PublicKey, NodeId)
|
||||
*Client\PeerName = FindPeerName(*Server\Config, PublicKey, NodeId)
|
||||
DefaultTopicId = -1
|
||||
If ClientName <> "" And FindMapElement(*Server\Config\Clients(), ClientName)
|
||||
DefaultTopicId = *Server\Config\Clients()\DefaultTopicId
|
||||
*Client\Permissions\Read = *Server\Config\Clients()\Permissions\Read
|
||||
*Client\Permissions\Write = *Server\Config\Clients()\Permissions\Write
|
||||
*Client\Permissions\Query = *Server\Config\Clients()\Permissions\Query
|
||||
@@ -270,12 +270,12 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
EndIf
|
||||
UnlockMutex(*Server\Mutex)
|
||||
If ClientName = ""
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to use " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + " with its public key")
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " isn't allowed to write as node " + BakaShrot_Names_NodeRef(NodeId) + " with its public key")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
*Client\Metadata\TopicId = TopicId
|
||||
*Client\Metadata\NodeId = NodeId
|
||||
*Client\Metadata\DefaultTopicId = DefaultTopicId
|
||||
*Client\Metadata\NodeId = NodeId
|
||||
|
||||
|
||||
; 2. Challenge request, in plain text, signed by this server
|
||||
@@ -386,9 +386,9 @@ Procedure.i BakaShrot_NetClient_Authenticate(*Client.BakaShrot_NetClient)
|
||||
|
||||
*Client\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated
|
||||
If *Client\PeerName = ""
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId))
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId))
|
||||
Else
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "' " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'")
|
||||
PrintN("[Net] Client " + Str(*Client\ClientId) + " authenticated as '" + ClientName + "', node " + BakaShrot_Names_NodeRef(NodeId) + ", peer '" + *Client\PeerName + "'")
|
||||
EndIf
|
||||
|
||||
ProcedureReturn #True
|
||||
@@ -397,12 +397,13 @@ EndProcedure
|
||||
|
||||
; Encodes and sends a RequestRefused.
|
||||
; Returns #False if it couldn't be sent, the client must then be aborted.
|
||||
Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Reason.s)
|
||||
Procedure.i BakaShrot_NetClient_Refuse(*Client.BakaShrot_NetClient, Code.l, Reason.s)
|
||||
Protected Refused.BakaShrot_RequestRefused
|
||||
Protected *Packet, PacketSize.Integer, Sent.i
|
||||
|
||||
PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + ": " + Reason)
|
||||
PrintN("[Net] Refused a request from client " + Str(*Client\ClientId) + " (" + BakaShrot_ErrorName(Code) + "): " + Reason)
|
||||
|
||||
Refused\Code = Code
|
||||
Refused\Reason = Reason
|
||||
*Packet = BakaShrot_RequestRefusedPacket_Encode(@Refused, @PacketSize)
|
||||
If Not *Packet
|
||||
@@ -449,51 +450,54 @@ Procedure.i BakaShrot_NetClient_HandlePushMessage(*Client.BakaShrot_NetClient, *
|
||||
EndIf
|
||||
|
||||
If Not *Client\Permissions\Write
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write")
|
||||
EndIf
|
||||
|
||||
If TopicRef = ""
|
||||
TopicId = *Client\Metadata\TopicId
|
||||
TopicId = *Client\Metadata\DefaultTopicId
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic")
|
||||
EndIf
|
||||
Else
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
|
||||
; So it fits in every packet that carries it later, see Packets.pbi.
|
||||
JsonSize = StringByteLength(JsonData, #PB_UTF8)
|
||||
If JsonSize > #BakaShrot_MaxMessageSize
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The message is too big: " + Str(JsonSize) + " bytes, at most " + Str(#BakaShrot_MaxMessageSize))
|
||||
EndIf
|
||||
|
||||
; A topic allowed by "*" may be new here, it needs its row for the
|
||||
; "messages" view.
|
||||
If Not BakaShrot_Names_EnsureTopicId(TopicId, @StoreError)
|
||||
PrintN("[Net] Failed to register topic " + Str(TopicId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored")
|
||||
EndIf
|
||||
|
||||
; Its attachment: one of this client's complete uploads, for that topic.
|
||||
If UploadId
|
||||
If Not GetStorageBlob(*Client\DbId, UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload")
|
||||
EndIf
|
||||
If Blob\State <> #BakaShrot_Blob_Complete
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload isn't complete, or is attached already")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload isn't complete, or is attached already")
|
||||
EndIf
|
||||
If Blob\TopicId <> TopicId
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The upload is for topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
|
||||
MessageId = InsertNextMessage(TopicId, *Client\Metadata\NodeId, JsonData, @StoreError, UploadId)
|
||||
If MessageId < 1
|
||||
PrintN("[Net] Failed to store a message from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The message couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The message couldn't be stored")
|
||||
EndIf
|
||||
|
||||
Pushed\MessageId = MessageId
|
||||
@@ -542,23 +546,23 @@ Procedure.i BakaShrot_NetClient_HandleGetLatestMessage(*Client.BakaShrot_NetClie
|
||||
EndIf
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read")
|
||||
EndIf
|
||||
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
If Not GetLatestMessage(*Client\DbId, TopicId, NodeId, @Message)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No message for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId))
|
||||
EndIf
|
||||
|
||||
Latest\TopicId = TopicId
|
||||
@@ -619,24 +623,24 @@ Procedure.i BakaShrot_NetClient_HandleGetMessages(*Client.BakaShrot_NetClient, *
|
||||
EndIf
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read")
|
||||
EndIf
|
||||
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
; In characters, the bytes are counted below: never less than that.
|
||||
If Not GetMessagesAfter(*Client\DbId, TopicId, NodeId, AfterMessageId, Limit, #BakaShrot_MessagesBatchBytes, Messages(), @More)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be read")
|
||||
EndIf
|
||||
|
||||
; As many as fit in #BakaShrot_MessagesBatchBytes, the rest is for the
|
||||
@@ -702,16 +706,16 @@ Procedure.i BakaShrot_NetClient_HandleQuery(*Client.BakaShrot_NetClient, *Packet
|
||||
FreeStructure(*Request)
|
||||
|
||||
If Not *Client\Permissions\Query
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to query")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to query")
|
||||
EndIf
|
||||
|
||||
If Not RunReadOnlyQuery(*Client\Server\DatabasePath, Sql, @JsonResult, @QueryError)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Query failed: " + QueryError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_QueryFailed, "Query failed: " + QueryError\s)
|
||||
EndIf
|
||||
|
||||
; Leaves room for the packet's own fields.
|
||||
If StringByteLength(JsonResult\s, #PB_UTF8) > #BakaShrot_MaxPacketSize - 64
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The result is too big for one packet, add a LIMIT")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The result is too big for one packet, add a LIMIT")
|
||||
EndIf
|
||||
|
||||
Result\JsonResult = JsonResult\s
|
||||
@@ -755,16 +759,16 @@ Procedure.i BakaShrot_NetClient_HandleResolveName(*Client.BakaShrot_NetClient, *
|
||||
If Kind = #BakaShrot_NameKind_Topic
|
||||
Id = BakaShrot_Names_ResolveTopic(Ref)
|
||||
If Id < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
EndIf
|
||||
If Not *Client\Permissions\Query And Not NameSetHas(@*Client\PushTopics, Id, BakaShrot_Names_TopicName(Id)) And Not NameSetHas(@*Client\ReadTopics, Id, BakaShrot_Names_TopicName(Id))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(Ref, 80) + "'")
|
||||
EndIf
|
||||
Resolved\Name = BakaShrot_Names_TopicName(Id)
|
||||
Else
|
||||
Id = BakaShrot_Names_ResolveNode(Ref)
|
||||
If Id < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(Ref, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(Ref, 80) + "'")
|
||||
EndIf
|
||||
Resolved\Name = BakaShrot_Names_NodeName(Id)
|
||||
EndIf
|
||||
@@ -878,12 +882,12 @@ Procedure.i BakaShrot_NetClient_HandleSyncStateRequest(*Client.BakaShrot_NetClie
|
||||
FreeStructure(*Request)
|
||||
|
||||
If *Client\PeerName = ""
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
If Not GetSyncState(*Client\DbId, AllPairs())
|
||||
PrintN("[Net] Failed to read the sync state for peer '" + *Client\PeerName + "': " + DatabaseError())
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The sync state couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The sync state couldn't be read")
|
||||
EndIf
|
||||
|
||||
; Every name this server knows, the peer only sends those.
|
||||
@@ -963,20 +967,20 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
|
||||
If *Client\PeerName = ""
|
||||
FreeStructure(*Batch)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
TopicId = BakaShrot_Names_TopicByName(TopicRef)
|
||||
If Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef)
|
||||
FreeStructure(*Batch)
|
||||
BakaShrot_Names_NoteDropped(*Client\PeerName, "topic", TopicRef, "not taken here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Topic '" + TopicRef + "' isn't replicated here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Topic '" + TopicRef + "' isn't replicated here")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_NodeByName(NodeRef)
|
||||
If Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef)
|
||||
FreeStructure(*Batch)
|
||||
BakaShrot_Names_NoteDropped(*Client\PeerName, "node", NodeRef, "not taken here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Node '" + NodeRef + "' isn't replicated here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Node '" + NodeRef + "' isn't replicated here")
|
||||
EndIf
|
||||
|
||||
; Taken by a wildcard, new here.
|
||||
@@ -989,7 +993,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
If TopicId < 0 Or NodeId < 0
|
||||
FreeStructure(*Batch)
|
||||
PrintN("[Net] Failed to add '" + TopicRef + "':'" + NodeRef + "' from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored")
|
||||
EndIf
|
||||
|
||||
MaxAge = RetentionMaxAgeMs(*Client\Retention(), TopicId, TopicRef)
|
||||
@@ -1003,7 +1007,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateMessages(*Client.BakaShrot_NetCli
|
||||
EndIf
|
||||
If Not IsStored
|
||||
PrintN("[Net] Failed to store messages from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The messages couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The messages couldn't be stored")
|
||||
EndIf
|
||||
|
||||
Pushed\MessageId = LastMessageId
|
||||
@@ -1062,29 +1066,32 @@ Procedure.i BakaShrot_NetClient_HandleUploadStart(*Client.BakaShrot_NetClient, *
|
||||
FreeStructure(*Start)
|
||||
|
||||
If Not *Client\Permissions\Write
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to write")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to write")
|
||||
EndIf
|
||||
If TopicRef = ""
|
||||
TopicId = *Client\Metadata\TopicId
|
||||
TopicId = *Client\Metadata\DefaultTopicId
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NoDefaultTopic, "No default topic for this client (DefaultTopic in its server's config): name the topic")
|
||||
EndIf
|
||||
Else
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\PushTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
|
||||
MaxSize = *Client\Server\Config\Server\MaxAttachmentSize
|
||||
If Size > MaxSize
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment is too big: " + Str(Size) + " bytes, at most " + Str(MaxSize) + " here")
|
||||
EndIf
|
||||
|
||||
BlobId = CreateStorageBlob(TopicId, *Client\Metadata\NodeId, Size, @Sha256(0), @StoreError)
|
||||
If Not BlobId
|
||||
PrintN("[Net] Failed to start an upload for client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be started")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be started")
|
||||
EndIf
|
||||
|
||||
Started\UploadId = BlobId
|
||||
@@ -1120,23 +1127,23 @@ Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *
|
||||
; Only its own uploads: same node, a topic it may still push to.
|
||||
If Not GetStorageBlob(*Client\DbId, *Chunk\UploadId, @Blob) Or Blob\NodeId <> *Client\Metadata\NodeId Or Blob\State <> #BakaShrot_Blob_Receiving
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No such upload in progress")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No such upload in progress")
|
||||
EndIf
|
||||
If Not *Client\Permissions\Write Or Not NameSetHas(@*Client\PushTopics, Blob\TopicId, BakaShrot_Names_TopicName(Blob\TopicId))
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to push to topic '" + BakaShrot_Names_TopicRef(Blob\TopicId) + "'")
|
||||
EndIf
|
||||
Expected = BakaShrot_AttachmentChunkBytes(Blob\Size, *Chunk\ChunkIndex)
|
||||
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Blob\Received Or *Chunk\DataSize <> Expected
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Blob\Received / #BakaShrot_AttachmentChunkSize) + " of " + Str(BakaShrot_AttachmentChunkCount(Blob\Size)) + ", " + Str(BakaShrot_AttachmentChunkBytes(Blob\Size, Blob\Received / #BakaShrot_AttachmentChunkSize)) + " bytes")
|
||||
EndIf
|
||||
|
||||
Received = StoreStorageBlobChunk(Blob\BlobId, *Chunk\ChunkIndex, *Chunk\Data, *Chunk\DataSize, @StoreError)
|
||||
BakaShrot_UploadChunkPacket_Free(*Chunk)
|
||||
If Received < 0
|
||||
PrintN("[Net] Failed to store a part of an upload from client " + Str(*Client\ClientId) + ": " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored")
|
||||
EndIf
|
||||
|
||||
If Received < Blob\Size
|
||||
@@ -1146,10 +1153,10 @@ Procedure.i BakaShrot_NetClient_HandleUploadChunk(*Client.BakaShrot_NetClient, *
|
||||
; All of it: the SHA-256 given at the start must match.
|
||||
If Not HashStorageBlob(*Client\DbId, Blob\BlobId, Blob\Size, @Blob\Sha256[0])
|
||||
SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Deleted)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload doesn't match its SHA-256, it's dropped")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The upload doesn't match its SHA-256, it's dropped")
|
||||
EndIf
|
||||
If Not SetStorageBlobState(Blob\BlobId, #BakaShrot_Blob_Complete)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The upload couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The upload couldn't be stored")
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||
EndProcedure
|
||||
@@ -1181,36 +1188,36 @@ Procedure.i BakaShrot_NetClient_HandleGetAttachment(*Client.BakaShrot_NetClient,
|
||||
FreeStructure(*Request)
|
||||
|
||||
If Not *Client\Permissions\Read
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read")
|
||||
EndIf
|
||||
TopicId = BakaShrot_Names_ResolveTopic(TopicRef)
|
||||
If TopicId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown topic '" + Left(TopicRef, 80) + "'")
|
||||
EndIf
|
||||
If Not NameSetHas(@*Client\ReadTopics, TopicId, BakaShrot_Names_TopicName(TopicId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Not allowed to read topic '" + BakaShrot_Names_TopicRef(TopicId) + "'")
|
||||
EndIf
|
||||
NodeId = BakaShrot_Names_ResolveNode(NodeRef)
|
||||
If NodeId < 0
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_UnknownName, "Unknown node '" + Left(NodeRef, 80) + "'")
|
||||
EndIf
|
||||
|
||||
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotFound, "No attachment for " + BakaShrot_Names_TopicRef(TopicId) + ":" + BakaShrot_Names_NodeRef(NodeId) + "#" + Str(MessageId))
|
||||
EndIf
|
||||
Select Attachment\State
|
||||
Case #BakaShrot_Attachment_NotKept
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here: " + Str(Attachment\Size) + " bytes, more than MaxAttachmentSize")
|
||||
Case #BakaShrot_Attachment_Missing, #BakaShrot_Attachment_Receiving
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotReady, "The attachment isn't here yet: " + Str(Attachment\Received) + " of " + Str(Attachment\Size) + " bytes")
|
||||
EndSelect
|
||||
If Index >= BakaShrot_AttachmentChunkCount(Attachment\Size)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "The attachment has " + Str(BakaShrot_AttachmentChunkCount(Attachment\Size)) + " parts")
|
||||
EndIf
|
||||
|
||||
Chunk\Data = ReadStorageBlobChunk(*Client\DbId, Attachment\BlobId, Index, @DataSize)
|
||||
If Not Chunk\Data
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be read")
|
||||
EndIf
|
||||
Chunk\DataSize = DataSize\i
|
||||
Chunk\TopicId = TopicId
|
||||
@@ -1252,12 +1259,12 @@ Procedure.i BakaShrot_NetClient_HandleMissingAttachmentsRequest(*Client.BakaShro
|
||||
FreeStructure(*Request)
|
||||
|
||||
If *Client\PeerName = ""
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
|
||||
; More than one answer holds, some of them may be someone else's.
|
||||
If Not GetMissingStorageAttachments(*Client\DbId, 4 * #BakaShrot_MaxMissingAttachments, Missing())
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The missing attachments couldn't be read")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The missing attachments couldn't be read")
|
||||
EndIf
|
||||
ForEach Missing()
|
||||
If ListSize(Answer\Attachments()) >= #BakaShrot_MaxMissingAttachments
|
||||
@@ -1312,18 +1319,18 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
|
||||
If *Client\PeerName = ""
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Only peers can replicate")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_NotAllowed, "Only peers can replicate")
|
||||
EndIf
|
||||
TopicId = BakaShrot_Names_TopicByName(TopicRef)
|
||||
NodeId = BakaShrot_Names_NodeByName(NodeRef)
|
||||
If TopicId < 0 Or NodeId < 0 Or Not NameSetHas(@*Client\AcceptTopics, TopicId, TopicRef) Or Not NameSetHas(@*Client\AcceptNodes, NodeId, NodeRef)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "'" + TopicRef + "':'" + NodeRef + "' isn't replicated here")
|
||||
EndIf
|
||||
|
||||
If Not GetStorageAttachment(*Client\DbId, TopicId, NodeId, MessageId, @Attachment)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "No attachment expected for " + TopicRef + ":" + NodeRef + "#" + Str(MessageId))
|
||||
EndIf
|
||||
If Attachment\State = #BakaShrot_Attachment_Ready
|
||||
; Someone else's link was faster: done.
|
||||
@@ -1332,11 +1339,11 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
EndIf
|
||||
If Attachment\State = #BakaShrot_Attachment_NotKept
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment isn't kept here")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_TooBig, "The attachment isn't kept here")
|
||||
EndIf
|
||||
If *Chunk\ChunkIndex * #BakaShrot_AttachmentChunkSize <> Attachment\Received Or *Chunk\DataSize <> BakaShrot_AttachmentChunkBytes(Attachment\Size, *Chunk\ChunkIndex)
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize))
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_InvalidRequest, "Expected part " + Str(Attachment\Received / #BakaShrot_AttachmentChunkSize))
|
||||
EndIf
|
||||
|
||||
BlobId = Attachment\BlobId
|
||||
@@ -1351,7 +1358,7 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
|
||||
If Received < 0
|
||||
PrintN("[Net] Failed to store an attachment's part from peer '" + *Client\PeerName + "': " + StoreError\s)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The part couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The part couldn't be stored")
|
||||
EndIf
|
||||
|
||||
If Received < Attachment\Size
|
||||
@@ -1360,11 +1367,11 @@ Procedure.i BakaShrot_NetClient_HandleReplicateAttachmentChunk(*Client.BakaShrot
|
||||
|
||||
IsValid = HashStorageBlob(*Client\DbId, BlobId, Attachment\Size, @Attachment\Sha256[0])
|
||||
If Not FinishReplicatedAttachment(TopicId, NodeId, MessageId, BlobId, IsValid)
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment couldn't be stored")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_ServerError, "The attachment couldn't be stored")
|
||||
EndIf
|
||||
If Not IsValid
|
||||
PrintN("[Net] The attachment of " + TopicRef + ":" + NodeRef + "#" + Str(MessageId) + " from peer '" + *Client\PeerName + "' doesn't match its SHA-256, dropped")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, "The attachment doesn't match its SHA-256, send it again")
|
||||
ProcedureReturn BakaShrot_NetClient_Refuse(*Client, #BakaShrot_Refused_DataMismatch, "The attachment doesn't match its SHA-256, send it again")
|
||||
EndIf
|
||||
ProcedureReturn BakaShrot_NetClient_SendChunkStored(*Client, Received, #True)
|
||||
EndProcedure
|
||||
|
||||
@@ -141,7 +141,7 @@ Procedure.i BakaShrot_PeerLink_LogRefusal(*Link.BakaShrot_PeerLink, *Answer, Ans
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
PrintN("[Peer] '" + *Link\Name + "' refused: " + *Refused\Reason)
|
||||
PrintN("[Peer] '" + *Link\Name + "' refused (" + BakaShrot_ErrorName(*Refused\Code) + "): " + *Refused\Reason)
|
||||
FreeStructure(*Refused)
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
@@ -665,7 +665,6 @@ Procedure.i BakaShrot_PeerLinks_Start(*Config.BakaShrot_CoreConfig)
|
||||
GetPublicKeyFromPrivateKey(@*Links\PrivateKey[0], @*Links\PublicKey[0])
|
||||
|
||||
; By name: the peer has its own ids for them.
|
||||
*Links\Identity\Topic = BakaShrot_Names_TopicRef(*Config\TopicId)
|
||||
*Links\Identity\Node = BakaShrot_Names_NodeRef(*Config\NodeId)
|
||||
*Links\Identity\PublicKey = EncodeKeyToString(@*Links\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
|
||||
*Links\Identity\PrivateKey = @*Links\PrivateKey[0]
|
||||
|
||||
+23
-3
@@ -52,8 +52,24 @@ EndStructure
|
||||
; Only while the workers are stopped, they use the config.
|
||||
Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root)
|
||||
Protected *Config.BakaShrot_CoreConfig
|
||||
Protected Known.BakaShrot_KnownNames, KnownError.String, DatabasePath.s, DbId.i
|
||||
|
||||
*Config = LoadConfig(*Root\ConfigPath)
|
||||
; The names the database has first, so the ones the config lists without
|
||||
; an id keep theirs (Storage/Names.pbi). Nothing to read on a new one.
|
||||
DatabasePath = ReadConfigDatabasePath(*Root\ConfigPath)
|
||||
If DatabasePath <> "" And FileSize(DatabasePath) > 0
|
||||
DbId = OpenStorageDatabase(DatabasePath)
|
||||
If Not DbId Or Not SetupStorageDatabase(DbId) Or Not BakaShrot_Names_ReadKnown(DbId, @Known, @KnownError)
|
||||
PrintN("[Root] Failed to read the names of the database '" + DatabasePath + "': " + KnownError\s + DatabaseError())
|
||||
If DbId
|
||||
CloseDatabase(DbId)
|
||||
EndIf
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
CloseDatabase(DbId)
|
||||
EndIf
|
||||
|
||||
*Config = LoadConfig(*Root\ConfigPath, @Known)
|
||||
If Not *Config
|
||||
PrintN("[Root] Failed to load the config from '" + *Root\ConfigPath + "': " + BakaShrot_ConfigError)
|
||||
ProcedureReturn #False
|
||||
@@ -64,7 +80,7 @@ Procedure.i BakaShrot_Root_LoadConfig(*Root.BakaShrot_Root)
|
||||
EndIf
|
||||
*Root\Config = *Config
|
||||
|
||||
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Topic=" + *Config\TopicText + ", Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
|
||||
PrintN("[Root] Loaded config '" + *Root\ConfigPath + "' (Node=" + *Config\NodeText + ", " + Str(MapSize(*Config\TopicNames())) + " named topics, " +
|
||||
Str(MapSize(*Config\NodeNames())) + " named nodes, " + Str(MapSize(*Config\Peers())) + " peers, " + Str(MapSize(*Config\Clients())) + " clients)")
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
@@ -77,6 +93,10 @@ Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root)
|
||||
Protected DatabasePath.s = *Root\Config\Server\DatabasePath
|
||||
Protected NamesError.String
|
||||
|
||||
; Every connection opened from here on, the workers' included (they're
|
||||
; stopped meanwhile), takes it.
|
||||
BakaShrot_Storage_Synchronous = *Root\Config\Server\Synchronous
|
||||
|
||||
*Root\DbId = OpenStorageDatabase(DatabasePath)
|
||||
If Not *Root\DbId
|
||||
PrintN("[Root] Failed to open the database '" + DatabasePath + "': " + DatabaseError())
|
||||
@@ -97,7 +117,7 @@ Procedure.i BakaShrot_Root_OpenDatabase(*Root.BakaShrot_Root)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
PrintN("[Root] Database '" + DatabasePath + "' is ready")
|
||||
PrintN("[Root] Database '" + DatabasePath + "' is ready (synchronous " + BakaShrot_Storage_Synchronous + ")")
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
@@ -21,10 +21,16 @@
|
||||
; Kept in the "topics" and "nodes" tables (Storage.pbi), so raw queries can
|
||||
; join on them (the "messages" view), and in memory for the server, guarded
|
||||
; by BakaShrot_Names_Mutex. Every id in "data" has a row:
|
||||
; origin "config" named in [BakaShrot.Topics] / [BakaShrot.Nodes]
|
||||
; origin "config" named by the config: in [BakaShrot.Topics] /
|
||||
; [BakaShrot.Nodes], or a peer's or client's Node
|
||||
; origin "id" unnamed, its name is its id in digits
|
||||
; origin "peer" sent by a peer, taken by a wildcard, named by the peer
|
||||
;
|
||||
; Ids are this server's to pick: a name the config lists without one keeps
|
||||
; the one these tables have for it, a new one gets the lowest free one
|
||||
; (LoadConfig(), after BakaShrot_Names_ReadKnown()). The config may still
|
||||
; pin one ("logs = 1").
|
||||
;
|
||||
; BakaShrot_Names_Load() reconciles the config with the tables at start (and
|
||||
; on restart). The config wins, except when it would give a name to another
|
||||
; id than the one the database has it under (or rename a "peer" one): that
|
||||
@@ -219,6 +225,47 @@ Procedure.i BakaShrot_Names_Load(DbId.i, *Config.BakaShrot_CoreConfig, *Error.St
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Fills *Known with what the database has, for LoadConfig() (Config.pbi):
|
||||
; the id of every name, and every id with a row or messages. Before the
|
||||
; config is loaded, on a connection of its own, the database set up.
|
||||
; Returns #False with the reason in *Error\s.
|
||||
Procedure.i BakaShrot_Names_ReadKnown(DbId.i, *Known.BakaShrot_KnownNames, *Error.String)
|
||||
Protected Name.s, Id.i
|
||||
|
||||
; Topics
|
||||
If Not DatabaseQuery(DbId, "SELECT topic_id, name FROM topics UNION SELECT DISTINCT topic_id, '' FROM node_heads")
|
||||
*Error\s = "can't read the topics: " + DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
While NextDatabaseRow(DbId)
|
||||
Id = GetDatabaseLong(DbId, 0)
|
||||
Name = GetDatabaseString(DbId, 1)
|
||||
*Known\TopicUsed(Str(Id)) = #True
|
||||
If Name <> "" And Not BakaShrot_IsDigits(Name)
|
||||
*Known\TopicIds(LCase(Name)) = Id
|
||||
EndIf
|
||||
Wend
|
||||
FinishDatabaseQuery(DbId)
|
||||
|
||||
; Nodes
|
||||
If Not DatabaseQuery(DbId, "SELECT node_id, name FROM nodes UNION SELECT DISTINCT node_id, '' FROM node_heads")
|
||||
*Error\s = "can't read the nodes: " + DatabaseError()
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
While NextDatabaseRow(DbId)
|
||||
Id = GetDatabaseLong(DbId, 0)
|
||||
Name = GetDatabaseString(DbId, 1)
|
||||
*Known\NodeUsed(Str(Id)) = #True
|
||||
If Name <> "" And Not BakaShrot_IsDigits(Name)
|
||||
*Known\NodeIds(LCase(Name)) = Id
|
||||
EndIf
|
||||
Wend
|
||||
FinishDatabaseQuery(DbId)
|
||||
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
; --- Lookups -----------------------------------------------------------------
|
||||
|
||||
; The id Ref stands for: an id in digits is that id, a name must be known.
|
||||
|
||||
+44
-14
@@ -3,7 +3,7 @@
|
||||
;
|
||||
; Opens the SQLite database file that backs the node's local storage, and
|
||||
; provides the basic read/write operations on top of it.
|
||||
; Schema: see db_schema_v7.dbml in this same folder. Attachments: see
|
||||
; Schema: see db_schema_v8.dbml in this same folder. Attachments: see
|
||||
; Attachments.pbi and Design/Attachments.md.
|
||||
;
|
||||
; Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), which the one
|
||||
@@ -37,7 +37,7 @@ CompilerElse
|
||||
CompilerEndIf
|
||||
|
||||
|
||||
; One row of the "data" table (see db_schema_v7.dbml).
|
||||
; One row of the "data" table (see db_schema_v8.dbml).
|
||||
; PushedAt: when it was pushed, ms since 1970 UTC (Packets.pbi).
|
||||
; AttachmentSize: its attachment's size, 0 for none (the "attachments"
|
||||
; table), AttachmentReady #True once all of it is here, AttachmentSha256 its
|
||||
@@ -82,15 +82,18 @@ EndProcedure
|
||||
; The database runs in WAL mode (set up by SetupStorageDatabase(), stored in
|
||||
; the file): readers and the writer don't block each other anymore, so a
|
||||
; long raw query no longer stalls every push.
|
||||
; With WAL, NORMAL only syncs to disk at checkpoints instead of on every
|
||||
; commit, which is most of what a push used to cost. The database can't get
|
||||
; corrupted, but the last commits before a power loss or an OS crash (not a
|
||||
; crash of the server itself) can be lost. Those messages were acknowledged,
|
||||
; and maybe replicated already, so their ids could then be handed out again
|
||||
; for other messages: drift, see Design/ReplicationIssues.md #1.
|
||||
; FULL syncs every commit, like before, but still lets reads and writes run
|
||||
; side by side.
|
||||
#BakaShrot_Storage_Synchronous = "NORMAL"
|
||||
; PRAGMA synchronous of every connection: [BakaShrot.Server] Synchronous,
|
||||
; set by the root before it opens any (Server/Root.pbi). FULL by default.
|
||||
; FULL syncs the WAL on every commit: an acknowledged push is on disk. It
|
||||
; costs one flush per transaction, shared by a group commit's pushes.
|
||||
; NORMAL only syncs at checkpoints (about every second, Writer.pbi): the
|
||||
; database can't get corrupted, but the last commits before a power loss or
|
||||
; an OS crash (not a crash of the server itself) can be lost. Those messages
|
||||
; were acknowledged, and maybe replicated already, so their ids could then
|
||||
; be handed out again for other messages: drift, see
|
||||
; Design/ReplicationIssues.md #1. Measured: Design/StorageConcurrency.md.
|
||||
#BakaShrot_Storage_DefaultSynchronous = "FULL"
|
||||
Global BakaShrot_Storage_Synchronous.s = #BakaShrot_Storage_DefaultSynchronous
|
||||
|
||||
|
||||
; Opens (and creates, if missing) the SQLite database at DatabasePath, as a
|
||||
@@ -120,8 +123,8 @@ Procedure.i OpenStorageDatabase(DatabasePath.s)
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
|
||||
; Per connection, see #BakaShrot_Storage_Synchronous.
|
||||
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + #BakaShrot_Storage_Synchronous)
|
||||
; Per connection, see BakaShrot_Storage_Synchronous.
|
||||
If Not DatabaseUpdate(DbId, "PRAGMA synchronous = " + BakaShrot_Storage_Synchronous)
|
||||
CloseDatabase(DbId)
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
@@ -232,7 +235,7 @@ Procedure.i MigrateStoragePushedAt(DbId.i)
|
||||
EndProcedure
|
||||
|
||||
|
||||
; Creates the tables and indexes described by db_schema_v7.dbml, if they
|
||||
; Creates the tables and indexes described by db_schema_v8.dbml, if they
|
||||
; don't exist yet. Plain "CREATE IF NOT EXISTS" for now - a real versioned
|
||||
; upgrade mechanism (DbUpdater) will replace this later.
|
||||
; Fails on a database made with an older schema, since it would be left as is.
|
||||
@@ -430,6 +433,33 @@ Procedure.i SetupStorageDatabase(DbId.i)
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; For browsing with a database tool: set browse's one row to a topic
|
||||
; (and optionally a node), open browse_messages. The foreign keys are
|
||||
; only there for the tools: SQLiteStudio shows a dropdown of the names
|
||||
; for a column that references them. The server never turns foreign keys
|
||||
; on, so they never get in its way (a topic renamed in the config only
|
||||
; leaves a stale name here). The server never writes to browse either.
|
||||
If Not DatabaseUpdate(DbId, "CREATE TABLE IF NOT EXISTS browse (" +
|
||||
"id INTEGER PRIMARY KEY CHECK (id = 1), " +
|
||||
"topic TEXT COLLATE NOCASE REFERENCES topics (name), " +
|
||||
"node TEXT COLLATE NOCASE REFERENCES nodes (name))") Or
|
||||
Not DatabaseUpdate(DbId, "INSERT OR IGNORE INTO browse (id) VALUES (1)")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
; Newest first, by the (topic_id, pushed_at) index. Made again on every
|
||||
; start, like messages.
|
||||
If Not DatabaseUpdate(DbId, "DROP VIEW IF EXISTS browse_messages") Or
|
||||
Not DatabaseUpdate(DbId, "CREATE VIEW browse_messages AS " +
|
||||
"SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json, " +
|
||||
"a.size AS attachment_size, m.topic " +
|
||||
"FROM browse b JOIN messages m ON m.topic = b.topic " +
|
||||
"LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id AND a.message_id = m.message_id " +
|
||||
"WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node) " +
|
||||
"ORDER BY m.pushed_at DESC, m.node, m.message_id DESC")
|
||||
ProcedureReturn #False
|
||||
EndIf
|
||||
|
||||
ProcedureReturn #True
|
||||
EndProcedure
|
||||
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// Changes from v7:
|
||||
// - browse: one row (id 1), the topic and optionally the node to browse,
|
||||
// referencing topics and nodes by name so database tools (SQLiteStudio)
|
||||
// show a dropdown of them. Never written by the server, its foreign keys
|
||||
// never turned on by it.
|
||||
// - browse_messages: the view of what browse selects, newest first.
|
||||
// - The origins of topics and nodes: "config" also covers the nodes the
|
||||
// config's sections define, "peer" the names peers sent (AcceptTopics /
|
||||
// AcceptNodes wildcards).
|
||||
//
|
||||
// Needs SQLite 3.38+ with its JSON functions (json_valid, ->>), see Storage.pbi.
|
||||
// The database is in WAL mode, see Storage.pbi and Writer.pbi.
|
||||
|
||||
table data {
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
message_id integer [not null]
|
||||
message_data text [not null]
|
||||
|
||||
// 1 if message_data is well-formed JSON, 0 otherwise.
|
||||
// Can't be written, SQLite computes it on insert and stores it.
|
||||
is_json integer [not null, note: 'GENERATED ALWAYS AS (json_valid(message_data)) STORED']
|
||||
|
||||
// When it was pushed to its origin, ms since 1970-01-01 UTC.
|
||||
pushed_at integer [not null, default: 0]
|
||||
|
||||
indexes {
|
||||
(topic_id, node_id, message_id) [unique]
|
||||
message_id
|
||||
(topic_id, pushed_at)
|
||||
}
|
||||
}
|
||||
|
||||
// One row per topic/node id that has ever had messages: deleting messages
|
||||
// (the retention) leaves it as is, so ids never go back.
|
||||
// AFTER INSERT ON data: INSERT ... ON CONFLICT DO UPDATE SET
|
||||
// max_message_id = MAX(max_message_id, excluded.max_message_id)
|
||||
// Only fires for rows actually inserted (not the ones INSERT OR IGNORE drops).
|
||||
table node_heads [note: 'WITHOUT ROWID'] {
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
max_message_id integer [not null]
|
||||
|
||||
indexes {
|
||||
(topic_id, node_id) [pk]
|
||||
}
|
||||
}
|
||||
|
||||
// A message's attachment (Design/Attachments.md). Its size and SHA-256 come
|
||||
// with it (pushed, or replicated), its data in blob_id once any is here.
|
||||
// state: 0 missing (replicated, none here yet), 1 receiving, 2 ready,
|
||||
// 3 not kept (bigger than this server's MaxAttachmentSize).
|
||||
// AFTER DELETE ON data deletes it, AFTER DELETE ON attachments marks its
|
||||
// blob to delete (state 3).
|
||||
table attachments [note: 'WITHOUT ROWID'] {
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
message_id integer [not null]
|
||||
size integer [not null]
|
||||
sha256 blob [not null]
|
||||
blob_id integer
|
||||
state integer [not null]
|
||||
|
||||
indexes {
|
||||
(topic_id, node_id, message_id) [pk]
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
// The data of one attachment, being received (an upload, or replicated) or
|
||||
// stored. topic_id, node_id: an upload's owner, or the message's pair.
|
||||
// received: bytes stored so far. created_at: ms since 1970 UTC, an upload
|
||||
// not pushed with its message within UploadTimeout is deleted.
|
||||
// state: 0 receiving, 1 complete (an upload waiting for its message),
|
||||
// 2 attached, 3 to delete.
|
||||
table blobs {
|
||||
blob_id integer [pk]
|
||||
topic_id integer [not null]
|
||||
node_id integer [not null]
|
||||
size integer [not null]
|
||||
sha256 blob [not null]
|
||||
received integer [not null, default: 0]
|
||||
state integer [not null]
|
||||
created_at integer [not null]
|
||||
|
||||
indexes {
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
// Its parts, #BakaShrot_AttachmentChunkSize (1 MB) each, the last one
|
||||
// what's left.
|
||||
table blob_chunks {
|
||||
blob_id integer [not null]
|
||||
chunk_index integer [not null]
|
||||
chunk_data blob [not null]
|
||||
|
||||
indexes {
|
||||
(blob_id, chunk_index) [pk]
|
||||
}
|
||||
}
|
||||
|
||||
// origin: "config" (named in [BakaShrot.Topics]), "peer" (taken from a
|
||||
// peer by a wildcard), "id" (unnamed, name is the id in digits).
|
||||
table topics {
|
||||
topic_id integer [pk]
|
||||
name text [not null, unique, note: 'COLLATE NOCASE']
|
||||
origin text [not null]
|
||||
}
|
||||
|
||||
// origin: "config" (named in [BakaShrot.Nodes], or a node the config's
|
||||
// [BakaShrot], peer or client sections define), "peer" (taken from a peer:
|
||||
// AcceptNodes is * by default), "id" (unnamed).
|
||||
table nodes {
|
||||
node_id integer [pk]
|
||||
name text [not null, unique, note: 'COLLATE NOCASE']
|
||||
origin text [not null]
|
||||
}
|
||||
|
||||
// View messages:
|
||||
// SELECT t.name AS topic, n.name AS node, d.message_id, d.message_data,
|
||||
// d.is_json, d.topic_id, d.node_id, d.pushed_at,
|
||||
// strftime('%Y-%m-%dT%H:%M:%fZ', d.pushed_at / 1000.0, 'unixepoch') AS pushed_utc
|
||||
// FROM data d JOIN topics t ON t.topic_id = d.topic_id
|
||||
// JOIN nodes n ON n.node_id = d.node_id
|
||||
// WHERE topic = ... AND node = ... goes through the name indexes, then
|
||||
// data's (topic_id, node_id, message_id) one.
|
||||
|
||||
// What to browse with a database tool: set topic (and node, NULL for every
|
||||
// one) in its one row, open browse_messages. The references are for the
|
||||
// tools' dropdowns only: the server doesn't turn foreign keys on.
|
||||
table browse {
|
||||
id integer [pk, note: 'CHECK (id = 1)']
|
||||
topic text [ref: > topics.name, note: 'COLLATE NOCASE']
|
||||
node text [ref: > nodes.name, note: 'COLLATE NOCASE']
|
||||
}
|
||||
|
||||
// View browse_messages:
|
||||
// SELECT m.node, m.message_id, m.pushed_utc, m.message_data, m.is_json,
|
||||
// a.size AS attachment_size, m.topic
|
||||
// FROM browse b JOIN messages m ON m.topic = b.topic
|
||||
// LEFT JOIN attachments a ON a.topic_id = m.topic_id AND a.node_id = m.node_id
|
||||
// AND a.message_id = m.message_id
|
||||
// WHERE b.id = 1 AND (b.node IS NULL OR m.node = b.node)
|
||||
// ORDER BY m.pushed_at DESC, m.node, m.message_id DESC
|
||||
|
||||
// Note, ignore it
|
||||
// msg_type TEXT GENERATED ALWAYS AS (data ->> '$.messageData.MsgType') VIRTUAL
|
||||
Reference in New Issue
Block a user