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

Got close to the final version

comitting Claude's code before the last mile improvements
This commit is contained in:
2026-11-08 13:16:37 +01:00
parent a0daf73c8e
commit 12fbe5f4da
95 changed files with 19130 additions and 841 deletions
+238
View File
@@ -0,0 +1,238 @@
; ============================================================================
; BakaShrot Cipher
;
; Encrypts and authenticates buffers with a shared key, and checks and
; decrypts them, so the rest of the code never touches the crypto: give it
; a key once, then hand it buffers.
;
; Cipher.BakaShrot_Cipher
; BakaShrot_Cipher_Init(@Cipher, *Key, #BakaShrot_Cipher_Client)
; *Sealed = BakaShrot_Cipher_Encrypt(@Cipher, *Packet, PacketSize, @SealedSize)
; ... send it, and on the other end, with a cipher for #BakaShrot_Cipher_Server:
; *Packet = BakaShrot_Cipher_Decrypt(@Cipher, *Sealed, SealedSize, @PacketSize)
; If Not *Packet : abort the connection : EndIf
; BakaShrot_Cipher_Clear(@Cipher) once done, wipes the keys.
;
; What it guarantees, for buffers sent in order over one connection (TCP):
; - Nobody without the key can read them (XChaCha20).
; - Nobody without the key can change, forge or truncate one (Poly1305):
; decrypting it fails.
; - Nobody can replay, reorder, drop or reflect one: each buffer carries
; its sequence number, the receiver only takes the next one it expects,
; and each direction encrypts under its own nonces (or its own key), so
; a buffer sent back to its sender doesn't decrypt either.
; Any failure means the stream can't be trusted anymore: abort the
; connection, don't try the next buffer.
;
; What it doesn't do: get the key. Both ends must already share it, agreed
; on for this connection only (Session.pbi does it for the handshake), never
; a key reused across connections: the sequence numbers start over at 0.
;
; A sealed buffer is:
; [sequence number, 8 bytes, little-endian][encrypted data][tag, 16 bytes]
; #BakaShrot_Cipher_Overhead bytes more than the data. The nonce (24 bytes)
; is the direction (1 byte), zeros, then the sequence number, never sent.
; The sequence number is authenticated too (additional data).
;
; libsodium's crypto_aead_xchacha20poly1305_ietf_*, imported in
; Libsodium.pbi: nothing here implements a primitive. InitCryptography()
; must have been called.
;
; Threads: encrypting and decrypting use separate state, so one thread may
; send while another receives. Two threads must not encrypt (or decrypt)
; with the same cipher at once.
; ============================================================================
XIncludeFile "Libsodium.pbi"
#BakaShrot_Cipher_KeySize = #BakaShrot_XChaCha20Poly1305_KeySize
#BakaShrot_Cipher_SequenceSize = 8
#BakaShrot_Cipher_Overhead = #BakaShrot_Cipher_SequenceSize + #BakaShrot_XChaCha20Poly1305_TagSize
; Which end of the connection a cipher is on, when both share one key: each
; encrypts under its own nonces. Never 0.
#BakaShrot_Cipher_Client = 1
#BakaShrot_Cipher_Server = 2
; Past this many buffers in one direction, encrypting refuses: never reached
; in practice (2^63), but a sequence number must never wrap around.
#BakaShrot_Cipher_MaxSequence = $7FFFFFFFFFFFFFFF
Structure BakaShrot_CipherNonce
Bytes.a[#BakaShrot_XChaCha20Poly1305_NonceSize]
EndStructure
Structure BakaShrot_Cipher
SendKey.a[#BakaShrot_Cipher_KeySize]
ReceiveKey.a[#BakaShrot_Cipher_KeySize]
; First byte of the nonces of each direction.
SendDirection.a
ReceiveDirection.a
; Sequence number of the next buffer to send, and of the next one
; expected.
SendSequence.q
ReceiveSequence.q
IsReady.l
EndStructure
; Fills *Key (#BakaShrot_Cipher_KeySize bytes) with a new random key.
Procedure BakaShrot_Cipher_GenerateKey(*Key)
crypto_aead_xchacha20poly1305_ietf_keygen(*Key)
EndProcedure
; Wipes *Cipher's keys and state, it refuses everything until initialized
; again. Call it once the connection is over.
Procedure BakaShrot_Cipher_Clear(*Cipher.BakaShrot_Cipher)
sodium_memzero(*Cipher, SizeOf(BakaShrot_Cipher))
EndProcedure
; Sets *Cipher up with one key shared by both ends (*Key,
; #BakaShrot_Cipher_KeySize bytes, copied), Role being which end this is:
; #BakaShrot_Cipher_Client or #BakaShrot_Cipher_Server, the other end must
; take the other one.
; Returns #False if Role isn't one of them.
Procedure.i BakaShrot_Cipher_Init(*Cipher.BakaShrot_Cipher, *Key, Role.i)
BakaShrot_Cipher_Clear(*Cipher)
If Not *Key Or (Role <> #BakaShrot_Cipher_Client And Role <> #BakaShrot_Cipher_Server)
ProcedureReturn #False
EndIf
CopyMemory(*Key, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize)
CopyMemory(*Key, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize)
*Cipher\SendDirection = Role
If Role = #BakaShrot_Cipher_Client
*Cipher\ReceiveDirection = #BakaShrot_Cipher_Server
Else
*Cipher\ReceiveDirection = #BakaShrot_Cipher_Client
EndIf
*Cipher\IsReady = #True
ProcedureReturn #True
EndProcedure
; Sets *Cipher up with a key per direction (each #BakaShrot_Cipher_KeySize
; bytes, copied), like libsodium's crypto_kx_* gives: the other end's
; *SendKey is this one's *ReceiveKey.
; Returns #False if they're the same key: the two directions would then
; encrypt under the same nonces, use BakaShrot_Cipher_Init() for one key.
Procedure.i BakaShrot_Cipher_InitWithKeys(*Cipher.BakaShrot_Cipher, *SendKey, *ReceiveKey)
BakaShrot_Cipher_Clear(*Cipher)
If Not *SendKey Or Not *ReceiveKey Or CompareMemory(*SendKey, *ReceiveKey, #BakaShrot_Cipher_KeySize)
ProcedureReturn #False
EndIf
CopyMemory(*SendKey, @*Cipher\SendKey[0], #BakaShrot_Cipher_KeySize)
CopyMemory(*ReceiveKey, @*Cipher\ReceiveKey[0], #BakaShrot_Cipher_KeySize)
; Different keys already keep the directions apart.
*Cipher\SendDirection = 0
*Cipher\ReceiveDirection = 0
*Cipher\IsReady = #True
ProcedureReturn #True
EndProcedure
; The nonce of the buffer with that direction and sequence number.
Procedure BakaShrot_Cipher_MakeNonce(*Nonce.BakaShrot_CipherNonce, Direction.a, Sequence.q)
FillMemory(*Nonce, #BakaShrot_XChaCha20Poly1305_NonceSize, 0)
*Nonce\Bytes[0] = Direction
PokeQ(@*Nonce\Bytes[#BakaShrot_XChaCha20Poly1305_NonceSize - 8], Sequence)
EndProcedure
; Encrypts and authenticates *Data (Size bytes, may be 0) into *Sealed,
; which must have room for Size + #BakaShrot_Cipher_Overhead bytes and not
; overlap *Data. *Data is left untouched.
; Returns #False, writing nothing, if *Cipher isn't set up.
Procedure.i BakaShrot_Cipher_EncryptTo(*Cipher.BakaShrot_Cipher, *Data, Size.i, *Sealed)
Protected Nonce.BakaShrot_CipherNonce
If Not *Cipher\IsReady Or Not *Sealed Or Size < 0 Or (Size > 0 And Not *Data) Or *Cipher\SendSequence >= #BakaShrot_Cipher_MaxSequence
ProcedureReturn #False
EndIf
; libsodium wants a valid pointer even for no data.
If Size = 0
*Data = *Sealed
EndIf
PokeQ(*Sealed, *Cipher\SendSequence)
BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\SendDirection, *Cipher\SendSequence)
crypto_aead_xchacha20poly1305_ietf_encrypt(*Sealed + #BakaShrot_Cipher_SequenceSize, 0, *Data, Size,
*Sealed, #BakaShrot_Cipher_SequenceSize, 0, @Nonce, @*Cipher\SendKey[0])
*Cipher\SendSequence + 1
ProcedureReturn #True
EndProcedure
; Same, into a freshly allocated buffer of Size + #BakaShrot_Cipher_Overhead
; bytes, its size in *OutSize\i.
; Returns 0 if *Cipher isn't set up, or out of memory. The caller owns the
; returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Cipher_Encrypt(*Cipher.BakaShrot_Cipher, *Data, Size.i, *OutSize.Integer)
Protected *Sealed
If Not *Cipher\IsReady Or Size < 0
ProcedureReturn 0
EndIf
*Sealed = AllocateMemory(Size + #BakaShrot_Cipher_Overhead, #PB_Memory_NoClear)
If Not *Sealed
ProcedureReturn 0
EndIf
If Not BakaShrot_Cipher_EncryptTo(*Cipher, *Data, Size, *Sealed)
FreeMemory(*Sealed)
ProcedureReturn 0
EndIf
*OutSize\i = Size + #BakaShrot_Cipher_Overhead
ProcedureReturn *Sealed
EndProcedure
; Checks and decrypts *Sealed (Size bytes, as BakaShrot_Cipher_Encrypt()
; made it on the other end) into a freshly allocated buffer, the data's size
; in *OutSize\i (0 or more, the buffer is at least 1 byte).
; Returns 0 if it isn't the next buffer expected (replayed, reordered, one
; missing), was tampered with, made with another key, sent by this end, or
; is too short; also if *Cipher isn't set up, or out of memory. Nothing
; changes then, but the connection can't be trusted anymore: abort it.
; The caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Cipher_Decrypt(*Cipher.BakaShrot_Cipher, *Sealed, Size.i, *OutSize.Integer)
Protected *Data, DataSize.i, Nonce.BakaShrot_CipherNonce, Genuine.i
If Not *Cipher\IsReady Or Not *Sealed Or Size < #BakaShrot_Cipher_Overhead
ProcedureReturn 0
EndIf
; Only the next one: a replayed, reordered or missing buffer stops here.
If PeekQ(*Sealed) <> *Cipher\ReceiveSequence
ProcedureReturn 0
EndIf
DataSize = Size - #BakaShrot_Cipher_Overhead
If DataSize > 0
*Data = AllocateMemory(DataSize, #PB_Memory_NoClear)
Else
*Data = AllocateMemory(1)
EndIf
If Not *Data
ProcedureReturn 0
EndIf
BakaShrot_Cipher_MakeNonce(@Nonce, *Cipher\ReceiveDirection, *Cipher\ReceiveSequence)
Genuine = Bool(crypto_aead_xchacha20poly1305_ietf_decrypt(*Data, 0, 0, *Sealed + #BakaShrot_Cipher_SequenceSize, Size - #BakaShrot_Cipher_SequenceSize,
*Sealed, #BakaShrot_Cipher_SequenceSize, @Nonce, @*Cipher\ReceiveKey[0]) = 0)
If Not Genuine
FreeMemory(*Data)
ProcedureReturn 0
EndIf
*Cipher\ReceiveSequence + 1
*OutSize\i = DataSize
ProcedureReturn *Data
EndProcedure
+91 -11
View File
@@ -1,17 +1,18 @@
; ============================================================================
; BakaShrot Cryptography
;
; Authenticates packets using Ed25519 signatures (via libsodium - this does
; NOT reimplement any cryptographic primitive).
; Ed25519 signatures via libsodium (this does NOT reimplement any
; cryptographic primitive).
;
; EncodeData signs a buffer with the sending node's own private key.
; DecodeData checks that signature against the claimed sender's public key.
; (Misnamed: they sign and verify, nothing is encoded or decoded.)
;
; This buys integrity + authenticity, NOT confidentiality: anyone who can see
; the packet can still read it, but they cannot forge one or tamper with one
; without the signature check failing. That matches BakaShrot's
; replication/broadcast model, where a message is meant to be read by every
; peer in the group - encrypting it for a single recipient would defeat that.
; The signatures prove each end's identity in the handshake. The sealed
; boxes, key exchange and XChaCha20-Poly1305 below encrypt the connections:
; Session.pbi and Cipher.pbi use them, nothing else should.
; What's done, what isn't, and the plan to abstract it:
; Design/Cryptography.md.
;
; Key material:
; - Public key: #BakaShrot_Ed25519_PublicKeySize (32) raw bytes.
@@ -24,8 +25,9 @@
; file - see EncodeKeyToString()/DecodeKeyFromString() below.
;
; Setup required to build/run this:
; - Windows: the official libsodium release's "libsodium.lib" (import
; library) and "libsodium.dll" alongside the executable.
; - Windows: the official libsodium MSVC release's dynamic build, extracted
; to Libs/libsodium/<x64|x86>/ by Build.ps1, and "libsodium.dll"
; alongside the executable.
; - Linux: libsodium-dev (Debian/Ubuntu) or libsodium-devel (Fedora)
; installed, so "-lsodium" resolves at link time and
; libsodium.so.* is available at runtime.
@@ -38,9 +40,27 @@
#BakaShrot_Ed25519_PrivateKeySize = 64
#BakaShrot_Ed25519_SignatureSize = 64
; XChaCha20-Poly1305 (IETF), libsodium's crypto_aead_xchacha20poly1305_ietf_*:
; encryption and authentication of a buffer with a shared key, used by
; Commons/Cryptography/Cipher.pbi.
#BakaShrot_XChaCha20Poly1305_KeySize = 32
#BakaShrot_XChaCha20Poly1305_NonceSize = 24
#BakaShrot_XChaCha20Poly1305_TagSize = 16
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
ImportC "libsodium.lib"
; X25519 (crypto_box_seal, crypto_kx_*): sealed Hellos and the key exchange,
; used by Commons/Cryptography/Session.pbi.
#BakaShrot_X25519_PublicKeySize = 32
#BakaShrot_X25519_SecretKeySize = 32
#BakaShrot_SealedBoxOverhead = 48
#BakaShrot_KxSessionKeySize = 32
; Windows: the dynamic build's import library, libsodium.dll must be next to
; the program. Both are extracted from Libs/libsodium-*-msvc.zip by Build.ps1.
CompilerIf #PB_Compiler_OS = #PB_OS_Windows And #PB_Compiler_Processor = #PB_Processor_x64
ImportC "../../Libs/libsodium/x64/libsodium.lib"
CompilerElseIf #PB_Compiler_OS = #PB_OS_Windows
ImportC "../../Libs/libsodium/x86/libsodium.lib"
CompilerElse
ImportC "-lsodium"
CompilerEndIf
@@ -63,6 +83,58 @@ CompilerEndIf
; non-zero otherwise (forged, corrupted, or signed different data).
crypto_sign_verify_detached.l(*Signature, *Message, MessageLength.q, *PublicKey)
; Encrypts *Message (MessageLength bytes) into *Ciphertext (MessageLength +
; #BakaShrot_XChaCha20Poly1305_TagSize bytes, the tag at the end), with
; *Key (32 bytes) and *Nonce (24 bytes, never twice with the same key).
; *AdditionalData (AdLength bytes, may be 0) is authenticated, not
; encrypted. *Nsec is always 0. Always returns 0.
crypto_aead_xchacha20poly1305_ietf_encrypt.l(*Ciphertext, *CiphertextLength, *Message, MessageLength.q, *AdditionalData, AdLength.q, *Nsec, *Nonce, *Key)
; Checks and decrypts *Ciphertext (CiphertextLength bytes, tag included)
; into *Message (CiphertextLength - TagSize bytes). Returns 0 if it's
; genuine, -1 if it was tampered with, or made with another key, nonce or
; additional data: *Message must not be used then.
crypto_aead_xchacha20poly1305_ietf_decrypt.l(*Message, *MessageLength, *Nsec, *Ciphertext, CiphertextLength.q, *AdditionalData, AdLength.q, *Nonce, *Key)
; Fills *Key (32 bytes) with a random XChaCha20-Poly1305 key.
crypto_aead_xchacha20poly1305_ietf_keygen(*Key)
; Zeroes Length bytes at *Memory, in a way the compiler can't optimize out:
; for wiping keys.
sodium_memzero(*Memory, Length.i)
; Copies the public key embedded in *PrivateKey (64 bytes) into *PublicKey
; (32 bytes). Always returns 0.
crypto_sign_ed25519_sk_to_pk.l(*PublicKey, *PrivateKey)
; The X25519 key (32 bytes) matching an Ed25519 public key (32 bytes) or
; private key (64 bytes), so one identity key both signs and receives
; sealed boxes. The public one returns -1 if it isn't a valid key.
crypto_sign_ed25519_pk_to_curve25519.l(*X25519PublicKey, *Ed25519PublicKey)
crypto_sign_ed25519_sk_to_curve25519.l(*X25519SecretKey, *Ed25519PrivateKey)
; Encrypts *Message (MessageLength bytes) for the holder of *PublicKey
; (X25519) into *Ciphertext (MessageLength + 48 bytes), with a throwaway
; key pair: only *PublicKey's holder can open it, and it doesn't tell who
; sealed it. Returns 0, -1 on failure.
crypto_box_seal.l(*Ciphertext, *Message, MessageLength.q, *PublicKey)
; Opens *Ciphertext (CiphertextLength bytes) sealed for *PublicKey into
; *Message (CiphertextLength - 48 bytes). Returns 0, or -1 if it wasn't
; sealed for this key or was tampered with.
crypto_box_seal_open.l(*Message, *Ciphertext, CiphertextLength.q, *PublicKey, *SecretKey)
; Fills *PublicKey and *SecretKey (32 bytes each) with a fresh X25519 key
; pair, for one key exchange. Returns 0.
crypto_kx_keypair.l(*PublicKey, *SecretKey)
; Both ends of a key exchange get the same two 32-byte keys from their own
; key pair and the other end's public key: *Rx decrypts what this end
; receives, *Tx encrypts what it sends (the client's Tx is the server's
; Rx). Return -1 if the other end's public key isn't acceptable.
crypto_kx_client_session_keys.l(*Rx, *Tx, *ClientPublicKey, *ClientSecretKey, *ServerPublicKey)
crypto_kx_server_session_keys.l(*Rx, *Tx, *ServerPublicKey, *ServerSecretKey, *ClientPublicKey)
EndImport
@@ -82,6 +154,14 @@ Procedure GenerateKeyPair(*PublicKey, *PrivateKey)
EndProcedure
; Fills *PublicKey (#BakaShrot_Ed25519_PublicKeySize bytes) with the public
; key matching *PrivateKey (#BakaShrot_Ed25519_PrivateKeySize bytes), so a
; node only needs its private key in its config.
Procedure GetPublicKeyFromPrivateKey(*PrivateKey, *PublicKey)
crypto_sign_ed25519_sk_to_pk(*PublicKey, *PrivateKey)
EndProcedure
; Signs *Data (DataLength bytes) with *PrivateKey (this node's own private
; key, #BakaShrot_Ed25519_PrivateKeySize bytes).
; Writes the signature to *Signature, which must point to
+186
View File
@@ -0,0 +1,186 @@
; ============================================================================
; BakaShrot Session
;
; The handshake's cryptography, so the connections only call these
; (the handshake itself is in Commons/Networking/Connections.pbi):
;
; - The Hello is sealed for the server's identity key: crypto_box_seal,
; for the X25519 key matching the server's Ed25519 one. Only that
; server can read it, and someone watching doesn't learn who connects.
; BakaShrot_Session_SealHello() / _OpenHello().
; - Each end makes a key pair for this one connection (crypto_kx). The
; client's public half travels in the sealed Hello, the server's in the
; ChallengeRequest; both ends sign them with their identity keys
; (Connections.pbi), so nobody in the middle can swap them.
; BakaShrot_Session_NewKeyPair().
; - From its own pair and the other end's public half, each end gets a
; key per direction and sets its BakaShrot_Cipher (Cipher.pbi) up with
; them: every packet after the ChallengeRequest is encrypted.
; BakaShrot_Session_StartClient() / _StartServer().
;
; The key pair's secret and the derived keys are wiped once the cipher has
; them: a recorded connection can't be decrypted later, even with the
; identity keys (forward secrecy).
;
; libsodium does all of it (Libsodium.pbi), InitCryptography() must have
; been called.
; ============================================================================
XIncludeFile "Cipher.pbi"
#BakaShrot_Session_PublicKeySize = #BakaShrot_X25519_PublicKeySize
Structure BakaShrot_SessionKey
Bytes.a[32]
EndStructure
; One end's key pair for one connection.
Structure BakaShrot_SessionKeyPair
PublicKey.a[#BakaShrot_X25519_PublicKeySize]
SecretKey.a[#BakaShrot_X25519_SecretKeySize]
EndStructure
; A server's keys to open the Hellos sealed for it, from its Ed25519
; private key. Read-only once loaded, every client thread may use them.
Structure BakaShrot_HelloKeys
PublicKey.a[#BakaShrot_X25519_PublicKeySize]
SecretKey.a[#BakaShrot_X25519_SecretKeySize]
EndStructure
Structure BakaShrot_SessionDirections
Rx.a[#BakaShrot_KxSessionKeySize]
Tx.a[#BakaShrot_KxSessionKeySize]
EndStructure
; Fills *Keys from *PrivateKey (Ed25519, #BakaShrot_Ed25519_PrivateKeySize
; bytes), for a server to open the Hellos sealed for its public key.
; Returns #False if it isn't a usable key.
Procedure.i BakaShrot_Session_LoadHelloKeys(*Keys.BakaShrot_HelloKeys, *PrivateKey)
Protected Ed25519PublicKey.BakaShrot_SessionKey, IsValid.i
crypto_sign_ed25519_sk_to_pk(@Ed25519PublicKey, *PrivateKey)
IsValid = Bool(crypto_sign_ed25519_pk_to_curve25519(@*Keys\PublicKey[0], @Ed25519PublicKey) = 0)
If IsValid
IsValid = Bool(crypto_sign_ed25519_sk_to_curve25519(@*Keys\SecretKey[0], *PrivateKey) = 0)
EndIf
If Not IsValid
sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys))
EndIf
ProcedureReturn IsValid
EndProcedure
; Wipes *Keys.
Procedure BakaShrot_Session_ClearHelloKeys(*Keys.BakaShrot_HelloKeys)
sodium_memzero(*Keys, SizeOf(BakaShrot_HelloKeys))
EndProcedure
; Seals *Data (Size bytes, at least 1) for the server whose Ed25519 public
; key is *ServerPublicKey (#BakaShrot_Ed25519_PublicKeySize bytes), into a
; freshly allocated buffer of Size + #BakaShrot_SealedBoxOverhead bytes,
; its size in *OutSize\i.
; Returns 0 if *ServerPublicKey isn't a valid key, or out of memory. The
; caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_Session_SealHello(*ServerPublicKey, *Data, Size.i, *OutSize.Integer)
Protected BoxPublicKey.BakaShrot_SessionKey, *Sealed
If Not *ServerPublicKey Or Not *Data Or Size < 1
ProcedureReturn 0
EndIf
If crypto_sign_ed25519_pk_to_curve25519(@BoxPublicKey, *ServerPublicKey) <> 0
ProcedureReturn 0
EndIf
*Sealed = AllocateMemory(Size + #BakaShrot_SealedBoxOverhead, #PB_Memory_NoClear)
If Not *Sealed
ProcedureReturn 0
EndIf
If crypto_box_seal(*Sealed, *Data, Size, @BoxPublicKey) <> 0
FreeMemory(*Sealed)
ProcedureReturn 0
EndIf
*OutSize\i = Size + #BakaShrot_SealedBoxOverhead
ProcedureReturn *Sealed
EndProcedure
; Opens *Sealed (Size bytes), sealed by BakaShrot_Session_SealHello() for
; *Keys' server, into a freshly allocated buffer, its size in *OutSize\i.
; Returns 0 if it wasn't sealed for this server, was tampered with, is too
; short, or out of memory. The caller owns the returned buffer - free it
; with FreeMemory.
Procedure.i BakaShrot_Session_OpenHello(*Keys.BakaShrot_HelloKeys, *Sealed, Size.i, *OutSize.Integer)
Protected *Data, DataSize.i
If Not *Sealed Or Size <= #BakaShrot_SealedBoxOverhead
ProcedureReturn 0
EndIf
DataSize = Size - #BakaShrot_SealedBoxOverhead
*Data = AllocateMemory(DataSize, #PB_Memory_NoClear)
If Not *Data
ProcedureReturn 0
EndIf
If crypto_box_seal_open(*Data, *Sealed, Size, @*Keys\PublicKey[0], @*Keys\SecretKey[0]) <> 0
FreeMemory(*Data)
ProcedureReturn 0
EndIf
*OutSize\i = DataSize
ProcedureReturn *Data
EndProcedure
; Fills *KeyPair with a fresh key pair, for one connection. Its PublicKey
; goes to the other end.
Procedure BakaShrot_Session_NewKeyPair(*KeyPair.BakaShrot_SessionKeyPair)
crypto_kx_keypair(@*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0])
EndProcedure
; Wipes *KeyPair.
Procedure BakaShrot_Session_ClearKeyPair(*KeyPair.BakaShrot_SessionKeyPair)
sodium_memzero(*KeyPair, SizeOf(BakaShrot_SessionKeyPair))
EndProcedure
; Sets *Cipher up for the client's end of the connection, from the client's
; *KeyPair and the server's public half (*ServerSessionKey,
; #BakaShrot_Session_PublicKeySize bytes). *KeyPair is wiped either way.
; Returns #False if the server's half isn't acceptable: abort then.
Procedure.i BakaShrot_Session_StartClient(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ServerSessionKey)
Protected Keys.BakaShrot_SessionDirections, IsReady.i
BakaShrot_Cipher_Clear(*Cipher)
If crypto_kx_client_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ServerSessionKey) = 0
IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0])
EndIf
sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections))
BakaShrot_Session_ClearKeyPair(*KeyPair)
ProcedureReturn IsReady
EndProcedure
; Same for the server's end, from the server's *KeyPair and the client's
; public half (*ClientSessionKey).
Procedure.i BakaShrot_Session_StartServer(*Cipher.BakaShrot_Cipher, *KeyPair.BakaShrot_SessionKeyPair, *ClientSessionKey)
Protected Keys.BakaShrot_SessionDirections, IsReady.i
BakaShrot_Cipher_Clear(*Cipher)
If crypto_kx_server_session_keys(@Keys\Rx[0], @Keys\Tx[0], @*KeyPair\PublicKey[0], @*KeyPair\SecretKey[0], *ClientSessionKey) = 0
IsReady = BakaShrot_Cipher_InitWithKeys(*Cipher, @Keys\Tx[0], @Keys\Rx[0])
EndIf
sodium_memzero(@Keys, SizeOf(BakaShrot_SessionDirections))
BakaShrot_Session_ClearKeyPair(*KeyPair)
ProcedureReturn IsReady
EndProcedure
+404 -1
View File
@@ -1,21 +1,424 @@
; ============================================================================
; 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
; 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
;
;
; 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"
; 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_Idk
#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
; Identity from the Hello, as the server's own ids (unused on the client
; side), only trusted once Status is Authenticated.
TopicId.u
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
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.
Procedure.i BakaShrot_SendPacket(ConnectionId.i, *Packet, PacketSize.i, *Cipher.BakaShrot_Cipher)
Protected *Frame, FrameSize.i, PayloadSize.i, Offset.i, Sent.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
While Offset < FrameSize
Sent = SendNetworkData(ConnectionId, *Frame + Offset, FrameSize - Offset)
If Sent <= 0
FreeMemory(*Frame)
ProcedureReturn #False
EndIf
Offset + Sent
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
+152
View File
@@ -0,0 +1,152 @@
; ============================================================================
; 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
+329
View File
@@ -0,0 +1,329 @@
; ============================================================================
; 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
; Each a name or an id in digits (Names.pbi), resolved by the server.
Topic.s
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
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
If *Outbound\ConnectionId Or Not *ServerPublicKey
ProcedureReturn #False
EndIf
If Port < 1 Or Port > 65535
ProcedureReturn #False
EndIf
; Only needed before PureBasic 6.00.
CompilerIf #PB_Compiler_Version < 600
If Not InitNetwork()
ProcedureReturn #False
EndIf
CompilerEndIf
If Not InitCryptography()
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
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
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\ClientTopic = *Identity\Topic
Hello\ClientNode = *Identity\Node
Hello\ClientPubKeyB64 = *Identity\PublicKey
CopyMemory(@KeyPair\PublicKey[0], @Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
*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
Sent = BakaShrot_SendPacket(*Outbound\ConnectionId, *Sealed, SealedSize\i, 0)
FreeMemory(*Sealed)
If Not Sent
Goto ConnectFailed
EndIf
; 2. Challenge request, in plain text
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
If Not *Packet
Goto ConnectFailed
EndIf
*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
Goto ConnectFailed
EndIf
; Every packet is encrypted from now on.
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
Sent = BakaShrot_Outbound_Send(*Outbound, *Packet, PacketSize\i)
FreeMemory(*Packet)
If Not Sent
Goto ConnectFailed
EndIf
; 4. Accepted
*Packet = BakaShrot_Outbound_WaitPacket(*Outbound, @PacketSize, #BakaShrot_Outbound_Timeout)
If Not *Packet
Goto ConnectFailed
EndIf
*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
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
+134 -4
View File
@@ -1,4 +1,7 @@
XIncludeFile "../../Includes/PB-MessagePack/Includes/MessagePack.pbi"
XIncludeFile "Names.pbi"
; Represents the root of all BakaShrot packets.
; Any packets below this size MUST be thrown out.
@@ -8,19 +11,146 @@ Structure BakaShrot_PacketBase
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"
#BakaShrot_ProtocolVersion = 1
; 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).
#BakaShrot_ProtocolVersion = 3
; 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
; 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
#BakaShrot_PacketType_AuthenticationRequest = 1
#BakaShrot_PacketType_AuthenticationChallenge = 2
#BakaShrot_PacketType_AuthenticationResult = 3
; 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
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,65 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, tells the client its challenge response was accepted and it is now authenticated.
; Only carries the base fields.
Structure BakaShrot_AuthAccepted Extends BakaShrot_PacketBase
EndStructure
; Encodes *Accepted into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_AuthAcceptedPacket_Encode(*Accepted.BakaShrot_AuthAccepted, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Accepted\Magic = #BakaShrot_ProtocolMagic
*Accepted\Version = #BakaShrot_ProtocolVersion
*Accepted\PacketType = #BakaShrot_PacketType_AuthAccepted
*MsgPackData = MsgPackCreate(16)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Accepted, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_AuthAcceptedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Accepted.BakaShrot_AuthAccepted
*Accepted = AllocateStructure(BakaShrot_AuthAccepted)
If Not *Accepted
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Accepted, *MsgPackData) Or *Accepted\PacketType <> #BakaShrot_PacketType_AuthAccepted
FreeStructure(*Accepted)
ProcedureReturn 0
EndIf
ProcedureReturn *Accepted
EndProcedure
@@ -1,303 +0,0 @@
; ============================================================================
; BakaShrot Authentication Packets
;
; The three packets exchanged during the auth handshake:
; C2S AuthRequest - client introduces itself and its public key.
; S2C AuthChallenge - server sends back something for the client to sign.
; C2S AuthResult - client replies with the signed challenge.
;
; Wire format: BakaShrot_PacketBase (Magic, Version, PacketType - see
; Packets.pbi) followed by each struct's own fields, in declaration order.
; Every string field is packed as {len}{str}: a 4-byte (Long) UTF-8 byte
; length, followed by exactly that many UTF-8 bytes - no null terminator.
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S auth request
Structure BakaShrot_AuthRequest Extends BakaShrot_PacketBase
ClientGroupId.l
ClientNodeId.l
ClientPubKeyB64.s
EndStructure
; S2C Chalenge the client must sign it with their private key
Structure BakaShrot_AuthChallenge Extends BakaShrot_PacketBase
ClientPubKeyB64.s
EndStructure
; C2S Response with the chalenge signed by their private key
Structure BakaShrot_AuthResult Extends BakaShrot_PacketBase
ChallengeResponseB64.s
EndStructure
DeclareModule BakaShrot_AuthenticationPacket
; Encodes *Request/*Challenge/*Result into a freshly allocated buffer.
; *OutSize receives its size in bytes. Returns 0 (and leaves *OutSize
; untouched) if the input is invalid (null) or the buffer could not be
; allocated. Caller owns the returned buffer - free it with FreeMemory.
Declare.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l)
Declare.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l)
Declare.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l)
; Decodes *Buffer (BufferSize bytes) into a freshly allocated struct.
; Returns 0 if the packet is too small, malformed, truncated, or not of
; the expected kind. Caller owns the returned struct - free it with
; FreeStructure.
Declare.i DecodeRequest(*Buffer, BufferSize.i)
Declare.i DecodeChallenge(*Buffer, BufferSize.i)
Declare.i DecodeResult(*Buffer, BufferSize.i)
EndDeclareModule
Module BakaShrot_AuthenticationPacket
; ------------------------------------------------------------------------
; Wire helpers. Every string on the wire is {len}{str}: a 4-byte UTF-8
; byte length followed by exactly that many UTF-8 bytes.
; ------------------------------------------------------------------------
; Size, in bytes, Str will take once written as {len}{str}.
Procedure.i PackedStringSize(Str.s)
ProcedureReturn 4 + StringByteLength(Str, #PB_UTF8)
EndProcedure
; Writes Str at *Buffer + Offset as {len}{str}. *Buffer must have room
; for at least PackedStringSize(Str) bytes from Offset onward.
Procedure WritePackedString(*Buffer, Offset.i, Str.s)
PokeL(*Buffer + Offset, StringByteLength(Str, #PB_UTF8))
PokeS(*Buffer + Offset + 4, Str, -1, #PB_UTF8)
EndProcedure
; #True if a {len}{str} value starting at Offset is fully contained
; within the first BufferSize bytes of *Buffer. Always check this before
; calling ReadPackedString() - it does no bounds checking of its own.
Procedure.i PackedStringFits(*Buffer, BufferSize.i, Offset.i)
Protected ByteLen.l
If Offset + 4 > BufferSize
ProcedureReturn #False
EndIf
ByteLen = PeekL(*Buffer + Offset)
If ByteLen < 0 Or Offset + 4 + ByteLen > BufferSize
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Reads the {len}{str} value at *Buffer + Offset. Caller MUST have
; checked PackedStringFits() first.
Procedure.s ReadPackedString(*Buffer, Offset.i)
ProcedureReturn PeekS(*Buffer + Offset + 4, PeekL(*Buffer + Offset), #PB_UTF8 | #PB_ByteLength)
EndProcedure
; ------------------------------------------------------------------------
; Header. All three packets share the same BakaShrot_PacketBase layout:
; Magic.l, Version.l, PacketType.l.
; ------------------------------------------------------------------------
; Writes the packet header at the start of *Buffer. Returns the offset of
; the first byte after the header.
Procedure.i WriteHeader(*Buffer, PacketType.l)
PokeL(*Buffer, #BakaShrot_ProtocolMagic)
PokeL(*Buffer + 4, #BakaShrot_ProtocolVersion)
PokeL(*Buffer + 8, PacketType)
ProcedureReturn SizeOf(BakaShrot_PacketBase)
EndProcedure
; Validates the header at the start of *Buffer: big enough to hold one,
; correct Magic/Version, and PacketType matching ExpectedPacketType.
; Returns the offset of the first byte after the header on success, or
; -1 if the packet must be thrown out.
Procedure.i ReadHeader(*Buffer, BufferSize.i, ExpectedPacketType.l)
If BufferSize < SizeOf(BakaShrot_PacketBase)
ProcedureReturn -1
EndIf
If PeekL(*Buffer) <> #BakaShrot_ProtocolMagic
ProcedureReturn -1
EndIf
If PeekL(*Buffer + 4) <> #BakaShrot_ProtocolVersion
ProcedureReturn -1
EndIf
If PeekL(*Buffer + 8) <> ExpectedPacketType
ProcedureReturn -1
EndIf
ProcedureReturn SizeOf(BakaShrot_PacketBase)
EndProcedure
; ------------------------------------------------------------------------
; AuthRequest (C2S)
; ------------------------------------------------------------------------
Procedure.i EncodeRequest(*Request.BakaShrot_AuthRequest, *OutSize.l)
Protected Size.i, *Buffer, Offset.i
If Not *Request
ProcedureReturn 0
EndIf
Size = SizeOf(BakaShrot_PacketBase) + 4 + 4 + PackedStringSize(*Request\ClientPubKeyB64)
*Buffer = AllocateMemory(Size)
If Not *Buffer
ProcedureReturn 0
EndIf
Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationRequest)
PokeL(*Buffer + Offset, *Request\ClientGroupId)
Offset = Offset + 4
PokeL(*Buffer + Offset, *Request\ClientNodeId)
Offset = Offset + 4
WritePackedString(*Buffer, Offset, *Request\ClientPubKeyB64)
*OutSize\l = Size
ProcedureReturn *Buffer
EndProcedure
Procedure.i DecodeRequest(*Buffer, BufferSize.i)
Protected Offset.i, *Request.BakaShrot_AuthRequest
Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationRequest)
If Offset = -1
ProcedureReturn 0
EndIf
If Offset + 4 + 4 > BufferSize
ProcedureReturn 0
EndIf
*Request = AllocateStructure(BakaShrot_AuthRequest)
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_AuthenticationRequest
*Request\ClientGroupId = PeekL(*Buffer + Offset)
Offset = Offset + 4
*Request\ClientNodeId = PeekL(*Buffer + Offset)
Offset = Offset + 4
If Not PackedStringFits(*Buffer, BufferSize, Offset)
FreeStructure(*Request)
ProcedureReturn 0
EndIf
*Request\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset)
ProcedureReturn *Request
EndProcedure
; ------------------------------------------------------------------------
; AuthChallenge (S2C)
; ------------------------------------------------------------------------
Procedure.i EncodeChallenge(*Challenge.BakaShrot_AuthChallenge, *OutSize.l)
Protected Size.i, *Buffer, Offset.i
If Not *Challenge
ProcedureReturn 0
EndIf
Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Challenge\ClientPubKeyB64)
*Buffer = AllocateMemory(Size)
If Not *Buffer
ProcedureReturn 0
EndIf
Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationChallenge)
WritePackedString(*Buffer, Offset, *Challenge\ClientPubKeyB64)
*OutSize\l = Size
ProcedureReturn *Buffer
EndProcedure
Procedure.i DecodeChallenge(*Buffer, BufferSize.i)
Protected Offset.i, *Challenge.BakaShrot_AuthChallenge
Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationChallenge)
If Offset = -1
ProcedureReturn 0
EndIf
If Not PackedStringFits(*Buffer, BufferSize, Offset)
ProcedureReturn 0
EndIf
*Challenge = AllocateStructure(BakaShrot_AuthChallenge)
*Challenge\Magic = #BakaShrot_ProtocolMagic
*Challenge\Version = #BakaShrot_ProtocolVersion
*Challenge\PacketType = #BakaShrot_PacketType_AuthenticationChallenge
*Challenge\ClientPubKeyB64 = ReadPackedString(*Buffer, Offset)
ProcedureReturn *Challenge
EndProcedure
; ------------------------------------------------------------------------
; AuthResult (C2S)
; ------------------------------------------------------------------------
Procedure.i EncodeResult(*Result.BakaShrot_AuthResult, *OutSize.l)
Protected Size.i, *Buffer, Offset.i
If Not *Result
ProcedureReturn 0
EndIf
Size = SizeOf(BakaShrot_PacketBase) + PackedStringSize(*Result\ChallengeResponseB64)
*Buffer = AllocateMemory(Size)
If Not *Buffer
ProcedureReturn 0
EndIf
Offset = WriteHeader(*Buffer, #BakaShrot_PacketType_AuthenticationResult)
WritePackedString(*Buffer, Offset, *Result\ChallengeResponseB64)
*OutSize\l = Size
ProcedureReturn *Buffer
EndProcedure
Procedure.i DecodeResult(*Buffer, BufferSize.i)
Protected Offset.i, *Result.BakaShrot_AuthResult
Offset = ReadHeader(*Buffer, BufferSize, #BakaShrot_PacketType_AuthenticationResult)
If Offset = -1
ProcedureReturn 0
EndIf
If Not PackedStringFits(*Buffer, BufferSize, Offset)
ProcedureReturn 0
EndIf
*Result = AllocateStructure(BakaShrot_AuthResult)
*Result\Magic = #BakaShrot_ProtocolMagic
*Result\Version = #BakaShrot_ProtocolVersion
*Result\PacketType = #BakaShrot_PacketType_AuthenticationResult
*Result\ChallengeResponseB64 = ReadPackedString(*Buffer, Offset)
ProcedureReturn *Result
EndProcedure
EndModule
@@ -0,0 +1,131 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C challenge the client must sign with its private key, the last packet sent in plain text.
; Nonce is fresh random data tied to this connection, the client must echo it back in its response.
; ServerSessionKey: the public half of the server's key pair for this connection.
; ServerSignature: the server's signature of the handshake so far, made with its identity key
; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi), so the client knows it's the right server.
Structure BakaShrot_ChallengeRequest Extends BakaShrot_PacketBase
ChallengeB64.s
Nonce.a[#BakaShrot_NonceSize]
ServerSessionKey.a[#BakaShrot_SessionKeySize]
ServerSignature.a[#BakaShrot_HandshakeSignatureSize]
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *Request\Nonce must already be filled by the caller with CryptRandomData().
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChallengeRequestPacket_Encode(*Request.BakaShrot_ChallengeRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ChallengeRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\ChallengeB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChallengeRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ChallengeRequest
Protected ReadSize.q
*Request = AllocateStructure(BakaShrot_ChallengeRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ChallengeRequest
Goto DecodeFailed
EndIf
; ChallengeB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\ChallengeB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Nonce
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\Nonce[0], #BakaShrot_NonceSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize
Goto DecodeFailed
EndIf
; ServerSessionKey
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSessionKey[0], #BakaShrot_SessionKeySize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize
Goto DecodeFailed
EndIf
; ServerSignature
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Request\ServerSignature[0], #BakaShrot_HandshakeSignatureSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_HandshakeSignatureSize
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S response with the handshake (challenge included) signed by the client's private key
; (BakaShrot_MakeHandshakeTranscript(), Connections.pbi). Sent encrypted, as everything after it.
; Nonce is the one received in the challenge request, echoed back as-is.
; The server MUST compare it with the nonce it issued for this connection and drop the client on mismatch.
Structure BakaShrot_ChallengeResponse Extends BakaShrot_PacketBase
ChallengeResponseB64.s
Nonce.a[#BakaShrot_NonceSize]
EndStructure
; Encodes *Response into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ChallengeResponsePacket_Encode(*Response.BakaShrot_ChallengeResponse, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Response\Magic = #BakaShrot_ProtocolMagic
*Response\Version = #BakaShrot_ProtocolVersion
*Response\PacketType = #BakaShrot_PacketType_ChallengeResponse
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Response, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Response\ChallengeResponseB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ChallengeResponsePacket_Decode(*MsgPackData.MsgPackData)
Protected *Response.BakaShrot_ChallengeResponse
Protected ReadSize.q
*Response = AllocateStructure(BakaShrot_ChallengeResponse)
If Not *Response
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Response, *MsgPackData) Or *Response\PacketType <> #BakaShrot_PacketType_ChallengeResponse
Goto DecodeFailed
EndIf
; ChallengeResponseB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Response\ChallengeResponseB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Nonce
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Response\Nonce[0], #BakaShrot_NonceSize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_NonceSize
Goto DecodeFailed
EndIf
ProcedureReturn *Response
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Response)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,99 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks for the latest message stored for a topic/node combination.
; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi).
; The client's [BakaShrot.Client.<name>] ReadTopics must allow the topic.
; Answered with a LatestMessage or a RequestRefused.
Structure BakaShrot_GetLatestMessage Extends BakaShrot_PacketBase
Topic.s
Node.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetLatestMessagePacket_Encode(*Request.BakaShrot_GetLatestMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetLatestMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetLatestMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetLatestMessage
*Request = AllocateStructure(BakaShrot_GetLatestMessage)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetLatestMessage
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,138 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Most messages a GetMessages may ask for.
#BakaShrot_MaxGetMessages = 10000
; C2S, asks for the messages of a topic/node combination stored after
; AfterMessageId (0 for the first ones), in message id order, at most Limit
; (1-#BakaShrot_MaxGetMessages) of them.
; Topic, Node: each a name or an id in digits (Commons/Networking/Names.pbi).
; The client's [BakaShrot.Client.<name>] ReadTopics must allow the topic.
; Answered with a Messages (maybe with none) or a RequestRefused.
Structure BakaShrot_GetMessages Extends BakaShrot_PacketBase
Topic.s
Node.s
AfterMessageId.q
Limit.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_GetMessagesPacket_Encode(*Request.BakaShrot_GetMessages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_GetMessages
If *Request\AfterMessageId < 0 Or *Request\Limit < 1 Or *Request\Limit > #BakaShrot_MaxGetMessages
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\AfterMessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Limit) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_GetMessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_GetMessages
Protected Value.q
*Request = AllocateStructure(BakaShrot_GetMessages)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_GetMessages
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; AfterMessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Request\AfterMessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Request\AfterMessageId < 0
Goto DecodeFailed
EndIf
; Limit
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 1 Or Value > #BakaShrot_MaxGetMessages
Goto DecodeFailed
EndIf
*Request\Limit = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
+130
View File
@@ -0,0 +1,130 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S auth request, sent sealed for the server's public key (Connections.pbi).
; ClientTopic, ClientNode: who the client is, each a name or an id in digits
; (Commons/Networking/Names.pbi), resolved by the server in its own names.
; ClientSessionKey: the public half of the client's key pair for this
; connection (Commons/Cryptography/Session.pbi).
Structure BakaShrot_AuthHello Extends BakaShrot_PacketBase
ClientTopic.s
ClientNode.s
ClientPubKeyB64.s
ClientSessionKey.a[#BakaShrot_SessionKeySize]
EndStructure
; Encodes *Hello into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_HelloPacket_Encode(*Hello.BakaShrot_AuthHello, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Hello\Magic = #BakaShrot_ProtocolMagic
*Hello\Version = #BakaShrot_ProtocolVersion
*Hello\PacketType = #BakaShrot_PacketType_ClientHello
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Hello, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientTopic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientNode) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Hello\ClientPubKeyB64) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_HelloPacket_Decode(*MsgPackData.MsgPackData)
Protected *Hello.BakaShrot_AuthHello
Protected ReadSize.q
*Hello = AllocateStructure(BakaShrot_AuthHello)
If Not *Hello
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Hello, *MsgPackData) Or *Hello\PacketType <> #BakaShrot_PacketType_ClientHello
Goto DecodeFailed
EndIf
; ClientTopic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientTopic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientNode
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientNode = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientPubKeyB64
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Hello\ClientPubKeyB64 = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; ClientSessionKey
; Anything bigger than the struct's array is rejected by MsgPackReadBinary, anything smaller by the size check.
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Binary
Goto DecodeFailed
EndIf
ReadSize = MsgPackReadBinary(*MsgPackData, @*Hello\ClientSessionKey[0], #BakaShrot_SessionKeySize)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or ReadSize <> #BakaShrot_SessionKeySize
Goto DecodeFailed
EndIf
ProcedureReturn *Hello
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Hello)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,157 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a GetLatestMessage with the latest message of that topic/node combination.
; TopicId, NodeId: the server's own ids for them.
; TopicName, NodeName: their names, or their ids in digits if they have none.
Structure BakaShrot_LatestMessage Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
MessageId.q
JsonData.s
EndStructure
; Encodes *Latest into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_LatestMessagePacket_Encode(*Latest.BakaShrot_LatestMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Latest\Magic = #BakaShrot_ProtocolMagic
*Latest\Version = #BakaShrot_ProtocolVersion
*Latest\PacketType = #BakaShrot_PacketType_LatestMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Latest, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\TopicName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\NodeName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Latest\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Latest\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_LatestMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Latest.BakaShrot_LatestMessage
Protected Value.q
*Latest = AllocateStructure(BakaShrot_LatestMessage)
If Not *Latest
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Latest, *MsgPackData) Or *Latest\PacketType <> #BakaShrot_PacketType_LatestMessage
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Latest\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Latest\NodeId = Value
; TopicName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\TopicName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; NodeName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\NodeName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Latest\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Latest\MessageId < 1
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Latest\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Latest
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Latest)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,87 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; C2S, asks for every topic or node the server has, with their ids and names.
; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Topics: only those the client may push to or read, unless it may query.
; Answered with a NamesList.
Structure BakaShrot_ListNames Extends BakaShrot_PacketBase
Kind.l
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ListNamesPacket_Encode(*Request.BakaShrot_ListNames, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ListNames
*MsgPackData = MsgPackCreate(32)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ListNamesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ListNames
Protected Value.q
*Request = AllocateStructure(BakaShrot_ListNames)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ListNames
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Request\Kind = Value
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,82 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a PushMessage with the id the message was stored under.
Structure BakaShrot_MessagePushed Extends BakaShrot_PacketBase
MessageId.q
EndStructure
; Encodes *Pushed into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MessagePushedPacket_Encode(*Pushed.BakaShrot_MessagePushed, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Pushed\Magic = #BakaShrot_ProtocolMagic
*Pushed\Version = #BakaShrot_ProtocolVersion
*Pushed\PacketType = #BakaShrot_PacketType_MessagePushed
*MsgPackData = MsgPackCreate(32)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Pushed, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Pushed\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MessagePushedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Pushed.BakaShrot_MessagePushed
*Pushed = AllocateStructure(BakaShrot_MessagePushed)
If Not *Pushed
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Pushed, *MsgPackData) Or *Pushed\PacketType <> #BakaShrot_PacketType_MessagePushed
Goto DecodeFailed
EndIf
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Pushed\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Pushed\MessageId < 1
Goto DecodeFailed
EndIf
ProcedureReturn *Pushed
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Pushed)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,219 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
XIncludeFile "GetMessagesPacket.pbi"
; One message of a Messages answer.
Structure BakaShrot_MessagesEntry
MessageId.q
JsonData.s
EndStructure
; About how big a Messages answer gets: messages are added while they fit
; in it, and a bigger one goes alone (up to #BakaShrot_MaxMessageSize).
#BakaShrot_MessagesBatchBytes = 1024 * 1024
; Encoded size of the answer's own fields, and of each message on top of its
; JSON, rounded up. Used to stop an answer before it gets over #BakaShrot_MaxPacketSize.
#BakaShrot_MessagesOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
#BakaShrot_MessagesMessageOverhead = 16
; S2C, answers a GetMessages with the messages of that topic/node combination
; stored after the asked id, in message id order: as many as were asked for,
; or fewer if they didn't fit in about #BakaShrot_MessagesBatchBytes. None
; if there are no more.
; TopicId, NodeId: the server's own ids for them.
; TopicName, NodeName: their names, or their ids in digits if they have none.
; More: 1 if more messages follow the last one, ask again after it.
; On the wire: topic id, node id, topic name, node name, more, message
; count, then each message's id and JSON.
Structure BakaShrot_Messages Extends BakaShrot_PacketBase
TopicId.l
NodeId.l
TopicName.s
NodeName.s
More.l
List Messages.BakaShrot_MessagesEntry()
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_MessagesPacket_Encode(*Answer.BakaShrot_Messages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_Messages
If ListSize(*Answer\Messages()) > #BakaShrot_MaxGetMessages
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\TopicName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\NodeName) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, Bool(*Answer\More)) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Messages
If MsgPackWriteInteger(*MsgPackData, ListSize(*Answer\Messages())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Answer\Messages()
If MsgPackWriteInteger(*MsgPackData, *Answer\Messages()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; Message ids must be 1 or more, and strictly increasing.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_MessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_Messages
Protected Value.q, Count.q, i.q, PreviousMessageId.q
*Answer = AllocateStructure(BakaShrot_Messages)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_Messages
Goto DecodeFailed
EndIf
; TopicId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Answer\TopicId = Value
; NodeId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 65535
Goto DecodeFailed
EndIf
*Answer\NodeId = Value
; TopicName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\TopicName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; NodeName
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\NodeName = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; More
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*Answer\More = Value
; Message count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxGetMessages
Goto DecodeFailed
EndIf
; Messages
PreviousMessageId = 0
For i = 1 To Count
AddElement(*Answer\Messages())
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Answer\Messages()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Answer\Messages()\MessageId <= PreviousMessageId
Goto DecodeFailed
EndIf
PreviousMessageId = *Answer\Messages()\MessageId
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Messages()\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,116 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; S2C, answers a ResolveName.
; Kind: the one asked about, #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Id: the server's own id for it, 0-65535.
; Name: its name, "" if it has none.
Structure BakaShrot_NameResolved Extends BakaShrot_PacketBase
Kind.l
Id.l
Name.s
EndStructure
; Encodes *Answer into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_NameResolvedPacket_Encode(*Answer.BakaShrot_NameResolved, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Answer\Magic = #BakaShrot_ProtocolMagic
*Answer\Version = #BakaShrot_ProtocolVersion
*Answer\PacketType = #BakaShrot_PacketType_NameResolved
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Answer, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Answer\Id) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Answer\Name) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_NameResolvedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Answer.BakaShrot_NameResolved
Protected Value.q
*Answer = AllocateStructure(BakaShrot_NameResolved)
If Not *Answer
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Answer, *MsgPackData) Or *Answer\PacketType <> #BakaShrot_PacketType_NameResolved
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Answer\Kind = Value
; Id
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*Answer\Id = Value
; Name
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Answer\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Answer
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Answer)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,177 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "ResolveNamePacket.pbi"
; One topic or node of a NamesList.
; Origin: where its name comes from, "config" (named in the config) or "id"
; (unnamed, Name is ""). See Server/Storage/Names.pbi.
Structure BakaShrot_NameEntry
Id.l
Name.s
Origin.s
EndStructure
#BakaShrot_MaxNamesListEntries = 65536
; S2C, answers a ListNames, by id.
; Kind: the one asked about. Truncated: 1 if there were more than fit in one
; packet, the first ones by id are listed.
; On the wire: Kind, Truncated, entry count, then each entry's id, name and origin.
Structure BakaShrot_NamesList Extends BakaShrot_PacketBase
Kind.l
Truncated.l
List Entries.BakaShrot_NameEntry()
EndStructure
; Encoded size of the packet's own fields, and of each entry on top of its
; name and origin, rounded up. Used to cut a list before it gets over
; #BakaShrot_MaxPacketSize.
#BakaShrot_NamesListOverhead = 64
#BakaShrot_NamesListEntryOverhead = 16
; Encodes *List into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_NamesListPacket_Encode(*List.BakaShrot_NamesList, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*List\Magic = #BakaShrot_ProtocolMagic
*List\Version = #BakaShrot_ProtocolVersion
*List\PacketType = #BakaShrot_PacketType_NamesList
If ListSize(*List\Entries()) > #BakaShrot_MaxNamesListEntries
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*List, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *List\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, Bool(*List\Truncated)) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, ListSize(*List\Entries())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *List\Entries()
If MsgPackWriteInteger(*MsgPackData, *List\Entries()\Id) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *List\Entries()\Name) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *List\Entries()\Origin) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_NamesListPacket_Decode(*MsgPackData.MsgPackData)
Protected *List.BakaShrot_NamesList
Protected Value.q, Count.q, i.q
*List = AllocateStructure(BakaShrot_NamesList)
If Not *List
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*List, *MsgPackData) Or *List\PacketType <> #BakaShrot_PacketType_NamesList
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*List\Kind = Value
; Truncated
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > 1
Goto DecodeFailed
EndIf
*List\Truncated = Value
; Entries
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 0 Or Count > #BakaShrot_MaxNamesListEntries
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*List\Entries())
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Value < 0 Or Value > #BakaShrot_MaxId
Goto DecodeFailed
EndIf
*List\Entries()\Id = Value
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*List\Entries()\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*List\Entries()\Origin = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *List
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*List)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,101 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, asks the server to store a JSON message.
; Topic: where to push it, a name or an id in digits (Commons/Networking/Names.pbi),
; "" for the topic of the client's authenticated identity. The client's
; [BakaShrot.Client.<name>] PushTopics must allow it.
; The node is always the client's authenticated one, the client can't pick it.
; Answered with a MessagePushed or a RequestRefused.
Structure BakaShrot_PushMessage Extends BakaShrot_PacketBase
Topic.s
JsonData.s
EndStructure
; Encodes *Push into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_PushMessagePacket_Encode(*Push.BakaShrot_PushMessage, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Push\Magic = #BakaShrot_ProtocolMagic
*Push\Version = #BakaShrot_ProtocolVersion
*Push\PacketType = #BakaShrot_PacketType_PushMessage
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Push, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Push\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Push\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_PushMessagePacket_Decode(*MsgPackData.MsgPackData)
Protected *Push.BakaShrot_PushMessage
*Push = AllocateStructure(BakaShrot_PushMessage)
If Not *Push
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Push, *MsgPackData) Or *Push\PacketType <> #BakaShrot_PacketType_PushMessage
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Push\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Push\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Push
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Push)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,84 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; C2S, a raw SQL query to run read-only on the server's database.
; Must be a single SELECT (or WITH ... SELECT), anything after the first statement is ignored.
; Answered with a QueryResult or a RequestRefused.
Structure BakaShrot_QueryRequest Extends BakaShrot_PacketBase
Sql.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_QueryRequestPacket_Encode(*Request.BakaShrot_QueryRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_QueryRequest
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Sql) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_QueryRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_QueryRequest
*Request = AllocateStructure(BakaShrot_QueryRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_QueryRequest
Goto DecodeFailed
EndIf
; Sql
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Sql = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,84 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a QueryRequest with its rows, as JSON:
; {"columns": ["name", ...], "rows": [["value", ...], ...]}
; Every value is a string, or null for NULL: PureBasic doesn't report SQLite's column types.
Structure BakaShrot_QueryResult Extends BakaShrot_PacketBase
JsonResult.s
EndStructure
; Encodes *Result into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_QueryResultPacket_Encode(*Result.BakaShrot_QueryResult, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Result\Magic = #BakaShrot_ProtocolMagic
*Result\Version = #BakaShrot_ProtocolVersion
*Result\PacketType = #BakaShrot_PacketType_QueryResult
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Result, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Result\JsonResult) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_QueryResultPacket_Decode(*MsgPackData.MsgPackData)
Protected *Result.BakaShrot_QueryResult
*Result = AllocateStructure(BakaShrot_QueryResult)
If Not *Result
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Result, *MsgPackData) Or *Result\PacketType <> #BakaShrot_PacketType_QueryResult
Goto DecodeFailed
EndIf
; JsonResult
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Result\JsonResult = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Result
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Result)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,177 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; One message of a ReplicateMessages batch.
Structure BakaShrot_ReplicatedMessage
MessageId.q
JsonData.s
EndStructure
; Most messages a batch may carry, whatever the sender's PeerBatchSize.
; #BakaShrot_ReplicateBatchBytes usually stops a batch well before that.
#BakaShrot_MaxReplicateBatch = 10000
; About how big a batch gets: messages are added while they fit in it, and
; a bigger one goes alone (up to #BakaShrot_MaxMessageSize). Small enough to
; keep each batch's transaction and memory short, like when 64 KB was the
; biggest packet.
#BakaShrot_ReplicateBatchBytes = 65536
; Encoded size of a batch's own fields, and of each message on top of its
; JSON, rounded up. Used to stop a batch before it gets over #BakaShrot_MaxPacketSize.
#BakaShrot_ReplicateBatchOverhead = 64 + 2 * (#BakaShrot_MaxNameLength + 2)
#BakaShrot_ReplicateMessageOverhead = 16
; Peer -> Server, messages the server is missing for one topic/node, in
; message id order, with the message ids they were stored under on their
; origin. Topic and Node are names, never ids (Commons/Networking/Names.pbi):
; the server stores them under its own ids for those names, and refuses
; names it doesn't know.
; On the wire: topic, node, message count, then each message's id and JSON.
; Answered with a MessagePushed carrying the last message's id, or a RequestRefused.
Structure BakaShrot_ReplicateMessages Extends BakaShrot_PacketBase
Topic.s
Node.s
List Messages.BakaShrot_ReplicatedMessage()
EndStructure
; Encodes *Batch into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ReplicateMessagesPacket_Encode(*Batch.BakaShrot_ReplicateMessages, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Batch\Magic = #BakaShrot_ProtocolMagic
*Batch\Version = #BakaShrot_ProtocolVersion
*Batch\PacketType = #BakaShrot_PacketType_ReplicateMessages
If ListSize(*Batch\Messages()) < 1 Or ListSize(*Batch\Messages()) > #BakaShrot_MaxReplicateBatch
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(256)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Batch, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Topic) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Node) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Messages
If MsgPackWriteInteger(*MsgPackData, ListSize(*Batch\Messages())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *Batch\Messages()
If MsgPackWriteInteger(*MsgPackData, *Batch\Messages()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Batch\Messages()\JsonData) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; Message ids must be 1 or more, and strictly increasing.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ReplicateMessagesPacket_Decode(*MsgPackData.MsgPackData)
Protected *Batch.BakaShrot_ReplicateMessages
Protected Value.q, Count.q, i.q, PreviousMessageId.q
*Batch = AllocateStructure(BakaShrot_ReplicateMessages)
If Not *Batch
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Batch, *MsgPackData) Or *Batch\PacketType <> #BakaShrot_PacketType_ReplicateMessages
Goto DecodeFailed
EndIf
; Topic
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Topic = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Topic)
Goto DecodeFailed
EndIf
; Node
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Node = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(*Batch\Node)
Goto DecodeFailed
EndIf
; Message count
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Count = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Count < 1 Or Count > #BakaShrot_MaxReplicateBatch
Goto DecodeFailed
EndIf
; Messages
PreviousMessageId = 0
For i = 1 To Count
AddElement(*Batch\Messages())
; MessageId
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
*Batch\Messages()\MessageId = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Batch\Messages()\MessageId <= PreviousMessageId
Goto DecodeFailed
EndIf
PreviousMessageId = *Batch\Messages()\MessageId
; JsonData
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Batch\Messages()\JsonData = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
Next
ProcedureReturn *Batch
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Batch)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,83 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; S2C, answers a request the server won't fulfill, the connection stays open.
; Reason is only meant for logs and humans.
Structure BakaShrot_RequestRefused Extends BakaShrot_PacketBase
Reason.s
EndStructure
; Encodes *Refused into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_RequestRefusedPacket_Encode(*Refused.BakaShrot_RequestRefused, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Refused\Magic = #BakaShrot_ProtocolMagic
*Refused\Version = #BakaShrot_ProtocolVersion
*Refused\PacketType = #BakaShrot_PacketType_RequestRefused
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Refused, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Refused\Reason) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_RequestRefusedPacket_Decode(*MsgPackData.MsgPackData)
Protected *Refused.BakaShrot_RequestRefused
*Refused = AllocateStructure(BakaShrot_RequestRefused)
If Not *Refused
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Refused, *MsgPackData) Or *Refused\PacketType <> #BakaShrot_PacketType_RequestRefused
Goto DecodeFailed
EndIf
; Reason
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Refused\Reason = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Refused
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Refused)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,107 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; What a ResolveName / NameResolved is about.
#BakaShrot_NameKind_Topic = 1
#BakaShrot_NameKind_Node = 2
; C2S, asks for the server's id and name of a topic or node.
; Kind: #BakaShrot_NameKind_Topic or #BakaShrot_NameKind_Node.
; Ref: a name or an id in digits (Commons/Networking/Names.pbi).
; Answered with a NameResolved, or a RequestRefused if the server doesn't
; know it, or if it's a topic the client may neither push to nor read
; (unless it may query, which reads everything anyway).
Structure BakaShrot_ResolveName Extends BakaShrot_PacketBase
Kind.l
Ref.s
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_ResolveNamePacket_Encode(*Request.BakaShrot_ResolveName, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_ResolveName
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *Request\Kind) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteString(*MsgPackData, *Request\Ref) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_ResolveNamePacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_ResolveName
Protected Value.q
*Request = AllocateStructure(BakaShrot_ResolveName)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_ResolveName
Goto DecodeFailed
EndIf
; Kind
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
Goto DecodeFailed
EndIf
Value = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or (Value <> #BakaShrot_NameKind_Topic And Value <> #BakaShrot_NameKind_Node)
Goto DecodeFailed
EndIf
*Request\Kind = Value
; Ref
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
Goto DecodeFailed
EndIf
*Request\Ref = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success
Goto DecodeFailed
EndIf
ProcedureReturn *Request
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*Request)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,279 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Highest message id a node has for a topic/node id combination.
Structure BakaShrot_SyncPair
TopicId.l
NodeId.l
MessageId.q
EndStructure
; One of the sender's ids, and what it's called: its name, or its id in
; digits if it has none (Commons/Networking/Names.pbi).
Structure BakaShrot_SyncName
Id.l
Name.s
EndStructure
; Biggest lists accepted, the packet size limit keeps the real ones well under it.
#BakaShrot_MaxSyncTopics = 65536
#BakaShrot_MaxSyncNodes = 65536
#BakaShrot_MaxSyncPairs = 65536
#BakaShrot_MaxSyncPatterns = 4096
; Server -> Peer, answers a SyncStateRequest, at every check-in. Ids are the
; sender's own, names are what the peer matches them by: each server has its
; own ids. Only named topics and nodes replicate, and only those named on
; both servers: this is how the peer learns which names this server knows,
; so it never sends anything this server would refuse.
; Topics: the named topics it takes from this peer (its AcceptTopics).
; Nodes: the named nodes it takes from this peer (its AcceptNodes).
; TopicPatterns, NodePatterns: the wildcards ("*", "sensors.*") of its
; AcceptTopics / AcceptNodes: it also takes names it doesn't have yet if
; they match one (Commons/Networking/Names.pbi).
; Pairs: the highest message id it has for each topic/node of those.
; A combination that isn't listed has no message yet.
; Names are names, never ids in digits.
; On the wire: topic count, each topic's id and name, node count, each
; node's id and name, topic pattern count, each pattern, node pattern
; count, each pattern, pair count, then each pair's topic id, node id and
; message id.
Structure BakaShrot_SyncState Extends BakaShrot_PacketBase
List Topics.BakaShrot_SyncName()
List Nodes.BakaShrot_SyncName()
List TopicPatterns.s()
List NodePatterns.s()
List Pairs.BakaShrot_SyncPair()
EndStructure
; Writes a list of ids and names, with its count first.
Procedure.i BakaShrot_SyncStatePacket_WriteNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName())
If MsgPackWriteInteger(*MsgPackData, ListSize(Names())) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ForEach Names()
If MsgPackWriteInteger(*MsgPackData, Names()\Id) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
If MsgPackWriteString(*MsgPackData, Names()\Name) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Writes a list of patterns, with its count first.
Procedure.i BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData.MsgPackData, List Patterns.s())
If MsgPackWriteInteger(*MsgPackData, ListSize(Patterns())) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
ForEach Patterns()
If MsgPackWriteString(*MsgPackData, Patterns()) <> #MsgPack_Error_Success
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Encodes *State into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_SyncStatePacket_Encode(*State.BakaShrot_SyncState, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*State\Magic = #BakaShrot_ProtocolMagic
*State\Version = #BakaShrot_ProtocolVersion
*State\PacketType = #BakaShrot_PacketType_SyncState
If ListSize(*State\Topics()) > #BakaShrot_MaxSyncTopics Or ListSize(*State\Nodes()) > #BakaShrot_MaxSyncNodes Or ListSize(*State\Pairs()) > #BakaShrot_MaxSyncPairs
ProcedureReturn 0
EndIf
If ListSize(*State\TopicPatterns()) > #BakaShrot_MaxSyncPatterns Or ListSize(*State\NodePatterns()) > #BakaShrot_MaxSyncPatterns
ProcedureReturn 0
EndIf
*MsgPackData = MsgPackCreate(64)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*State, *MsgPackData)
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Topics())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WriteNames(*MsgPackData, *State\Nodes())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\TopicPatterns())
Goto EncodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_WritePatterns(*MsgPackData, *State\NodePatterns())
Goto EncodeFailed
EndIf
; Pairs
If MsgPackWriteInteger(*MsgPackData, ListSize(*State\Pairs())) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
ForEach *State\Pairs()
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\TopicId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\NodeId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
If MsgPackWriteInteger(*MsgPackData, *State\Pairs()\MessageId) <> #MsgPack_Error_Success
Goto EncodeFailed
EndIf
Next
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Reads one integer within Minimum-Maximum into *Value\q.
; Returns #False if it's not an integer, couldn't be read, or is out of range.
Procedure.i BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData.MsgPackData, *Value.Quad, Minimum.q, Maximum.q)
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_Integer
ProcedureReturn #False
EndIf
*Value\q = MsgPackReadInteger(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or *Value\q < Minimum Or *Value\q > Maximum
ProcedureReturn #False
EndIf
ProcedureReturn #True
EndProcedure
; Reads a list of ids and names, with its count first. Every name must be a
; valid name, not an id in digits.
; Returns #False if anything is invalid.
Procedure.i BakaShrot_SyncStatePacket_ReadNames(*MsgPackData.MsgPackData, List Names.BakaShrot_SyncName(), MaxCount.i)
Protected Count.q, Value.q, i.q
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, MaxCount)
ProcedureReturn #False
EndIf
For i = 1 To Count
AddElement(Names())
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
ProcedureReturn #False
EndIf
Names()\Id = Value
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
ProcedureReturn #False
EndIf
Names()\Name = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidName(Names()\Name)
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Reads a list of patterns, with its count first. Each one must be a valid
; pattern, see Commons/Networking/Names.pbi.
; Returns #False if anything is invalid.
Procedure.i BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData.MsgPackData, List Patterns.s())
Protected Count.q, i.q
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPatterns)
ProcedureReturn #False
EndIf
For i = 1 To Count
AddElement(Patterns())
If MsgPackFormatCodeToDataType(MsgPackGetFormatCode(*MsgPackData)) <> #MsgPack_DataTypes_String
ProcedureReturn #False
EndIf
Patterns() = MsgPackReadString(*MsgPackData)
If MsgPackLastError(*MsgPackData) <> #MsgPack_Error_Success Or Not BakaShrot_IsValidPattern(Patterns())
ProcedureReturn #False
EndIf
Next
ProcedureReturn #True
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_SyncStatePacket_Decode(*MsgPackData.MsgPackData)
Protected *State.BakaShrot_SyncState
Protected Count.q, Value.q, i.q
*State = AllocateStructure(BakaShrot_SyncState)
If Not *State
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*State, *MsgPackData) Or *State\PacketType <> #BakaShrot_PacketType_SyncState
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Topics(), #BakaShrot_MaxSyncTopics)
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadNames(*MsgPackData, *State\Nodes(), #BakaShrot_MaxSyncNodes)
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\TopicPatterns())
Goto DecodeFailed
EndIf
If Not BakaShrot_SyncStatePacket_ReadPatterns(*MsgPackData, *State\NodePatterns())
Goto DecodeFailed
EndIf
; Pairs
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Count, 0, #BakaShrot_MaxSyncPairs)
Goto DecodeFailed
EndIf
For i = 1 To Count
AddElement(*State\Pairs())
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
Goto DecodeFailed
EndIf
*State\Pairs()\TopicId = Value
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 0, #BakaShrot_MaxId)
Goto DecodeFailed
EndIf
*State\Pairs()\NodeId = Value
If Not BakaShrot_SyncStatePacket_ReadInteger(*MsgPackData, @Value, 1, 9223372036854775807)
Goto DecodeFailed
EndIf
*State\Pairs()\MessageId = Value
Next
ProcedureReturn *State
; Everything read so far is tainted, drop it.
DecodeFailed:
FreeStructure(*State)
ProcedureReturn 0
EndProcedure
@@ -0,0 +1,65 @@
; ============================================================================
; ...
; ============================================================================
XIncludeFile "../Packets.pbi"
; Peer -> Server, asks for the server's sync state, to know which messages it's missing.
; Answered with a SyncState or a RequestRefused. Only carries the base fields.
Structure BakaShrot_SyncStateRequest Extends BakaShrot_PacketBase
EndStructure
; Encodes *Request into a freshly allocated buffer, its base fields are set by this procedure.
; *OutSize receives its size in bytes.
; Returns 0 on failure, the caller owns the returned buffer - free it with FreeMemory.
Procedure.i BakaShrot_SyncStateRequestPacket_Encode(*Request.BakaShrot_SyncStateRequest, *OutSize.Integer)
Protected *MsgPackData.MsgPackData, *Buffer
*Request\Magic = #BakaShrot_ProtocolMagic
*Request\Version = #BakaShrot_ProtocolVersion
*Request\PacketType = #BakaShrot_PacketType_SyncStateRequest
*MsgPackData = MsgPackCreate(16)
If Not *MsgPackData
ProcedureReturn 0
EndIf
If Not BakaShrot_WritePacketBase(*Request, *MsgPackData)
Goto EncodeFailed
EndIf
; Frees *MsgPackData on success, leaves it untouched on failure.
*Buffer = MsgPackFinalize(*MsgPackData)
If Not *Buffer
Goto EncodeFailed
EndIf
*OutSize\i = MemorySize(*Buffer)
ProcedureReturn *Buffer
EncodeFailed:
MsgPackFree(*MsgPackData, #True)
ProcedureReturn 0
EndProcedure
; Decodes the packet at *MsgPackData's current offset into a freshly allocated struct.
; *MsgPackData stays owned by the caller, and should be discarded on failure.
; Returns 0 on failure, the caller owns the returned struct - free it with FreeStructure.
Procedure.i BakaShrot_SyncStateRequestPacket_Decode(*MsgPackData.MsgPackData)
Protected *Request.BakaShrot_SyncStateRequest
*Request = AllocateStructure(BakaShrot_SyncStateRequest)
If Not *Request
ProcedureReturn 0
EndIf
; The base parser doesn't check which packet it is, that's on us.
If Not BakaShrot_ReadPacketBase(*Request, *MsgPackData) Or *Request\PacketType <> #BakaShrot_PacketType_SyncStateRequest
FreeStructure(*Request)
ProcedureReturn 0
EndIf
ProcedureReturn *Request
EndProcedure
+124
View File
@@ -0,0 +1,124 @@
; ============================================================================
; 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
+69
View File
@@ -0,0 +1,69 @@
; ============================================================================
; BakaShrot Signal
;
; Wakes up a thread waiting for something, instead of it polling with Delay():
; Waiter: BakaShrot_Signal_Wait(Signal, TimeoutMs), then checks for work.
; Waker: does the work's setup, then BakaShrot_Signal_Set(Signal).
; Signals don't stack: several Set() before a Wait() wake it once, so the
; waiter must handle everything that's there once woken. A Set() before the
; Wait() isn't lost, the Wait() returns right away.
;
; Windows: an auto-reset event. Elsewhere: a semaphore polled every ms, until
; something better is needed there.
; ============================================================================
CompilerIf #PB_Compiler_OS = #PB_OS_Windows
; Returns 0 on failure.
Procedure.i BakaShrot_Signal_Create()
; Auto-reset, not set.
ProcedureReturn CreateEvent_(0, #False, #False, 0)
EndProcedure
Procedure BakaShrot_Signal_Set(Signal.i)
SetEvent_(Signal)
EndProcedure
; Waits until Signal is set, for up to TimeoutMs.
; Returns #True if it was set, #False if it timed out.
Procedure.i BakaShrot_Signal_Wait(Signal.i, TimeoutMs.i)
; WAIT_OBJECT_0
ProcedureReturn Bool(WaitForSingleObject_(Signal, TimeoutMs) = 0)
EndProcedure
Procedure BakaShrot_Signal_Free(Signal.i)
CloseHandle_(Signal)
EndProcedure
CompilerElse
Procedure.i BakaShrot_Signal_Create()
ProcedureReturn CreateSemaphore(0)
EndProcedure
Procedure BakaShrot_Signal_Set(Signal.i)
SignalSemaphore(Signal)
EndProcedure
Procedure.i BakaShrot_Signal_Wait(Signal.i, TimeoutMs.i)
Protected StartTime.i = ElapsedMilliseconds()
Repeat
If TrySemaphore(Signal)
; Doesn't stack, like the Windows version.
While TrySemaphore(Signal)
Wend
ProcedureReturn #True
EndIf
If ElapsedMilliseconds() - StartTime >= TimeoutMs
ProcedureReturn #False
EndIf
Delay(1)
ForEver
EndProcedure
Procedure BakaShrot_Signal_Free(Signal.i)
FreeSemaphore(Signal)
EndProcedure
CompilerEndIf