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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RwFeVTGs2SsufaH6zquzcb
This commit is contained in:
2026-11-14 12:47:40 +01:00
parent d0048b17c8
commit e044fcf359
225 changed files with 21849 additions and 123 deletions
@@ -0,0 +1,475 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Connections.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Connections
;
; What both ends need to keep track of a connection and authenticate it.
;
; Handshake, anything out of order or unexpected aborts the connection.
; The client must already know the server's public key (client.ini's
; ServerPublicKey, a peer section's PublicKey).
; C->S Hello Sealed for the server's public key, only it can
; read it (Session.pbi): the client's identity and
; public key, and the public half of its key pair
; for this connection.
; The server checks they're registered together.
; S->C ChallengeRequest In plain text: random challenge (Base64) and
; nonce, the public half of the server's key pair
; for this connection, and the server's signature
; of the handshake (BakaShrot_MakeHandshakeTranscript()).
; The client checks it with the server's public
; key: it's the right server, and nobody swapped
; the halves. Both ends now have this connection's
; keys, every packet from here on is encrypted
; (Cipher.pbi).
; C->S ChallengeResponse The client's signature of the handshake, and
; the nonce echoed back.
; S->C AuthAccepted The client is authenticated.
;
; Requests, only once authenticated, each one gets one answer:
; C->S PushMessage -> S->C MessagePushed or RequestRefused
; C->S GetLatestMessage -> S->C LatestMessage or RequestRefused
; C->S GetMessages -> S->C Messages (maybe none) or RequestRefused
; C->S QueryRequest -> S->C QueryResult or RequestRefused
; C->S ResolveName -> S->C NameResolved or RequestRefused
; C->S ListNames -> S->C NamesList
; C->S UploadStart -> S->C UploadStarted or RequestRefused
; C->S UploadChunk -> S->C ChunkStored or RequestRefused
; then a PushMessage with the UploadId attaches it to the message
; C->S GetAttachment -> S->C AttachmentChunk or RequestRefused
; Topics and nodes are given by name or id, see Names.pbi.
; A refusal keeps the connection open, a malformed or unexpected packet
; still aborts it.
;
; Replication, only from a peer (see Server/Networking/Peers.pbi), over the
; link it opened to the server:
; P->S SyncStateRequest -> S->P SyncState or RequestRefused
; P->S ReplicateMessages -> S->P MessagePushed (last id) or RequestRefused
; once the messages are caught up:
; P->S MissingAttachmentsRequest -> S->P MissingAttachments or RequestRefused
; P->S ReplicateAttachmentChunk -> S->P ChunkStored or RequestRefused
;
;
; Framing: every packet is sent as its size (4 bytes, little-endian),
; followed by the packet itself, so the receiver knows where it ends.
; Once the connection's cipher is set up, the packet is encrypted first
; (#BakaShrot_Cipher_Overhead bytes more), the size isn't: see
; BakaShrot_SendPacket() and BakaShrot_OpenFrame().
; Up to #BakaShrot_MaxHandshakePacketSize until the other end authenticated,
; then up to #BakaShrot_MaxPacketSize (BakaShrot_Inbox_Lift()): anyone can
; connect, only those with a key get to make the other end hold big frames.
; ============================================================================
XIncludeFile "../Cryptography/Session.pbi"
XIncludeFile "Packets/HelloPacket.pbi"
XIncludeFile "Packets/ChallengeRequestPacket.pbi"
XIncludeFile "Packets/ChallengeResponsePacket.pbi"
XIncludeFile "Packets/AuthAcceptedPacket.pbi"
XIncludeFile "Packets/PushMessagePacket.pbi"
XIncludeFile "Packets/MessagePushedPacket.pbi"
XIncludeFile "Packets/GetLatestMessagePacket.pbi"
XIncludeFile "Packets/LatestMessagePacket.pbi"
XIncludeFile "Packets/RequestRefusedPacket.pbi"
XIncludeFile "Packets/SyncStateRequestPacket.pbi"
XIncludeFile "Packets/SyncStatePacket.pbi"
XIncludeFile "Packets/ReplicateMessagesPacket.pbi"
XIncludeFile "Packets/QueryRequestPacket.pbi"
XIncludeFile "Packets/QueryResultPacket.pbi"
XIncludeFile "Packets/ResolveNamePacket.pbi"
XIncludeFile "Packets/NameResolvedPacket.pbi"
XIncludeFile "Packets/ListNamesPacket.pbi"
XIncludeFile "Packets/NamesListPacket.pbi"
XIncludeFile "Packets/GetMessagesPacket.pbi"
XIncludeFile "Packets/MessagesPacket.pbi"
XIncludeFile "Packets/UploadStartPacket.pbi"
XIncludeFile "Packets/UploadStartedPacket.pbi"
XIncludeFile "Packets/UploadChunkPacket.pbi"
XIncludeFile "Packets/ChunkStoredPacket.pbi"
XIncludeFile "Packets/GetAttachmentPacket.pbi"
XIncludeFile "Packets/AttachmentChunkPacket.pbi"
XIncludeFile "Packets/MissingAttachmentsRequestPacket.pbi"
XIncludeFile "Packets/MissingAttachmentsPacket.pbi"
XIncludeFile "Packets/ReplicateAttachmentChunkPacket.pbi"
; Reads the type of a received packet, to know which decoder to use.
; Returns #BakaShrot_PacketType_None if the packet's base fields are invalid.
Procedure.i BakaShrot_GetPacketType(*Packet, PacketSize.i)
Protected *View.MsgPackData, Base.BakaShrot_PacketBase, IsValid.i
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize)
If Not *View
ProcedureReturn #BakaShrot_PacketType_None
EndIf
IsValid = BakaShrot_ReadPacketBase(@Base, *View)
MsgPackFree(*View, #False)
If Not IsValid
ProcedureReturn #BakaShrot_PacketType_None
EndIf
ProcedureReturn Base\PacketType
EndProcedure
Enumeration BakaShrot_ConnectionStatuses
; Connected, the Hello hasn't been sent/received yet.
#BakaShrot_ConnectionStatus_New
; The challenge was issued, its response hasn't been sent/received yet.
#BakaShrot_ConnectionStatus_Challenged
#BakaShrot_ConnectionStatus_Authenticated
#BakaShrot_ConnectionStatus_Disconnected
#BakaShrot_ConnectionStatus_Aborted
EndEnumeration
CompilerIf #BakaShrot_SessionKeySize <> #BakaShrot_Session_PublicKeySize Or #BakaShrot_HandshakeSignatureSize <> #BakaShrot_Ed25519_SignatureSize
CompilerError "Packets.pbi's handshake sizes don't match the cryptography's."
CompilerEndIf
Structure BakaShrot_ConnectionMetadata
Status.i
; Server side only, trusted once Status is Authenticated: the node from
; the Hello, and the default topic of its pushes from its client
; section's DefaultTopic (-1 without one: pushes must name their topic),
; both as the server's own ids.
DefaultTopicId.l
NodeId.u
; The client's Ed25519 public key, on both sides.
PublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
; The server's Ed25519 public key, on both sides.
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
; TempKey to prevent replay attacks, fresh random data for every connection.
Challenge.a[#BakaShrot_ChallengeSize]
Nonce.a[#BakaShrot_NonceSize]
; Public halves of both ends' key pairs for this connection.
ClientSessionKey.a[#BakaShrot_SessionKeySize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
; Set up once both ends have their keys (after the ChallengeRequest),
; then every packet is encrypted with it. Wiped when the connection ends.
Cipher.BakaShrot_Cipher
EndStructure
; What each end signs: proves it holds its identity key, for this
; connection (the challenge, the nonce, both key pairs), to this other end.
; Label tells which end signed it, so one end's signature can't be sent
; back as the other's.
#BakaShrot_TranscriptLabelSize = 16
#BakaShrot_TranscriptServerLabel = "BakaShrot3 srv"
#BakaShrot_TranscriptClientLabel = "BakaShrot3 cli"
Structure BakaShrot_HandshakeTranscript
Label.a[#BakaShrot_TranscriptLabelSize]
ClientPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
ServerPublicKey.a[#BakaShrot_Ed25519_PublicKeySize]
ClientSessionKey.a[#BakaShrot_SessionKeySize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
Challenge.a[#BakaShrot_ChallengeSize]
Nonce.a[#BakaShrot_NonceSize]
EndStructure
Structure BakaShrot_ChallengeProof
Message.BakaShrot_HandshakeTranscript
Signature.a[#BakaShrot_Ed25519_SignatureSize]
EndStructure
; Fills *Proof\Message from *Metadata, as signed by one end: Label is
; #BakaShrot_TranscriptServerLabel or #BakaShrot_TranscriptClientLabel.
Procedure BakaShrot_MakeHandshakeTranscript(*Metadata.BakaShrot_ConnectionMetadata, Label.s, *Proof.BakaShrot_ChallengeProof)
FillMemory(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), 0)
PokeS(@*Proof\Message\Label[0], Label, #BakaShrot_TranscriptLabelSize - 1, #PB_Ascii)
CopyMemory(@*Metadata\PublicKey[0], @*Proof\Message\ClientPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
CopyMemory(@*Metadata\ServerPublicKey[0], @*Proof\Message\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
CopyMemory(@*Metadata\ClientSessionKey[0], @*Proof\Message\ClientSessionKey[0], #BakaShrot_SessionKeySize)
CopyMemory(@*Metadata\ServerSessionKey[0], @*Proof\Message\ServerSessionKey[0], #BakaShrot_SessionKeySize)
CopyMemory(@*Metadata\Challenge[0], @*Proof\Message\Challenge[0], #BakaShrot_ChallengeSize)
CopyMemory(@*Metadata\Nonce[0], @*Proof\Message\Nonce[0], #BakaShrot_NonceSize)
EndProcedure
; Signs *Proof\Message with *PrivateKey into *Proof\Signature.
Procedure.i BakaShrot_SignHandshake(*Proof.BakaShrot_ChallengeProof, *PrivateKey)
ProcedureReturn EncodeData(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), *PrivateKey, @*Proof\Signature[0])
EndProcedure
; #True if *Proof\Signature is *PublicKey's holder's signature of *Proof\Message.
Procedure.i BakaShrot_VerifyHandshake(*Proof.BakaShrot_ChallengeProof, *PublicKey)
ProcedureReturn DecodeData(@*Proof\Message, SizeOf(BakaShrot_HandshakeTranscript), *PublicKey, @*Proof\Signature[0])
EndProcedure
; Wipes what's secret in *Metadata, once the connection is over.
Procedure BakaShrot_ClearConnectionMetadata(*Metadata.BakaShrot_ConnectionMetadata)
BakaShrot_Cipher_Clear(@*Metadata\Cipher)
EndProcedure
; --- Framing -----------------------------------------------------------------
#BakaShrot_FrameHeaderSize = 4
; Biggest packet before the other end is authenticated. The handshake's are a
; few hundred bytes.
#BakaShrot_MaxHandshakePacketSize = 4096
; A buffer this big or more is freed once emptied, instead of kept for the
; next packets.
#BakaShrot_InboxKeptCapacity = 256 * 1024
; How long a send waits for the other end to make room, without a single
; byte going out, before it gives up. Same as how long a client waits for
; each packet (#BakaShrot_Outbound_Timeout).
#BakaShrot_SendStallTimeout = 10000
Enumeration BakaShrot_InboxResults
#BakaShrot_Inbox_Incomplete
#BakaShrot_Inbox_Packet
#BakaShrot_Inbox_Invalid
EndEnumeration
; Received data that hasn't been read as packets yet: Size bytes, from
; Buffer + Start.
Structure BakaShrot_Inbox
*Buffer
Start.i
Size.i
Capacity.i
; Biggest packet accepted: #BakaShrot_MaxHandshakePacketSize while 0,
; #BakaShrot_MaxPacketSize once lifted.
MaxPacketSize.i
EndStructure
; Biggest packet *Inbox accepts.
Procedure.i BakaShrot_Inbox_MaxPacketSize(*Inbox.BakaShrot_Inbox)
If *Inbox\MaxPacketSize
ProcedureReturn *Inbox\MaxPacketSize
EndIf
ProcedureReturn #BakaShrot_MaxHandshakePacketSize
EndProcedure
; Biggest amount of received data waiting to be read as packets, anything
; more aborts the connection: two of the biggest packets.
Procedure.i BakaShrot_Inbox_MaxSize(*Inbox.BakaShrot_Inbox)
ProcedureReturn 2 * (#BakaShrot_FrameHeaderSize + BakaShrot_Inbox_MaxPacketSize(*Inbox))
EndProcedure
; Accepts packets up to #BakaShrot_MaxPacketSize (encrypted) from now on. Call
; it once the other end is authenticated, before it can send anything big:
; on the server, before sending AuthAccepted.
Procedure BakaShrot_Inbox_Lift(*Inbox.BakaShrot_Inbox)
*Inbox\MaxPacketSize = #BakaShrot_MaxPacketSize + #BakaShrot_Cipher_Overhead
EndProcedure
; Sends *Packet as one frame, encrypted with *Cipher, or in plain text if
; *Cipher is 0: only the Hello (sealed on its own) and the ChallengeRequest.
; Returns #False if the packet is too big, *Cipher isn't set up, or the data
; couldn't be sent.
; PureBasic's sockets don't block: SendNetworkData() returns -1 once the
; system's send buffer is full (EAGAIN on Linux, a few hundred KB), so -1 is
; retried until nothing went out for #BakaShrot_SendStallTimeout. PureBasic
; doesn't tell that from a broken connection, which then takes that long to
; give up on.
Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher)
Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.i, LastProgress.i
If PacketSize < 1 Or PacketSize > #BakaShrot_MaxPacketSize
ProcedureReturn #False
EndIf
PayloadSize = PacketSize
If *Cipher
If Not *Cipher\IsReady
ProcedureReturn #False
EndIf
PayloadSize + #BakaShrot_Cipher_Overhead
EndIf
FrameSize = #BakaShrot_FrameHeaderSize + PayloadSize
*Frame = AllocateMemory(FrameSize, #PB_Memory_NoClear)
If Not *Frame
ProcedureReturn #False
EndIf
PokeL(*Frame, PayloadSize)
If *Cipher
If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Packet, PacketSize, *Frame + #BakaShrot_FrameHeaderSize)
FreeMemory(*Frame)
ProcedureReturn #False
EndIf
Else
CopyMemory(*Packet, *Frame + #BakaShrot_FrameHeaderSize, PacketSize)
EndIf
LastProgress = ElapsedMilliseconds()
While Offset < FrameSize
Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset)
If Sent > 0
Offset + Sent
LastProgress = ElapsedMilliseconds()
ElseIf ElapsedMilliseconds() - LastProgress > #BakaShrot_SendStallTimeout
FreeMemory(*Frame)
ProcedureReturn #False
Else
; Full, until the other end reads some of it.
Delay(1)
EndIf
Wend
FreeMemory(*Frame)
ProcedureReturn #True
EndProcedure
; Adds received data at the end of *Inbox.
; Returns #False if it would go over BakaShrot_Inbox_MaxSize() or memory ran out.
Procedure.i BakaShrot_Inbox_Append(*Inbox.BakaShrot_Inbox, *Data, DataSize.i)
Protected *NewBuffer, Needed.i, MaxSize.i, NewCapacity.i
Needed = *Inbox\Size + DataSize
MaxSize = BakaShrot_Inbox_MaxSize(*Inbox)
If Needed > MaxSize
ProcedureReturn #False
EndIf
; Out of room at the end: moves what's left to the front, but only if it
; isn't bigger than the room that frees, so each byte gets moved about
; once. Otherwise the buffer grows instead, doubling: moving 32 MB under
; the server's mutex for every 64 KB received, near the limit, would stall
; every client. At worst it reaches twice BakaShrot_Inbox_MaxSize().
If *Inbox\Start + Needed > *Inbox\Capacity And *Inbox\Start > 0 And *Inbox\Size <= *Inbox\Start
MoveMemory(*Inbox\Buffer + *Inbox\Start, *Inbox\Buffer, *Inbox\Size)
*Inbox\Start = 0
EndIf
If *Inbox\Start + Needed > *Inbox\Capacity
NewCapacity = *Inbox\Capacity * 2
If NewCapacity < *Inbox\Start + Needed
NewCapacity = *Inbox\Start + Needed
EndIf
If NewCapacity > *Inbox\Start + MaxSize
NewCapacity = *Inbox\Start + MaxSize
EndIf
If *Inbox\Buffer
*NewBuffer = ReAllocateMemory(*Inbox\Buffer, NewCapacity, #PB_Memory_NoClear)
Else
*NewBuffer = AllocateMemory(NewCapacity, #PB_Memory_NoClear)
EndIf
If Not *NewBuffer
ProcedureReturn #False
EndIf
*Inbox\Buffer = *NewBuffer
*Inbox\Capacity = NewCapacity
EndIf
CopyMemory(*Data, *Inbox\Buffer + *Inbox\Start + *Inbox\Size, DataSize)
*Inbox\Size + DataSize
ProcedureReturn #True
EndProcedure
; Takes the first complete packet out of *Inbox.
; Returns:
; #BakaShrot_Inbox_Packet *OutPacket\i receives the packet (free it with FreeMemory), *OutSize\i its size.
; #BakaShrot_Inbox_Incomplete The next packet hasn't fully arrived yet.
; #BakaShrot_Inbox_Invalid The frame's size is invalid (too big for now included), or memory ran out. Abort the connection.
Procedure.i BakaShrot_Inbox_TakePacket(*Inbox.BakaShrot_Inbox, *OutPacket.Integer, *OutSize.Integer)
Protected PacketSize.i, *Packet, *Frame
If *Inbox\Size < #BakaShrot_FrameHeaderSize
ProcedureReturn #BakaShrot_Inbox_Incomplete
EndIf
; Checked as soon as the size arrived, not once the whole frame did.
*Frame = *Inbox\Buffer + *Inbox\Start
PacketSize = PeekL(*Frame) & $FFFFFFFF
If PacketSize < 1 Or PacketSize > BakaShrot_Inbox_MaxPacketSize(*Inbox)
ProcedureReturn #BakaShrot_Inbox_Invalid
EndIf
If *Inbox\Size < #BakaShrot_FrameHeaderSize + PacketSize
ProcedureReturn #BakaShrot_Inbox_Incomplete
EndIf
*Packet = AllocateMemory(PacketSize, #PB_Memory_NoClear)
If Not *Packet
ProcedureReturn #BakaShrot_Inbox_Invalid
EndIf
CopyMemory(*Frame + #BakaShrot_FrameHeaderSize, *Packet, PacketSize)
; What's left stays where it is, Append() moves it when it needs room.
*Inbox\Start + #BakaShrot_FrameHeaderSize + PacketSize
*Inbox\Size - (#BakaShrot_FrameHeaderSize + PacketSize)
If *Inbox\Size = 0
*Inbox\Start = 0
If *Inbox\Capacity >= #BakaShrot_InboxKeptCapacity
FreeMemory(*Inbox\Buffer)
*Inbox\Buffer = 0
*Inbox\Capacity = 0
EndIf
EndIf
*OutPacket\i = *Packet
*OutSize\i = PacketSize
ProcedureReturn #BakaShrot_Inbox_Packet
EndProcedure
; Turns a frame's content taken out of an inbox (*Frame, FrameSize bytes)
; into the packet: decrypts it with *Cipher once it's set up, as it must
; be from the ChallengeResponse on, else it's the packet already.
; Returns the packet (free it with FreeMemory), its size in *OutSize\i, or
; 0 if it doesn't decrypt: abort the connection. *Frame is freed or
; returned either way.
Procedure.i BakaShrot_OpenFrame(*Cipher.BakaShrot_Cipher, *Frame, FrameSize.i, *OutSize.Integer)
Protected *Packet
If Not *Cipher\IsReady
*OutSize\i = FrameSize
ProcedureReturn *Frame
EndIf
*Packet = BakaShrot_Cipher_Decrypt(*Cipher, *Frame, FrameSize, *OutSize)
FreeMemory(*Frame)
If *Packet And *OutSize\i < 1
; Never sent: BakaShrot_SendPacket() refuses empty packets.
FreeMemory(*Packet)
*Packet = 0
EndIf
ProcedureReturn *Packet
EndProcedure
; Frees *Inbox's data, and puts its limit back to the handshake's.
Procedure BakaShrot_Inbox_Clear(*Inbox.BakaShrot_Inbox)
If *Inbox\Buffer
FreeMemory(*Inbox\Buffer)
EndIf
*Inbox\Buffer = 0
*Inbox\Start = 0
*Inbox\Size = 0
*Inbox\Capacity = 0
*Inbox\MaxPacketSize = 0
EndProcedure
+169
View File
@@ -0,0 +1,169 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Names.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Names
;
; Topics and nodes have a numeric id (0-65535) on each server, and a name
; that's the same on every server: replication sends names, and each server
; translates them to its own ids (see Server/Storage/Names.pbi).
;
; Wherever a topic or node is given (config, requests, tools), it's a "ref":
; - a name: 1-64 characters out of A-Z a-z 0-9 _ . -, not only digits,
; compared without case ("Logs" is "logs"),
; - or an id written in digits, 0-65535, which is always that id.
; A topic or node without a name is known by its id in digits, "7".
; ============================================================================
#BakaShrot_MaxNameLength = 64
#BakaShrot_MaxId = 65535
; #True if Text is made of digits only (and isn't empty).
Procedure.i BakaShrot_IsDigits(Text.s)
Protected i.i, c.i
If Text = ""
ProcedureReturn #False
EndIf
For i = 1 To Len(Text)
c = Asc(Mid(Text, i, 1))
If c < '0' Or c > '9'
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; #True if Name can be a topic or node name: see the top of this file.
Procedure.i BakaShrot_IsValidName(Name.s)
Protected i.i, c.i
If Name = "" Or Len(Name) > #BakaShrot_MaxNameLength Or BakaShrot_IsDigits(Name)
ProcedureReturn #False
EndIf
For i = 1 To Len(Name)
c = Asc(Mid(Name, i, 1))
If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or c = '_' Or c = '.' Or c = '-')
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; The id a ref written in digits stands for, or -1 if it isn't one (a name,
; or out of range). Leading zeros are refused, "007" isn't "7".
Procedure.i BakaShrot_RefToId(Ref.s)
Protected Id.i
If Not BakaShrot_IsDigits(Ref) Or Len(Ref) > 5
ProcedureReturn -1
EndIf
Id = Val(Ref)
If Str(Id) <> Ref Or Id > #BakaShrot_MaxId
ProcedureReturn -1
EndIf
ProcedureReturn Id
EndProcedure
; #True if Ref is a valid name or a valid id in digits.
Procedure.i BakaShrot_IsValidRef(Ref.s)
ProcedureReturn Bool(BakaShrot_RefToId(Ref) >= 0 Or BakaShrot_IsValidName(Ref))
EndProcedure
; #True if Ref designates the topic or node Id, named Name ("" if unnamed).
Procedure.i BakaShrot_RefMatches(Ref.s, Id.i, Name.s)
If BakaShrot_IsDigits(Ref)
ProcedureReturn Bool(BakaShrot_RefToId(Ref) = Id)
EndIf
ProcedureReturn Bool(Name <> "" And LCase(Ref) = LCase(Name))
EndProcedure
; --- Wildcards ---------------------------------------------------------------
; Server-side lists of topics and nodes (topic lists, SendNodes, ...) also
; take patterns, like file names: "*" any characters (none included), "?"
; exactly one, everything else itself, without case. "sensors.*",
; "kitchen-??", "*". A pattern only matches names, never ids in digits.
; #True if Pattern is a valid pattern: has a * or a ?, and otherwise only
; characters a name can have.
Procedure.i BakaShrot_IsValidPattern(Pattern.s)
Protected i.i, c.i
If Pattern = "" Or Len(Pattern) > #BakaShrot_MaxNameLength
ProcedureReturn #False
EndIf
If Not FindString(Pattern, "*") And Not FindString(Pattern, "?")
ProcedureReturn #False
EndIf
For i = 1 To Len(Pattern)
c = Asc(Mid(Pattern, i, 1))
If Not ((c >= 'a' And c <= 'z') Or (c >= 'A' And c <= 'Z') Or (c >= '0' And c <= '9') Or c = '_' Or c = '.' Or c = '-' Or c = '*' Or c = '?')
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; #True if Name matches Pattern (see above), without case. Ids in digits
; never match.
Procedure.i BakaShrot_GlobMatch(Pattern.s, Name.s)
Protected p.i = 1, n.i = 1, StarP.i = 0, StarN.i = 0
Protected PLen.i, NLen.i, pc.s
If Not BakaShrot_IsValidName(Name)
ProcedureReturn #False
EndIf
Pattern = LCase(Pattern)
Name = LCase(Name)
PLen = Len(Pattern)
NLen = Len(Name)
; Greedy with backtracking to the last "*": linear enough for 64 characters.
While n <= NLen
If p <= PLen
pc = Mid(Pattern, p, 1)
Else
pc = ""
EndIf
If pc = "*"
StarP = p
StarN = n
p + 1
ElseIf pc <> "" And (pc = "?" Or pc = Mid(Name, n, 1))
p + 1
n + 1
ElseIf StarP
p = StarP + 1
StarN + 1
n = StarN
Else
ProcedureReturn #False
EndIf
Wend
While p <= PLen And Mid(Pattern, p, 1) = "*"
p + 1
Wend
ProcedureReturn Bool(p > PLen)
EndProcedure
+368
View File
@@ -0,0 +1,368 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Outbound.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Outbound connections
;
; The client side of a connection: connecting to a server and running the
; handshake from Connections.pbi as the one being authenticated, then
; sending requests (BakaShrot_Outbound_Send()) and waiting for the answers
; (BakaShrot_Outbound_WaitPacket()), encrypted for this connection.
; Used by the client DLL, and by the server to link to its peers.
;
; A BakaShrot_Outbound must only be used by one thread at a time.
; ============================================================================
XIncludeFile "Connections.pbi"
XIncludeFile "SocketWait.pbi"
#BakaShrot_Outbound_ReceiveBufferSize = 65536
; How long the server gets to send each packet, handshake or answer.
#BakaShrot_Outbound_Timeout = 10000
; Who to authenticate as.
Structure BakaShrot_OutboundIdentity
; The node it writes as, a name or an id in digits (Names.pbi), resolved
; by the server, which must allow it for this key.
Node.s
; Ed25519 public key (Base64), sent in the Hello.
PublicKey.s
; Ed25519 private key, #BakaShrot_Ed25519_PrivateKeySize bytes, used to
; answer the challenge. Must stay valid while connecting.
*PrivateKey
EndStructure
Structure BakaShrot_Outbound
; 0 when not connected.
ConnectionId.i
Inbox.BakaShrot_Inbox
Metadata.BakaShrot_ConnectionMetadata
; Optional, set by the owner: while it points to a non-zero value, waits
; for the server's packets give up right away, as if they timed out.
; Lets a server stop its peer links without waiting out their timeouts.
*StopRequested.Integer
; Why BakaShrot_Outbound_Connect() failed, a #BakaShrot_Error_* of
; Client/BakaShrot_ErrorCodes.pbi, 0 once it succeeded.
LastError.l
EndStructure
; Closes *Outbound's connection, if any, and sets its status to Status.
Procedure BakaShrot_Outbound_Close(*Outbound.BakaShrot_Outbound, Status.i)
If *Outbound\ConnectionId
CloseNetworkConnection(*Outbound\ConnectionId)
EndIf
*Outbound\ConnectionId = 0
BakaShrot_Inbox_Clear(@*Outbound\Inbox)
BakaShrot_ClearConnectionMetadata(@*Outbound\Metadata)
*Outbound\Metadata\Status = Status
EndProcedure
; Sends *Packet to the server, encrypted for this connection.
; Returns #False if it couldn't be sent: close the connection then.
Procedure.i BakaShrot_Outbound_Send(*Outbound.BakaShrot_Outbound, *Packet, PacketSize.i)
If Not *Outbound\ConnectionId
ProcedureReturn #False
EndIf
ProcedureReturn BakaShrot_SendPacket(*Outbound\ConnectionId, *Packet, PacketSize, @*Outbound\Metadata\Cipher)
EndProcedure
; Waits for the next packet from the server, for up to TimeoutMs, decrypted
; once the connection's cipher is set up.
; Returns the packet (free it with FreeMemory) with its size in *OutSize\i,
; or 0 if the server disconnected, sent an invalid frame, one that doesn't
; decrypt or too much data, timed out, or the owner asked to stop (see
; *StopRequested).
Procedure.i BakaShrot_Outbound_WaitPacket(*Outbound.BakaShrot_Outbound, *OutSize.Integer, TimeoutMs.i)
Protected *Packet = 0, *Buffer, Result.i, Received.i, StartTime.i, WaitMs.i
*Buffer = AllocateMemory(#BakaShrot_Outbound_ReceiveBufferSize)
If Not *Buffer
ProcedureReturn 0
EndIf
StartTime = ElapsedMilliseconds()
Repeat
Result = BakaShrot_Inbox_TakePacket(@*Outbound\Inbox, @*Packet, *OutSize)
If Result = #BakaShrot_Inbox_Packet Or Result = #BakaShrot_Inbox_Invalid
Break
EndIf
If ElapsedMilliseconds() - StartTime > TimeoutMs
Break
EndIf
If *Outbound\StopRequested
If *Outbound\StopRequested\i
Break
EndIf
EndIf
Select NetworkClientEvent(*Outbound\ConnectionId)
Case #PB_NetworkEvent_Data
Received = ReceiveNetworkData(*Outbound\ConnectionId, *Buffer, #BakaShrot_Outbound_ReceiveBufferSize)
If Received <= 0
Break
EndIf
If Not BakaShrot_Inbox_Append(@*Outbound\Inbox, *Buffer, Received)
Break
EndIf
Case #PB_NetworkEvent_Disconnect
Break
Default
; Sleeps until the server sends something, waking up at least
; every 50 ms to check the timeout and *StopRequested.
WaitMs = TimeoutMs - (ElapsedMilliseconds() - StartTime)
If WaitMs > 50
WaitMs = 50
EndIf
If WaitMs < 1
WaitMs = 1
EndIf
BakaShrot_WaitSocket(ConnectionID(*Outbound\ConnectionId), WaitMs)
EndSelect
ForEver
FreeMemory(*Buffer)
If *Packet
*Packet = BakaShrot_OpenFrame(@*Outbound\Metadata\Cipher, *Packet, *OutSize\i, *OutSize)
EndIf
ProcedureReturn *Packet
EndProcedure
; Connects to Host:Port and authenticates as *Identity, to the server whose
; Ed25519 public key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize
; bytes): sends the Hello sealed for that key, checks the server's
; signature in the challenge it gets back, sets up the connection's cipher,
; signs the handshake, then waits for the server to accept it.
; Fails if already connected, if *Identity's public key isn't valid Base64,
; if the server can't prove it holds *ServerPublicKey's private key, or if
; anything in the handshake is out of order or unexpected, in which case
; the connection is closed.
Procedure.i BakaShrot_Outbound_Connect(*Outbound.BakaShrot_Outbound, Host.s, Port.i, *Identity.BakaShrot_OutboundIdentity, *ServerPublicKey)
Protected *Packet, PacketSize.Integer, *View.MsgPackData, Sent.i, *Sealed, SealedSize.Integer
Protected Hello.BakaShrot_AuthHello
Protected *Request.BakaShrot_ChallengeRequest
Protected Response.BakaShrot_ChallengeResponse
Protected *Accepted.BakaShrot_AuthAccepted
Protected Proof.BakaShrot_ChallengeProof
Protected KeyPair.BakaShrot_SessionKeyPair
Protected ChallengeDecoded.i, ServerProved.i
*Outbound\LastError = #BakaShrot_Error_None
If *Outbound\ConnectionId
*Outbound\LastError = #BakaShrot_Error_AlreadyConnected
ProcedureReturn #False
EndIf
If Not *ServerPublicKey Or Port < 1 Or Port > 65535
*Outbound\LastError = #BakaShrot_Error_InvalidArgument
ProcedureReturn #False
EndIf
; Only needed before PureBasic 6.00.
CompilerIf #PB_Compiler_Version < 600
If Not InitNetwork()
*Outbound\LastError = #BakaShrot_Error_Internal
ProcedureReturn #False
EndIf
CompilerEndIf
If Not InitCryptography()
*Outbound\LastError = #BakaShrot_Error_Internal
ProcedureReturn #False
EndIf
BakaShrot_ClearConnectionMetadata(@*Outbound\Metadata)
ClearStructure(@*Outbound\Metadata, BakaShrot_ConnectionMetadata)
If Not DecodeKeyFromString(*Identity\PublicKey, @*Outbound\Metadata\PublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted
*Outbound\LastError = #BakaShrot_Error_InvalidArgument
ProcedureReturn #False
EndIf
CopyMemory(*ServerPublicKey, @*Outbound\Metadata\ServerPublicKey[0], #BakaShrot_Ed25519_PublicKeySize)
*Outbound\ConnectionId = OpenNetworkConnection(Host, Port, #PB_Network_TCP | #PB_Network_IPv4)
If Not *Outbound\ConnectionId
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Aborted
*Outbound\LastError = #BakaShrot_Error_ConnectFailed
ProcedureReturn #False
EndIf
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_New
; This connection's key pair, the public half goes in the Hello.
BakaShrot_Session_NewKeyPair(@KeyPair)
CopyMemory(@KeyPair\PublicKey[0], @*Outbound\Metadata\ClientSessionKey[0], #BakaShrot_SessionKeySize)
; 1. Hello, sealed for the server
Hello\ClientNode = *Identity\Node
Hello\ClientPubKeyB64 = *Identity\PublicKey
CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
*Outbound\LastError = #BakaShrot_Error_Internal
*Packet = BakaShrot_HelloPacket_Encode(@Hello, @PacketSize)
If Not *Packet
Goto ConnectFailed
EndIf
*Sealed = BakaShrot_Session_SealHello(*ServerPublicKey, *Packet, PacketSize\i, @SealedSize)
FreeMemory(*Packet)
If Not *Sealed
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_ConnectFailed
Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0)
FreeMemory(*Sealed)
If Not Sent
Goto ConnectFailed
EndIf
; 2. Challenge request, in plain text. No answer: the server closed the
; connection, it couldn't open the Hello or doesn't allow this key and
; node (or speaks another protocol version).
*Outbound\LastError = #BakaShrot_Error_AuthRejected
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
If Not *Packet
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_ProtocolError
*Request = 0
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i)
If *View
*Request = BakaShrot_ChallengeRequestPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Packet)
If Not *Request
Goto ConnectFailed
EndIf
ChallengeDecoded = DecodeKeyFromString(*Request\ChallengeB64, @*Outbound\Metadata\Challenge[0], #BakaShrot_ChallengeSize)
CopyMemory(@*Request\Nonce[0], @*Outbound\Metadata\Nonce[0], #BakaShrot_NonceSize)
CopyMemory(@*Request\ServerSessionKey[0], @*Outbound\Metadata\ServerSessionKey[0], #BakaShrot_SessionKeySize)
CopyMemory(@*Request\ServerSignature[0], @Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize)
FreeStructure(*Request)
If Not ChallengeDecoded
Goto ConnectFailed
EndIf
; Only the server holding *ServerPublicKey's private key could sign this
; connection's halves and challenge.
BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptServerLabel, @Proof)
ServerProved = BakaShrot_VerifyHandshake(@Proof, *ServerPublicKey)
If Not ServerProved
*Outbound\LastError = #BakaShrot_Error_ServerNotVerified
Goto ConnectFailed
EndIf
; Every packet is encrypted from now on.
*Outbound\LastError = #BakaShrot_Error_Internal
If Not BakaShrot_Session_StartClient(@*Outbound\Metadata\Cipher, @KeyPair, @*Outbound\Metadata\ServerSessionKey[0])
Goto ConnectFailed
EndIf
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Challenged
; 3. Challenge response
BakaShrot_MakeHandshakeTranscript(@*Outbound\Metadata, #BakaShrot_TranscriptClientLabel, @Proof)
If Not BakaShrot_SignHandshake(@Proof, *Identity\PrivateKey)
Goto ConnectFailed
EndIf
Response\ChallengeResponseB64 = EncodeKeyToString(@Proof\Signature[0], #BakaShrot_Ed25519_SignatureSize)
CopyMemory(@*Outbound\Metadata\Nonce[0], @Response\Nonce[0], #BakaShrot_NonceSize)
*Packet = BakaShrot_ChallengeResponsePacket_Encode(@Response, @PacketSize)
If Not *Packet
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_AuthRejected
Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i)
FreeMemory(*Packet)
If Not Sent
Goto ConnectFailed
EndIf
; 4. Accepted. No answer: the server didn't accept this key's signature.
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
If Not *Packet
Goto ConnectFailed
EndIf
*Outbound\LastError = #BakaShrot_Error_ProtocolError
*Accepted = 0
*View = MsgPackWrapMsgBuffer(*Packet, PacketSize\i)
If *View
*Accepted = BakaShrot_AuthAcceptedPacket_Decode(*View)
MsgPackFree(*View, #False)
EndIf
FreeMemory(*Packet)
If Not *Accepted
Goto ConnectFailed
EndIf
FreeStructure(*Accepted)
; The server's answers may be big from now on.
BakaShrot_Inbox_Lift(@*Outbound\Inbox)
*Outbound\Metadata\Status = #BakaShrot_ConnectionStatus_Authenticated
*Outbound\LastError = #BakaShrot_Error_None
ProcedureReturn #True
ConnectFailed:
BakaShrot_Session_ClearKeyPair(@KeyPair)
BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Aborted)
ProcedureReturn #False
EndProcedure
; Returns #True while *Outbound is connected, notices when the server closed
; the connection.
; Data the server sent is left to read, only a disconnect is acted upon.
Procedure.i BakaShrot_Outbound_IsConnected(*Outbound.BakaShrot_Outbound)
If Not *Outbound\ConnectionId
ProcedureReturn #False
EndIf
If NetworkClientEvent(*Outbound\ConnectionId) = #PB_NetworkEvent_Disconnect
BakaShrot_Outbound_Close(*Outbound, #BakaShrot_ConnectionStatus_Disconnected)
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
+229
View File
@@ -0,0 +1,229 @@
;{- Code Header
; ==- Basic Info -================================
; Name: Packets.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi"
XIncludeFile "Names.pbi"
; The refusal codes (RequestRefused) and the client's error codes.
XIncludeFile "../../Client/BakaShrot_ErrorCodes.pbi"
; Represents the root of all BakaShrot packets.
; Any packets below this size MUST be thrown out.
Structure BakaShrot_PacketBase
Magic.l
Version.l
PacketType.l
EndStructure
; Fixed values every BakaShrot_PacketBase must carry. Checked on decode so a
; packet from a different protocol/version is thrown out instead of being
; misparsed.
#BakaShrot_ProtocolMagic = $42534854 ; "BSHT"
; 2: topics and nodes by name (Commons/Networking/Names.pbi), see Design/Packets.md.
; 3: the Hello sealed for the server, a key per connection, everything after
; the ChallengeRequest encrypted (Connections.pbi). Messages carry when
; they were pushed (PushedAt).
; 4: attachments (Design/Attachments.md).
; 5: the Hello carries the client's node only: its default topic is the
; server's to say (DefaultTopic in its client section).
; 6: RequestRefused carries a Code (Client/BakaShrot_ErrorCodes.pbi).
#BakaShrot_ProtocolVersion = 6
; Size in bytes of the nonce sent in a challenge request and echoed in its response.
; It MUST be filled with CryptRandomData(), never reused, and be checked against the one the
; server issued for that connection, so a captured response can't be replayed.
#BakaShrot_NonceSize = 32
; Size in bytes of the random challenge sent Base64-encoded in a challenge request.
; The client proves it holds its private key by signing the challenge followed by the nonce.
#BakaShrot_ChallengeSize = 32
; Size in bytes of the public half of a connection's key pair, sent by the
; client in its Hello and by the server in its ChallengeRequest
; (#BakaShrot_Session_PublicKeySize, Commons/Cryptography/Session.pbi).
#BakaShrot_SessionKeySize = 32
; Size in bytes of the server's signature in a ChallengeRequest
; (#BakaShrot_Ed25519_SignatureSize).
#BakaShrot_HandshakeSignatureSize = 64
; When a message was pushed: milliseconds since 1970-01-01 00:00:00 UTC, set
; by the server it was pushed to, and kept as is by every server it's
; replicated to. Anything outside 1 to #BakaShrot_MaxTimestamp (9999-12-31)
; is invalid on the wire.
#BakaShrot_MaxTimestamp = 253402300799999
Procedure.i BakaShrot_IsValidTimestamp(Timestamp.q)
ProcedureReturn Bool(Timestamp >= 1 And Timestamp <= #BakaShrot_MaxTimestamp)
EndProcedure
; Attachments (Design/Attachments.md): at most one per message, sent and
; stored in parts of #BakaShrot_AttachmentChunkSize bytes (the last one what's
; left), checked with their SHA-256. #BakaShrot_MaxAttachmentSize is the
; protocol's limit, each server sets its own ([BakaShrot.Server]
; MaxAttachmentSize).
#BakaShrot_AttachmentChunkSize = 1048576
#BakaShrot_MaxAttachmentSize = 1099511627776
#BakaShrot_MaxAttachmentChunks = #BakaShrot_MaxAttachmentSize / #BakaShrot_AttachmentChunkSize
#BakaShrot_Sha256Size = 32
; How many parts Size bytes take.
Procedure.q BakaShrot_AttachmentChunkCount(Size.q)
ProcedureReturn (Size + #BakaShrot_AttachmentChunkSize - 1) / #BakaShrot_AttachmentChunkSize
EndProcedure
; How big part Index of Size bytes is, 0 if there's no such part.
Procedure.i BakaShrot_AttachmentChunkBytes(Size.q, Index.q)
Protected Left.q = Size - Index * #BakaShrot_AttachmentChunkSize
If Index < 0 Or Left <= 0
ProcedureReturn 0
ElseIf Left > #BakaShrot_AttachmentChunkSize
ProcedureReturn #BakaShrot_AttachmentChunkSize
EndIf
ProcedureReturn Left
EndProcedure
; Biggest packet accepted on the wire once authenticated, anything bigger
; aborts the connection. Before that, only #BakaShrot_MaxHandshakePacketSize
; (Connections.pbi).
#BakaShrot_MaxPacketSize = 16 * 1024 * 1024
; Biggest message a client may push (its JSON, in UTF-8 bytes). Leaves room
; for the fields around it, so a stored message fits in every packet that
; carries one: LatestMessage, a ReplicateMessages batch of one.
#BakaShrot_MaxMessageSize = #BakaShrot_MaxPacketSize - 4096
Enumeration BakaShrot_PacketTypes
; Safety fallback value, should be dropped when encountered
#BakaShrot_PacketType_None = 0
; 1-3 were used by the removed AuthenticationPacket.pbi, don't reuse them.
#BakaShrot_PacketType_ClientHello = 4
#BakaShrot_PacketType_ChallengeRequest = 5
#BakaShrot_PacketType_ChallengeResponse = 6
#BakaShrot_PacketType_AuthAccepted = 7
; Only accepted once authenticated.
#BakaShrot_PacketType_PushMessage = 8
#BakaShrot_PacketType_MessagePushed = 9
#BakaShrot_PacketType_GetLatestMessage = 10
#BakaShrot_PacketType_LatestMessage = 11
#BakaShrot_PacketType_RequestRefused = 12
; Replication, only accepted from peers once authenticated.
#BakaShrot_PacketType_SyncStateRequest = 13
#BakaShrot_PacketType_SyncState = 14
#BakaShrot_PacketType_ReplicateMessages = 15
; Raw read-only SQL, only accepted once authenticated, from clients allowed to.
#BakaShrot_PacketType_QueryRequest = 16
#BakaShrot_PacketType_QueryResult = 17
; Name <-> id of a topic or node, only accepted once authenticated.
#BakaShrot_PacketType_ResolveName = 18
#BakaShrot_PacketType_NameResolved = 19
; Every topic or node the client may see, only accepted once authenticated.
#BakaShrot_PacketType_ListNames = 20
#BakaShrot_PacketType_NamesList = 21
; A run of messages of a topic/node, only accepted once authenticated.
#BakaShrot_PacketType_GetMessages = 22
#BakaShrot_PacketType_Messages = 23
; Attachments, only accepted once authenticated: uploading one (before
; its PushMessage), and reading one, in parts.
#BakaShrot_PacketType_UploadStart = 24
#BakaShrot_PacketType_UploadStarted = 25
#BakaShrot_PacketType_UploadChunk = 26
#BakaShrot_PacketType_ChunkStored = 27
#BakaShrot_PacketType_GetAttachment = 28
#BakaShrot_PacketType_AttachmentChunk = 29
; Replicating attachments, only accepted from peers, once their messages are.
#BakaShrot_PacketType_MissingAttachmentsRequest = 30
#BakaShrot_PacketType_MissingAttachments = 31
#BakaShrot_PacketType_ReplicateAttachmentChunk = 32
EndEnumeration
; Checks and reads the given MsgPack data into a packet structure's common fields.
; The caller can handle the MsgPack data validation however it see fit.
; On success, the structure's fields will be populated, and the MsgPack structure will be ready to ready the packet's remaining fields.
; On failure, all data should be discarded and be treated as tainted.
Procedure.b BakaShrot_ReadPacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData)
; Returns true on success, false otherwise
; The caller will usually drop all data and tell the remote client to fuck off if this fails.
Protected TempValue.q
If Not *PacketStruct Or Not *MsgPackData
ProcedureReturn #False
EndIf
; Magic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
TempValue = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolMagic
ProcedureReturn #False
EndIf
*PacketStruct\Magic = TempValue
; Version
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
TempValue = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <> #BakaShrot_ProtocolVersion
ProcedureReturn #False
EndIf
*PacketStruct\Version = TempValue
; PacketType
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
TempValue = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or TempValue <= #BakaShrot_PacketType_None Or TempValue > 2147483647
ProcedureReturn #False
EndIf
*PacketStruct\PacketType = TempValue
ProcedureReturn #True
EndProcedure
; Writes a packet structure's common fields into the given MsgPack data.
; On success, the MsgPack structure will be ready to write the packet's remaining fields.
; On failure, the MsgPack data should be discarded and be treated as tainted.
Procedure.b BakaShrot_WritePacketBase(*PacketStruct.BakaShrot_PacketBase, *MsgPackData.MsgPackData)
; Returns true on success, false otherwise
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Magic) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\Version) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteInteger(*MsgPackData, *PacketStruct\PacketType) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
@@ -0,0 +1,212 @@
;{- Code Header
; ==- Basic Info -================================
; Name: AttachmentChunkPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a GetAttachment: part ChunkIndex of the attachment of
; TopicId:NodeId#MessageId (the server's ids), Size bytes in all, in parts of
; #BakaShrot_AttachmentChunkSize, whose SHA-256 is Sha256.
Structure BakaShrot_AttachmentChunk Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
MessageId.q
Size.q
Sha256.a[#BakaShrot_Sha256Size]
ChunkIndex.l
*Data
DataSize.l
EndStructure
; Encodes *Chunk 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_AttachmentChunkPacket_Encode(*Chunk.BakaShrot_AttachmentChunk, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Chunk\Magic = #BakaShrot_ProtocolMagic
*Chunk\Version = #BakaShrot_ProtocolVersion
*Chunk\PacketType = #BakaShrot_PacketType_AttachmentChunk
If *Chunk\TopicId < 0 Or *Chunk\TopicId > #BakaShrot_MaxId Or *Chunk\NodeId < 0 Or *Chunk\NodeId > #BakaShrot_MaxId Or *Chunk\MessageId < 1 Or *Chunk\Size < 1 Or *Chunk\Size > #BakaShrot_MaxAttachmentSize Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #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
; Frees a decoded *Chunk and the data it holds.
Procedure BakaShrot_AttachmentChunkPacket_Free(*Chunk.BakaShrot_AttachmentChunk)
If Not *Chunk
ProcedureReturn
EndIf
If *Chunk\Data
FreeMemory(*Chunk\Data)
EndIf
FreeStructure(*Chunk)
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 BakaShrot_AttachmentChunkPacket_Free().
Procedure.i BakaShrot_AttachmentChunkPacket_Decode(*MsgPackData.MsgPackData)
Protected *Chunk.BakaShrot_AttachmentChunk, Value.q, ReadSize.q
*Chunk = AllocateStructure(BakaShrot_AttachmentChunk)
If Not *Chunk
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_AttachmentChunk
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 > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Chunk\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 > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Chunk\NodeId = Value
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Chunk\MessageId = Value
; Size
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_MaxAttachmentSize
Goto DecodeFailed
EndIf
*Chunk\Size = Value
; Sha256
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
ReadSize = MsgPackReadBinary(*MsgPackData, @*Chunk\Sha256[0], #BakaShrot_Sha256Size)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size
Goto DecodeFailed
EndIf
; ChunkIndex
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_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Chunk\ChunkIndex = Value
; Data
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; A copy, freed with the packet (_Free()).
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
Goto DecodeFailed
EndIf
*Chunk\DataSize = MemorySize(*Chunk\Data)
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
ProcedureReturn *Chunk
; Everything read so far is tainted, drop it.
DecodeFailed:
BakaShrot_AttachmentChunkPacket_Free(*Chunk)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,82 @@
;{- Code Header
; ==- Basic Info -================================
; Name: AuthAcceptedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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
@@ -0,0 +1,148 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ChallengeRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,118 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ChallengeResponsePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,121 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ChunkStoredPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C (and S2P), answers an UploadChunk (or a ReplicateAttachmentChunk): Received
; bytes are stored so far. Complete is 1 once they all are, and their SHA-256
; checked out.
Structure BakaShrot_ChunkStored Extends BakaShrot_PacketBase
Received.q
Complete.l
EndStructure
; Encodes *Stored 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_ChunkStoredPacket_Encode(*Stored.BakaShrot_ChunkStored, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Stored\Magic = #BakaShrot_ProtocolMagic
*Stored\Version = #BakaShrot_ProtocolVersion
*Stored\PacketType = #BakaShrot_PacketType_ChunkStored
If *Stored\Received < 0 Or *Stored\Received > #BakaShrot_MaxAttachmentSize Or *Stored\Complete < 0 Or *Stored\Complete > 1
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Stored, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Stored\Received) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Stored\Complete) <> #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_ChunkStoredPacket_Decode(*MsgPackData.MsgPackData)
Protected *Stored.BakaShrot_ChunkStored, Value.q
*Stored = AllocateStructure(BakaShrot_ChunkStored)
If Not *Stored
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Stored, *MsgPackData) Or *Stored\PacketType <> #BakaShrot_PacketType_ChunkStored
Goto DecodeFailed
EndIf
; Received
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_MaxAttachmentSize
Goto DecodeFailed
EndIf
*Stored\Received = Value
; Complete
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
*Stored\Complete = Value
ProcedureReturn *Stored
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Stored)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,151 @@
;{- Code Header
; ==- Basic Info -================================
; Name: GetAttachmentPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks for part ChunkIndex (0 for the first) of the attachment of a message.
; Topic, Node: each a name or an id in digits, as GetMessages'. ReadTopics must
; allow the topic.
; Answered with an AttachmentChunk, or a RequestRefused (no such message, no
; attachment, or not here yet: replicated attachments come after their message).
Structure BakaShrot_GetAttachment Extends BakaShrot_PacketBase
Topic.s
Node.s
MessageId.q
ChunkIndex.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_GetAttachmentPacket_Encode(*Request.BakaShrot_GetAttachment, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetAttachment
If *Request\MessageId < 1 Or *Request\ChunkIndex < 0 Or *Request\ChunkIndex > #BakaShrot_MaxAttachmentChunks
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\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\ChunkIndex) <> #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_GetAttachmentPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetAttachment, Value.q
*Request = AllocateStructure(BakaShrot_GetAttachment)
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_GetAttachment
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
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Request\MessageId = Value
; ChunkIndex
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_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Request\ChunkIndex = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,116 @@
;{- Code Header
; ==- Basic Info -================================
; Name: GetLatestMessagePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,155 @@
;{- Code Header
; ==- Basic Info -================================
; Name: GetMessagesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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
@@ -0,0 +1,134 @@
;{- Code Header
; ==- Basic Info -================================
; Name: HelloPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S auth request, sent sealed for the server's public key (Connections.pbi).
; ClientNode: who the client is, the node it writes as, a name or an id in
; digits (Commons/Networking/Names.pbi), resolved by the server in its own
; names. Its default topic is the server's to say, not the client's.
; ClientSessionKey: the public half of the client's key pair for this
; connection (Commons/Cryptography/Session.pbi).
Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase
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\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
; 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,215 @@
;{- Code Header
; ==- Basic Info -================================
; Name: LatestMessagePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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.
; PushedAt: when it was pushed, see Packets.pbi.
Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
MessageId.q
PushedAt.q
JsonData.s
; Its attachment's size in bytes, 0 for none, and whether this server has
; all of it yet (a replicated one comes after its message).
AttachmentSize.q
AttachmentReady.l
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 MsgPackWriteInteger(*MsgPackData, *Latest\PushedAt) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\AttachmentReady) <> #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
; PushedAt
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\PushedAt = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Latest\PushedAt)
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
; AttachmentSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\AttachmentSize = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentSize < 0 Or *Latest\AttachmentSize > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
; AttachmentReady
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\AttachmentReady = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\AttachmentReady < 0 Or *Latest\AttachmentReady > 1
Goto DecodeFailed
EndIf
ProcedureReturn *Latest
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Latest)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,104 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ListNamesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,99 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MessagePushedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,277 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MessagesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
XIncludeFile "GetMessagesPacket.pbi"
; One message of a Messages answer.
Structure BakaShrot_MessagesEntry
MessageId.q
; When it was pushed, see Packets.pbi.
PushedAt.q
; Its attachment's size in bytes, 0 for none, and whether this server has
; all of it yet (a replicated one comes after its message).
AttachmentSize.q
AttachmentReady.l
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 = 40
; 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 MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\PushedAt) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\AttachmentReady) <> #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
; PushedAt
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Answer\Messages()\PushedAt)
Goto DecodeFailed
EndIf
; 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
; AttachmentSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentSize < 0 Or *Answer\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
; AttachmentReady
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\AttachmentReady = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\AttachmentReady < 0 Or *Answer\Messages()\AttachmentReady > 1
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,173 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MissingAttachmentsPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Most attachments one MissingAttachments lists, the next check-in asks again.
#BakaShrot_MaxMissingAttachments = 256
; One attachment the server is missing: of Topic:Node#MessageId (names, never
; digits), from part NextChunk on (0 if it has none of it yet).
Structure BakaShrot_MissingAttachment
Topic.s
Node.s
MessageId.q
NextChunk.l
EndStructure
; S2P, answers a MissingAttachmentsRequest: attachments of messages the server
; has, that it takes from this peer, and doesn't have all of yet. Maybe none.
; On the wire: the count, then each one's topic, node, message id and next chunk.
Structure BakaShrot_MissingAttachments Extends BakaShrot_PacketBase
List Attachments.BakaShrot_MissingAttachment()
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_MissingAttachmentsPacket_Encode(*Answer.BakaShrot_MissingAttachments, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_MissingAttachments
If ListSize(*Answer\Attachments()) > #BakaShrot_MaxMissingAttachments
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Attachments())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Answer\Attachments()
If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Attachments()\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Attachments()\NextChunk) <> #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_MissingAttachmentsPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_MissingAttachments
Protected Value.q, Count.q, i.q
*Answer = AllocateStructure(BakaShrot_MissingAttachments)
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_MissingAttachments
Goto DecodeFailed
EndIf
; 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_MaxMissingAttachments
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*Answer\Attachments())
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Attachments()\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Attachments()\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Answer\Attachments()\Node)
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Attachments()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Attachments()\MessageId < 1
Goto DecodeFailed
EndIf
; NextChunk
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_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Answer\Attachments()\NextChunk = Value
Next
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,88 @@
;{- Code Header
; ==- Basic Info -================================
; Name: MissingAttachmentsRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; P2S, asks which attachments the server is still missing from this peer, once
; the messages are caught up. Only the base fields.
; Answered with a MissingAttachments, or a RequestRefused.
Structure BakaShrot_MissingAttachmentsRequest 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_MissingAttachmentsRequestPacket_Encode(*Request.BakaShrot_MissingAttachmentsRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_MissingAttachmentsRequest
*MsgPackData = MsgPackCreate(64)
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_MissingAttachmentsRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_MissingAttachmentsRequest
*Request = AllocateStructure(BakaShrot_MissingAttachmentsRequest)
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_MissingAttachmentsRequest
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,133 @@
;{- Code Header
; ==- Basic Info -================================
; Name: NameResolvedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,194 @@
;{- Code Header
; ==- Basic Info -================================
; Name: NamesListPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,133 @@
;{- Code Header
; ==- Basic Info -================================
; Name: PushMessagePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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.
; UploadId: the attachment uploaded for it (UploadStart, all of it stored), 0 for none.
; Answered with a MessagePushed or a RequestRefused.
Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase
Topic.s
JsonData.s
UploadId.q
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
If *Push\UploadId < 0 Or MsgPackWriteInteger(*MsgPackData, *Push\UploadId) <> #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
; UploadId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Push\UploadId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Push\UploadId < 0
Goto DecodeFailed
EndIf
ProcedureReturn *Push
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Push)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
;{- Code Header
; ==- Basic Info -================================
; Name: QueryRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,101 @@
;{- Code Header
; ==- Basic Info -================================
; Name: QueryResultPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,181 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ReplicateAttachmentChunkPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; P2S, part ChunkIndex of the attachment of Topic:Node#MessageId (names, never
; digits), a message the server already has, as MissingAttachments asked for.
; The size and SHA-256 came with the message (ReplicateMessages).
; Answered with a ChunkStored, or a RequestRefused.
Structure BakaShrot_ReplicateAttachmentChunk Extends BakaShrot_PacketBase
Topic.s
Node.s
MessageId.q
ChunkIndex.l
*Data
DataSize.l
EndStructure
; Encodes *Chunk 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_ReplicateAttachmentChunkPacket_Encode(*Chunk.BakaShrot_ReplicateAttachmentChunk, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Chunk\Magic = #BakaShrot_ProtocolMagic
*Chunk\Version = #BakaShrot_ProtocolVersion
*Chunk\PacketType = #BakaShrot_PacketType_ReplicateAttachmentChunk
If Not BakaShrot_IsValidName(*Chunk\Topic) Or Not BakaShrot_IsValidName(*Chunk\Node) Or *Chunk\MessageId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Chunk\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Chunk\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #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
; Frees a decoded *Chunk and the data it holds.
Procedure BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk.BakaShrot_ReplicateAttachmentChunk)
If Not *Chunk
ProcedureReturn
EndIf
If *Chunk\Data
FreeMemory(*Chunk\Data)
EndIf
FreeStructure(*Chunk)
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 BakaShrot_ReplicateAttachmentChunkPacket_Free().
Procedure.i BakaShrot_ReplicateAttachmentChunkPacket_Decode(*MsgPackData.MsgPackData)
Protected *Chunk.BakaShrot_ReplicateAttachmentChunk, Value.q
*Chunk = AllocateStructure(BakaShrot_ReplicateAttachmentChunk)
If Not *Chunk
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_ReplicateAttachmentChunk
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Chunk\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Chunk\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Chunk\Node)
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Chunk\MessageId = Value
; ChunkIndex
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_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Chunk\ChunkIndex = Value
; Data
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; A copy, freed with the packet (_Free()).
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
Goto DecodeFailed
EndIf
*Chunk\DataSize = MemorySize(*Chunk\Data)
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
ProcedureReturn *Chunk
; Everything read so far is tainted, drop it.
DecodeFailed:
BakaShrot_ReplicateAttachmentChunkPacket_Free(*Chunk)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,242 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ReplicateMessagesPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; One message of a ReplicateMessages batch.
; PushedAt: when it was pushed to its origin (Packets.pbi), stored as is.
; AttachmentSize, AttachmentSha256: its attachment's, 0 for none. The data
; itself follows on its own, once the messages are caught up
; (MissingAttachments, ReplicateAttachmentChunk).
Structure BakaShrot_ReplicatedMessage
MessageId.q
PushedAt.q
JsonData.s
AttachmentSize.q
AttachmentSha256.a[#BakaShrot_Sha256Size]
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 = 70
; 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, PushedAt,
; JSON, attachment size and SHA-256.
; 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 MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\PushedAt) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\AttachmentSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Empty without an attachment.
If *Batch\Messages()\AttachmentSize > 0
If MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ElseIf MsgPackWriteBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], 0) <> #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, ReadSize.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
; PushedAt
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\PushedAt = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidTimestamp(*Batch\Messages()\PushedAt)
Goto DecodeFailed
EndIf
; 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
; AttachmentSize
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\AttachmentSize = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\AttachmentSize < 0 Or *Batch\Messages()\AttachmentSize > #BakaShrot_MaxAttachmentSize
Goto DecodeFailed
EndIf
; AttachmentSha256: 32 bytes with an attachment, empty without.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Batch\Messages()\AttachmentSha256[0], #BakaShrot_Sha256Size)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (ReadSize <> #BakaShrot_Sha256Size And *Batch\Messages()\AttachmentSize > 0) Or (ReadSize <> 0 And *Batch\Messages()\AttachmentSize = 0)
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Batch
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Batch)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,121 @@
;{- Code Header
; ==- Basic Info -================================
; Name: RequestRefusedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a request the server won't fulfill, the connection stays open.
; Code: what kind of refusal, 1-#BakaShrot_Refused_Max, one of the
; #BakaShrot_Refused_* in Client/BakaShrot_ErrorCodes.pbi: what clients act
; on (protocol 6). Reason is only meant for logs and humans.
Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase
Code.l
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
If Not BakaShrot_IsRefusalCode(*Refused\Code)
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Refused, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Refused\Code) <> #MsgPack_Error_Success
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, Value.q
*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
; Code
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsRefusalCode(Value)
Goto DecodeFailed
EndIf
*Refused\Code = Value
; 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,124 @@
;{- Code Header
; ==- Basic Info -================================
; Name: ResolveNamePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,296 @@
;{- Code Header
; ==- Basic Info -================================
; Name: SyncStatePacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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,82 @@
;{- Code Header
; ==- Basic Info -================================
; Name: SyncStateRequestPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
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
@@ -0,0 +1,151 @@
;{- Code Header
; ==- Basic Info -================================
; Name: UploadChunkPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, the next part of an upload: ChunkIndex (0 for the first) of UploadId.
; Answered with a ChunkStored, or a RequestRefused (the upload is then dropped).
Structure BakaShrot_UploadChunk Extends BakaShrot_PacketBase
UploadId.q
ChunkIndex.l
*Data
DataSize.l
EndStructure
; Encodes *Chunk 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_UploadChunkPacket_Encode(*Chunk.BakaShrot_UploadChunk, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Chunk\Magic = #BakaShrot_ProtocolMagic
*Chunk\Version = #BakaShrot_ProtocolVersion
*Chunk\PacketType = #BakaShrot_PacketType_UploadChunk
If *Chunk\UploadId < 1 Or *Chunk\ChunkIndex < 0 Or *Chunk\ChunkIndex > #BakaShrot_MaxAttachmentChunks Or Not *Chunk\Data Or *Chunk\DataSize < 1 Or *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(#BakaShrot_AttachmentChunkSize + 256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Chunk, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\UploadId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Chunk\ChunkIndex) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, *Chunk\Data, *Chunk\DataSize) <> #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
; Frees a decoded *Chunk and the data it holds.
Procedure BakaShrot_UploadChunkPacket_Free(*Chunk.BakaShrot_UploadChunk)
If Not *Chunk
ProcedureReturn
EndIf
If *Chunk\Data
FreeMemory(*Chunk\Data)
EndIf
FreeStructure(*Chunk)
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 BakaShrot_UploadChunkPacket_Free().
Procedure.i BakaShrot_UploadChunkPacket_Decode(*MsgPackData.MsgPackData)
Protected *Chunk.BakaShrot_UploadChunk, Value.q
*Chunk = AllocateStructure(BakaShrot_UploadChunk)
If Not *Chunk
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Chunk, *MsgPackData) Or *Chunk\PacketType <> #BakaShrot_PacketType_UploadChunk
Goto DecodeFailed
EndIf
; UploadId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Chunk\UploadId = Value
; ChunkIndex
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_MaxAttachmentChunks
Goto DecodeFailed
EndIf
*Chunk\ChunkIndex = Value
; Data
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; A copy, freed with the packet (_Free()).
*Chunk\Data = MsgPackCopyBinary(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not *Chunk\Data
Goto DecodeFailed
EndIf
*Chunk\DataSize = MemorySize(*Chunk\Data)
If *Chunk\DataSize > #BakaShrot_AttachmentChunkSize
Goto DecodeFailed
EndIf
ProcedureReturn *Chunk
; Everything read so far is tainted, drop it.
DecodeFailed:
BakaShrot_UploadChunkPacket_Free(*Chunk)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,138 @@
;{- Code Header
; ==- Basic Info -================================
; Name: UploadStartPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, starts uploading an attachment, before pushing the message it goes with
; (PushMessage's UploadId): Size bytes (1 to #BakaShrot_MaxAttachmentSize, and the
; server's [BakaShrot.Server] MaxAttachmentSize), whose SHA-256 is Sha256.
; Topic: where the message will be pushed, as PushMessage's: "" for the client's
; own. The client's PushTopics must allow it.
; Answered with an UploadStarted, or a RequestRefused.
Structure BakaShrot_UploadStart Extends BakaShrot_PacketBase
Topic.s
Size.q
Sha256.a[#BakaShrot_Sha256Size]
EndStructure
; Encodes *Start 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_UploadStartPacket_Encode(*Start.BakaShrot_UploadStart, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Start\Magic = #BakaShrot_ProtocolMagic
*Start\Version = #BakaShrot_ProtocolVersion
*Start\PacketType = #BakaShrot_PacketType_UploadStart
If *Start\Size < 1 Or *Start\Size > #BakaShrot_MaxAttachmentSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Start, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Start\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Start\Size) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size) <> #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_UploadStartPacket_Decode(*MsgPackData.MsgPackData)
Protected *Start.BakaShrot_UploadStart, Value.q, ReadSize.q
*Start = AllocateStructure(BakaShrot_UploadStart)
If Not *Start
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Start, *MsgPackData) Or *Start\PacketType <> #BakaShrot_PacketType_UploadStart
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Start\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Size
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_MaxAttachmentSize
Goto DecodeFailed
EndIf
*Start\Size = Value
; Sha256
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
ReadSize = MsgPackReadBinary(*MsgPackData, @*Start\Sha256[0], #BakaShrot_Sha256Size)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_Sha256Size
Goto DecodeFailed
EndIf
ProcedureReturn *Start
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Start)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,120 @@
;{- Code Header
; ==- Basic Info -================================
; Name: UploadStartedPacket.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers an UploadStart: send the data with UploadChunks for UploadId, in
; order, ChunkSize bytes each (the last one what's left).
Structure BakaShrot_UploadStarted Extends BakaShrot_PacketBase
UploadId.q
ChunkSize.l
EndStructure
; Encodes *Started 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_UploadStartedPacket_Encode(*Started.BakaShrot_UploadStarted, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Started\Magic = #BakaShrot_ProtocolMagic
*Started\Version = #BakaShrot_ProtocolVersion
*Started\PacketType = #BakaShrot_PacketType_UploadStarted
If *Started\UploadId < 1 Or *Started\ChunkSize < 1 Or *Started\ChunkSize > #BakaShrot_AttachmentChunkSize
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Started, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Started\UploadId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Started\ChunkSize) <> #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_UploadStartedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Started.BakaShrot_UploadStarted, Value.q
*Started = AllocateStructure(BakaShrot_UploadStarted)
If Not *Started
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Started, *MsgPackData) Or *Started\PacketType <> #BakaShrot_PacketType_UploadStarted
Goto DecodeFailed
EndIf
; UploadId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1
Goto DecodeFailed
EndIf
*Started\UploadId = Value
; ChunkSize
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_AttachmentChunkSize
Goto DecodeFailed
EndIf
*Started\ChunkSize = Value
ProcedureReturn *Started
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Started)
ProcedureReturn 0
EndProcedure
+141
View File
@@ -0,0 +1,141 @@
;{- Code Header
; ==- Basic Info -================================
; Name: SocketWait.pbi
; Version: 0.0.1
; Author: Herwin Bozet (NibblePoker)
;
; ==- Compatibility -=============================
; Tested compiler versions:
; * PureBasic 5.73 LTS (Windows x64, Linux x64)
; * PureBasic 6.40 C Backend (Windows x64)
; * PureBasic 6.41 (Linux x64)
; * PureBasic 6.41 C Backend (Linux x64)
;
; ==- Links -=====================================
; GitHub: https://github.com/aziascreations/BakaShrot
;}
; ============================================================================
; BakaShrot Socket waits
;
; Sleeps until one of a few sockets has something to read (data, a new
; connection, or a disconnect), instead of polling NetworkClientEvent() /
; NetworkServerEvent() with Delay():
; BakaShrot_SocketSet_Clear(@Set)
; BakaShrot_SocketSet_Add(@Set, ConnectionID(Connection)) ; or ServerID()
; BakaShrot_SocketSet_Wait(@Set, TimeoutMs)
; ... then NetworkClientEvent() / NetworkServerEvent() as usual.
; Only call it once those returned #PB_NetworkEvent_None: PureBasic may
; already hold events it hasn't returned yet, that select() can't see.
;
; Windows: select() from ws2_32. Elsewhere: a plain Delay(1) for now.
; ============================================================================
; Most sockets in one wait, the others are left out (they're still served,
; just with up to TimeoutMs of delay).
#BakaShrot_SocketSet_MaxSockets = 1024
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; Same layout as Winsock's fd_set, with a bigger array: Winsock reads
; Count entries, whatever FD_SETSIZE says.
Structure BakaShrot_SocketSet
Count.l
CompilerIf #PB_Compiler_Processor = #PB_Processor_x64
Padding.l
CompilerEndIf
Sockets.i[#BakaShrot_SocketSet_MaxSockets]
EndStructure
Structure BakaShrot_TimeVal
Seconds.l
Microseconds.l
EndStructure
Prototype.l BakaShrot_Select_Prototype(Ignored.l, *ReadSet, *WriteSet, *ErrorSet, *Timeout)
Global BakaShrot_Select.BakaShrot_Select_Prototype = 0
Global BakaShrot_SelectLoaded.i = #False
Global BakaShrot_SelectMutex.i = CreateMutex()
Procedure BakaShrot_SocketSet_Load()
Protected Library.i
LockMutex(BakaShrot_SelectMutex)
If Not BakaShrot_SelectLoaded
Library = OpenLibrary(#PB_Any, "ws2_32.dll")
If Library
BakaShrot_Select = GetFunction(Library, "select")
EndIf
BakaShrot_SelectLoaded = #True
EndIf
UnlockMutex(BakaShrot_SelectMutex)
EndProcedure
Procedure BakaShrot_SocketSet_Clear(*Set.BakaShrot_SocketSet)
*Set\Count = 0
EndProcedure
Procedure BakaShrot_SocketSet_Add(*Set.BakaShrot_SocketSet, Socket.i)
If Socket And *Set\Count < #BakaShrot_SocketSet_MaxSockets
*Set\Sockets[*Set\Count] = Socket
*Set\Count + 1
EndIf
EndProcedure
; Waits until a socket of *Set is readable, for up to TimeoutMs.
; Returns #True if one is (or select() failed, to be safe), #False if it
; timed out. *Set is overwritten, clear and fill it again before reusing it.
Procedure.i BakaShrot_SocketSet_Wait(*Set.BakaShrot_SocketSet, TimeoutMs.i)
Protected Timeout.BakaShrot_TimeVal, Result.l
If Not BakaShrot_SelectLoaded
BakaShrot_SocketSet_Load()
EndIf
If Not BakaShrot_Select Or *Set\Count = 0
Delay(1)
ProcedureReturn #True
EndIf
Timeout\Seconds = TimeoutMs / 1000
Timeout\Microseconds = (TimeoutMs % 1000) * 1000
Result = BakaShrot_Select(0, *Set, 0, 0, @Timeout)
If Result < 0
; A socket closed meanwhile by another thread, most likely.
Delay(1)
ProcedureReturn #True
EndIf
ProcedureReturn Bool(Result > 0)
EndProcedure
CompilerElse
Structure BakaShrot_SocketSet
Count.l
EndStructure
Procedure BakaShrot_SocketSet_Clear(*Set.BakaShrot_SocketSet)
*Set\Count = 0
EndProcedure
Procedure BakaShrot_SocketSet_Add(*Set.BakaShrot_SocketSet, Socket.i)
*Set\Count + 1
EndProcedure
Procedure.i BakaShrot_SocketSet_Wait(*Set.BakaShrot_SocketSet, TimeoutMs.i)
Delay(1)
ProcedureReturn #True
EndProcedure
CompilerEndIf
; Waits until Socket is readable, for up to TimeoutMs.
Procedure.i BakaShrot_WaitSocket(Socket.i, TimeoutMs.i)
Protected Set.BakaShrot_SocketSet
BakaShrot_SocketSet_Clear(@Set)
BakaShrot_SocketSet_Add(@Set, Socket)
ProcedureReturn BakaShrot_SocketSet_Wait(@Set, TimeoutMs)
EndProcedure