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

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
@@ -0,0 +1,65 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, tells the client its challenge response was accepted and it is now authenticated.
; Only carries the base fields.
Structure BakaShrot_AuthAccepted Extends BakaShrot_PacketBase
EndStructure
; Encodes *Accepted into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_AuthAcceptedPacket_Encode(*Accepted.BakaShrot_AuthAccepted, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Accepted\Magic = #BakaShrot_ProtocolMagic
*Accepted\Version = #BakaShrot_ProtocolVersion
*Accepted\PacketType = #BakaShrot_PacketType_AuthAccepted
*MsgPackData = MsgPackCreate(16)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Accepted, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_AuthAcceptedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Accepted.BakaShrot_AuthAccepted
*Accepted = AllocateStructure(BakaShrot_AuthAccepted)
If Not *Accepted
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Accepted, *MsgPackData) Or *Accepted\PacketType <> #BakaShrot_PacketType_AuthAccepted
FreeStructure(*Accepted)
ProcedureReturn 0
EndIf
ProcedureReturn *Accepted
EndProcedure
@@ -1,303 +0,0 @@
; ============================================================================
; BakaShrot Authentication Packets
;
; The three packets exchanged during the auth handshake:
; C2S AuthRequest - client introduces itself and its public key.
; S2C AuthChallenge - server sends back something for the client to sign.
; C2S AuthResult - client replies with the signed challenge.
;
; Wire format: BakaShrot_PacketBase (Magic, Version, PacketType - see
; Packets.pbi) followed by each struct's own fields, in declaration order.
; Every string field is packed as {len}{str}: a 4-byte (Long) UTF-8 byte
; length, followed by exactly that many UTF-8 bytes - no null terminator.
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S auth request
Structure BakaShrot_AuthRequest Extends BakaShrot_PacketBase
ClientGroupId.l
ClientNodeId.l
ClientPubKeyB64.s
EndStructure
; S2C Chalenge the client must sign it with their private key
Structure BakaShrot_AuthChallenge Extends BakaShrot_PacketBase
ClientPubKeyB64.s
EndStructure
; C2S Response with the chalenge signed by their private key
Structure BakaShrot_AuthResult Extends BakaShrot_PacketBase
ChallengeResponseB64.s
EndStructure
DeclareModule BakaShrot_AuthenticationPacket
; Encodes *Request/*Challenge/*Result into a freshly allocated buffer.
; *OutSize receives its size in bytes. Returns 0 (and leaves *OutSize
; untouched) if the input is invalid (null) or the buffer could not be
; allocated. Caller owns the returned buffer - free it with FreeMemory.
Declare.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l)
Declare.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l)
Declare.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l)
; Decodes *Buffer (BufferSize bytes) into a freshly allocated struct.
; Returns 0 if the packet is too small, malformed, truncated, or not of
; the expected kind. Caller owns the returned struct - free it with
; FreeStructure.
Declare.i DecodeRequest(*Buffer, BufferSize.i)
Declare.i DecodeChallenge(*Buffer, BufferSize.i)
Declare.i DecodeResult(*Buffer, BufferSize.i)
EndDeclareModule
Module BakaShrot_AuthenticationPacket
; ------------------------------------------------------------------------
; Wire helpers. Every string on the wire is {len}{str}: a 4-byte UTF-8
; byte length followed by exactly that many UTF-8 bytes.
; ------------------------------------------------------------------------
; Size, in bytes, Str will take once written as {len}{str}.
Procedure.i PackedStringSize(Str.s)
ProcedureReturn 4 + StringByteLength(Str, #PB_UTF8)
EndProcedure
; Writes Str at *Buffer + Offset as {len}{str}. *Buffer must have room
; for at least PackedStringSize(Str) bytes from Offset onward.
Procedure WritePackedString(*Buffer, Offset.i, Str.s)
PokeL(*Buffer + Offset, StringByteLength(Str, #PB_UTF8))
PokeS(*Buffer + Offset + 4, Str, -1, #PB_UTF8)
EndProcedure
; #True if a {len}{str} value starting at Offset is fully contained
; within the first BufferSize bytes of *Buffer. Always check this before
; calling ReadPackedString() - it does no bounds checking of its own.
Procedure.i PackedStringFits(*Buffer, BufferSize.i, Offset.i)
Protected ByteLen.l
If Offset + 4 > BufferSize
ProcedureReturn #False
EndIf
ByteLen = PeekL(*Buffer + Offset)
If ByteLen < 0 Or Offset + 4 + ByteLen > BufferSize
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Reads the {len}{str} value at *Buffer + Offset. Caller MUST have
; checked PackedStringFits() first.
Procedure.s ReadPackedString(*Buffer, Offset.i)
ProcedureReturn PeekS(*Buffer + Offset + 4, PeekL(*Buffer + Offset), #PB_UTF8 | #PB_ByteLength)
EndProcedure
; ------------------------------------------------------------------------
; Header. All three packets share the same BakaShrot_PacketBase layout:
; Magic.l, Version.l, PacketType.l.
; ------------------------------------------------------------------------
; Writes the packet header at the start of *Buffer. Returns the offset of
; the first byte after the header.
Procedure.i WriteHeader(*Buffer, PacketType.l)
PokeL(*Buffer, #BakaShrot_ProtocolMagic)
PokeL(*Buffer + 4, #BakaShrot_ProtocolVersion)
PokeL(*Buffer + 8, PacketType)
ProcedureReturn SizeOf(BakaShrot_PacketBase)
EndProcedure
; Validates the header at the start of *Buffer: big enough to hold one,
; correct Magic/Version, and PacketType matching ExpectedPacketType.
; Returns the offset of the first byte after the header on success, or
; -1 if the packet must be thrown out.
Procedure.i ReadHeader(*Buffer, BufferSize.i, ExpectedPacketType.l)
If BufferSize < SizeOf(BakaShrot_PacketBase)
ProcedureReturn -1
EndIf
If PeekL(*Buffer) <> #BakaShrot_ProtocolMagic
ProcedureReturn -1
EndIf
If PeekL(*Buffer + 4) <> #BakaShrot_ProtocolVersion
ProcedureReturn -1
EndIf
If PeekL(*Buffer + 8) <> ExpectedPacketType
ProcedureReturn -1
EndIf
ProcedureReturn SizeOf(BakaShrot_PacketBase)
EndProcedure
; ------------------------------------------------------------------------
; AuthRequest (C2S)
; ------------------------------------------------------------------------
Procedure.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l)
Protected Size.i, *Buffer, Offset.i
If Not *Request
ProcedureReturn 0
EndIf
Size = SizeOf(BakaShrot_PacketBase) + 4 + 4 + PackedStringSize(*Request\ClientPubKeyB64)
*Buffer = AllocateMemory(Size)
If Not *Buffer
ProcedureReturn 0
EndIf
Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationRequest)
PokeL(*Buffer + Offset, *Request\ClientGroupId)
Offset = Offset + 4
PokeL(*Buffer + Offset, *Request\ClientNodeId)
Offset = Offset + 4
WritePackedString(*Buffer, Offset, *Request\ClientPubKeyB64)
*OutSize\l = Size
ProcedureReturn *Buffer
EndProcedure
Procedure.i DecodeRequest(*Buffer, BufferSize.i)
Protected Offset.i, *Request.BakaShrot_AuthRequest
Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationRequest)
If Offset = -1
ProcedureReturn 0
EndIf
If Offset + 4 + 4 > BufferSize
ProcedureReturn 0
EndIf
*Request = AllocateStructure(BakaShrot_AuthRequest)
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_AuthenticationRequest
*Request\ClientGroupId = PeekL(*Buffer + Offset)
Offset = Offset + 4
*Request\ClientNodeId = PeekL(*Buffer + Offset)
Offset = Offset + 4
If Not PackedStringFits(*Buffer, BufferSize, Offset)
FreeStructure(*Request)
ProcedureReturn 0
EndIf
*Request\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset)
ProcedureReturn *Request
EndProcedure
; ------------------------------------------------------------------------
; AuthChallenge (S2C)
; ------------------------------------------------------------------------
Procedure.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l)
Protected Size.i, *Buffer, Offset.i
If Not *Challenge
ProcedureReturn 0
EndIf
Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Challenge\ClientPubKeyB64)
*Buffer = AllocateMemory(Size)
If Not *Buffer
ProcedureReturn 0
EndIf
Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationChallenge)
WritePackedString(*Buffer, Offset, *Challenge\ClientPubKeyB64)
*OutSize\l = Size
ProcedureReturn *Buffer
EndProcedure
Procedure.i DecodeChallenge(*Buffer, BufferSize.i)
Protected Offset.i, *Challenge.BakaShrot_AuthChallenge
Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationChallenge)
If Offset = -1
ProcedureReturn 0
EndIf
If Not PackedStringFits(*Buffer, BufferSize, Offset)
ProcedureReturn 0
EndIf
*Challenge = AllocateStructure(BakaShrot_AuthChallenge)
*Challenge\Magic = #BakaShrot_ProtocolMagic
*Challenge\Version = #BakaShrot_ProtocolVersion
*Challenge\PacketType = #BakaShrot_PacketType_AuthenticationChallenge
*Challenge\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset)
ProcedureReturn *Challenge
EndProcedure
; ------------------------------------------------------------------------
; AuthResult (C2S)
; ------------------------------------------------------------------------
Procedure.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l)
Protected Size.i, *Buffer, Offset.i
If Not *Result
ProcedureReturn 0
EndIf
Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Result\ChallengeResponseB64)
*Buffer = AllocateMemory(Size)
If Not *Buffer
ProcedureReturn 0
EndIf
Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationResult)
WritePackedString(*Buffer, Offset, *Result\ChallengeResponseB64)
*OutSize\l = Size
ProcedureReturn *Buffer
EndProcedure
Procedure.i DecodeResult(*Buffer, BufferSize.i)
Protected Offset.i, *Result.BakaShrot_AuthResult
Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationResult)
If Offset = -1
ProcedureReturn 0
EndIf
If Not PackedStringFits(*Buffer, BufferSize, Offset)
ProcedureReturn 0
EndIf
*Result = AllocateStructure(BakaShrot_AuthResult)
*Result\Magic = #BakaShrot_ProtocolMagic
*Result\Version = #BakaShrot_ProtocolVersion
*Result\PacketType = #BakaShrot_PacketType_AuthenticationResult
*Result\ChallengeResponseB64 = ReadPackedString(*Buffer, Offset)
ProcedureReturn *Result
EndProcedure
EndModule
@@ -0,0 +1,131 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C challenge the client must sign with its private key, the last packet sent in plain text.
; Nonce is fresh random data tied to this connection, the client must echo it back in its response.
; ServerSessionKey: the public half of the server's key pair for this connection.
; ServerSignature: the server's signature of the handshake so far, made with its identity key
; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi), so the client knows it's the right server.
Structure BakaShrot_ChallengeRequest Extends BakaShrot_PacketBase
ChallengeB64.s
Nonce.a[#BakaShrot_NonceSize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
ServerSignature.a[#BakaShrot_HandshakeSignatureSize]
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *Request\Nonce must already be filled by the caller with CryptRandomData().
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChallengeRequestPacket_Encode(*Request.BakaShrot_ChallengeRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ChallengeRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\ChallengeB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChallengeRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ChallengeRequest
Protected ReadSize.q
*Request = AllocateStructure(BakaShrot_ChallengeRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ChallengeRequest
Goto DecodeFailed
EndIf
; ChallengeB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\ChallengeB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Nonce
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize
Goto DecodeFailed
EndIf
; ServerSessionKey
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize
Goto DecodeFailed
EndIf
; ServerSignature
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_HandshakeSignatureSize
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S response with the handshake (challenge included) signed by the client's private key
; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi). Sent encrypted, as everything after it.
; Nonce is the one received in the challenge request, echoed back as-is.
; The server MUST compare it with the nonce it issued for this connection and drop the client on mismatch.
Structure BakaShrot_ChallengeResponse Extends BakaShrot_PacketBase
ChallengeResponseB64.s
Nonce.a[#BakaShrot_NonceSize]
EndStructure
; Encodes *Response into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChallengeResponsePacket_Encode(*Response.BakaShrot_ChallengeResponse, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Response\Magic = #BakaShrot_ProtocolMagic
*Response\Version = #BakaShrot_ProtocolVersion
*Response\PacketType = #BakaShrot_PacketType_ChallengeResponse
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Response, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Response\ChallengeResponseB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChallengeResponsePacket_Decode(*MsgPackData.MsgPackData)
Protected *Response.BakaShrot_ChallengeResponse
Protected ReadSize.q
*Response = AllocateStructure(BakaShrot_ChallengeResponse)
If Not *Response
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Response, *MsgPackData) Or *Response\PacketType <> #BakaShrot_PacketType_ChallengeResponse
Goto DecodeFailed
EndIf
; ChallengeResponseB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Response\ChallengeResponseB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Nonce
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize
Goto DecodeFailed
EndIf
ProcedureReturn *Response
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Response)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,99 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks for the latest message stored for a topic/node combination.
; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi).
; The client's [BakaShrot.Client.<name>] ReadTopics must allow the topic.
; Answered with a LatestMessage or a RequestRefused.
Structure BakaShrot_GetLatestMessage Extends BakaShrot_PacketBase
Topic.s
Node.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetLatestMessagePacket_Encode(*Request.BakaShrot_GetLatestMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetLatestMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetLatestMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetLatestMessage
*Request = AllocateStructure(BakaShrot_GetLatestMessage)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetLatestMessage
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,138 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Most messages a GetMessages may ask for.
#BakaShrot_MaxGetMessages = 10000
; C2S, asks for the messages of a topic/node combination stored after
; AfterMessageId (0 for the first ones), in message id order, at most Limit
; (1-#BakaShrot_MaxGetMessages) of them.
; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi).
; The client's [BakaShrot.Client.<name>] ReadTopics must allow the topic.
; Answered with a Messages (maybe with none) or a RequestRefused.
Structure BakaShrot_GetMessages Extends BakaShrot_PacketBase
Topic.s
Node.s
AfterMessageId.q
Limit.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetMessagesPacket_Encode(*Request.BakaShrot_GetMessages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetMessages
If *Request\AfterMessageId < 0 Or *Request\Limit < 1 Or *Request\Limit > #BakaShrot_MaxGetMessages
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\AfterMessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Limit) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetMessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetMessages
Protected Value.q
*Request = AllocateStructure(BakaShrot_GetMessages)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetMessages
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; AfterMessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Request\AfterMessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Request\AfterMessageId < 0
Goto DecodeFailed
EndIf
; Limit
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxGetMessages
Goto DecodeFailed
EndIf
*Request\Limit = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
+130
View File
@@ -0,0 +1,130 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S auth request, sent sealed for the server's public key (Connections.pbi).
; ClientTopic, ClientNode: who the client is, each a name or an id in digits
; (Commons/Networking/Names.pbi), resolved by the server in its own names.
; ClientSessionKey: the public half of the client's key pair for this
; connection (Commons/Cryptography/Session.pbi).
Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase
ClientTopic.s
ClientNode.s
ClientPubKeyB64.s
ClientSessionKey.a[#BakaShrot_SessionKeySize]
EndStructure
; Encodes *Hello into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_HelloPacket_Encode(*Hello.BakaShrot_AuthHello, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Hello\Magic = #BakaShrot_ProtocolMagic
*Hello\Version = #BakaShrot_ProtocolVersion
*Hello\PacketType = #BakaShrot_PacketType_ClientHello
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Hello, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientTopic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientNode) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientPubKeyB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_HelloPacket_Decode(*MsgPackData.MsgPackData)
Protected *Hello.BakaShrot_AuthHello
Protected ReadSize.q
*Hello = AllocateStructure(BakaShrot_AuthHello)
If Not *Hello
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Hello, *MsgPackData) Or *Hello\PacketType <> #BakaShrot_PacketType_ClientHello
Goto DecodeFailed
EndIf
; ClientTopic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientTopic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientNode
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientNode = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientPubKeyB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientPubKeyB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientSessionKey
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize
Goto DecodeFailed
EndIf
ProcedureReturn *Hello
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Hello)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,157 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a GetLatestMessage with the latest message of that topic/node combination.
; TopicId, NodeId: the server's own ids for them.
; TopicName, NodeName: their names, or their ids in digits if they have none.
Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
MessageId.q
JsonData.s
EndStructure
; Encodes *Latest into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Latest\Magic = #BakaShrot_ProtocolMagic
*Latest\Version = #BakaShrot_ProtocolVersion
*Latest\PacketType = #BakaShrot_PacketType_LatestMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Latest, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\TopicName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\NodeName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Latest.BakaShrot_LatestMessage
Protected Value.q
*Latest = AllocateStructure(BakaShrot_LatestMessage)
If Not *Latest
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Latest, *MsgPackData) Or *Latest\PacketType <> #BakaShrot_PacketType_LatestMessage
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Latest\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Latest\NodeId = Value
; TopicName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\TopicName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; NodeName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\NodeName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\MessageId < 1
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Latest
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Latest)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,87 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; C2S, asks for every topic or node the server has, with their ids and names.
; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Topics: only those the client may push to or read, unless it may query.
; Answered with a NamesList.
Structure BakaShrot_ListNames Extends BakaShrot_PacketBase
Kind.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ListNamesPacket_Encode(*Request.BakaShrot_ListNames, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ListNames
*MsgPackData = MsgPackCreate(32)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ListNamesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ListNames
Protected Value.q
*Request = AllocateStructure(BakaShrot_ListNames)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ListNames
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Request\Kind = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,82 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a PushMessage with the id the message was stored under.
Structure BakaShrot_MessagePushed Extends BakaShrot_PacketBase
MessageId.q
EndStructure
; Encodes *Pushed into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MessagePushedPacket_Encode(*Pushed.BakaShrot_MessagePushed, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Pushed\Magic = #BakaShrot_ProtocolMagic
*Pushed\Version = #BakaShrot_ProtocolVersion
*Pushed\PacketType = #BakaShrot_PacketType_MessagePushed
*MsgPackData = MsgPackCreate(32)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Pushed, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Pushed\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MessagePushedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Pushed.BakaShrot_MessagePushed
*Pushed = AllocateStructure(BakaShrot_MessagePushed)
If Not *Pushed
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Pushed, *MsgPackData) Or *Pushed\PacketType <> #BakaShrot_PacketType_MessagePushed
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Pushed\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Pushed\MessageId < 1
Goto DecodeFailed
EndIf
ProcedureReturn *Pushed
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Pushed)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,219 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
XIncludeFile "GetMessagesPacket.pbi"
; One message of a Messages answer.
Structure BakaShrot_MessagesEntry
MessageId.q
JsonData.s
EndStructure
; About how big a Messages answer gets: messages are added while they fit
; in it, and a bigger one goes alone (up to #BakaShrot_MaxMessageSize).
#BakaShrot_MessagesBatchBytes = 1024 * 1024
; Encoded size of the answer's own fields, and of each message on top of its
; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize.
#BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
#BakaShrot_MessagesMessageOverhead = 16
; S2C, answers a GetMessages with the messages of that topic/node combination
; stored after the asked id, in message id order: as many as were asked for,
; or fewer if they didn't fit in about #BakaShrot_MessagesBatchBytes. None
; if there are no more.
; TopicId, NodeId: the server's own ids for them.
; TopicName, NodeName: their names, or their ids in digits if they have none.
; More: 1 if more messages follow the last one, ask again after it.
; On the wire: topic id, node id, topic name, node name, more, message
; count, then each message's id and JSON.
Structure BakaShrot_Messages Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
More.l
List Messages.BakaShrot_MessagesEntry()
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_Messages
If ListSize(*Answer\Messages()) > #BakaShrot_MaxGetMessages
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\TopicName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\NodeName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, Bool(*Answer\More)) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Messages
If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Messages())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Answer\Messages()
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; Message ids must be 1 or more, and strictly increasing.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_Messages
Protected Value.q, Count.q, i.q, PreviousMessageId.q
*Answer = AllocateStructure(BakaShrot_Messages)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_Messages
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Answer\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Answer\NodeId = Value
; TopicName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\TopicName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; NodeName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\NodeName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; More
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*Answer\More = Value
; Message count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxGetMessages
Goto DecodeFailed
EndIf
; Messages
PreviousMessageId = 0
For i = 1 To Count
AddElement(*Answer\Messages())
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\MessageId <= PreviousMessageId
Goto DecodeFailed
EndIf
PreviousMessageId = *Answer\Messages()\MessageId
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Messages()\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,116 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; S2C, answers a ResolveName.
; Kind: the one asked about, #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Id: the server's own id for it, 0-65535.
; Name: its name, "" if it has none.
Structure BakaShrot_NameResolved Extends BakaShrot_PacketBase
Kind.l
Id.l
Name.s
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_NameResolvedPacket_Encode(*Answer.BakaShrot_NameResolved, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_NameResolved
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Id) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Name) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_NameResolvedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_NameResolved
Protected Value.q
*Answer = AllocateStructure(BakaShrot_NameResolved)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_NameResolved
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Answer\Kind = Value
; Id
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Answer\Id = Value
; Name
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,177 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; One topic or node of a NamesList.
; Origin: where its name comes from, "config" (named in the config) or "id"
; (unnamed, Name is ""). See Server/Storage/Names.pbi.
Structure BakaShrot_NameEntry
Id.l
Name.s
Origin.s
EndStructure
#BakaShrot_MaxNamesListEntries = 65536
; S2C, answers a ListNames, by id.
; Kind: the one asked about. Truncated: 1 if there were more than fit in one
; packet, the first ones by id are listed.
; On the wire: Kind, Truncated, entry count, then each entry's id, name and origin.
Structure BakaShrot_NamesList Extends BakaShrot_PacketBase
Kind.l
Truncated.l
List Entries.BakaShrot_NameEntry()
EndStructure
; Encoded size of the packet's own fields, and of each entry on top of its
; name and origin, rounded up. Used to cut a list before it gets over
; #BakaShrot_MaxPacketSize.
#BakaShrot_NamesListOverhead = 64
#BakaShrot_NamesListEntryOverhead = 16
; Encodes *List into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_NamesListPacket_Encode(*List.BakaShrot_NamesList, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*List\Magic = #BakaShrot_ProtocolMagic
*List\Version = #BakaShrot_ProtocolVersion
*List\PacketType = #BakaShrot_PacketType_NamesList
If ListSize(*List\Entries()) > #BakaShrot_MaxNamesListEntries
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*List, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *List\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, Bool(*List\Truncated)) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, ListSize(*List\Entries())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *List\Entries()
If MsgPackWriteInteger(*MsgPackData, *List\Entries()\Id) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *List\Entries()\Name) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *List\Entries()\Origin) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_NamesListPacket_Decode(*MsgPackData.MsgPackData)
Protected *List.BakaShrot_NamesList
Protected Value.q, Count.q, i.q
*List = AllocateStructure(BakaShrot_NamesList)
If Not *List
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*List, *MsgPackData) Or *List\PacketType <> #BakaShrot_PacketType_NamesList
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*List\Kind = Value
; Truncated
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*List\Truncated = Value
; Entries
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxNamesListEntries
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*List\Entries())
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*List\Entries()\Id = Value
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*List\Entries()\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*List\Entries()\Origin = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *List
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*List)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks the server to store a JSON message.
; Topic: where to push it, a name or an id in digits (Commons/Networking/Names.pbi),
; "" for the topic of the client's authenticated identity. The client's
; [BakaShrot.Client.<name>] PushTopics must allow it.
; The node is always the client's authenticated one, the client can't pick it.
; Answered with a MessagePushed or a RequestRefused.
Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase
Topic.s
JsonData.s
EndStructure
; Encodes *Push into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_PushMessagePacket_Encode(*Push.BakaShrot_PushMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Push\Magic = #BakaShrot_ProtocolMagic
*Push\Version = #BakaShrot_ProtocolVersion
*Push\PacketType = #BakaShrot_PacketType_PushMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Push, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Push\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Push\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_PushMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Push.BakaShrot_PushMessage
*Push = AllocateStructure(BakaShrot_PushMessage)
If Not *Push
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Push, *MsgPackData) Or *Push\PacketType <> #BakaShrot_PacketType_PushMessage
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Push\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Push\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Push
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Push)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,84 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, a raw SQL query to run read-only on the server's database.
; Must be a single SELECT (or WITH ... SELECT), anything after the first statement is ignored.
; Answered with a QueryResult or a RequestRefused.
Structure BakaShrot_QueryRequest Extends BakaShrot_PacketBase
Sql.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_QueryRequestPacket_Encode(*Request.BakaShrot_QueryRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_QueryRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Sql) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_QueryRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_QueryRequest
*Request = AllocateStructure(BakaShrot_QueryRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_QueryRequest
Goto DecodeFailed
EndIf
; Sql
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Sql = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,84 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a QueryRequest with its rows, as JSON:
; {"columns": ["name", ...], "rows": [["value", ...], ...]}
; Every value is a string, or null for NULL: PureBasic doesn't report SQLite's column types.
Structure BakaShrot_QueryResult Extends BakaShrot_PacketBase
JsonResult.s
EndStructure
; Encodes *Result into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_QueryResultPacket_Encode(*Result.BakaShrot_QueryResult, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Result\Magic = #BakaShrot_ProtocolMagic
*Result\Version = #BakaShrot_ProtocolVersion
*Result\PacketType = #BakaShrot_PacketType_QueryResult
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Result, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Result\JsonResult) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_QueryResultPacket_Decode(*MsgPackData.MsgPackData)
Protected *Result.BakaShrot_QueryResult
*Result = AllocateStructure(BakaShrot_QueryResult)
If Not *Result
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Result, *MsgPackData) Or *Result\PacketType <> #BakaShrot_PacketType_QueryResult
Goto DecodeFailed
EndIf
; JsonResult
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Result\JsonResult = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Result
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Result)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,177 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; One message of a ReplicateMessages batch.
Structure BakaShrot_ReplicatedMessage
MessageId.q
JsonData.s
EndStructure
; Most messages a batch may carry, whatever the sender's PeerBatchSize.
; #BakaShrot_ReplicateBatchBytes usually stops a batch well before that.
#BakaShrot_MaxReplicateBatch = 10000
; About how big a batch gets: messages are added while they fit in it, and
; a bigger one goes alone (up to #BakaShrot_MaxMessageSize). Small enough to
; keep each batch's transaction and memory short, like when 64 KB was the
; biggest packet.
#BakaShrot_ReplicateBatchBytes = 65536
; Encoded size of a batch's own fields, and of each message on top of its
; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize.
#BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
#BakaShrot_ReplicateMessageOverhead = 16
; Peer -> Server, messages the server is missing for one topic/node, in
; message id order, with the message ids they were stored under on their
; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi):
; the server stores them under its own ids for those names, and refuses
; names it doesn't know.
; On the wire: topic, node, message count, then each message's id and JSON.
; Answered with a MessagePushed carrying the last message's id, or a RequestRefused.
Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase
Topic.s
Node.s
List Messages.BakaShrot_ReplicatedMessage()
EndStructure
; Encodes *Batch into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateMessages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Batch\Magic = #BakaShrot_ProtocolMagic
*Batch\Version = #BakaShrot_ProtocolVersion
*Batch\PacketType = #BakaShrot_PacketType_ReplicateMessages
If ListSize(*Batch\Messages()) < 1 Or ListSize(*Batch\Messages()) > #BakaShrot_MaxReplicateBatch
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Batch, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Messages
If MsgPackWriteInteger(*MsgPackData, ListSize(*Batch\Messages())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Batch\Messages()
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; Message ids must be 1 or more, and strictly increasing.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Batch.BakaShrot_ReplicateMessages
Protected Value.q, Count.q, i.q, PreviousMessageId.q
*Batch = AllocateStructure(BakaShrot_ReplicateMessages)
If Not *Batch
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Batch, *MsgPackData) Or *Batch\PacketType <> #BakaShrot_PacketType_ReplicateMessages
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Node)
Goto DecodeFailed
EndIf
; Message count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 1 Or Count > #BakaShrot_MaxReplicateBatch
Goto DecodeFailed
EndIf
; Messages
PreviousMessageId = 0
For i = 1 To Count
AddElement(*Batch\Messages())
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\MessageId <= PreviousMessageId
Goto DecodeFailed
EndIf
PreviousMessageId = *Batch\Messages()\MessageId
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Messages()\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Batch
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Batch)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,83 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a request the server won't fulfill, the connection stays open.
; Reason is only meant for logs and humans.
Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase
Reason.s
EndStructure
; Encodes *Refused into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefused, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Refused\Magic = #BakaShrot_ProtocolMagic
*Refused\Version = #BakaShrot_ProtocolVersion
*Refused\PacketType = #BakaShrot_PacketType_RequestRefused
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Refused, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Refused\Reason) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Refused.BakaShrot_RequestRefused
*Refused = AllocateStructure(BakaShrot_RequestRefused)
If Not *Refused
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Refused, *MsgPackData) Or *Refused\PacketType <> #BakaShrot_PacketType_RequestRefused
Goto DecodeFailed
EndIf
; Reason
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Refused\Reason = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Refused
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Refused)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,107 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; What a ResolveName / NameResolved is about.
#BakaShrot_NameKind_Topic = 1
#BakaShrot_NameKind_Node = 2
; C2S, asks for the server's id and name of a topic or node.
; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Ref: a name or an id in digits (Commons/Networking/Names.pbi).
; Answered with a NameResolved, or a RequestRefused if the server doesn't
; know it, or if it's a topic the client may neither push to nor read
; (unless it may query, which reads everything anyway).
Structure BakaShrot_ResolveName Extends BakaShrot_PacketBase
Kind.l
Ref.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ResolveNamePacket_Encode(*Request.BakaShrot_ResolveName, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ResolveName
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Ref) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ResolveNamePacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ResolveName
Protected Value.q
*Request = AllocateStructure(BakaShrot_ResolveName)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ResolveName
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Request\Kind = Value
; Ref
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Ref = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,279 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Highest message id a node has for a topic/node id combination.
Structure BakaShrot_SyncPair
TopicId.l
NodeId.l
MessageId.q
EndStructure
; One of the sender's ids, and what it's called: its name, or its id in
; digits if it has none (Commons/Networking/Names.pbi).
Structure BakaShrot_SyncName
Id.l
Name.s
EndStructure
; Biggest lists accepted, the packet size limit keeps the real ones well under it.
#BakaShrot_MaxSyncTopics = 65536
#BakaShrot_MaxSyncNodes = 65536
#BakaShrot_MaxSyncPairs = 65536
#BakaShrot_MaxSyncPatterns = 4096
; Server -> Peer, answers a SyncStateRequest, at every check-in. Ids are the
; sender's own, names are what the peer matches them by: each server has its
; own ids. Only named topics and nodes replicate, and only those named on
; both servers: this is how the peer learns which names this server knows,
; so it never sends anything this server would refuse.
; Topics: the named topics it takes from this peer (its AcceptTopics).
; Nodes: the named nodes it takes from this peer (its AcceptNodes).
; TopicPatterns, NodePatterns: the wildcards ("*", "sensors.*") of its
; AcceptTopics / AcceptNodes: it also takes names it doesn't have yet if
; they match one (Commons/Networking/Names.pbi).
; Pairs: the highest message id it has for each topic/node of those.
; A combination that isn't listed has no message yet.
; Names are names, never ids in digits.
; On the wire: topic count, each topic's id and name, node count, each
; node's id and name, topic pattern count, each pattern, node pattern
; count, each pattern, pair count, then each pair's topic id, node id and
; message id.
Structure BakaShrot_SyncState Extends BakaShrot_PacketBase
List Topics.BakaShrot_SyncName()
List Nodes.BakaShrot_SyncName()
List TopicPatterns.s()
List NodePatterns.s()
List Pairs.BakaShrot_SyncPair()
EndStructure
; Writes a list of ids and names, with its count first.
Procedure.i BakaShrot_SyncStatePacket_WriteNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName())
If MsgPackWriteInteger(*MsgPackData, ListSize(Names())) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ForEach Names()
If MsgPackWriteInteger(*MsgPackData, Names()\Id) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteString(*MsgPackData, Names()\Name) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Writes a list of patterns, with its count first.
Procedure.i BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData.MsgPackData, List Patterns.s())
If MsgPackWriteInteger(*MsgPackData, ListSize(Patterns())) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ForEach Patterns()
If MsgPackWriteString(*MsgPackData, Patterns()) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Encodes *State into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_SyncStatePacket_Encode(*State.BakaShrot_SyncState, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*State\Magic = #BakaShrot_ProtocolMagic
*State\Version = #BakaShrot_ProtocolVersion
*State\PacketType = #BakaShrot_PacketType_SyncState
If ListSize(*State\Topics()) > #BakaShrot_MaxSyncTopics Or ListSize(*State\Nodes()) > #BakaShrot_MaxSyncNodes Or ListSize(*State\Pairs()) > #BakaShrot_MaxSyncPairs
ProcedureReturn 0
EndIf
If ListSize(*State\TopicPatterns()) > #BakaShrot_MaxSyncPatterns Or ListSize(*State\NodePatterns()) > #BakaShrot_MaxSyncPatterns
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*State, *MsgPackData)
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Topics())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Nodes())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\TopicPatterns())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\NodePatterns())
Goto EncodeFailed
EndIf
; Pairs
If MsgPackWriteInteger(*MsgPackData, ListSize(*State\Pairs())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *State\Pairs()
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Reads one integer within Minimum-Maximum into *Value\q.
; Returns #False if it's not an integer, couldn't be read, or is out of range.
Procedure.i BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData.MsgPackData, *Value.Quad, Minimum.q, Maximum.q)
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
*Value\q = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Value\q < Minimum Or *Value\q > Maximum
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Reads a list of ids and names, with its count first. Every name must be a
; valid name, not an id in digits.
; Returns #False if anything is invalid.
Procedure.i BakaShrot_SyncStatePacket_ReadNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName(), MaxCount.i)
Protected Count.q, Value.q, i.q
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, MaxCount)
ProcedureReturn #False
EndIf
For i = 1 To Count
AddElement(Names())
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
ProcedureReturn #False
EndIf
Names()\Id = Value
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
ProcedureReturn #False
EndIf
Names()\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(Names()\Name)
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Reads a list of patterns, with its count first. Each one must be a valid
; pattern, see Commons/Networking/Names.pbi.
; Returns #False if anything is invalid.
Procedure.i BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData.MsgPackData, List Patterns.s())
Protected Count.q, i.q
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPatterns)
ProcedureReturn #False
EndIf
For i = 1 To Count
AddElement(Patterns())
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
ProcedureReturn #False
EndIf
Patterns() = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidPattern(Patterns())
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_SyncStatePacket_Decode(*MsgPackData.MsgPackData)
Protected *State.BakaShrot_SyncState
Protected Count.q, Value.q, i.q
*State = AllocateStructure(BakaShrot_SyncState)
If Not *State
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*State, *MsgPackData) Or *State\PacketType <> #BakaShrot_PacketType_SyncState
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Topics(), #BakaShrot_MaxSyncTopics)
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Nodes(), #BakaShrot_MaxSyncNodes)
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\TopicPatterns())
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\NodePatterns())
Goto DecodeFailed
EndIf
; Pairs
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPairs)
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*State\Pairs())
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
Goto DecodeFailed
EndIf
*State\Pairs()\TopicId = Value
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
Goto DecodeFailed
EndIf
*State\Pairs()\NodeId = Value
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 1, 9223372036854775807)
Goto DecodeFailed
EndIf
*State\Pairs()\MessageId = Value
Next
ProcedureReturn *State
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*State)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,65 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Peer -> Server, asks for the server's sync state, to know which messages it's missing.
; Answered with a SyncState or a RequestRefused. Only carries the base fields.
Structure BakaShrot_SyncStateRequest Extends BakaShrot_PacketBase
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_SyncStateRequestPacket_Encode(*Request.BakaShrot_SyncStateRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_SyncStateRequest
*MsgPackData = MsgPackCreate(16)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_SyncStateRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_SyncStateRequest
*Request = AllocateStructure(BakaShrot_SyncStateRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_SyncStateRequest
FreeStructure(*Request)
ProcedureReturn 0
EndIf
ProcedureReturn *Request
EndProcedure