diff --git a/bindings/c/bakashrot.h b/bindings/c/bakashrot.h index 5553e2a..4aa2759 100644 --- a/bindings/c/bakashrot.h +++ b/bindings/c/bakashrot.h @@ -18,67 +18,79 @@ extern "C" { #endif // __cplusplus /** - * Why the last call failed: a protocol error code (1-99 a server's - * refusal, the connection still open; 100 and up the client's own), 0 if - * it succeeded. Getters don't change it. + * Makes a client: its handle (1 and up, never reused), 0 if it failed. */ -int32_t BakaShrot_GetLastError(void); +int64_t BakaShrot_CreateClient(void); /** - * Why the last call failed, in words: the server's reason for a refusal, - * the client's otherwise. Empty if it succeeded. + * Frees a client and closes its connection (once a call on it in another + * thread ends): 1, or 0 if it wasn't one. */ -ptrdiff_t BakaShrot_GetRefusalReasonA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_FreeClient(int64_t client); + +/** + * Why the client's last call failed: a protocol error code (1-99 a + * server's refusal, the connection still open; 100 and up the client's + * own), 0 if it succeeded. Getters don't change it. `InvalidArgument` for + * a bad handle. + */ +int32_t BakaShrot_GetLastError(int64_t client); + +/** + * Why the client's last call failed, in words: the server's reason for a + * refusal, the client's otherwise. Empty if it succeeded. + */ +ptrdiff_t BakaShrot_GetRefusalReasonA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetRefusalReasonW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetRefusalReasonW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Sets the CA's certificate, which the server's must be issued by: PEM * text, or the path of a file holding it. Before connecting. */ -ptrdiff_t BakaShrot_SetCaCertificateA(const char *certificate); +ptrdiff_t BakaShrot_SetCaCertificateA(int64_t client, const char *certificate); /** * The same as `BakaShrot_SetCaCertificateA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetCaCertificateW(const uint16_t *certificate); +ptrdiff_t BakaShrot_SetCaCertificateW(int64_t client, const uint16_t *certificate); /** - * Sets this client's certificate, which says its node and its roles: PEM + * Sets the client's certificate, which says its node and its roles: PEM * text, or the path of a file holding it. Before connecting. */ -ptrdiff_t BakaShrot_SetCertificateA(const char *certificate); +ptrdiff_t BakaShrot_SetCertificateA(int64_t client, const char *certificate); /** * The same as `BakaShrot_SetCertificateA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetCertificateW(const uint16_t *certificate); +ptrdiff_t BakaShrot_SetCertificateW(int64_t client, const uint16_t *certificate); /** - * Sets this client's private key, its certificate's: PEM text, or the path + * Sets the client's private key, its certificate's: PEM text, or the path * of a file holding it. Before connecting. */ -ptrdiff_t BakaShrot_SetPrivateKeyA(const char *key); +ptrdiff_t BakaShrot_SetPrivateKeyA(int64_t client, const char *key); /** * The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetPrivateKeyW(const uint16_t *key); +ptrdiff_t BakaShrot_SetPrivateKeyW(int64_t client, const uint16_t *key); /** * Sets the CA's CRL, optional: servers it revokes are refused. PEM text, * or the path of a file holding it (one that isn't there is a * `FileError`); null or empty for none. Before connecting. */ -ptrdiff_t BakaShrot_SetCrlA(const char *crl); +ptrdiff_t BakaShrot_SetCrlA(int64_t client, const char *crl); /** * The same as `BakaShrot_SetCrlA`, in UTF-16. */ -ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl); +ptrdiff_t BakaShrot_SetCrlW(int64_t client, const uint16_t *crl); /** * Connects to the server at `host` (a name or an address) and `port`: @@ -87,57 +99,59 @@ ptrdiff_t BakaShrot_SetCrlW(const uint16_t *crl); * the server refused the certificate, `ServerNotVerified` this client * refused the server's, `NotAllowed` none of its roles is the server's). */ -ptrdiff_t BakaShrot_ConnectA(const char *host, int32_t port); +ptrdiff_t BakaShrot_ConnectA(int64_t client, const char *host, int32_t port); /** * The same as `BakaShrot_ConnectA`, in UTF-16. */ -ptrdiff_t BakaShrot_ConnectW(const uint16_t *host, int32_t port); +ptrdiff_t BakaShrot_ConnectW(int64_t client, const uint16_t *host, int32_t port); /** * 1 while connected: notices when the server closed the connection * (forgotten then: connect again). */ -ptrdiff_t BakaShrot_IsConnected(void); +ptrdiff_t BakaShrot_IsConnected(int64_t client); /** * Closes the connection: 0 if there was none. The settings stay. */ -ptrdiff_t BakaShrot_Disconnect(void); +ptrdiff_t BakaShrot_Disconnect(int64_t client); /** * The node this client is, as the server said when connecting: its * certificate's name. Empty when not connected. */ -ptrdiff_t BakaShrot_GetNodeA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNodeA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetNodeA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetNodeW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Pushes a message (JSON or not) to `topic`, as this client's node: its * id (1 and up), -1 on failure. A push whose answer was lost * (`ConnectionLost`) may have been stored all the same. */ -int64_t BakaShrot_PushMessageToA(const char *topic, const char *data); +int64_t BakaShrot_PushMessageToA(int64_t client, const char *topic, const char *data); /** * The same as `BakaShrot_PushMessageToA`, in UTF-16. */ -int64_t BakaShrot_PushMessageToW(const uint16_t *topic, const uint16_t *data); +int64_t BakaShrot_PushMessageToW(int64_t client, const uint16_t *topic, const uint16_t *data); /** * Gets the latest message of `topic` and `node`, then read with the * `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. */ -ptrdiff_t BakaShrot_GetLatestMessageOfA(const char *topic, const char *node); +ptrdiff_t BakaShrot_GetLatestMessageOfA(int64_t client, const char *topic, const char *node); /** * The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *node); +ptrdiff_t BakaShrot_GetLatestMessageOfW(int64_t client, + const uint16_t *topic, + const uint16_t *node); /** * Gets the messages of `topic` and `node` after id `after` (0 for the @@ -146,12 +160,17 @@ ptrdiff_t BakaShrot_GetLatestMessageOfW(const uint16_t *topic, const uint16_t *n * first is selected; `BakaShrot_SelectMessage()` selects the others, * `BakaShrot_HasMoreMessages()` says whether more follow the last one. */ -int32_t BakaShrot_GetMessagesA(const char *topic, const char *node, int64_t after, int32_t limit); +int32_t BakaShrot_GetMessagesA(int64_t client, + const char *topic, + const char *node, + int64_t after, + int32_t limit); /** * The same as `BakaShrot_GetMessagesA`, in UTF-16. */ -int32_t BakaShrot_GetMessagesW(const uint16_t *topic, +int32_t BakaShrot_GetMessagesW(int64_t client, + const uint16_t *topic, const uint16_t *node, int64_t after, int32_t limit); @@ -159,119 +178,119 @@ int32_t BakaShrot_GetMessagesW(const uint16_t *topic, /** * How many messages the last `GetMessages` or `GetLatestMessageOf` got. */ -int32_t BakaShrot_GetMessageCount(void); +int32_t BakaShrot_GetMessageCount(int64_t client); /** * Selects the message at `index` (0 to the count - 1) for the getters: 0 * if there's none there (`InvalidArgument`), the selection unchanged. */ -ptrdiff_t BakaShrot_SelectMessage(int32_t index); +ptrdiff_t BakaShrot_SelectMessage(int64_t client, int32_t index); /** * 1 if more messages follow the last one the last `GetMessages` got: ask * again after its id. */ -ptrdiff_t BakaShrot_HasMoreMessages(void); +ptrdiff_t BakaShrot_HasMoreMessages(int64_t client); /** * The selected message's id, 0 if none. */ -int64_t BakaShrot_GetMessageId(void); +int64_t BakaShrot_GetMessageId(int64_t client); /** * When the selected message was pushed, by the server it was pushed to: * milliseconds since 1970-01-01 UTC, 0 if none. */ -int64_t BakaShrot_GetMessagePushedAt(void); +int64_t BakaShrot_GetMessagePushedAt(int64_t client); /** * The selected message's attachment's size, 0 without one. */ -int64_t BakaShrot_GetMessageAttachmentSize(void); +int64_t BakaShrot_GetMessageAttachmentSize(int64_t client); /** * 1 if the selected message's attachment is all on this server (a * replicated one may still be on its way). */ -ptrdiff_t BakaShrot_IsMessageAttachmentReady(void); +ptrdiff_t BakaShrot_IsMessageAttachmentReady(int64_t client); /** * The selected message's data, as pushed (JSON or not). */ -ptrdiff_t BakaShrot_GetMessageDataA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageDataA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetMessageDataA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetMessageDataW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageDataW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * The topic the last `GetMessages` or `GetLatestMessageOf` asked for. */ -ptrdiff_t BakaShrot_GetMessageTopicA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageTopicA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetMessageTopicA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetMessageTopicW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageTopicW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * The node the last `GetMessages` or `GetLatestMessageOf` asked for. */ -ptrdiff_t BakaShrot_GetMessageNodeA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageNodeA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetMessageNodeA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetMessageNodeW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetMessageNodeW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Lists the topics with messages that this client may push to or read * (every one if its roles have `list_topics` or `query`): how many, -1 on * failure. Then `BakaShrot_GetNamesList()`. */ -int32_t BakaShrot_ListTopics(void); +int32_t BakaShrot_ListTopics(int64_t client); /** * Lists the nodes with messages in the topics this client may read (every * one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then * `BakaShrot_GetNamesList()`. */ -int32_t BakaShrot_ListNodes(void); +int32_t BakaShrot_ListNodes(int64_t client); /** * The last list, as JSON: * `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` * if some didn't fit. */ -ptrdiff_t BakaShrot_GetNamesListA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNamesListA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetNamesListA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetNamesListW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetNamesListW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Runs read-only SQL on the server (one SELECT or WITH), if this client * may query. Then `BakaShrot_GetQueryResult()`. */ -ptrdiff_t BakaShrot_QueryA(const char *sql); +ptrdiff_t BakaShrot_QueryA(int64_t client, const char *sql); /** * The same as `BakaShrot_QueryA`, in UTF-16. */ -ptrdiff_t BakaShrot_QueryW(const uint16_t *sql); +ptrdiff_t BakaShrot_QueryW(int64_t client, const uint16_t *sql); /** * The last query's result, as JSON: * `{"columns":[...],"rows":[[...],...]}`, every value a string or null. */ -ptrdiff_t BakaShrot_GetQueryResultA(char *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetQueryResultA(int64_t client, char *buffer, ptrdiff_t size); /** * The same as `BakaShrot_GetQueryResultA`, in UTF-16. */ -ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size); +ptrdiff_t BakaShrot_GetQueryResultW(int64_t client, uint16_t *buffer, ptrdiff_t size); /** * Pushes a message with the file at `FilePath` as its attachment (1 byte @@ -280,12 +299,16 @@ ptrdiff_t BakaShrot_GetQueryResultW(uint16_t *buffer, ptrdiff_t size); * read twice (its SHA-256 first): one changed in between is refused * (`DataMismatch`). */ -int64_t BakaShrot_PushMessageWithFileA(const char *topic, const char *data, const char *file_path); +int64_t BakaShrot_PushMessageWithFileA(int64_t client, + const char *topic, + const char *data, + const char *file_path); /** * The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. */ -int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic, +int64_t BakaShrot_PushMessageWithFileW(int64_t client, + const uint16_t *topic, const uint16_t *data, const uint16_t *file_path); @@ -293,7 +316,8 @@ int64_t BakaShrot_PushMessageWithFileW(const uint16_t *topic, * Pushes a message with the `Size` bytes at `Data` as its attachment, as * `BakaShrot_PushMessageWithFileA` does. */ -int64_t BakaShrot_PushMessageWithDataA(const char *topic, +int64_t BakaShrot_PushMessageWithDataA(int64_t client, + const char *topic, const char *data, const void *attachment, int64_t size); @@ -301,7 +325,8 @@ int64_t BakaShrot_PushMessageWithDataA(const char *topic, /** * The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. */ -int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic, +int64_t BakaShrot_PushMessageWithDataW(int64_t client, + const uint16_t *topic, const uint16_t *data, const void *attachment, int64_t size); @@ -313,7 +338,8 @@ int64_t BakaShrot_PushMessageWithDataW(const uint16_t *topic, * `NotReady` if it isn't on this server yet, `AttachmentMismatch`). A * failed one leaves no file. */ -int64_t BakaShrot_SaveAttachmentA(const char *topic, +int64_t BakaShrot_SaveAttachmentA(int64_t client, + const char *topic, const char *node, int64_t message_id, const char *file_path); @@ -321,7 +347,8 @@ int64_t BakaShrot_SaveAttachmentA(const char *topic, /** * The same as `BakaShrot_SaveAttachmentA`, in UTF-16. */ -int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic, +int64_t BakaShrot_SaveAttachmentW(int64_t client, + const uint16_t *topic, const uint16_t *node, int64_t message_id, const uint16_t *file_path); @@ -331,24 +358,30 @@ int64_t BakaShrot_SaveAttachmentW(const uint16_t *topic, * memory, checked with its SHA-256 (`BakaShrot_SaveAttachmentA` for big * ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. */ -int64_t BakaShrot_LoadAttachmentA(const char *topic, const char *node, int64_t message_id); +int64_t BakaShrot_LoadAttachmentA(int64_t client, + const char *topic, + const char *node, + int64_t message_id); /** * The same as `BakaShrot_LoadAttachmentA`, in UTF-16. */ -int64_t BakaShrot_LoadAttachmentW(const uint16_t *topic, const uint16_t *node, int64_t message_id); +int64_t BakaShrot_LoadAttachmentW(int64_t client, + const uint16_t *topic, + const uint16_t *node, + int64_t message_id); /** * Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if * `BufferSize` is enough: returns its size (0 if none), copies nothing if * it doesn't fit (a null `Buffer` asks for the size). */ -int64_t BakaShrot_GetAttachmentData(void *buffer, int64_t buffer_size); +int64_t BakaShrot_GetAttachmentData(int64_t client, void *buffer, int64_t buffer_size); /** * Frees what `BakaShrot_LoadAttachment()` read: 1. */ -ptrdiff_t BakaShrot_FreeAttachmentData(void); +ptrdiff_t BakaShrot_FreeAttachmentData(int64_t client); #ifdef __cplusplus } // extern "C" diff --git a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi index 1308748..1528e25 100644 --- a/bindings/purebasic/BakaShrot_Client_Prototypes.pbi +++ b/bindings/purebasic/BakaShrot_Client_Prototypes.pbi @@ -18,65 +18,74 @@ ; Include this in an app to use bakashrot.dll (libbakashrot.so on Linux): ; XIncludeFile "BakaShrot_Client_Prototypes.pbi" ; If BakaShrot_LoadClient("bakashrot.dll") -; BakaShrot_SetCaCertificate("ca.crt") ; a file, or PEM text -; BakaShrot_SetCertificate("kitchen.crt") -; BakaShrot_SetPrivateKey("kitchen.key") -; If BakaShrot_Connect("10.0.0.2", 7000) -; BakaShrot_PushMessageTo("logs", ~"{\"temp\": 21}") +; Client = BakaShrot_CreateClient() +; BakaShrot_SetCaCertificate(Client, "ca.crt") ; a file, or PEM text +; BakaShrot_SetCertificate(Client, "kitchen.crt") +; BakaShrot_SetPrivateKey(Client, "kitchen.key") +; If BakaShrot_Connect(Client, "10.0.0.2", 7000) +; BakaShrot_PushMessageTo(Client, "logs", ~"{\"temp\": 21}") ; ... ; EndIf +; BakaShrot_FreeClient(Client) ; BakaShrot_UnloadClient() ; EndIf ; +; Every function but BakaShrot_CreateClient() takes the client first (a +; quad). Make as many as needed: each has its own connection and errors. +; ; docs/client.md has what each function does (and ; bindings/c/bakashrot.h, generated from the DLL). The string ; functions are mapped to the DLL's W (UTF-16) variants. After a failed -; call, BakaShrot_GetLastError() tells why: the codes and what to do about -; each are in BakaShrot_ErrorCodes.pbi, next to this file (included below), -; BakaShrot_ErrorName() names them; BakaShrot_GetRefusalReasonString() says -; why in words. _GetNamesList() is -; {"kind":"topic","names":[...],"truncated":false}. +; call, BakaShrot_GetLastError(Client) tells why: the codes and what to do +; about each are in BakaShrot_ErrorCodes.pbi, next to this file (included +; below), BakaShrot_ErrorName() names them; +; BakaShrot_GetRefusalReasonString(Client) says why in words. +; _GetNamesList() is {"kind":"topic","names":[...],"truncated":false}. ; ============================================================================ XIncludeFile "BakaShrot_ErrorCodes.pbi" -PrototypeC.l BakaShrot_GetLastError_Prototype() -PrototypeC.i BakaShrot_GetRefusalReason_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Certificate.p-unicode) -PrototypeC.i BakaShrot_SetCertificate_Prototype(Certificate.p-unicode) -PrototypeC.i BakaShrot_SetPrivateKey_Prototype(PrivateKey.p-unicode) -PrototypeC.i BakaShrot_SetCrl_Prototype(Crl.p-unicode) -PrototypeC.i BakaShrot_Connect_Prototype(Host.p-unicode, Port.l) -PrototypeC.i BakaShrot_IsConnected_Prototype() -PrototypeC.i BakaShrot_Disconnect_Prototype() -PrototypeC.i BakaShrot_GetNode_Prototype(*Buffer, BufferSize.i) -PrototypeC.q BakaShrot_PushMessageTo_Prototype(Topic.p-unicode, JsonData.p-unicode) -PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Topic.p-unicode, Node.p-unicode) -PrototypeC.l BakaShrot_GetMessages_Prototype(Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) -PrototypeC.l BakaShrot_GetMessageCount_Prototype() -PrototypeC.i BakaShrot_SelectMessage_Prototype(Index.l) -PrototypeC.i BakaShrot_HasMoreMessages_Prototype() -PrototypeC.q BakaShrot_GetMessageId_Prototype() -PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype() -PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype() -PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype() -PrototypeC.i BakaShrot_GetMessageData_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_GetMessageTopic_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_GetMessageNode_Prototype(*Buffer, BufferSize.i) -PrototypeC.l BakaShrot_ListTopics_Prototype() -PrototypeC.l BakaShrot_ListNodes_Prototype() -PrototypeC.i BakaShrot_GetNamesList_Prototype(*Buffer, BufferSize.i) -PrototypeC.i BakaShrot_Query_Prototype(Sql.p-unicode) -PrototypeC.i BakaShrot_GetQueryResult_Prototype(*Buffer, BufferSize.i) -PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) -PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) -PrototypeC.q BakaShrot_SaveAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) -PrototypeC.q BakaShrot_LoadAttachment_Prototype(Topic.p-unicode, Node.p-unicode, MessageId.q) -PrototypeC.q BakaShrot_GetAttachmentData_Prototype(*Buffer, BufferSize.q) -PrototypeC.i BakaShrot_FreeAttachmentData_Prototype() +PrototypeC.q BakaShrot_CreateClient_Prototype() +PrototypeC.i BakaShrot_FreeClient_Prototype(Client.q) +PrototypeC.l BakaShrot_GetLastError_Prototype(Client.q) +PrototypeC.i BakaShrot_GetRefusalReason_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_SetCaCertificate_Prototype(Client.q, Certificate.p-unicode) +PrototypeC.i BakaShrot_SetCertificate_Prototype(Client.q, Certificate.p-unicode) +PrototypeC.i BakaShrot_SetPrivateKey_Prototype(Client.q, PrivateKey.p-unicode) +PrototypeC.i BakaShrot_SetCrl_Prototype(Client.q, Crl.p-unicode) +PrototypeC.i BakaShrot_Connect_Prototype(Client.q, Host.p-unicode, Port.l) +PrototypeC.i BakaShrot_IsConnected_Prototype(Client.q) +PrototypeC.i BakaShrot_Disconnect_Prototype(Client.q) +PrototypeC.i BakaShrot_GetNode_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.q BakaShrot_PushMessageTo_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode) +PrototypeC.i BakaShrot_GetLatestMessageOf_Prototype(Client.q, Topic.p-unicode, Node.p-unicode) +PrototypeC.l BakaShrot_GetMessages_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, AfterMessageId.q, Limit.l) +PrototypeC.l BakaShrot_GetMessageCount_Prototype(Client.q) +PrototypeC.i BakaShrot_SelectMessage_Prototype(Client.q, Index.l) +PrototypeC.i BakaShrot_HasMoreMessages_Prototype(Client.q) +PrototypeC.q BakaShrot_GetMessageId_Prototype(Client.q) +PrototypeC.q BakaShrot_GetMessagePushedAt_Prototype(Client.q) +PrototypeC.q BakaShrot_GetMessageAttachmentSize_Prototype(Client.q) +PrototypeC.i BakaShrot_IsMessageAttachmentReady_Prototype(Client.q) +PrototypeC.i BakaShrot_GetMessageData_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetMessageTopic_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_GetMessageNode_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.l BakaShrot_ListTopics_Prototype(Client.q) +PrototypeC.l BakaShrot_ListNodes_Prototype(Client.q) +PrototypeC.i BakaShrot_GetNamesList_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.i BakaShrot_Query_Prototype(Client.q, Sql.p-unicode) +PrototypeC.i BakaShrot_GetQueryResult_Prototype(Client.q, *Buffer, BufferSize.i) +PrototypeC.q BakaShrot_PushMessageWithFile_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, FilePath.p-unicode) +PrototypeC.q BakaShrot_PushMessageWithData_Prototype(Client.q, Topic.p-unicode, JsonData.p-unicode, *Data, Size.q) +PrototypeC.q BakaShrot_SaveAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q, FilePath.p-unicode) +PrototypeC.q BakaShrot_LoadAttachment_Prototype(Client.q, Topic.p-unicode, Node.p-unicode, MessageId.q) +PrototypeC.q BakaShrot_GetAttachmentData_Prototype(Client.q, *Buffer, BufferSize.q) +PrototypeC.i BakaShrot_FreeAttachmentData_Prototype(Client.q) +Global BakaShrot_CreateClient.BakaShrot_CreateClient_Prototype +Global BakaShrot_FreeClient.BakaShrot_FreeClient_Prototype Global BakaShrot_GetLastError.BakaShrot_GetLastError_Prototype Global BakaShrot_GetRefusalReason.BakaShrot_GetRefusalReason_Prototype Global BakaShrot_SetCaCertificate.BakaShrot_SetCaCertificate_Prototype @@ -151,40 +160,42 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) BakaShrot_ClientMissing = "" ; PureBasic strings are UTF-16, so the W variants are used. - BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") - BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") - BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") - BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW") - BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW") - BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW") - BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") - BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") - BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") - BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW") - BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") - BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") - BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW") - BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount") - BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage") - BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages") - BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId") - BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt") + BakaShrot_CreateClient = BakaShrot_ClientFunction("BakaShrot_CreateClient") + BakaShrot_FreeClient = BakaShrot_ClientFunction("BakaShrot_FreeClient") + BakaShrot_GetLastError = BakaShrot_ClientFunction("BakaShrot_GetLastError") + BakaShrot_GetRefusalReason = BakaShrot_ClientFunction("BakaShrot_GetRefusalReasonW") + BakaShrot_SetCaCertificate = BakaShrot_ClientFunction("BakaShrot_SetCaCertificateW") + BakaShrot_SetCertificate = BakaShrot_ClientFunction("BakaShrot_SetCertificateW") + BakaShrot_SetPrivateKey = BakaShrot_ClientFunction("BakaShrot_SetPrivateKeyW") + BakaShrot_SetCrl = BakaShrot_ClientFunction("BakaShrot_SetCrlW") + BakaShrot_Connect = BakaShrot_ClientFunction("BakaShrot_ConnectW") + BakaShrot_IsConnected = BakaShrot_ClientFunction("BakaShrot_IsConnected") + BakaShrot_Disconnect = BakaShrot_ClientFunction("BakaShrot_Disconnect") + BakaShrot_GetNode = BakaShrot_ClientFunction("BakaShrot_GetNodeW") + BakaShrot_PushMessageTo = BakaShrot_ClientFunction("BakaShrot_PushMessageToW") + BakaShrot_GetLatestMessageOf = BakaShrot_ClientFunction("BakaShrot_GetLatestMessageOfW") + BakaShrot_GetMessages = BakaShrot_ClientFunction("BakaShrot_GetMessagesW") + BakaShrot_GetMessageCount = BakaShrot_ClientFunction("BakaShrot_GetMessageCount") + BakaShrot_SelectMessage = BakaShrot_ClientFunction("BakaShrot_SelectMessage") + BakaShrot_HasMoreMessages = BakaShrot_ClientFunction("BakaShrot_HasMoreMessages") + BakaShrot_GetMessageId = BakaShrot_ClientFunction("BakaShrot_GetMessageId") + BakaShrot_GetMessagePushedAt = BakaShrot_ClientFunction("BakaShrot_GetMessagePushedAt") BakaShrot_GetMessageAttachmentSize = BakaShrot_ClientFunction("BakaShrot_GetMessageAttachmentSize") BakaShrot_IsMessageAttachmentReady = BakaShrot_ClientFunction("BakaShrot_IsMessageAttachmentReady") - BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") - BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") - BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") - BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics") - BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes") - BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW") - BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW") - BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW") - BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW") - BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") - BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") - BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW") - BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData") - BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData") + BakaShrot_GetMessageData = BakaShrot_ClientFunction("BakaShrot_GetMessageDataW") + BakaShrot_GetMessageTopic = BakaShrot_ClientFunction("BakaShrot_GetMessageTopicW") + BakaShrot_GetMessageNode = BakaShrot_ClientFunction("BakaShrot_GetMessageNodeW") + BakaShrot_ListTopics = BakaShrot_ClientFunction("BakaShrot_ListTopics") + BakaShrot_ListNodes = BakaShrot_ClientFunction("BakaShrot_ListNodes") + BakaShrot_GetNamesList = BakaShrot_ClientFunction("BakaShrot_GetNamesListW") + BakaShrot_Query = BakaShrot_ClientFunction("BakaShrot_QueryW") + BakaShrot_GetQueryResult = BakaShrot_ClientFunction("BakaShrot_GetQueryResultW") + BakaShrot_PushMessageWithFile = BakaShrot_ClientFunction("BakaShrot_PushMessageWithFileW") + BakaShrot_PushMessageWithData = BakaShrot_ClientFunction("BakaShrot_PushMessageWithDataW") + BakaShrot_SaveAttachment = BakaShrot_ClientFunction("BakaShrot_SaveAttachmentW") + BakaShrot_LoadAttachment = BakaShrot_ClientFunction("BakaShrot_LoadAttachmentW") + BakaShrot_GetAttachmentData = BakaShrot_ClientFunction("BakaShrot_GetAttachmentData") + BakaShrot_FreeAttachmentData = BakaShrot_ClientFunction("BakaShrot_FreeAttachmentData") If BakaShrot_ClientMissing <> "" BakaShrot_UnloadClient() @@ -194,18 +205,21 @@ Procedure.i BakaShrot_LoadClient(DllPath.s) EndProcedure -; Calls a string getter of the DLL (Getter(*Buffer, BufferSize)) and +; Calls a client's string getter (Getter(Client, *Buffer, BufferSize)) and ; returns the string: asks for the size, then copies. -PrototypeC.i BakaShrot_StringGetter_Prototype(*Buffer, BufferSize.i) -Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) +PrototypeC.i BakaShrot_StringGetter_Prototype(Client.q, *Buffer, BufferSize.i) +Procedure.s BakaShrot_GetString(Client.q, Getter.BakaShrot_StringGetter_Prototype) Protected *Buffer, BufferSize.i, Text.s - BufferSize = Getter(0, 0) + BufferSize = Getter(Client, 0, 0) + If BufferSize <= 0 + ProcedureReturn "" + EndIf *Buffer = AllocateMemory(BufferSize) If Not *Buffer ProcedureReturn "" EndIf - Getter(*Buffer, BufferSize) + Getter(Client, *Buffer, BufferSize) Text = PeekS(*Buffer, -1, #PB_Unicode) FreeMemory(*Buffer) @@ -213,32 +227,32 @@ Procedure.s BakaShrot_GetString(Getter.BakaShrot_StringGetter_Prototype) EndProcedure ; The string getters, as strings. -Procedure.s BakaShrot_GetRefusalReasonString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetRefusalReason) +Procedure.s BakaShrot_GetRefusalReasonString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetRefusalReason) EndProcedure -Procedure.s BakaShrot_GetNodeString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetNode) +Procedure.s BakaShrot_GetNodeString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNode) EndProcedure -Procedure.s BakaShrot_GetMessageDataString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageData) +Procedure.s BakaShrot_GetMessageDataString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageData) EndProcedure -Procedure.s BakaShrot_GetMessageTopicString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageTopic) +Procedure.s BakaShrot_GetMessageTopicString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageTopic) EndProcedure -Procedure.s BakaShrot_GetMessageNodeString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetMessageNode) +Procedure.s BakaShrot_GetMessageNodeString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetMessageNode) EndProcedure -Procedure.s BakaShrot_GetNamesListString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetNamesList) +Procedure.s BakaShrot_GetNamesListString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetNamesList) EndProcedure -Procedure.s BakaShrot_GetQueryResultString() - ProcedureReturn BakaShrot_GetString(BakaShrot_GetQueryResult) +Procedure.s BakaShrot_GetQueryResultString(Client.q) + ProcedureReturn BakaShrot_GetString(Client, BakaShrot_GetQueryResult) EndProcedure @@ -246,18 +260,29 @@ EndProcedure ; IDE), not when it's included by an app. ; ClientExample ; Pushes a message to "logs", reads it back, pushes one with an -; attachment and reads that back, lists the topics. +; attachment and reads that back, lists the topics; then a second client +; connected at the same time reads it too. CompilerIf #PB_Compiler_IsMainFile - Define Id.q, Size.q, *Attachment, *Copy + Define Client.q, Second.q, Id.q, Size.q, *Attachment, *Copy - ; Prints why the last call failed, then ends. - Procedure Failed(What.s) - PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) + ; Prints why a client's last call failed, then ends. + Procedure Failed(Client.q, What.s) + PrintN(What + " failed: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client)) BakaShrot_UnloadClient() End 1 EndProcedure + ; A new client, connected with the certificates given. + Procedure.q Connected(What.s) + Protected Client.q = BakaShrot_CreateClient() + If Not BakaShrot_SetCaCertificate(Client, ProgramParameter(1)) : Failed(Client, What + ": setting the CA's certificate") : EndIf + If Not BakaShrot_SetCertificate(Client, ProgramParameter(2)) : Failed(Client, What + ": setting the certificate") : EndIf + If Not BakaShrot_SetPrivateKey(Client, ProgramParameter(3)) : Failed(Client, What + ": setting the private key") : EndIf + If Not BakaShrot_Connect(Client, ProgramParameter(4), Val(ProgramParameter(5))) : Failed(Client, What + ": connecting") : EndIf + ProcedureReturn Client + EndProcedure + OpenConsole() If CountProgramParameters() < 6 PrintN("Usage: ClientExample ") @@ -269,28 +294,25 @@ CompilerIf #PB_Compiler_IsMainFile End 1 EndIf - If Not BakaShrot_SetCaCertificate(ProgramParameter(1)) : Failed("Setting the CA's certificate") : EndIf - If Not BakaShrot_SetCertificate(ProgramParameter(2)) : Failed("Setting the certificate") : EndIf - If Not BakaShrot_SetPrivateKey(ProgramParameter(3)) : Failed("Setting the private key") : EndIf - If Not BakaShrot_Connect(ProgramParameter(4), Val(ProgramParameter(5))) : Failed("Connecting") : EndIf - PrintN("Connected as " + BakaShrot_GetNodeString()) + Client = Connected("The client") + PrintN("Client #" + Str(Client) + " connected as " + BakaShrot_GetNodeString(Client)) - Id = BakaShrot_PushMessageTo("logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}") - If Id < 1 : Failed("Pushing") : EndIf + Id = BakaShrot_PushMessageTo(Client, "logs", ~"{\"from\": \"PureBasic\", \"text\": \"hello\"}") + If Id < 1 : Failed(Client, "Pushing") : EndIf PrintN("Pushed #" + Str(Id)) - If Not BakaShrot_GetLatestMessageOf("logs", BakaShrot_GetNodeString()) : Failed("Reading") : EndIf - PrintN("Latest: #" + Str(BakaShrot_GetMessageId()) + " " + BakaShrot_GetMessageDataString()) + If Not BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) : Failed(Client, "Reading") : EndIf + PrintN("Latest: #" + Str(BakaShrot_GetMessageId(Client)) + " " + BakaShrot_GetMessageDataString(Client)) *Attachment = AllocateMemory(3000) FillMemory(*Attachment, 3000, 42, #PB_Byte) - Id = BakaShrot_PushMessageWithData("logs", ~"{\"photo\": 1}", *Attachment, 3000) - If Id < 1 : Failed("Pushing an attachment") : EndIf - Size = BakaShrot_LoadAttachment("logs", BakaShrot_GetNodeString(), Id) - If Size < 0 : Failed("Reading the attachment") : EndIf + Id = BakaShrot_PushMessageWithData(Client, "logs", ~"{\"photo\": 1}", *Attachment, 3000) + If Id < 1 : Failed(Client, "Pushing an attachment") : EndIf + Size = BakaShrot_LoadAttachment(Client, "logs", BakaShrot_GetNodeString(Client), Id) + If Size < 0 : Failed(Client, "Reading the attachment") : EndIf *Copy = AllocateMemory(Size) - BakaShrot_GetAttachmentData(*Copy, Size) - BakaShrot_FreeAttachmentData() + BakaShrot_GetAttachmentData(Client, *Copy, Size) + BakaShrot_FreeAttachmentData(Client) If CompareMemory(*Attachment, *Copy, 3000) PrintN("Pushed #" + Str(Id) + " with " + Str(Size) + " bytes, read back the same") Else @@ -299,15 +321,28 @@ CompilerIf #PB_Compiler_IsMainFile EndIf FreeMemory(*Attachment) : FreeMemory(*Copy) - If BakaShrot_ListTopics() < 0 : Failed("Listing") : EndIf - PrintN("Topics: " + BakaShrot_GetNamesListString()) + If BakaShrot_ListTopics(Client) < 0 : Failed(Client, "Listing") : EndIf + PrintN("Topics: " + BakaShrot_GetNamesListString(Client)) - If BakaShrot_PushMessageTo("nothing", "{}") < 0 - PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError()) + ", " + BakaShrot_GetRefusalReasonString()) + If BakaShrot_PushMessageTo(Client, "nothing", "{}") < 0 + PrintN("A push to a topic it may not push to: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client)) + ", " + BakaShrot_GetRefusalReasonString(Client)) EndIf - BakaShrot_Disconnect() - PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected())) + ; A second client, connected at the same time. + Second = Connected("The second client") + If Not BakaShrot_GetLatestMessageOf(Second, "logs", BakaShrot_GetNodeString(Second)) : Failed(Second, "The second client reading") : EndIf + PrintN("Second client #" + Str(Second) + ", both connected (" + Str(BakaShrot_IsConnected(Client)) + Str(BakaShrot_IsConnected(Second)) + "), its latest: #" + Str(BakaShrot_GetMessageId(Second))) + ; Its errors are its own: the first client's last call succeeds, its fails. + BakaShrot_GetLatestMessageOf(Client, "logs", BakaShrot_GetNodeString(Client)) + If BakaShrot_PushMessageTo(Second, "nothing", "{}") < 0 + PrintN("Its own error: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second)) + ", the first client's: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Client))) + EndIf + BakaShrot_FreeClient(Second) + PrintN("Freed, IsConnected: " + Str(BakaShrot_IsConnected(Second)) + ", its error now: " + BakaShrot_ErrorName(BakaShrot_GetLastError(Second))) + + BakaShrot_Disconnect(Client) + PrintN("IsConnected after disconnecting: " + Str(BakaShrot_IsConnected(Client))) + BakaShrot_FreeClient(Client) BakaShrot_UnloadClient() End 0 diff --git a/bindings/python/bakashrot.py b/bindings/python/bakashrot.py index a84e14e..f65d6f9 100644 --- a/bindings/python/bakashrot.py +++ b/bindings/python/bakashrot.py @@ -37,9 +37,9 @@ numbers as the DLL's BakaShrot_GetLastError()): A push whose answer was lost (ConnectionLostError) may have been stored all the same: pushed again, it's stored twice. Delivery is at least once. -The DLL holds a single connection per process: only one Client may be -connected at a time. Calls are serialized with a lock, so a Client can be -shared between threads, one request at a time. +Each Client has its own client in the DLL, so several can be connected at +once, from different threads. A Client's own calls are serialized with a +lock: one can be shared between threads, one request at a time. The DLL is looked for, in order: the dll_path given, the BAKASHROT_DLL environment variable, next to this file, then in the current directory. @@ -237,41 +237,44 @@ class _Dll: self.path = path I, L, Q, P, S = ctypes.c_ssize_t, ctypes.c_int32, ctypes.c_int64, ctypes.c_char_p, ctypes.c_void_p + H = Q # a client's handle signatures = { - "BakaShrot_GetLastError": (L, []), - "BakaShrot_GetRefusalReasonA": (I, [S, I]), - "BakaShrot_SetCaCertificateA": (I, [P]), - "BakaShrot_SetCertificateA": (I, [P]), - "BakaShrot_SetPrivateKeyA": (I, [P]), - "BakaShrot_SetCrlA": (I, [P]), - "BakaShrot_ConnectA": (I, [P, L]), - "BakaShrot_IsConnected": (I, []), - "BakaShrot_Disconnect": (I, []), - "BakaShrot_GetNodeA": (I, [S, I]), - "BakaShrot_PushMessageToA": (Q, [P, P]), - "BakaShrot_GetLatestMessageOfA": (I, [P, P]), - "BakaShrot_GetMessagesA": (L, [P, P, Q, L]), - "BakaShrot_GetMessageCount": (L, []), - "BakaShrot_SelectMessage": (I, [L]), - "BakaShrot_HasMoreMessages": (I, []), - "BakaShrot_GetMessageId": (Q, []), - "BakaShrot_GetMessagePushedAt": (Q, []), - "BakaShrot_GetMessageAttachmentSize": (Q, []), - "BakaShrot_IsMessageAttachmentReady": (I, []), - "BakaShrot_GetMessageTopicA": (I, [S, I]), - "BakaShrot_GetMessageNodeA": (I, [S, I]), - "BakaShrot_GetMessageDataA": (I, [S, I]), - "BakaShrot_ListTopics": (L, []), - "BakaShrot_ListNodes": (L, []), - "BakaShrot_GetNamesListA": (I, [S, I]), - "BakaShrot_QueryA": (I, [P]), - "BakaShrot_GetQueryResultA": (I, [S, I]), - "BakaShrot_PushMessageWithFileA": (Q, [P, P, P]), - "BakaShrot_PushMessageWithDataA": (Q, [P, P, P, Q]), - "BakaShrot_SaveAttachmentA": (Q, [P, P, Q, P]), - "BakaShrot_LoadAttachmentA": (Q, [P, P, Q]), - "BakaShrot_GetAttachmentData": (Q, [S, Q]), - "BakaShrot_FreeAttachmentData": (I, []), + "BakaShrot_CreateClient": (Q, []), + "BakaShrot_FreeClient": (I, [H]), + "BakaShrot_GetLastError": (L, [H]), + "BakaShrot_GetRefusalReasonA": (I, [H, S, I]), + "BakaShrot_SetCaCertificateA": (I, [H, P]), + "BakaShrot_SetCertificateA": (I, [H, P]), + "BakaShrot_SetPrivateKeyA": (I, [H, P]), + "BakaShrot_SetCrlA": (I, [H, P]), + "BakaShrot_ConnectA": (I, [H, P, L]), + "BakaShrot_IsConnected": (I, [H]), + "BakaShrot_Disconnect": (I, [H]), + "BakaShrot_GetNodeA": (I, [H, S, I]), + "BakaShrot_PushMessageToA": (Q, [H, P, P]), + "BakaShrot_GetLatestMessageOfA": (I, [H, P, P]), + "BakaShrot_GetMessagesA": (L, [H, P, P, Q, L]), + "BakaShrot_GetMessageCount": (L, [H]), + "BakaShrot_SelectMessage": (I, [H, L]), + "BakaShrot_HasMoreMessages": (I, [H]), + "BakaShrot_GetMessageId": (Q, [H]), + "BakaShrot_GetMessagePushedAt": (Q, [H]), + "BakaShrot_GetMessageAttachmentSize": (Q, [H]), + "BakaShrot_IsMessageAttachmentReady": (I, [H]), + "BakaShrot_GetMessageTopicA": (I, [H, S, I]), + "BakaShrot_GetMessageNodeA": (I, [H, S, I]), + "BakaShrot_GetMessageDataA": (I, [H, S, I]), + "BakaShrot_ListTopics": (L, [H]), + "BakaShrot_ListNodes": (L, [H]), + "BakaShrot_GetNamesListA": (I, [H, S, I]), + "BakaShrot_QueryA": (I, [H, P]), + "BakaShrot_GetQueryResultA": (I, [H, S, I]), + "BakaShrot_PushMessageWithFileA": (Q, [H, P, P, P]), + "BakaShrot_PushMessageWithDataA": (Q, [H, P, P, P, Q]), + "BakaShrot_SaveAttachmentA": (Q, [H, P, P, Q, P]), + "BakaShrot_LoadAttachmentA": (Q, [H, P, P, Q]), + "BakaShrot_GetAttachmentData": (Q, [H, S, Q]), + "BakaShrot_FreeAttachmentData": (I, [H]), } for name, (restype, argtypes) in signatures.items(): try: @@ -280,15 +283,16 @@ class _Dll: raise BakaShrotError(f"{path} has no {name}, is it an older build?", ErrorCode.INTERNAL) from error function.restype = restype function.argtypes = argtypes + # BakaShrot_PushMessageToA as PushMessageToA. setattr(self, name[len("BakaShrot_"):], function) - def string(self, getter) -> str: - """Calls a string getter: asks for the size, then copies (UTF-8).""" - size = getter(None, 0) + def string(self, getter, handle: int) -> str: + """Calls a client's string getter: asks for the size, then copies (UTF-8).""" + size = getter(handle, None, 0) if size <= 1: return "" buffer = ctypes.create_string_buffer(size) - getter(buffer, size) + getter(handle, buffer, size) return buffer.raw[: size - 1].decode("utf-8") @@ -309,8 +313,6 @@ class Client: its private key, the CA's CRL (servers it revokes are refused). """ - _connected_client: Optional["Client"] = None - def __init__(self, server: str, ca: str, certificate: str, key: str, crl: Optional[str] = None, dll_path: Optional[str] = None): self._dll = _Dll.get(dll_path) @@ -321,6 +323,8 @@ class Client: self.key = os.fspath(key) self.crl = os.fspath(crl) if crl else None self.node = "" + # Its client in the DLL, from connect() to close(). + self._handle: Optional[int] = None @classmethod def from_file(cls, path: Union[str, os.PathLike], dll_path: Optional[str] = None) -> "Client": @@ -360,34 +364,44 @@ class Client: def connect(self) -> "Client": """Connects. Raises ConnectionLostError when the server can't be reached (CONNECT_FAILED), AuthError when a certificate is refused, - BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR) or - another Client holding the DLL's connection (ALREADY_CONNECTED).""" + BakaShrotError on a bad setting (INVALID_ARGUMENT, FILE_ERROR).""" with self._lock: - owner = Client._connected_client - if owner is not None and owner is not self and owner.connected: - raise BakaShrotError("The DLL holds one connection, another Client is connected", ErrorCode.ALREADY_CONNECTED) if self.connected: return self dll = self._dll + if self._handle is None: + handle = dll.CreateClient() + if handle < 1: + raise BakaShrotError("The DLL made no client", ErrorCode.INTERNAL) + self._handle = handle + handle = self._handle for setter, value in ((dll.SetCaCertificateA, self.ca), (dll.SetCertificateA, self.certificate), (dll.SetPrivateKeyA, self.key), (dll.SetCrlA, self.crl or "")): - if not setter(value.encode("utf-8")): + if not setter(handle, value.encode("utf-8")): raise self._failed("Certificates") - if not dll.ConnectA(self.host.encode("utf-8"), self.port): + if not dll.ConnectA(handle, self.host.encode("utf-8"), self.port): raise self._failed(f"Connect to {self.host}:{self.port}", connecting=True) - self.node = dll.string(dll.GetNodeA) - Client._connected_client = self + self.node = dll.string(dll.GetNodeA, handle) return self def close(self) -> None: + """Disconnects, and frees its client in the DLL. connect() again + reconnects.""" with self._lock: - if Client._connected_client is self: - self._dll.Disconnect() - Client._connected_client = None + if self._handle is not None: + self._dll.FreeClient(self._handle) + self._handle = None + + def __del__(self): + try: + self.close() + except Exception: # noqa: BLE001 - the interpreter may be shutting down + pass @property def connected(self) -> bool: - return Client._connected_client is self and bool(self._dll.IsConnected()) + handle = self._handle + return handle is not None and bool(self._dll.IsConnected(handle)) def __enter__(self) -> "Client": return self.connect() @@ -401,15 +415,13 @@ class Client: def _failed(self, what: str, connecting: bool = False) -> BakaShrotError: """The error for a failed call, by the DLL's BakaShrot_GetLastError().""" - code = _error_code(self._dll.GetLastError()) - reason = self._dll.string(self._dll.GetRefusalReasonA) + code = _error_code(self._dll.GetLastError(self._handle)) + reason = self._dll.string(self._dll.GetRefusalReasonA, self._handle) if connecting and code in (ErrorCode.AUTH_REJECTED, ErrorCode.SERVER_NOT_VERIFIED, ErrorCode.NOT_ALLOWED, ErrorCode.VERSION_MISMATCH): return AuthError(f"{what}: {reason}", code) if isinstance(code, int) and 1 <= int(code) <= 99: return RefusedError(reason, code) - if not self._dll.IsConnected() and Client._connected_client is self: - Client._connected_client = None name = code.name if isinstance(code, ErrorCode) else str(code) message = f"{what} ({name}): {reason or 'failed'}" if code in (ErrorCode.NOT_CONNECTED, ErrorCode.CONNECT_FAILED, ErrorCode.CONNECTION_LOST, ErrorCode.PROTOCOL_ERROR): @@ -435,13 +447,13 @@ class Client: with self._lock: self._check_connected() if attachment is None: - message_id = self._dll.PushMessageToA(_name(topic), encoded) + message_id = self._dll.PushMessageToA(self._handle, _name(topic), encoded) elif isinstance(attachment, (bytes, bytearray, memoryview)): raw = bytes(attachment) - message_id = self._dll.PushMessageWithDataA(_name(topic), encoded, raw, len(raw)) + message_id = self._dll.PushMessageWithDataA(self._handle, _name(topic), encoded, raw, len(raw)) else: path = os.fspath(attachment).encode("utf-8") - message_id = self._dll.PushMessageWithFileA(_name(topic), encoded, path) + message_id = self._dll.PushMessageWithFileA(self._handle, _name(topic), encoded, path) if message_id < 1: raise self._failed("Push") return message_id @@ -452,15 +464,15 @@ class Client: (NOT_FOUND) or it isn't on this server yet (NOT_READY).""" with self._lock: self._check_connected() - size = self._dll.LoadAttachmentA(_name(topic), _name(node), int(message_id)) + size = self._dll.LoadAttachmentA(self._handle, _name(topic), _name(node), int(message_id)) if size < 0: raise self._failed("Attachment") try: buffer = ctypes.create_string_buffer(size) - self._dll.GetAttachmentData(buffer, size) + self._dll.GetAttachmentData(self._handle, buffer, size) return buffer.raw[:size] finally: - self._dll.FreeAttachmentData() + self._dll.FreeAttachmentData(self._handle) def save_attachment(self, topic: str, node: str, message_id: int, path: Union[str, os.PathLike]) -> int: """Saves the attachment of a message as path (replaced), a part at a @@ -468,23 +480,24 @@ class Client: leaves no file.""" with self._lock: self._check_connected() - size = self._dll.SaveAttachmentA(_name(topic), _name(node), int(message_id), + size = self._dll.SaveAttachmentA(self._handle, _name(topic), _name(node), int(message_id), os.fspath(path).encode("utf-8")) if size < 0: raise self._failed("Attachment") return size def _current(self) -> Message: - dll = self._dll - return Message(dll.GetMessageId(), dll.string(dll.GetMessageTopicA), dll.string(dll.GetMessageNodeA), - dll.string(dll.GetMessageDataA), dll.GetMessagePushedAt(), dll.GetMessageAttachmentSize(), - bool(dll.IsMessageAttachmentReady())) + dll, handle = self._dll, self._handle + return Message(dll.GetMessageId(handle), dll.string(dll.GetMessageTopicA, handle), + dll.string(dll.GetMessageNodeA, handle), dll.string(dll.GetMessageDataA, handle), + dll.GetMessagePushedAt(handle), dll.GetMessageAttachmentSize(handle), + bool(dll.IsMessageAttachmentReady(handle))) def latest(self, topic: str, node: str) -> Optional[Message]: """The latest message of topic/node, None if there's none yet.""" with self._lock: self._check_connected() - if not self._dll.GetLatestMessageOfA(_name(topic), _name(node)): + if not self._dll.GetLatestMessageOfA(self._handle, _name(topic), _name(node)): error = self._failed("Latest message") if isinstance(error, RefusedError) and error.code == ErrorCode.NOT_FOUND: return None @@ -503,14 +516,14 @@ class Client: with self._lock: self._check_connected() dll = self._dll - count = dll.GetMessagesA(_name(topic), _name(node), after, limit) + count = dll.GetMessagesA(self._handle, _name(topic), _name(node), after, limit) if count < 0: raise self._failed("Get messages") messages = [] for index in range(count): - dll.SelectMessage(index) + dll.SelectMessage(self._handle, index) messages.append(self._current()) - return MessagesPage(messages, bool(dll.HasMoreMessages())) + return MessagesPage(messages, bool(dll.HasMoreMessages(self._handle))) def iter_messages(self, topic: str, node: str, after: int = 0, batch: int = 1000) -> Iterator[Message]: """Every message of topic/node after `after`, asking for batch at a @@ -554,9 +567,9 @@ class Client: def _list(self, function, what: str) -> NamesList: with self._lock: self._check_connected() - if function() < 0: + if function(self._handle) < 0: raise self._failed(what) - parsed = json.loads(self._dll.string(self._dll.GetNamesListA)) + parsed = json.loads(self._dll.string(self._dll.GetNamesListA, self._handle)) return NamesList(parsed["kind"], parsed["names"], bool(parsed["truncated"])) def query_raw(self, sql: str) -> str: @@ -568,9 +581,9 @@ class Client: query is refused: RefusedError "malformed JSON".""" with self._lock: self._check_connected() - if not self._dll.QueryA(sql.encode("utf-8")): + if not self._dll.QueryA(self._handle, sql.encode("utf-8")): raise self._failed("Query") - return self._dll.string(self._dll.GetQueryResultA) + return self._dll.string(self._dll.GetQueryResultA, self._handle) def query(self, sql: str) -> list: """query_raw(), as a list of dicts, one per row, by column name.""" diff --git a/bindings/python/check_bakashrot.py b/bindings/python/check_bakashrot.py index baf7e28..144f896 100644 --- a/bindings/python/check_bakashrot.py +++ b/bindings/python/check_bakashrot.py @@ -140,8 +140,13 @@ with kitchen: check("A message over the limit: refused before sending", ok, detail) secret_id = kitchen.push({"s": 1}, "secret") check("Push to another allowed topic", secret_id == 1, secret_id) - ok, detail = raises(lambda: lounge.connect(), BakaShrotError, "one connection", ErrorCode.ALREADY_CONNECTED) - check("A second Client can't connect while one is", ok and not lounge.connected, detail) + with lounge: + page = lounge.get_messages("logs", "kitchen", after=0, limit=2) + check("A second Client connected at the same time: both work", + lounge.connected and lounge.node == "lounge" and [m.id for m in page] == [1, 2] + and kitchen.connected and kitchen.latest("secret", "kitchen").id == secret_id, + f"{lounge.node}, {[m.id for m in page]}") + check("Closing one leaves the other connected", kitchen.connected and not lounge.connected) topics = kitchen.list_topics() check("list_topics()", topics.kind == "topic" and topics.names == ["logs", "secret"] and not topics.truncated, topics) @@ -211,6 +216,26 @@ with kitchen: check("A missing file: refused before sending", ok, detail) check("Still connected", kitchen.connected) + # --- Two Clients, two threads, at the same time -------------------------- + other = Client.from_file(os.path.join(folder, "kitchen.toml"), dll_path).connect() + pushed = {} + + def pusher(name, client): + pushed[name] = [client.push({"thread": name, "n": n}, "secret") for n in range(30)] + + threads = [threading.Thread(target=pusher, args=("a", kitchen)), threading.Thread(target=pusher, args=("b", other))] + started = time.perf_counter() + for thread in threads: + thread.start() + for thread in threads: + thread.join(30) + elapsed = time.perf_counter() - started + every = sorted(pushed.get("a", []) + pushed.get("b", [])) + check("Two Clients pushing from two threads at once: every push stored, each id once", + len(every) == 60 and every == list(range(every[0], every[0] + 60)), + f"{len(every)} pushes in {elapsed * 1000:.0f} ms") + other.close() + check("close(): disconnected", not kitchen.connected) ok, detail = raises(lambda: kitchen.push("x", "logs"), ConnectionLostError, code=ErrorCode.NOT_CONNECTED) check("A request once closed: ConnectionLostError, NOT_CONNECTED", ok, detail) diff --git a/crates/bakashrot-capi/Cargo.toml b/crates/bakashrot-capi/Cargo.toml index 8a1dff3..c2bfb6b 100644 --- a/crates/bakashrot-capi/Cargo.toml +++ b/crates/bakashrot-capi/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "bakashrot-capi" -description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, one connection per process." +description = "BakaShrot's C DLL: the BakaShrot_* exports over bakashrot-client, as many clients as needed." version.workspace = true edition.workspace = true rust-version.workspace = true diff --git a/crates/bakashrot-capi/src/lib.rs b/crates/bakashrot-capi/src/lib.rs index ce1deb4..0a18668 100644 --- a/crates/bakashrot-capi/src/lib.rs +++ b/crates/bakashrot-capi/src/lib.rs @@ -1,27 +1,29 @@ -//! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the old +//! BakaShrot's C DLL (`bakashrot.dll`, `libbakashrot.so`): the //! `BakaShrot_*` exports over [`bakashrot_client`], for C, PureBasic, //! Python (ctypes) and anything that loads a DLL. `docs/client.md` //! has the whole API; `bindings/c/bakashrot.h` is generated from this file. //! //! The conventions: //! -//! - **One connection per process:** set the certificates, connect, send -//! requests, one at a time (calls from several threads wait for each -//! other). +//! - **Clients:** `BakaShrot_CreateClient()` makes one; its handle is the +//! first argument of every other export. Each has its own connection, +//! answers and errors; different clients can be used from different +//! threads at once. //! - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or //! UTF-16 (`uint16_t*`, `wchar_t*` on Windows), null-terminated. //! - **Strings out** are copied into the caller's buffer of `BufferSize` //! bytes: the getter returns the bytes needed, terminator included, and //! copies nothing if they don't fit (a null buffer asks for the size). //! - **Failures:** 0 (or -1 where a count or an id is returned), then -//! `BakaShrot_GetLastError()` gives the code (1-99 a server's refusal, the -//! connection still open; 100 and up the client's own) and +//! `BakaShrot_GetLastError(Client)` gives the code (1-99 a server's +//! refusal, the connection still open; 100 and up the client's own) and //! `BakaShrot_GetRefusalReason()` why, in words. After `ConnectionLost` //! or `ProtocolError` the connection is closed: connect again. //! - **Safety:** pointers are null or valid for what's said, strings -//! terminated, buffers writable for their size. A panic inside is caught -//! and reported as `Internal`; nothing allocated here is freed by the -//! caller, or the other way. +//! terminated, buffers writable for their size. A bad handle fails +//! (`InvalidArgument`). A panic inside is caught and reported as +//! `Internal`; nothing allocated here is freed by the caller, or the +//! other way. #![allow(unsafe_code, non_snake_case, clippy::missing_safety_doc)] @@ -30,20 +32,24 @@ mod text; use bakashrot_client::{Client, Error, Settings}; use bakashrot_proto::ErrorCode; use bakashrot_proto::packets::{MessageEntry, NameKind}; +use std::collections::BTreeMap; use std::ffi::{c_char, c_void}; use std::fs::File; use std::io::Cursor; use std::panic::{AssertUnwindSafe, catch_unwind}; use std::path::Path; -use std::sync::{Mutex, MutexGuard, PoisonError}; +use std::sync::{Arc, Mutex, MutexGuard, PoisonError}; use text::{Text, Utf8, Utf16}; type Result = std::result::Result; -/// Everything the DLL holds: its one connection, its settings, the last -/// answers. -static STATE: Mutex = Mutex::new(State::new()); +/// The next handle, and the clients by handle. A call holds its client's +/// `Arc`, so a client freed during a call goes when the call ends. +static CLIENTS: Mutex<(i64, BTreeMap)> = Mutex::new((1, BTreeMap::new())); +type Shared = Arc>; + +/// A client: its settings, its connection, the last answers. struct State { ca: Option, certificate: Option, @@ -124,15 +130,22 @@ impl State { } } -fn state() -> MutexGuard<'static, State> { - STATE.lock().unwrap_or_else(PoisonError::into_inner) +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex.lock().unwrap_or_else(PoisonError::into_inner) } -/// Runs a call that can fail: the last error reset, then set if it fails -/// (or panics), `failed` returned then. -fn call(failed: T, run: impl FnOnce(&mut State) -> Result) -> T { +fn find(client: i64) -> Option { + lock(&CLIENTS).1.get(&client).cloned() +} + +/// Runs a call that can fail on a client: its last error reset, then set +/// if it fails (or panics). `failed` then, or for a bad handle. +fn call(client: i64, failed: T, run: impl FnOnce(&mut State) -> Result) -> T { + let Some(shared) = find(client) else { + return failed; + }; let outcome = catch_unwind(AssertUnwindSafe(|| { - let mut state = state(); + let mut state = lock(&shared); state.last_error = 0; state.reason.clear(); let outcome = run(&mut state); @@ -142,20 +155,29 @@ fn call(failed: T, run: impl FnOnce(&mut State) -> Result) -> T { Ok(Ok(value)) => value, Ok(Err(())) => failed, Err(_) => { - state().fail(Error::new(ErrorCode::Internal, "the DLL panicked")); + lock(&shared).fail(Error::new(ErrorCode::Internal, "the DLL panicked")); failed } } } -/// Runs a getter: the last error stays as it is. -fn get(default: T, read: impl FnOnce(&State) -> T) -> T { - catch_unwind(AssertUnwindSafe(|| read(&state()))).unwrap_or(default) +/// Runs a getter on a client, its last error unchanged. `default` for a +/// bad handle. +fn get(client: i64, default: T, read: impl FnOnce(&mut State) -> T) -> T { + let Some(shared) = find(client) else { + return default; + }; + catch_unwind(AssertUnwindSafe(|| read(&mut lock(&shared)))).unwrap_or(default) } -/// Copies a string of the state into the caller's buffer. -unsafe fn get_text(buffer: *mut T::Unit, size: isize, text: fn(&State) -> &str) -> isize { - get(0, |state| unsafe { +/// Copies a string of a client's state into the caller's buffer. +unsafe fn get_text( + client: i64, + buffer: *mut T::Unit, + size: isize, + text: fn(&State) -> &str, +) -> isize { + get(client, 0, |state| unsafe { text::copy::(text(state), buffer, size) }) } @@ -172,29 +194,71 @@ fn bool_result(ok: bool) -> isize { isize::from(ok) } +// --- Clients ----------------------------------------------------------------- + +/// Makes a client: its handle (1 and up, never reused), 0 if it failed. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_CreateClient() -> i64 { + let made = catch_unwind(|| { + let (next, clients) = &mut *lock(&CLIENTS); + clients.insert(*next, Arc::new(Mutex::new(State::new()))); + *next += 1; + *next - 1 + }); + made.unwrap_or(0) +} + +/// Frees a client and closes its connection (once a call on it in another +/// thread ends): 1, or 0 if it wasn't one. +#[unsafe(no_mangle)] +pub extern "C" fn BakaShrot_FreeClient(client: i64) -> isize { + let freed = catch_unwind(|| lock(&CLIENTS).1.remove(&client).is_some()); + bool_result(freed.unwrap_or(false)) +} + // --- Errors ------------------------------------------------------------------ -/// Why the last call failed: a protocol error code (1-99 a server's -/// refusal, the connection still open; 100 and up the client's own), 0 if -/// it succeeded. Getters don't change it. +/// Why the client's last call failed: a protocol error code (1-99 a +/// server's refusal, the connection still open; 100 and up the client's +/// own), 0 if it succeeded. Getters don't change it. `InvalidArgument` for +/// a bad handle. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetLastError() -> i32 { - get(ErrorCode::Internal.code() as i32, |state| { +pub extern "C" fn BakaShrot_GetLastError(client: i64) -> i32 { + get(client, ErrorCode::InvalidArgument.code() as i32, |state| { state.last_error as i32 }) } -/// Why the last call failed, in words: the server's reason for a refusal, -/// the client's otherwise. Empty if it succeeded. +/// The client's reason, or why its handle is bad. +unsafe fn refusal_reason(client: i64, buffer: *mut T::Unit, size: isize) -> isize { + match find(client) { + Some(_) => unsafe { get_text::(client, buffer, size, |state| &state.reason) }, + None => { + let why = format!("no client {client}: never made, or freed"); + unsafe { text::copy::(&why, buffer, size) } + } + } +} + +/// Why the client's last call failed, in words: the server's reason for a +/// refusal, the client's otherwise. Empty if it succeeded. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.reason) } +pub unsafe extern "C" fn BakaShrot_GetRefusalReasonA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { refusal_reason::(client, buffer.cast(), size) } } /// The same as `BakaShrot_GetRefusalReasonA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.reason) } +pub unsafe extern "C" fn BakaShrot_GetRefusalReasonW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { refusal_reason::(client, buffer, size) } } // --- Settings ---------------------------------------------------------------- @@ -218,12 +282,13 @@ fn pem_or_file(value: Option, what: &str, optional: bool) -> Result( + client: i64, value: *const T::Unit, what: &str, optional: bool, slot: fn(&mut State) -> &mut Option, ) -> isize { - call(0, |state| { + call(client, 0, |state| { if state.client.is_some() { return Err(Error::new( ErrorCode::AlreadyConnected, @@ -239,26 +304,43 @@ unsafe fn set( /// Sets the CA's certificate, which the server's must be issued by: PEM /// text, or the path of a file holding it. Before connecting. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCaCertificateA(certificate: *const c_char) -> isize { +pub unsafe extern "C" fn BakaShrot_SetCaCertificateA( + client: i64, + certificate: *const c_char, +) -> isize { unsafe { - set::(certificate.cast(), "CA certificate", false, |state| { - &mut state.ca - }) + set::( + client, + certificate.cast(), + "CA certificate", + false, + |state| &mut state.ca, + ) } } /// The same as `BakaShrot_SetCaCertificateA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCaCertificateW(certificate: *const u16) -> isize { - unsafe { set::(certificate, "CA certificate", false, |state| &mut state.ca) } +pub unsafe extern "C" fn BakaShrot_SetCaCertificateW( + client: i64, + certificate: *const u16, +) -> isize { + unsafe { + set::(client, certificate, "CA certificate", false, |state| { + &mut state.ca + }) + } } -/// Sets this client's certificate, which says its node and its roles: PEM +/// Sets the client's certificate, which says its node and its roles: PEM /// text, or the path of a file holding it. Before connecting. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) -> isize { +pub unsafe extern "C" fn BakaShrot_SetCertificateA( + client: i64, + certificate: *const c_char, +) -> isize { unsafe { - set::(certificate.cast(), "certificate", false, |state| { + set::(client, certificate.cast(), "certificate", false, |state| { &mut state.certificate }) } @@ -266,45 +348,49 @@ pub unsafe extern "C" fn BakaShrot_SetCertificateA(certificate: *const c_char) - /// The same as `BakaShrot_SetCertificateA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCertificateW(certificate: *const u16) -> isize { +pub unsafe extern "C" fn BakaShrot_SetCertificateW(client: i64, certificate: *const u16) -> isize { unsafe { - set::(certificate, "certificate", false, |state| { + set::(client, certificate, "certificate", false, |state| { &mut state.certificate }) } } -/// Sets this client's private key, its certificate's: PEM text, or the path +/// Sets the client's private key, its certificate's: PEM text, or the path /// of a file holding it. Before connecting. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(key: *const c_char) -> isize { - unsafe { set::(key.cast(), "private key", false, |state| &mut state.key) } +pub unsafe extern "C" fn BakaShrot_SetPrivateKeyA(client: i64, key: *const c_char) -> isize { + unsafe { + set::(client, key.cast(), "private key", false, |state| { + &mut state.key + }) + } } /// The same as `BakaShrot_SetPrivateKeyA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(key: *const u16) -> isize { - unsafe { set::(key, "private key", false, |state| &mut state.key) } +pub unsafe extern "C" fn BakaShrot_SetPrivateKeyW(client: i64, key: *const u16) -> isize { + unsafe { set::(client, key, "private key", false, |state| &mut state.key) } } /// Sets the CA's CRL, optional: servers it revokes are refused. PEM text, /// or the path of a file holding it (one that isn't there is a /// `FileError`); null or empty for none. Before connecting. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCrlA(crl: *const c_char) -> isize { - unsafe { set::(crl.cast(), "CRL", true, |state| &mut state.crl) } +pub unsafe extern "C" fn BakaShrot_SetCrlA(client: i64, crl: *const c_char) -> isize { + unsafe { set::(client, crl.cast(), "CRL", true, |state| &mut state.crl) } } /// The same as `BakaShrot_SetCrlA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_SetCrlW(crl: *const u16) -> isize { - unsafe { set::(crl, "CRL", true, |state| &mut state.crl) } +pub unsafe extern "C" fn BakaShrot_SetCrlW(client: i64, crl: *const u16) -> isize { + unsafe { set::(client, crl, "CRL", true, |state| &mut state.crl) } } // --- The connection ---------------------------------------------------------- -unsafe fn connect(host: *const T::Unit, port: i32) -> isize { - call(0, |state| { +unsafe fn connect(client: i64, host: *const T::Unit, port: i32) -> isize { + call(client, 0, |state| { if state.client.is_some() { return Err(Error::new( ErrorCode::AlreadyConnected, @@ -349,44 +435,47 @@ unsafe fn connect(host: *const T::Unit, port: i32) -> isize { /// the server refused the certificate, `ServerNotVerified` this client /// refused the server's, `NotAllowed` none of its roles is the server's). #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_ConnectA(host: *const c_char, port: i32) -> isize { - unsafe { connect::(host.cast(), port) } +pub unsafe extern "C" fn BakaShrot_ConnectA(client: i64, host: *const c_char, port: i32) -> isize { + unsafe { connect::(client, host.cast(), port) } } /// The same as `BakaShrot_ConnectA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_ConnectW(host: *const u16, port: i32) -> isize { - unsafe { connect::(host, port) } +pub unsafe extern "C" fn BakaShrot_ConnectW(client: i64, host: *const u16, port: i32) -> isize { + unsafe { connect::(client, host, port) } } /// 1 while connected: notices when the server closed the connection /// (forgotten then: connect again). #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_IsConnected() -> isize { - let open = catch_unwind(AssertUnwindSafe(|| { - let mut state = state(); +pub extern "C" fn BakaShrot_IsConnected(client: i64) -> isize { + get(client, 0, |state| { let open = state.client.as_ref().is_some_and(Client::is_open); if !open { state.client = None; } - open - })); - bool_result(open.unwrap_or(false)) + bool_result(open) + }) } /// Closes the connection: 0 if there was none. The settings stay. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_Disconnect() -> isize { - let closed = catch_unwind(AssertUnwindSafe(|| state().client.take().is_some())); - bool_result(closed.unwrap_or(false)) +pub extern "C" fn BakaShrot_Disconnect(client: i64) -> isize { + get(client, 0, |state| { + bool_result(state.client.take().is_some()) + }) } /// The node this client is, as the server said when connecting: its /// certificate's name. Empty when not connected. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> isize { +pub unsafe extern "C" fn BakaShrot_GetNodeA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { unsafe { - get_text::(buffer.cast(), size, |state| { + get_text::(client, buffer.cast(), size, |state| { state.client.as_ref().map_or("", Client::node) }) } @@ -394,9 +483,9 @@ pub unsafe extern "C" fn BakaShrot_GetNodeA(buffer: *mut c_char, size: isize) -> /// The same as `BakaShrot_GetNodeA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNodeW(buffer: *mut u16, size: isize) -> isize { +pub unsafe extern "C" fn BakaShrot_GetNodeW(client: i64, buffer: *mut u16, size: isize) -> isize { unsafe { - get_text::(buffer, size, |state| { + get_text::(client, buffer, size, |state| { state.client.as_ref().map_or("", Client::node) }) } @@ -415,8 +504,8 @@ unsafe fn topic_and_data( Ok((topic, data)) } -unsafe fn push_to(topic: *const T::Unit, data: *const T::Unit) -> i64 { - call(-1, |state| { +unsafe fn push_to(client: i64, topic: *const T::Unit, data: *const T::Unit) -> i64 { + call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; let id = state.client()?.push(&topic, &data)?; Ok(id as i64) @@ -428,16 +517,21 @@ unsafe fn push_to(topic: *const T::Unit, data: *const T::Unit) -> i64 { /// (`ConnectionLost`) may have been stored all the same. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageToA( + client: i64, topic: *const c_char, data: *const c_char, ) -> i64 { - unsafe { push_to::(topic.cast(), data.cast()) } + unsafe { push_to::(client, topic.cast(), data.cast()) } } /// The same as `BakaShrot_PushMessageToA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_PushMessageToW(topic: *const u16, data: *const u16) -> i64 { - unsafe { push_to::(topic, data) } +pub unsafe extern "C" fn BakaShrot_PushMessageToW( + client: i64, + topic: *const u16, + data: *const u16, +) -> i64 { + unsafe { push_to::(client, topic, data) } } // --- Reading ----------------------------------------------------------------- @@ -452,8 +546,8 @@ unsafe fn topic_and_node( Ok((topic, node)) } -unsafe fn latest_of(topic: *const T::Unit, node: *const T::Unit) -> isize { - call(0, |state| { +unsafe fn latest_of(client: i64, topic: *const T::Unit, node: *const T::Unit) -> isize { + call(client, 0, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; state.clear_messages(&topic, &node); let answer = state.client()?.get_messages(&topic, &node, None, 1)?; @@ -472,28 +566,31 @@ unsafe fn latest_of(topic: *const T::Unit, node: *const T::Unit) -> isi /// `BakaShrot_GetMessage*()` getters. `NotFound` if there's none yet. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfA( + client: i64, topic: *const c_char, node: *const c_char, ) -> isize { - unsafe { latest_of::(topic.cast(), node.cast()) } + unsafe { latest_of::(client, topic.cast(), node.cast()) } } /// The same as `BakaShrot_GetLatestMessageOfA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetLatestMessageOfW( + client: i64, topic: *const u16, node: *const u16, ) -> isize { - unsafe { latest_of::(topic, node) } + unsafe { latest_of::(client, topic, node) } } unsafe fn messages( + client: i64, topic: *const T::Unit, node: *const T::Unit, after: i64, limit: i32, ) -> i32 { - call(-1, |state| { + call(client, -1, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; state.clear_messages(&topic, &node); let after = @@ -515,36 +612,38 @@ unsafe fn messages( /// `BakaShrot_HasMoreMessages()` says whether more follow the last one. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetMessagesA( + client: i64, topic: *const c_char, node: *const c_char, after: i64, limit: i32, ) -> i32 { - unsafe { messages::(topic.cast(), node.cast(), after, limit) } + unsafe { messages::(client, topic.cast(), node.cast(), after, limit) } } /// The same as `BakaShrot_GetMessagesA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_GetMessagesW( + client: i64, topic: *const u16, node: *const u16, after: i64, limit: i32, ) -> i32 { - unsafe { messages::(topic, node, after, limit) } + unsafe { messages::(client, topic, node, after, limit) } } /// How many messages the last `GetMessages` or `GetLatestMessageOf` got. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessageCount() -> i32 { - get(0, |state| state.messages.len() as i32) +pub extern "C" fn BakaShrot_GetMessageCount(client: i64) -> i32 { + get(client, 0, |state| state.messages.len() as i32) } /// Selects the message at `index` (0 to the count - 1) for the getters: 0 /// if there's none there (`InvalidArgument`), the selection unchanged. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize { - call(0, |state| { +pub extern "C" fn BakaShrot_SelectMessage(client: i64, index: i32) -> isize { + call(client, 0, |state| { let index = usize::try_from(index) .ok() .filter(|index| *index < state.messages.len()) @@ -557,14 +656,14 @@ pub extern "C" fn BakaShrot_SelectMessage(index: i32) -> isize { /// 1 if more messages follow the last one the last `GetMessages` got: ask /// again after its id. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_HasMoreMessages() -> isize { - get(0, |state| bool_result(state.more)) +pub extern "C" fn BakaShrot_HasMoreMessages(client: i64) -> isize { + get(client, 0, |state| bool_result(state.more)) } /// The selected message's id, 0 if none. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessageId() -> i64 { - get(0, |state| { +pub extern "C" fn BakaShrot_GetMessageId(client: i64) -> i64 { + get(client, 0, |state| { state.message().map_or(0, |message| message.id as i64) }) } @@ -572,8 +671,8 @@ pub extern "C" fn BakaShrot_GetMessageId() -> i64 { /// When the selected message was pushed, by the server it was pushed to: /// milliseconds since 1970-01-01 UTC, 0 if none. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 { - get(0, |state| { +pub extern "C" fn BakaShrot_GetMessagePushedAt(client: i64) -> i64 { + get(client, 0, |state| { state .message() .map_or(0, |message| message.pushed_at as i64) @@ -582,8 +681,8 @@ pub extern "C" fn BakaShrot_GetMessagePushedAt() -> i64 { /// The selected message's attachment's size, 0 without one. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 { - get(0, |state| { +pub extern "C" fn BakaShrot_GetMessageAttachmentSize(client: i64) -> i64 { + get(client, 0, |state| { state .message() .and_then(|message| message.attachment.as_ref()) @@ -594,8 +693,8 @@ pub extern "C" fn BakaShrot_GetMessageAttachmentSize() -> i64 { /// 1 if the selected message's attachment is all on this server (a /// replicated one may still be on its way). #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize { - get(0, |state| { +pub extern "C" fn BakaShrot_IsMessageAttachmentReady(client: i64) -> isize { + get(client, 0, |state| { let attachment = state .message() .and_then(|message| message.attachment.as_ref()); @@ -605,9 +704,13 @@ pub extern "C" fn BakaShrot_IsMessageAttachmentReady() -> isize { /// The selected message's data, as pushed (JSON or not). #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: isize) -> isize { +pub unsafe extern "C" fn BakaShrot_GetMessageDataA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { unsafe { - get_text::(buffer.cast(), size, |state| { + get_text::(client, buffer.cast(), size, |state| { state.message().map_or("", |message| &message.data) }) } @@ -615,9 +718,13 @@ pub unsafe extern "C" fn BakaShrot_GetMessageDataA(buffer: *mut c_char, size: is /// The same as `BakaShrot_GetMessageDataA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize) -> isize { +pub unsafe extern "C" fn BakaShrot_GetMessageDataW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { unsafe { - get_text::(buffer, size, |state| { + get_text::(client, buffer, size, |state| { state.message().map_or("", |message| &message.data) }) } @@ -625,32 +732,48 @@ pub unsafe extern "C" fn BakaShrot_GetMessageDataW(buffer: *mut u16, size: isize /// The topic the last `GetMessages` or `GetLatestMessageOf` asked for. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageTopicA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.topic) } +pub unsafe extern "C" fn BakaShrot_GetMessageTopicA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.topic) } } /// The same as `BakaShrot_GetMessageTopicA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageTopicW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.topic) } +pub unsafe extern "C" fn BakaShrot_GetMessageTopicW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.topic) } } /// The node the last `GetMessages` or `GetLatestMessageOf` asked for. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageNodeA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.node) } +pub unsafe extern "C" fn BakaShrot_GetMessageNodeA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.node) } } /// The same as `BakaShrot_GetMessageNodeA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetMessageNodeW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.node) } +pub unsafe extern "C" fn BakaShrot_GetMessageNodeW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.node) } } // --- Names ------------------------------------------------------------------- -fn list(kind: NameKind) -> i32 { - call(-1, |state| { +fn list(client: i64, kind: NameKind) -> i32 { + call(client, -1, |state| { state.names.clear(); let list = state.client()?.list_names(kind)?; let kind = match kind { @@ -672,36 +795,44 @@ fn list(kind: NameKind) -> i32 { /// (every one if its roles have `list_topics` or `query`): how many, -1 on /// failure. Then `BakaShrot_GetNamesList()`. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_ListTopics() -> i32 { - list(NameKind::Topic) +pub extern "C" fn BakaShrot_ListTopics(client: i64) -> i32 { + list(client, NameKind::Topic) } /// Lists the nodes with messages in the topics this client may read (every /// one if its roles have `list_nodes` or `query`): how many, -1 on failure. Then /// `BakaShrot_GetNamesList()`. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_ListNodes() -> i32 { - list(NameKind::Node) +pub extern "C" fn BakaShrot_ListNodes(client: i64) -> i32 { + list(client, NameKind::Node) } /// The last list, as JSON: /// `{"kind":"topic","truncated":false,"names":["logs",...]}`, `truncated` /// if some didn't fit. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNamesListA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.names) } +pub unsafe extern "C" fn BakaShrot_GetNamesListA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.names) } } /// The same as `BakaShrot_GetNamesListA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetNamesListW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.names) } +pub unsafe extern "C" fn BakaShrot_GetNamesListW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.names) } } // --- Queries ----------------------------------------------------------------- -unsafe fn query(sql: *const T::Unit) -> isize { - call(0, |state| { +unsafe fn query(client: i64, sql: *const T::Unit) -> isize { + call(client, 0, |state| { state.query.clear(); let sql = required(unsafe { text::read::(sql, "query")? }, "query")?; state.query = state.client()?.query(&sql)?; @@ -712,27 +843,35 @@ unsafe fn query(sql: *const T::Unit) -> isize { /// Runs read-only SQL on the server (one SELECT or WITH), if this client /// may query. Then `BakaShrot_GetQueryResult()`. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_QueryA(sql: *const c_char) -> isize { - unsafe { query::(sql.cast()) } +pub unsafe extern "C" fn BakaShrot_QueryA(client: i64, sql: *const c_char) -> isize { + unsafe { query::(client, sql.cast()) } } /// The same as `BakaShrot_QueryA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_QueryW(sql: *const u16) -> isize { - unsafe { query::(sql) } +pub unsafe extern "C" fn BakaShrot_QueryW(client: i64, sql: *const u16) -> isize { + unsafe { query::(client, sql) } } /// The last query's result, as JSON: /// `{"columns":[...],"rows":[[...],...]}`, every value a string or null. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetQueryResultA(buffer: *mut c_char, size: isize) -> isize { - unsafe { get_text::(buffer.cast(), size, |state| &state.query) } +pub unsafe extern "C" fn BakaShrot_GetQueryResultA( + client: i64, + buffer: *mut c_char, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer.cast(), size, |state| &state.query) } } /// The same as `BakaShrot_GetQueryResultA`, in UTF-16. #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetQueryResultW(buffer: *mut u16, size: isize) -> isize { - unsafe { get_text::(buffer, size, |state| &state.query) } +pub unsafe extern "C" fn BakaShrot_GetQueryResultW( + client: i64, + buffer: *mut u16, + size: isize, +) -> isize { + unsafe { get_text::(client, buffer, size, |state| &state.query) } } // --- Attachments ------------------------------------------------------------- @@ -743,11 +882,12 @@ fn message_id(id: i64) -> Result { } unsafe fn push_with_file( + client: i64, topic: *const T::Unit, data: *const T::Unit, path: *const T::Unit, ) -> i64 { - call(-1, |state| { + call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; let path = required(unsafe { text::read::(path, "the file")? }, "file")?; let mut file = File::open(&path) @@ -766,30 +906,33 @@ unsafe fn push_with_file( /// (`DataMismatch`). #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithFileA( + client: i64, topic: *const c_char, data: *const c_char, file_path: *const c_char, ) -> i64 { - unsafe { push_with_file::(topic.cast(), data.cast(), file_path.cast()) } + unsafe { push_with_file::(client, topic.cast(), data.cast(), file_path.cast()) } } /// The same as `BakaShrot_PushMessageWithFileA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithFileW( + client: i64, topic: *const u16, data: *const u16, file_path: *const u16, ) -> i64 { - unsafe { push_with_file::(topic, data, file_path) } + unsafe { push_with_file::(client, topic, data, file_path) } } unsafe fn push_with_data( + client: i64, topic: *const T::Unit, data: *const T::Unit, attachment: *const c_void, size: i64, ) -> i64 { - call(-1, |state| { + call(client, -1, |state| { let (topic, data) = unsafe { topic_and_data::(topic, data)? }; if attachment.is_null() { return Err(invalid("no attachment (a null pointer)")); @@ -810,32 +953,35 @@ unsafe fn push_with_data( /// `BakaShrot_PushMessageWithFileA` does. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithDataA( + client: i64, topic: *const c_char, data: *const c_char, attachment: *const c_void, size: i64, ) -> i64 { - unsafe { push_with_data::(topic.cast(), data.cast(), attachment, size) } + unsafe { push_with_data::(client, topic.cast(), data.cast(), attachment, size) } } /// The same as `BakaShrot_PushMessageWithDataA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_PushMessageWithDataW( + client: i64, topic: *const u16, data: *const u16, attachment: *const c_void, size: i64, ) -> i64 { - unsafe { push_with_data::(topic, data, attachment, size) } + unsafe { push_with_data::(client, topic, data, attachment, size) } } unsafe fn save( + client: i64, topic: *const T::Unit, node: *const T::Unit, id: i64, path: *const T::Unit, ) -> i64 { - call(-1, |state| { + call(client, -1, |state| { let (topic, node) = unsafe { topic_and_node::(topic, node)? }; let path = required(unsafe { text::read::(path, "the file")? }, "file")?; let size = @@ -853,27 +999,37 @@ unsafe fn save( /// failed one leaves no file. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_SaveAttachmentA( + client: i64, topic: *const c_char, node: *const c_char, message_id: i64, file_path: *const c_char, ) -> i64 { - unsafe { save::(topic.cast(), node.cast(), message_id, file_path.cast()) } + unsafe { + save::( + client, + topic.cast(), + node.cast(), + message_id, + file_path.cast(), + ) + } } /// The same as `BakaShrot_SaveAttachmentA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_SaveAttachmentW( + client: i64, topic: *const u16, node: *const u16, message_id: i64, file_path: *const u16, ) -> i64 { - unsafe { save::(topic, node, message_id, file_path) } + unsafe { save::(client, topic, node, message_id, file_path) } } -unsafe fn load(topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 { - call(-1, |state| { +unsafe fn load(client: i64, topic: *const T::Unit, node: *const T::Unit, id: i64) -> i64 { + call(client, -1, |state| { state.attachment = Vec::new(); let (topic, node) = unsafe { topic_and_node::(topic, node)? }; let mut attachment = Vec::new(); @@ -891,29 +1047,35 @@ unsafe fn load(topic: *const T::Unit, node: *const T::Unit, id: i64) -> /// ones): its size, -1 on failure. Then `BakaShrot_GetAttachmentData()`. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_LoadAttachmentA( + client: i64, topic: *const c_char, node: *const c_char, message_id: i64, ) -> i64 { - unsafe { load::(topic.cast(), node.cast(), message_id) } + unsafe { load::(client, topic.cast(), node.cast(), message_id) } } /// The same as `BakaShrot_LoadAttachmentA`, in UTF-16. #[unsafe(no_mangle)] pub unsafe extern "C" fn BakaShrot_LoadAttachmentW( + client: i64, topic: *const u16, node: *const u16, message_id: i64, ) -> i64 { - unsafe { load::(topic, node, message_id) } + unsafe { load::(client, topic, node, message_id) } } /// Copies what the last `BakaShrot_LoadAttachment()` read into `Buffer`, if /// `BufferSize` is enough: returns its size (0 if none), copies nothing if /// it doesn't fit (a null `Buffer` asks for the size). #[unsafe(no_mangle)] -pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer_size: i64) -> i64 { - get(0, |state| { +pub unsafe extern "C" fn BakaShrot_GetAttachmentData( + client: i64, + buffer: *mut c_void, + buffer_size: i64, +) -> i64 { + get(client, 0, |state| { let data = &state.attachment; if !buffer.is_null() && usize::try_from(buffer_size).is_ok_and(|size| size >= data.len()) { unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), buffer.cast(), data.len()) }; @@ -924,7 +1086,9 @@ pub unsafe extern "C" fn BakaShrot_GetAttachmentData(buffer: *mut c_void, buffer /// Frees what `BakaShrot_LoadAttachment()` read: 1. #[unsafe(no_mangle)] -pub extern "C" fn BakaShrot_FreeAttachmentData() -> isize { - let freed = catch_unwind(AssertUnwindSafe(|| state().attachment = Vec::new())); - bool_result(freed.is_ok()) +pub extern "C" fn BakaShrot_FreeAttachmentData(client: i64) -> isize { + get(client, 0, |state| { + state.attachment = Vec::new(); + 1 + }) } diff --git a/crates/bakashrot-capi/tests/exports.rs b/crates/bakashrot-capi/tests/exports.rs index ba33904..9615ae6 100644 --- a/crates/bakashrot-capi/tests/exports.rs +++ b/crates/bakashrot-capi/tests/exports.rs @@ -1,6 +1,7 @@ -//! The exports called as C would, against a server: the `W` ones (what -//! PureBasic uses; Python's check covers the `A` ones), the buffers, the -//! errors. One test: the DLL holds one connection per process. +//! The exports called as C would, against a server. `exports`: one client, +//! the `W` exports (what PureBasic uses; Python's check covers the `A` +//! ones), the buffers, the errors. `clients`: several clients at once, bad +//! handles, threads. #![allow(unsafe_code)] @@ -9,6 +10,8 @@ mod common; use bakashrot::*; use bakashrot_proto::ErrorCode; use std::ffi::{CString, c_char}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; fn w(text: &str) -> Vec { text.encode_utf16().chain([0]).collect() @@ -19,25 +22,28 @@ fn a(text: &str) -> CString { } /// A `W` getter's string: asks for the size, then copies. -fn get_w(getter: unsafe extern "C" fn(*mut u16, isize) -> isize) -> String { - let size = unsafe { getter(std::ptr::null_mut(), 0) }; +fn get_w(client: i64, getter: unsafe extern "C" fn(i64, *mut u16, isize) -> isize) -> String { + let size = unsafe { getter(client, std::ptr::null_mut(), 0) }; + if size == 0 { + return String::new(); + } let mut buffer = vec![0u16; size as usize / 2]; - unsafe { getter(buffer.as_mut_ptr(), size) }; + unsafe { getter(client, buffer.as_mut_ptr(), size) }; String::from_utf16(&buffer[..buffer.len() - 1]).unwrap() } -fn get_a(getter: unsafe extern "C" fn(*mut c_char, isize) -> isize) -> String { - let size = unsafe { getter(std::ptr::null_mut(), 0) }; +fn get_a(client: i64, getter: unsafe extern "C" fn(i64, *mut c_char, isize) -> isize) -> String { + let size = unsafe { getter(client, std::ptr::null_mut(), 0) }; let mut buffer = vec![0u8; size as usize]; - unsafe { getter(buffer.as_mut_ptr().cast(), size) }; + unsafe { getter(client, buffer.as_mut_ptr().cast(), size) }; String::from_utf8(buffer[..buffer.len() - 1].to_vec()).unwrap() } -/// The last error's code and reason. -fn error() -> (u32, String) { +/// The client's last error: its code and reason. +fn error(client: i64) -> (u32, String) { ( - BakaShrot_GetLastError() as u32, - get_w(BakaShrot_GetRefusalReasonW), + BakaShrot_GetLastError(client) as u32, + get_w(client, BakaShrot_GetRefusalReasonW), ) } @@ -54,172 +60,205 @@ fn exports() { let pem = |name: &str| std::fs::read_to_string(running.folder.join(name)).unwrap(); let localhost = w("127.0.0.1"); let port = i32::from(running.port); + let client = BakaShrot_CreateClient(); + assert!(client >= 1); unsafe { // Nothing set, not connected. assert_eq!( - BakaShrot_PushMessageToW(w("logs").as_ptr(), w("{}").as_ptr()), + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("{}").as_ptr()), -1 ); - assert_eq!(error().0, code(ErrorCode::NotConnected)); - assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); - let (failed, why) = error(); + assert_eq!(error(client).0, code(ErrorCode::NotConnected)); + assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0); + let (failed, why) = error(client); assert_eq!(failed, code(ErrorCode::InvalidArgument)); assert!(why.contains("BakaShrot_SetCaCertificate"), "{why}"); // Files or PEM text; a missing file, an empty setting. assert_eq!( - BakaShrot_SetCaCertificateW(w(&file("missing.crt")).as_ptr()), + BakaShrot_SetCaCertificateW(client, w(&file("missing.crt")).as_ptr()), 0 ); - assert_eq!(error().0, code(ErrorCode::FileError)); - assert_eq!(BakaShrot_SetCertificateW(std::ptr::null()), 0); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); - assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 1); - assert_eq!(BakaShrot_GetLastError(), 0); + assert_eq!(error(client).0, code(ErrorCode::FileError)); + assert_eq!(BakaShrot_SetCertificateW(client, std::ptr::null()), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); assert_eq!( - BakaShrot_SetCertificateW(w(&pem("kitchen.crt")).as_ptr()), + BakaShrot_SetCaCertificateW(client, w(&file("ca.crt")).as_ptr()), + 1 + ); + assert_eq!(BakaShrot_GetLastError(client), 0); + assert_eq!( + BakaShrot_SetCertificateW(client, w(&pem("kitchen.crt")).as_ptr()), 1 ); assert_eq!( - BakaShrot_SetPrivateKeyA(a(&file("kitchen.key")).as_ptr()), + BakaShrot_SetPrivateKeyA(client, a(&file("kitchen.key")).as_ptr()), 1 ); // A CRL file asked for is needed (client.toml's may be missing). - assert_eq!(BakaShrot_SetCrlW(w(&file("missing.crl")).as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::FileError)); - assert_eq!(BakaShrot_SetCrlW(std::ptr::null()), 1); - assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), 0), 0); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!( + BakaShrot_SetCrlW(client, w(&file("missing.crl")).as_ptr()), + 0 + ); + assert_eq!(error(client).0, code(ErrorCode::FileError)); + assert_eq!(BakaShrot_SetCrlW(client, std::ptr::null()), 1); + assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), 0), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); assert_eq!( - BakaShrot_ConnectW(localhost.as_ptr(), port), + BakaShrot_ConnectW(client, localhost.as_ptr(), port), 1, "{:?}", - error() + error(client) ); - assert_eq!(BakaShrot_IsConnected(), 1); - assert_eq!(get_w(BakaShrot_GetNodeW), "kitchen"); - assert_eq!(BakaShrot_ConnectW(localhost.as_ptr(), port), 0); - assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); - assert_eq!(BakaShrot_SetCaCertificateW(w(&file("ca.crt")).as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::AlreadyConnected)); + assert_eq!(BakaShrot_IsConnected(client), 1); + assert_eq!(get_w(client, BakaShrot_GetNodeW), "kitchen"); + assert_eq!(BakaShrot_ConnectW(client, localhost.as_ptr(), port), 0); + assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected)); + assert_eq!( + BakaShrot_SetCaCertificateW(client, w(&file("ca.crt")).as_ptr()), + 0 + ); + assert_eq!(error(client).0, code(ErrorCode::AlreadyConnected)); // Pushes: UTF-16, a null message is an empty one. assert_eq!( - BakaShrot_PushMessageToW(w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()), + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w(r#"{"i":1}"#).as_ptr()), 1 ); assert_eq!( - BakaShrot_PushMessageToW(w("logs").as_ptr(), w("héllo 🌍").as_ptr()), + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), w("héllo 🌍").as_ptr()), 2 ); assert_eq!( - BakaShrot_PushMessageToW(w("logs").as_ptr(), std::ptr::null()), + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), std::ptr::null()), 3 ); assert_eq!( - BakaShrot_PushMessageToW(std::ptr::null(), w("{}").as_ptr()), + BakaShrot_PushMessageToW(client, std::ptr::null(), w("{}").as_ptr()), -1 ); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); assert_eq!( - BakaShrot_PushMessageToW(w("nothing").as_ptr(), w("{}").as_ptr()), + BakaShrot_PushMessageToW(client, w("nothing").as_ptr(), w("{}").as_ptr()), -1 ); - let (failed, why) = error(); + let (failed, why) = error(client); assert_eq!(failed, code(ErrorCode::NotAllowed)); assert!(why.contains("may not push to 'nothing'"), "{why}"); // The latest; none yet in another topic. assert_eq!( - BakaShrot_GetLatestMessageOfW(w("logs").as_ptr(), w("kitchen").as_ptr()), + BakaShrot_GetLatestMessageOfW(client, w("logs").as_ptr(), w("kitchen").as_ptr()), 1 ); assert_eq!( - (BakaShrot_GetMessageCount(), BakaShrot_GetMessageId()), + ( + BakaShrot_GetMessageCount(client), + BakaShrot_GetMessageId(client) + ), (1, 3) ); - assert_eq!(get_w(BakaShrot_GetMessageDataW), ""); - assert!(BakaShrot_GetMessagePushedAt() > 1_700_000_000_000); - assert_eq!(BakaShrot_GetMessageAttachmentSize(), 0); - assert_eq!(BakaShrot_IsMessageAttachmentReady(), 0); + assert_eq!(get_w(client, BakaShrot_GetMessageDataW), ""); + assert!(BakaShrot_GetMessagePushedAt(client) > 1_700_000_000_000); + assert_eq!(BakaShrot_GetMessageAttachmentSize(client), 0); + assert_eq!(BakaShrot_IsMessageAttachmentReady(client), 0); assert_eq!( - BakaShrot_GetLatestMessageOfW(w("secret").as_ptr(), w("kitchen").as_ptr()), + BakaShrot_GetLatestMessageOfW(client, w("secret").as_ptr(), w("kitchen").as_ptr()), 0 ); - assert_eq!(error().0, code(ErrorCode::NotFound)); - assert_eq!(BakaShrot_GetMessageCount(), 0); + assert_eq!(error(client).0, code(ErrorCode::NotFound)); + assert_eq!(BakaShrot_GetMessageCount(client), 0); // A run of messages, selected one by one. assert_eq!( - BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2), + BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 2), 2 ); - assert_eq!(BakaShrot_HasMoreMessages(), 1); - assert_eq!(get_w(BakaShrot_GetMessageTopicW), "logs"); - assert_eq!(get_w(BakaShrot_GetMessageNodeW), "kitchen"); - assert_eq!(BakaShrot_GetMessageId(), 1); - assert_eq!(BakaShrot_SelectMessage(1), 1); - assert_eq!(get_w(BakaShrot_GetMessageDataW), "héllo 🌍"); - assert_eq!(get_a(BakaShrot_GetMessageDataA), "héllo 🌍"); - assert_eq!(BakaShrot_SelectMessage(2), 0); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); - assert_eq!(BakaShrot_GetMessageId(), 2, "the selection stays"); + assert_eq!(BakaShrot_HasMoreMessages(client), 1); + assert_eq!(get_w(client, BakaShrot_GetMessageTopicW), "logs"); + assert_eq!(get_w(client, BakaShrot_GetMessageNodeW), "kitchen"); + assert_eq!(BakaShrot_GetMessageId(client), 1); + assert_eq!(BakaShrot_SelectMessage(client, 1), 1); + assert_eq!(get_w(client, BakaShrot_GetMessageDataW), "héllo 🌍"); + assert_eq!(get_a(client, BakaShrot_GetMessageDataA), "héllo 🌍"); + assert_eq!(BakaShrot_SelectMessage(client, 2), 0); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); + assert_eq!(BakaShrot_GetMessageId(client), 2, "the selection stays"); assert_eq!( - BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10), + BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 3, 10), 0 ); - assert_eq!(BakaShrot_HasMoreMessages(), 0); - assert_eq!(BakaShrot_GetMessageId(), 0); + assert_eq!(BakaShrot_HasMoreMessages(client), 0); + assert_eq!(BakaShrot_GetMessageId(client), 0); for (after, limit) in [(-1, 10), (0, 0), (0, 10_001)] { assert_eq!( - BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), after, limit), + BakaShrot_GetMessagesW( + client, + w("logs").as_ptr(), + w("kitchen").as_ptr(), + after, + limit + ), -1 ); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); } assert_eq!( - BakaShrot_GetMessagesW(w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10), + BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("nobody").as_ptr(), 0, 10), -1 ); - assert_eq!(error().0, code(ErrorCode::UnknownName)); - assert_eq!(BakaShrot_IsConnected(), 1, "a refusal keeps the connection"); + assert_eq!(error(client).0, code(ErrorCode::UnknownName)); + assert_eq!( + BakaShrot_IsConnected(client), + 1, + "a refusal keeps the connection" + ); // The buffers: the size needed, nothing copied if it doesn't fit. - BakaShrot_GetMessagesW(w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); - assert_eq!(BakaShrot_GetMessageDataW(std::ptr::null_mut(), 0), 16); - assert_eq!(BakaShrot_GetMessageDataA(std::ptr::null_mut(), 0), 8); + BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 1); + assert_eq!( + BakaShrot_GetMessageDataW(client, std::ptr::null_mut(), 0), + 16 + ); + assert_eq!( + BakaShrot_GetMessageDataA(client, std::ptr::null_mut(), 0), + 8 + ); let mut small = [7u16; 7]; - assert_eq!(BakaShrot_GetMessageDataW(small.as_mut_ptr(), 14), 16); + assert_eq!( + BakaShrot_GetMessageDataW(client, small.as_mut_ptr(), 14), + 16 + ); assert_eq!(small, [7; 7]); // Unaligned: a byte buffer. let mut bytes = [0u8; 17]; assert_eq!( - BakaShrot_GetMessageDataW(bytes[1..].as_mut_ptr().cast(), 16), + BakaShrot_GetMessageDataW(client, bytes[1..].as_mut_ptr().cast(), 16), 16 ); assert_eq!(bytes[1..3], [b'{', 0]); // Names, queries. // Topics: those with messages (nothing in `secret` yet). - assert_eq!(BakaShrot_ListTopics(), 1); + assert_eq!(BakaShrot_ListTopics(client), 1); assert_eq!( - get_w(BakaShrot_GetNamesListW), + get_w(client, BakaShrot_GetNamesListW), r#"{"kind":"topic","names":["logs"],"truncated":false}"# ); - assert_eq!(BakaShrot_ListNodes(), 1); + assert_eq!(BakaShrot_ListNodes(client), 1); assert_eq!( - BakaShrot_QueryW(w("SELECT COUNT(*) AS n FROM data").as_ptr()), + BakaShrot_QueryW(client, w("SELECT COUNT(*) AS n FROM data").as_ptr()), 1 ); assert_eq!( - get_w(BakaShrot_GetQueryResultW), + get_w(client, BakaShrot_GetQueryResultW), r#"{"columns":["n"],"rows":[["3"]]}"# ); - assert_eq!(BakaShrot_QueryW(w("SELECT nope").as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::QueryFailed)); - assert_eq!(get_w(BakaShrot_GetQueryResultW), ""); + assert_eq!(BakaShrot_QueryW(client, w("SELECT nope").as_ptr()), 0); + assert_eq!(error(client).0, code(ErrorCode::QueryFailed)); + assert_eq!(get_w(client, BakaShrot_GetQueryResultW), ""); // Attachments: from a file or memory, saved or loaded back. let (logs, kitchen) = (w("logs"), w("kitchen")); @@ -227,34 +266,36 @@ fn exports() { std::fs::write(running.folder.join("photo.bin"), &photo).unwrap(); let photo_file = w(&file("photo.bin")); let pushed = BakaShrot_PushMessageWithFileW( + client, logs.as_ptr(), w(r#"{"photo":1}"#).as_ptr(), photo_file.as_ptr(), ); - assert_eq!(pushed, 4, "{:?}", error()); + assert_eq!(pushed, 4, "{:?}", error(client)); let tiny = b"tiny"; let pushed = BakaShrot_PushMessageWithDataW( + client, logs.as_ptr(), std::ptr::null(), tiny.as_ptr().cast(), 4, ); - assert_eq!(pushed, 5, "{:?}", error()); + assert_eq!(pushed, 5, "{:?}", error(client)); assert_eq!( - BakaShrot_GetLatestMessageOfW(logs.as_ptr(), kitchen.as_ptr()), + BakaShrot_GetLatestMessageOfW(client, logs.as_ptr(), kitchen.as_ptr()), 1 ); assert_eq!( ( - BakaShrot_GetMessageId(), - BakaShrot_GetMessageAttachmentSize(), - BakaShrot_IsMessageAttachmentReady() + BakaShrot_GetMessageId(client), + BakaShrot_GetMessageAttachmentSize(client), + BakaShrot_IsMessageAttachmentReady(client) ), (5, 4, 1) ); let saved = w(&file("saved.bin")); assert_eq!( - BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()), + BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 4, saved.as_ptr()), 1_500_000 ); assert_eq!( @@ -262,84 +303,264 @@ fn exports() { photo ); assert_eq!( - BakaShrot_LoadAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 5), + BakaShrot_LoadAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 5), + 4 + ); + assert_eq!( + BakaShrot_GetAttachmentData(client, std::ptr::null_mut(), 0), 4 ); - assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 4); let mut small = [9u8; 3]; - assert_eq!(BakaShrot_GetAttachmentData(small.as_mut_ptr().cast(), 3), 4); + assert_eq!( + BakaShrot_GetAttachmentData(client, small.as_mut_ptr().cast(), 3), + 4 + ); assert_eq!(small, [9; 3], "nothing copied if it doesn't fit"); let mut data = [0u8; 4]; - assert_eq!(BakaShrot_GetAttachmentData(data.as_mut_ptr().cast(), 4), 4); - assert_eq!(&data, tiny); - assert_eq!(BakaShrot_FreeAttachmentData(), 1); - assert_eq!(BakaShrot_GetAttachmentData(std::ptr::null_mut(), 0), 0); assert_eq!( - BakaShrot_LoadAttachmentA(a("logs").as_ptr(), a("kitchen").as_ptr(), 4), + BakaShrot_GetAttachmentData(client, data.as_mut_ptr().cast(), 4), + 4 + ); + assert_eq!(&data, tiny); + assert_eq!(BakaShrot_FreeAttachmentData(client), 1); + assert_eq!( + BakaShrot_GetAttachmentData(client, std::ptr::null_mut(), 0), + 0 + ); + assert_eq!( + BakaShrot_LoadAttachmentA(client, a("logs").as_ptr(), a("kitchen").as_ptr(), 4), 1_500_000 ); - BakaShrot_FreeAttachmentData(); + BakaShrot_FreeAttachmentData(client); // Refused, or the client's own failures: -1, no file. let none = w(&file("none.bin")); assert_eq!( - BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()), + BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), 1, none.as_ptr()), -1 ); - assert_eq!(error().0, code(ErrorCode::NotFound)); + assert_eq!(error(client).0, code(ErrorCode::NotFound)); assert!(!running.folder.join("none.bin").exists()); assert_eq!( - BakaShrot_SaveAttachmentW(logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()), + BakaShrot_SaveAttachmentW(client, logs.as_ptr(), kitchen.as_ptr(), -1, none.as_ptr()), -1 ); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); let missing = w(&file("missing.bin")); assert_eq!( - BakaShrot_PushMessageWithFileW(logs.as_ptr(), std::ptr::null(), missing.as_ptr()), + BakaShrot_PushMessageWithFileW( + client, + logs.as_ptr(), + std::ptr::null(), + missing.as_ptr() + ), -1 ); - assert_eq!(error().0, code(ErrorCode::FileError)); + assert_eq!(error(client).0, code(ErrorCode::FileError)); for (pointer, size) in [(std::ptr::null(), 4), (tiny.as_ptr(), 0)] { let pushed = BakaShrot_PushMessageWithDataW( + client, logs.as_ptr(), std::ptr::null(), pointer.cast(), size, ); assert_eq!(pushed, -1); - assert_eq!(error().0, code(ErrorCode::InvalidArgument)); + assert_eq!(error(client).0, code(ErrorCode::InvalidArgument)); } - assert_eq!(BakaShrot_IsConnected(), 1); + assert_eq!(BakaShrot_IsConnected(client), 1); // Closed: requests refused, the settings kept. - assert_eq!(BakaShrot_Disconnect(), 1); - assert_eq!(BakaShrot_Disconnect(), 0); - assert_eq!(BakaShrot_IsConnected(), 0); - assert_eq!(get_w(BakaShrot_GetNodeW), ""); - assert_eq!(BakaShrot_QueryW(w("SELECT 1").as_ptr()), 0); - assert_eq!(error().0, code(ErrorCode::NotConnected)); + assert_eq!(BakaShrot_Disconnect(client), 1); + assert_eq!(BakaShrot_Disconnect(client), 0); + assert_eq!(BakaShrot_IsConnected(client), 0); + assert_eq!(get_w(client, BakaShrot_GetNodeW), ""); + assert_eq!(BakaShrot_QueryW(client, w("SELECT 1").as_ptr()), 0); + assert_eq!(error(client).0, code(ErrorCode::NotConnected)); // Another identity, by the A exports: not allowed to query. assert_eq!( - BakaShrot_SetCertificateA(a(&file("lounge.crt")).as_ptr()), + BakaShrot_SetCertificateA(client, a(&file("lounge.crt")).as_ptr()), 1 ); - assert_eq!(BakaShrot_SetPrivateKeyA(a(&pem("lounge.key")).as_ptr()), 1); assert_eq!( - BakaShrot_ConnectA(a("localhost").as_ptr(), port), + BakaShrot_SetPrivateKeyA(client, a(&pem("lounge.key")).as_ptr()), + 1 + ); + assert_eq!( + BakaShrot_ConnectA(client, a("localhost").as_ptr(), port), 1, "{:?}", - error() + error(client) ); - assert_eq!(get_a(BakaShrot_GetNodeA), "lounge"); - assert_eq!(BakaShrot_QueryA(a("SELECT 1").as_ptr()), 0); - let (failed, why) = error(); + assert_eq!(get_a(client, BakaShrot_GetNodeA), "lounge"); + assert_eq!(BakaShrot_QueryA(client, a("SELECT 1").as_ptr()), 0); + let (failed, why) = error(client); assert_eq!(failed, code(ErrorCode::NotAllowed)); - assert_eq!(get_a(BakaShrot_GetRefusalReasonA), why); - BakaShrot_Disconnect(); + assert_eq!(get_a(client, BakaShrot_GetRefusalReasonA), why); + BakaShrot_Disconnect(client); // Nothing listening there. - assert_eq!(BakaShrot_ConnectA(a("127.0.0.1").as_ptr(), 1), 0); - assert_eq!(error().0, code(ErrorCode::ConnectFailed)); + assert_eq!(BakaShrot_ConnectA(client, a("127.0.0.1").as_ptr(), 1), 0); + assert_eq!(error(client).0, code(ErrorCode::ConnectFailed)); } + assert_eq!(BakaShrot_FreeClient(client), 1); +} + +/// A new client, connected as `name` (its certificate and key in files). +fn connected(running: &common::Running, name: &str) -> i64 { + let client = BakaShrot_CreateClient(); + assert!(client >= 1); + let file = |name: &str| w(&running.folder.join(name).display().to_string()); + unsafe { + assert_eq!( + BakaShrot_SetCaCertificateW(client, file("ca.crt").as_ptr()), + 1 + ); + assert_eq!( + BakaShrot_SetCertificateW(client, file(&format!("{name}.crt")).as_ptr()), + 1 + ); + assert_eq!( + BakaShrot_SetPrivateKeyW(client, file(&format!("{name}.key")).as_ptr()), + 1 + ); + let host = w("127.0.0.1"); + let connected = BakaShrot_ConnectW(client, host.as_ptr(), i32::from(running.port)); + assert_eq!(connected, 1, "{name}: {:?}", error(client)); + } + client +} + +#[test] +fn clients() { + let running = common::Running::start("clients"); + running.issue("kitchen", &["home"]); + running.issue("lounge", &["lounge"]); + + unsafe { + // Handles that aren't a client's: refused, never a crash. + assert_eq!( + BakaShrot_PushMessageToW(99, w("logs").as_ptr(), w("{}").as_ptr()), + -1 + ); + let (failed, why) = error(99); + assert_eq!(failed, code(ErrorCode::InvalidArgument)); + assert!(why.contains("no client 99"), "{why}"); + assert_eq!(BakaShrot_IsConnected(99), 0); + assert_eq!(BakaShrot_GetMessageId(-5), 0); + assert_eq!(get_w(99, BakaShrot_GetMessageDataW), ""); + assert_eq!(BakaShrot_FreeClient(99), 0); + assert_eq!(BakaShrot_FreeClient(0), 0); + let (failed, why) = error(0); + assert_eq!(failed, code(ErrorCode::InvalidArgument), "0 is never one"); + assert!(why.contains("no client 0"), "{why}"); + + // Two identities connected at once. + let kitchen = connected(&running, "kitchen"); + let lounge = connected(&running, "lounge"); + assert_ne!(kitchen, lounge); + assert_eq!(get_w(kitchen, BakaShrot_GetNodeW), "kitchen"); + assert_eq!(get_w(lounge, BakaShrot_GetNodeW), "lounge"); + + for i in 1..=3 { + let data = w(&format!(r#"{{"i":{i}}}"#)); + assert_eq!( + BakaShrot_PushMessageToW(kitchen, w("logs").as_ptr(), data.as_ptr()), + i + ); + } + + // Each its answers: one reads, the other's selection stays. + assert_eq!( + BakaShrot_GetLatestMessageOfW(kitchen, w("logs").as_ptr(), w("kitchen").as_ptr()), + 1 + ); + assert_eq!( + BakaShrot_GetMessagesW(lounge, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 10), + 3 + ); + assert_eq!(BakaShrot_SelectMessage(lounge, 1), 1); + assert_eq!(get_w(lounge, BakaShrot_GetMessageDataW), r#"{"i":2}"#); + assert_eq!(BakaShrot_GetMessageId(kitchen), 3); + assert_eq!(get_w(kitchen, BakaShrot_GetMessageDataW), r#"{"i":3}"#); + assert_eq!(BakaShrot_GetMessageCount(kitchen), 1); + + // Each its errors: lounge may only read logs. + assert_eq!( + BakaShrot_PushMessageToW(lounge, w("logs").as_ptr(), w("{}").as_ptr()), + -1 + ); + let (failed, why) = error(lounge); + assert_eq!(failed, code(ErrorCode::NotAllowed)); + assert!(why.contains("may not push"), "{why}"); + assert_eq!(error(kitchen), (0, String::new())); + + // Freed: closed, its handle refused, never given again. + assert_eq!(BakaShrot_FreeClient(lounge), 1); + assert_eq!(BakaShrot_FreeClient(lounge), 0); + assert_eq!(BakaShrot_IsConnected(lounge), 0); + assert_eq!( + BakaShrot_GetMessagesW(lounge, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 10), + -1 + ); + assert_eq!(error(lounge).0, code(ErrorCode::InvalidArgument)); + assert!(BakaShrot_CreateClient() > lounge.max(kitchen)); + assert_eq!(BakaShrot_IsConnected(kitchen), 1, "the other stays"); + assert_eq!(BakaShrot_Disconnect(kitchen), 1); + assert_eq!(BakaShrot_IsConnected(kitchen), 0); + assert_eq!(BakaShrot_FreeClient(kitchen), 1); + } + + // Threads, each with its client, pushing at once: every push stored, + // each id once. + let threads: Vec<_> = (0..4) + .map(|_| { + let client = connected(&running, "kitchen"); + std::thread::spawn(move || { + let ids: Vec = (0..50) + .map(|i| unsafe { + let data = w(&format!(r#"{{"t":{i}}}"#)); + BakaShrot_PushMessageToW(client, w("logs").as_ptr(), data.as_ptr()) + }) + .collect(); + assert_eq!(BakaShrot_FreeClient(client), 1); + ids + }) + }) + .collect(); + let mut ids: Vec = threads + .into_iter() + .flat_map(|thread| thread.join().unwrap()) + .collect(); + ids.sort_unstable(); + assert_eq!(ids, (4..=203).collect::>()); + + // A client freed while another thread uses it: that thread's calls + // fail from then on, nothing crashes. + let client = connected(&running, "kitchen"); + let started = Arc::new(AtomicBool::new(false)); + let reader = { + let started = started.clone(); + std::thread::spawn(move || { + let mut reads = 0; + loop { + let count = unsafe { + BakaShrot_GetMessagesW(client, w("logs").as_ptr(), w("kitchen").as_ptr(), 0, 50) + }; + started.store(true, Ordering::SeqCst); + if count < 0 { + return (reads, error(client).0); + } + reads += 1; + } + }) + }; + while !started.load(Ordering::SeqCst) { + std::thread::yield_now(); + } + assert_eq!(BakaShrot_FreeClient(client), 1); + let (reads, failed) = reader.join().unwrap(); + assert!(reads >= 1); + assert_eq!(failed, code(ErrorCode::InvalidArgument)); } diff --git a/docs/client.md b/docs/client.md index e8af0e1..216ce42 100644 --- a/docs/client.md +++ b/docs/client.md @@ -5,7 +5,7 @@ What apps connect with, in layers: | Layer | Where | For | |---|---|---| | `bakashrot-client` | `crates/bakashrot-client` | Rust: blocking, one connection per `Client` | -| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, one connection per process | +| The DLL | `crates/bakashrot-capi`: `bakashrot.dll`, `libbakashrot.so` | C and anything that loads a DLL: the `BakaShrot_*` exports, as many clients as needed | | C header | `bindings/c/bakashrot.h` | generated from the DLL (cbindgen) | | PureBasic | `bindings/purebasic/` | the prototypes and the error codes | | Python | `bindings/python/bakashrot.py` | `Client` over the DLL (ctypes), standard library only | @@ -15,7 +15,7 @@ Decided in `../revamp.md`, "Decided" (2026-11-13). What goes over the wire: `protocol.md`; the server's side: `server.md`. **Status:** steps 7 to 9: connecting, pushes, messages, attachments, -names, queries. +names, queries, several clients. ## Who connects: certificates @@ -42,8 +42,11 @@ crl = "ca.crl" # optional; a file not there yet: none Its conventions: -- **One connection per process.** Calls from several threads wait for each - other. +- **Clients.** `BakaShrot_CreateClient()` makes one and returns its + handle, the first argument of every other export; + `BakaShrot_FreeClient(Client)` frees it. Each client has its own + connection, answers and errors, and different clients can be used from + different threads at once. A bad handle fails with `InvalidArgument`. - **`A` and `W` exports:** strings in and out as UTF-8 (`char*`) or UTF-16 (`uint16_t*`, `wchar_t*` on Windows; PureBasic uses these), null-terminated. A null string is an empty one where that means @@ -63,8 +66,11 @@ Its conventions: on the other; the C runtime linked statically on Windows (the release DLL imports system DLLs only). +Every export but `CreateClient` takes the handle first (left out below). + | Exports | What | |---|---| +| `CreateClient()`, `FreeClient` | a new client's handle (0 if it failed); freed, 1 | | `SetCaCertificate`, `SetCertificate`, `SetPrivateKey`, `SetCrl` (`A`/`W`) | PEM text (starting with `-----BEGIN`), or the path of a file holding it; `SetCrl` null or empty for none. Before connecting (`AlreadyConnected`); a file that can't be read is `FileError` | | `Connect(Host, Port)` (`A`/`W`) | TLS with those; refused: `AuthRejected` (the server refused the certificate), `ServerNotVerified` (this client refused the server's), `NotAllowed` (none of its roles is the server's), `VersionMismatch` | | `IsConnected`, `Disconnect` | `IsConnected` notices a connection the server closed | @@ -78,7 +84,7 @@ Its conventions: | `PushMessageWithFile(Topic, Data, FilePath)`, `PushMessageWithData(Topic, Data, *Data, Size)` (`A`/`W`) | the id, -1 on failure; the attachment 1 byte and up, as much as the server takes (`TooBig`); a file read twice (its SHA-256 first), one changed in between refused (`DataMismatch`) | | `SaveAttachment(Topic, Node, MessageId, FilePath)` (`A`/`W`) | its size, -1 on failure (`NotFound`, `NotReady`, `AttachmentMismatch`); a failed one leaves no file | | `LoadAttachment(Topic, Node, MessageId)` (`A`/`W`), then `GetAttachmentData(*Buffer, Size)`, `FreeAttachmentData()` | into memory, for small ones; the getter returns the size, copies nothing if it doesn't fit | -| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the last call failed | +| `GetLastError`, `GetRefusalReason` (`A`/`W`) | why the client's last call failed | The header has each one's comment. Every name starts with `BakaShrot_`. @@ -92,6 +98,8 @@ attachment=None)` (the topic required; the attachment bytes or a path), `latest()`, `get_messages()`, `iter_messages()`, `follow()`, `get_attachment()` (bytes), `save_attachment()` (a file), `list_topics()` / `list_nodes()` (names), `query()` / `query_raw()`. +Each `Client` has its own client in the DLL: several can be connected at +once, from any threads. Errors: `RefusedError`, `ConnectionLostError`, `AuthError` (a certificate refused, either way, or no role allowed), `BakaShrotError`. The DLL is looked for next to the module, or `BAKASHROT_DLL`. The release has a @@ -102,11 +110,11 @@ wheel with the library in it (`pip install bakashrot-*.whl`, nothing else: `bindings/purebasic/BakaShrot_Client_Prototypes.pbi` (with `BakaShrot_ErrorCodes.pbi`): `BakaShrot_LoadClient("bakashrot.dll")`, then -the `W` exports without their suffix, `BakaShrot_*String()` helpers for the -getters. Run directly, it's an example: `ClientExample +the `W` exports without their suffix, the client first, and +`BakaShrot_*String(Client)` helpers for the getters. Run directly, it's an example: `ClientExample `, pushing a message and one -with an attachment, reading both back (run by hand against a server; -not in CI, which has no PureBasic). +with an attachment, reading both back, then a second client at the same +time (run by hand against a server; not in CI, which has no PureBasic). ## The tool @@ -152,12 +160,20 @@ bakashrot list nodes --json {"kind":"node","names":["kitchen" `crates/bakashrot-capi/tests/`, each against a server on a free port: -- `exports.rs`: the exports as C calls them: certificates from files and +- `exports.rs`, `exports`: the exports as C calls them, on one client: certificates from files and PEM, the `W` strings (and some `A`), the buffers (the size, too small, unaligned), selecting messages, attachments (from a file and memory, saved and loaded, the buffer, refused ones), every refusal and the client's own errors, closing, another identity. -- `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL; skipped, saying so, without Python 3.11+. +- `exports.rs`, `clients`: two clients at once, each with its own answers + and errors; bad and freed handles; 4 threads on 4 clients; a client + freed while another thread uses it. +- `python.rs`: runs `bindings/python/check_bakashrot.py` on the DLL (two + `Client`s at once, too); skipped, saying so, without Python 3.11+. +- PureBasic, by hand (no PureBasic in CI): run + `BakaShrot_Client_Prototypes.pbi` directly, `ClientExample + `. Passed 2026-11-17 + with PureBasic 5.73 LTS and 6.41 (C backend), x64. - `header.rs`: `bindings/c/bakashrot.h` matches the exports (rewritten when it doesn't: check it in). diff --git a/docs/known-issues.md b/docs/known-issues.md index a935dbf..0626083 100644 --- a/docs/known-issues.md +++ b/docs/known-issues.md @@ -42,9 +42,8 @@ network**, not exposed to the internet. So: server then needs every node's public key). - **Private keys sit in PEM files**, readable by whoever can read them: on trusted machines, file permissions are enough. -- **One connection per process in the DLL** (`revamp.md`, - "Open questions"): a handle-based API for several. Polling rather than - pushed subscriptions; nothing reconnects by itself, on purpose. +- **Polling rather than pushed subscriptions;** nothing reconnects by + itself, on purpose. - **At least once:** a push whose answer was lost (the server stopped between committing and answering) is stored twice if retried. A client that minds reads the latest message before retrying. diff --git a/revamp.md b/revamp.md index d2efe5d..248fc81 100644 --- a/revamp.md +++ b/revamp.md @@ -189,7 +189,8 @@ Also decided (2026-11-13): - **the old exports that don't fit any more are dropped**, not kept failing: the keys and node setters, the id-based ones, the default topic's `PushMessage()`; - - **one connection per process**, as before (handles maybe later); + - **one connection per process**, as before (replaced by handles + 2026-11-17, below); - **`client.toml`** (server, ca, certificate, key, crl) replaces `client.ini`: Python's `Client.from_file()`, the tools at step 8. - **The tools** (2026-11-14), `docs/client.md`, "The tools": one @@ -299,6 +300,13 @@ Also decided (2026-11-13): not for production. Worth another look if rustls-graviola lets a provider name its algorithms one by one, or ring gets ML-KEM. +- **Several clients per process in the DLL** (2026-11-17, the owner; + old open item 10): `BakaShrot_CreateClient()` returns a handle, the + first argument of every other export (same names as before); + `BakaShrot_FreeClient()` frees it. No default client and no exports + without a handle ("keep something clean"): apps built for the old DLL + need updating. A bad handle fails (`InvalidArgument`). + ## Proposed, to confirm - **A GUI explorer** (2026-11-16, set aside for later): likely **egui** @@ -311,8 +319,7 @@ Also decided (2026-11-13): ## Open questions -- **A handle-based DLL API** (several connections per process, old open item - 10): later maybe, the owner's call (one connection per process for now). +None right now. ## The old open items