├── .gitignore ├── Marefile ├── libzlimdbclient.mare ├── NOTICE ├── src ├── sha256.h ├── sha256.c └── zlimdbclient.c ├── include ├── zlimdbclient.h └── zlimdbprotocol.h └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | *.sdf 3 | *.opensdf 4 | *.suo 5 | *.vcxproj.user 6 | *.vcxproj 7 | *.vcxproj.filters 8 | *.sln 9 | -------------------------------------------------------------------------------- /Marefile: -------------------------------------------------------------------------------- 1 | 2 | targets = { 3 | include "libzlimdbclient.mare" 4 | libzlimdbclient += { 5 | buildDir = "build/$(configuration)" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /libzlimdbclient.mare: -------------------------------------------------------------------------------- 1 | 2 | libzlimdbclient = cStaticLibrary + { 3 | root = { "$(mareDir)/src", "$(mareDir)/include" } 4 | includePaths = { "$(mareDir)/include", "$(mareDir)/../lz4" } 5 | files = { 6 | "$(mareDir)/src/*.c" = cSource 7 | "$(mareDir)/src/*.h" 8 | "$(mareDir)/include/*.h" 9 | } 10 | if tool == "vcxproj" { 11 | libs += { "ws2_32" } 12 | linkFlags += { "/SUBSYSTEM:CONSOLE" } 13 | defines += { "_WINSOCK_DEPRECATED_NO_WARNINGS" } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | 2 | Copyright 2015 Colin Graf 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | -------------------------------------------------------------------------------- /src/sha256.h: -------------------------------------------------------------------------------- 1 | /* Sha256.h -- SHA-256 Hash 2 | 2013-11-27 : Unknown : Public domain 3 | 2010-06-11 : Igor Pavlov : Public domain */ 4 | 5 | #ifndef _SHA256_H 6 | #define _SHA256_H 7 | 8 | #include 9 | #include 10 | 11 | #define SHA256_BLOCK_SIZE 64 12 | #define SHA256_DIGEST_SIZE 32 13 | 14 | typedef struct 15 | { 16 | uint32_t state[8]; 17 | uint64_t count; 18 | uint8_t buffer[64]; 19 | } sha256; 20 | 21 | void sha256_init(sha256* context); 22 | 23 | void sha256_update(sha256* context, const uint8_t* data, size_t size); 24 | void sha256_finalize(sha256* context, uint8_t* digest); 25 | 26 | void sha256_hash(const uint8_t* data, size_t size, uint8_t* result); 27 | void sha256_hmac(const uint8_t* key, size_t keySize, const uint8_t* message, size_t messageSize, uint8_t* result); 28 | 29 | #endif 30 | -------------------------------------------------------------------------------- /include/zlimdbclient.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _ZLIMDB_CLIENT_H 3 | #define _ZLIMDB_CLIENT_H 4 | 5 | #include "zlimdbprotocol.h" 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | typedef struct _zlimdb_ zlimdb; 12 | 13 | typedef void (*zlimdb_callback)(void* user_data, const zlimdb_header* message); 14 | 15 | typedef enum 16 | { 17 | zlimdb_local_error_none, 18 | zlimdb_local_error_system, 19 | zlimdb_local_error_invalid_parameter, 20 | zlimdb_local_error_not_initialized, 21 | zlimdb_local_error_state, 22 | zlimdb_local_error_resolve, 23 | zlimdb_local_error_interrupted, 24 | zlimdb_local_error_timeout, 25 | zlimdb_local_error_invalid_message_data, 26 | zlimdb_local_error_invalid_response, 27 | zlimdb_local_error_buffer_size, 28 | zlimdb_local_error_connection_closed, 29 | } zlimdb_local_error; 30 | 31 | int zlimdb_init(); 32 | int zlimdb_cleanup(); 33 | 34 | zlimdb* zlimdb_create(zlimdb_callback callback, void* user_data); 35 | int zlimdb_free(zlimdb* zdb); 36 | 37 | int zlimdb_connect(zlimdb* zdb, const char* server, uint16_t port, const char* user_name, const char* password); 38 | int zlimdb_is_connected(zlimdb* zdb); 39 | 40 | int zlimdb_errno(); 41 | void zlimdb_seterrno(int errnum); 42 | const char* zlimdb_strerror(int errnum); 43 | 44 | int zlimdb_add_table(zlimdb* zdb, const char* name, uint32_t* table_id); 45 | int zlimdb_find_table(zlimdb* zdb, const char* name, uint32_t* table_id); 46 | int zlimdb_copy_table(zlimdb* zdb, uint32_t table_id, const char* name, uint32_t* new_table_id); 47 | int zlimdb_copy_table_replace(zlimdb* zdb, uint32_t table_id, uint32_t destination_table_id); 48 | int zlimdb_rename_table(zlimdb* zdb, uint32_t table_id, const char* name, uint32_t* new_table_id); 49 | int zlimdb_rename_table_replace(zlimdb* zdb, uint32_t table_id, uint32_t destination_table_id); 50 | int zlimdb_remove_table(zlimdb* zdb, uint32_t table_id); 51 | int zlimdb_add_user(zlimdb* zdb, const char* user_name, const char* password); 52 | 53 | int zlimdb_add(zlimdb* zdb, uint32_t table_id, const zlimdb_entity* data, uint64_t* id); 54 | int zlimdb_update(zlimdb* zdb, uint32_t table_id, const zlimdb_entity* data); 55 | int zlimdb_remove(zlimdb* zdb, uint32_t table_id, uint64_t entity_id); 56 | int zlimdb_clear(zlimdb* zdb, uint32_t table_id); 57 | int zlimdb_query(zlimdb* zdb, uint32_t table_id, zlimdb_query_type type, uint64_t param); 58 | int zlimdb_query_entity(zlimdb* zdb, uint32_t table_id, uint64_t entity_id, zlimdb_entity* entity, uint32_t min_size, uint32_t max_size); 59 | int zlimdb_subscribe(zlimdb* zdb, uint32_t table_id, zlimdb_query_type type, uint64_t param, uint8_t flags); 60 | int zlimdb_get_response(zlimdb* zdb, zlimdb_header* message, uint32_t max_size); 61 | int zlimdb_unsubscribe(zlimdb* zdb, uint32_t table_id); 62 | int zlimdb_sync(zlimdb* zdb, uint32_t table_id, int64_t* server_time, int64_t* table_time); 63 | int zlimdb_control(zlimdb* zdb, uint32_t table_id, uint64_t entity_id, uint32_t control_code, const void* data, uint32_t size, zlimdb_header* message, uint32_t max_size); 64 | int zlimdb_control_respond(zlimdb* zdb, uint32_t request_id, const void* data, uint32_t size); 65 | int zlimdb_control_respond_error(zlimdb* zdb, uint32_t request_id, uint16_t error); 66 | 67 | const zlimdb_entity* zlimdb_get_first_entity(const zlimdb_header* header, uint32_t min_size); 68 | const zlimdb_entity* zlimdb_get_next_entity(const zlimdb_header* header, uint32_t min_size, const zlimdb_entity* entity); 69 | const void* zlimdb_get_request_data(const zlimdb_header* header, uint32_t min_size); 70 | const void* zlimdb_get_response_data(const zlimdb_header* header, uint32_t min_size); 71 | const zlimdb_entity* zlimdb_data_get_first_entity(const void* data, uint32_t size, uint32_t min_size); 72 | const zlimdb_entity* zlimdb_data_get_next_entity(const void* data, uint32_t size, uint32_t min_size, const zlimdb_entity* entity); 73 | 74 | int zlimdb_exec(zlimdb* zdb, uint32_t timeout); 75 | int zlimdb_interrupt(zlimdb* zdb); 76 | 77 | #ifdef __cplusplus 78 | } 79 | #endif 80 | 81 | #endif /* _ZLIMDB_CLIENT_H */ 82 | -------------------------------------------------------------------------------- /include/zlimdbprotocol.h: -------------------------------------------------------------------------------- 1 | 2 | #ifndef _ZLIMDB_PROTOCOL_H 3 | #define _ZLIMDB_PROTOCOL_H 4 | 5 | #include 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | #define ZLIMDB_DEFAULT_PORT 13211 12 | #define ZLIMDB_MAX_ENTITY_SIZE 0xffff 13 | #define ZLIMDB_MAX_MESSAGE_SIZE (128 + ZLIMDB_MAX_ENTITY_SIZE) 14 | 15 | typedef enum 16 | { 17 | zlimdb_message_error_response, 18 | zlimdb_message_login_request, 19 | zlimdb_message_login_response, 20 | zlimdb_message_auth_request, 21 | zlimdb_message_auth_response, 22 | zlimdb_message_add_request, 23 | zlimdb_message_add_response, 24 | zlimdb_message_update_request, 25 | zlimdb_message_update_response, 26 | zlimdb_message_remove_request, 27 | zlimdb_message_remove_response, 28 | zlimdb_message_subscribe_request, 29 | zlimdb_message_subscribe_response, 30 | zlimdb_message_unsubscribe_request, 31 | zlimdb_message_unsubscribe_response, 32 | zlimdb_message_query_request, 33 | zlimdb_message_query_response, 34 | zlimdb_message_sync_request, 35 | zlimdb_message_sync_response, 36 | zlimdb_message_control_request, 37 | zlimdb_message_control_response, 38 | zlimdb_message_clear_request, 39 | zlimdb_message_clear_response, 40 | zlimdb_message_copy_request, 41 | zlimdb_message_copy_response, 42 | zlimdb_message_find_request, 43 | zlimdb_message_find_response, 44 | zlimdb_message_rename_request, 45 | zlimdb_message_rename_response, 46 | zlimdb_message_reload_request, 47 | zlimdb_message_shutdown_request, 48 | } zlimdb_message_type; 49 | 50 | typedef enum 51 | { 52 | zlimdb_table_clients = 1, 53 | zlimdb_table_tables, 54 | } zlimdb_table_id; 55 | 56 | typedef enum 57 | { 58 | zlimdb_error_invalid_message_data = 1000, 59 | zlimdb_error_invalid_message_type, 60 | zlimdb_error_entity_not_found, 61 | zlimdb_error_table_not_found, 62 | zlimdb_error_not_implemented, 63 | zlimdb_error_invalid_request, 64 | zlimdb_error_invalid_login, 65 | zlimdb_error_open_file, 66 | zlimdb_error_read_file, 67 | zlimdb_error_write_file, 68 | zlimdb_error_subscription_not_found, 69 | zlimdb_error_entity_id, 70 | zlimdb_error_table_already_exists, 71 | zlimdb_error_responder_not_available, 72 | zlimdb_error_responder_already_present, 73 | } zlimdb_message_error; 74 | 75 | typedef enum 76 | { 77 | zlimdb_header_flag_fragmented = 0x01, 78 | zlimdb_header_flag_compressed = 0x02, 79 | } zlimdb_header_flag; 80 | 81 | typedef enum 82 | { 83 | zlimdb_query_type_all, 84 | zlimdb_query_type_by_id, 85 | zlimdb_query_type_since_id, 86 | zlimdb_query_type_since_time, 87 | zlimdb_query_type_since_last, 88 | zlimdb_query_type_since_next, 89 | } zlimdb_query_type; 90 | 91 | #pragma pack(push, 1) 92 | typedef struct 93 | { 94 | uint32_t flags:8; ///< @see zlimdb_header_flag 95 | uint32_t size:24; ///< The size of the message including the header. 96 | uint16_t message_type; ///< @see zlimdb_message_type 97 | uint32_t request_id; ///< An identifier that can be chosen by the client. The response will carry the same identifier. 98 | } zlimdb_header; 99 | 100 | typedef struct 101 | { 102 | zlimdb_header header; 103 | uint16_t error; ///< @see zlimdb_message_error 104 | } zlimdb_error_response; 105 | 106 | typedef struct 107 | { 108 | zlimdb_header header; 109 | uint16_t user_name_size; ///< The length of the user name. 110 | } zlimdb_login_request; 111 | 112 | typedef struct 113 | { 114 | zlimdb_header header; 115 | uint8_t pw_salt[32]; 116 | uint8_t auth_salt[32]; 117 | } zlimdb_login_response; 118 | 119 | typedef struct 120 | { 121 | zlimdb_header header; 122 | uint8_t signature[32]; 123 | } zlimdb_auth_request; 124 | 125 | typedef struct 126 | { 127 | zlimdb_header header; 128 | uint32_t table_id; 129 | } zlimdb_add_request; 130 | 131 | typedef struct 132 | { 133 | zlimdb_header header; 134 | uint64_t id; 135 | } zlimdb_add_response; 136 | 137 | typedef zlimdb_add_request zlimdb_update_request; 138 | typedef zlimdb_add_request zlimdb_clear_request; 139 | typedef zlimdb_add_request zlimdb_find_request; 140 | typedef zlimdb_add_request zlimdb_reload_request; 141 | 142 | typedef struct 143 | { 144 | zlimdb_header header; 145 | uint32_t table_id; 146 | uint32_t destination_table_id; 147 | } zlimdb_copy_request; 148 | 149 | typedef zlimdb_copy_request zlimdb_rename_request; 150 | 151 | typedef struct 152 | { 153 | zlimdb_header header; 154 | uint32_t table_id; 155 | uint64_t id; 156 | } zlimdb_remove_request; 157 | 158 | typedef struct 159 | { 160 | zlimdb_header header; 161 | uint32_t table_id; 162 | uint8_t type; ///< @see zlimdb_query_type 163 | uint64_t param; 164 | } zlimdb_query_request; 165 | 166 | typedef enum 167 | { 168 | zlimdb_subscribe_flag_none = 0x00, 169 | zlimdb_subscribe_flag_responder = 0x01, 170 | } zlimdb_subscribe_flag; 171 | 172 | typedef struct 173 | { 174 | zlimdb_query_request query; 175 | uint8_t flags; ///< @see zlimdb_subscribe_flag 176 | } zlimdb_subscribe_request; 177 | 178 | typedef struct 179 | { 180 | zlimdb_header header; 181 | uint32_t table_id; 182 | } zlimdb_unsubscribe_request; 183 | 184 | typedef struct 185 | { 186 | zlimdb_header header; 187 | uint32_t table_id; 188 | } zlimdb_sync_request; 189 | 190 | typedef struct 191 | { 192 | zlimdb_header header; 193 | int64_t server_time; 194 | int64_t table_time; 195 | } zlimdb_sync_response; 196 | 197 | typedef struct 198 | { 199 | zlimdb_header header; 200 | uint32_t table_id; 201 | uint64_t id; 202 | uint32_t control_code; 203 | } zlimdb_control_request; 204 | 205 | typedef zlimdb_add_response zlimdb_copy_response; 206 | typedef zlimdb_add_response zlimdb_find_response; 207 | typedef zlimdb_add_response zlimdb_rename_response; 208 | 209 | typedef struct 210 | { 211 | uint64_t id; 212 | uint64_t time; 213 | uint16_t size; 214 | } zlimdb_entity; 215 | 216 | typedef struct 217 | { 218 | zlimdb_entity entity; 219 | uint8_t flags; // todo: flags like "private", "public"... 220 | uint16_t name_size; 221 | } zlimdb_table_entity; 222 | 223 | typedef struct 224 | { 225 | zlimdb_entity entity; 226 | uint8_t pw_salt[32]; 227 | uint8_t pw_hash[32]; 228 | } zlimdb_user_entity; 229 | 230 | #pragma pack(pop) 231 | 232 | #ifdef __cplusplus 233 | } 234 | #endif 235 | 236 | #endif // _ZLIMDB_PROTOCOL_H 237 | -------------------------------------------------------------------------------- /src/sha256.c: -------------------------------------------------------------------------------- 1 | /* Crypto/Sha256.c -- SHA-256 Hash 2 | 2013-11-27 : Unknown : Public domain 3 | 2010-06-11 : Igor Pavlov : Public domain 4 | This code is based on public domain code from Wei Dai's Crypto++ library. */ 5 | 6 | #include 7 | #ifdef _MSC_VER 8 | #include 9 | #endif 10 | 11 | #include "sha256.h" 12 | 13 | #ifdef _MSC_VER 14 | #define rotlFixed(x, n) _rotl((x), (n)) 15 | #define rotrFixed(x, n) _rotr((x), (n)) 16 | #else 17 | #define rotlFixed(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) 18 | #define rotrFixed(x, n) (((x) >> (n)) | ((x) << (32 - (n)))) 19 | #endif 20 | 21 | typedef uint32_t UInt32; 22 | typedef uint8_t Byte; 23 | typedef uint64_t UInt64; 24 | 25 | 26 | /* define it for speed optimization */ 27 | /* #define _SHA256_UNROLL */ 28 | /* #define _SHA256_UNROLL2 */ 29 | 30 | void sha256_init(sha256* p) 31 | { 32 | p->state[0] = 0x6a09e667; 33 | p->state[1] = 0xbb67ae85; 34 | p->state[2] = 0x3c6ef372; 35 | p->state[3] = 0xa54ff53a; 36 | p->state[4] = 0x510e527f; 37 | p->state[5] = 0x9b05688c; 38 | p->state[6] = 0x1f83d9ab; 39 | p->state[7] = 0x5be0cd19; 40 | p->count = 0; 41 | } 42 | 43 | #define S0(x) (rotrFixed(x, 2) ^ rotrFixed(x,13) ^ rotrFixed(x, 22)) 44 | #define S1(x) (rotrFixed(x, 6) ^ rotrFixed(x,11) ^ rotrFixed(x, 25)) 45 | #define s0(x) (rotrFixed(x, 7) ^ rotrFixed(x,18) ^ (x >> 3)) 46 | #define s1(x) (rotrFixed(x,17) ^ rotrFixed(x,19) ^ (x >> 10)) 47 | 48 | #define blk0(i) (W[i] = data[i]) 49 | #define blk2(i) (W[i&15] += s1(W[(i-2)&15]) + W[(i-7)&15] + s0(W[(i-15)&15])) 50 | 51 | #define Ch(x,y,z) (z^(x&(y^z))) 52 | #define Maj(x,y,z) ((x&y)|(z&(x|y))) 53 | 54 | #define a(i) T[(0-(i))&7] 55 | #define b(i) T[(1-(i))&7] 56 | #define c(i) T[(2-(i))&7] 57 | #define d(i) T[(3-(i))&7] 58 | #define e(i) T[(4-(i))&7] 59 | #define f(i) T[(5-(i))&7] 60 | #define g(i) T[(6-(i))&7] 61 | #define h(i) T[(7-(i))&7] 62 | 63 | 64 | #ifdef _SHA256_UNROLL2 65 | 66 | #define R(a,b,c,d,e,f,g,h, i) h += S1(e) + Ch(e,f,g) + K[i+j] + (j?blk2(i):blk0(i));\ 67 | d += h; h += S0(a) + Maj(a, b, c) 68 | 69 | #define RX_8(i) \ 70 | R(a,b,c,d,e,f,g,h, i); \ 71 | R(h,a,b,c,d,e,f,g, i+1); \ 72 | R(g,h,a,b,c,d,e,f, i+2); \ 73 | R(f,g,h,a,b,c,d,e, i+3); \ 74 | R(e,f,g,h,a,b,c,d, i+4); \ 75 | R(d,e,f,g,h,a,b,c, i+5); \ 76 | R(c,d,e,f,g,h,a,b, i+6); \ 77 | R(b,c,d,e,f,g,h,a, i+7) 78 | 79 | #else 80 | 81 | #define R(i) h(i) += S1(e(i)) + Ch(e(i),f(i),g(i)) + K[i+j] + (j?blk2(i):blk0(i));\ 82 | d(i) += h(i); h(i) += S0(a(i)) + Maj(a(i), b(i), c(i)) 83 | 84 | #ifdef _SHA256_UNROLL 85 | 86 | #define RX_8(i) R(i+0); R(i+1); R(i+2); R(i+3); R(i+4); R(i+5); R(i+6); R(i+7); 87 | 88 | #endif 89 | 90 | #endif 91 | 92 | static const UInt32 K[64] = { 93 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 94 | 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 95 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 96 | 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 97 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 98 | 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 99 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 100 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 101 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 102 | 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 103 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 104 | 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 105 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 106 | 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 107 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 108 | 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 109 | }; 110 | 111 | static void sha256_transform(UInt32 *state, const UInt32 *data) 112 | { 113 | UInt32 W[16]; 114 | unsigned j; 115 | #ifdef _SHA256_UNROLL2 116 | UInt32 a,b,c,d,e,f,g,h; 117 | a = state[0]; 118 | b = state[1]; 119 | c = state[2]; 120 | d = state[3]; 121 | e = state[4]; 122 | f = state[5]; 123 | g = state[6]; 124 | h = state[7]; 125 | #else 126 | UInt32 T[8]; 127 | for (j = 0; j < 8; j++) 128 | T[j] = state[j]; 129 | #endif 130 | 131 | for (j = 0; j < 64; j += 16) 132 | { 133 | #if defined(_SHA256_UNROLL) || defined(_SHA256_UNROLL2) 134 | RX_8(0); RX_8(8); 135 | #else 136 | unsigned i; 137 | for (i = 0; i < 16; i++) { R(i); } 138 | #endif 139 | } 140 | 141 | #ifdef _SHA256_UNROLL2 142 | state[0] += a; 143 | state[1] += b; 144 | state[2] += c; 145 | state[3] += d; 146 | state[4] += e; 147 | state[5] += f; 148 | state[6] += g; 149 | state[7] += h; 150 | #else 151 | for (j = 0; j < 8; j++) 152 | state[j] += T[j]; 153 | #endif 154 | 155 | /* Wipe variables */ 156 | /* memset(W, 0, sizeof(W)); */ 157 | /* memset(T, 0, sizeof(T)); */ 158 | } 159 | 160 | #undef S0 161 | #undef S1 162 | #undef s0 163 | #undef s1 164 | 165 | static void sha256_write_byte_block(sha256 *p) 166 | { 167 | UInt32 data32[16]; 168 | unsigned i; 169 | for (i = 0; i < 16; i++) 170 | data32[i] = 171 | ((UInt32)(p->buffer[i * 4 ]) << 24) + 172 | ((UInt32)(p->buffer[i * 4 + 1]) << 16) + 173 | ((UInt32)(p->buffer[i * 4 + 2]) << 8) + 174 | ((UInt32)(p->buffer[i * 4 + 3])); 175 | sha256_transform(p->state, data32); 176 | } 177 | 178 | void sha256_update(sha256* p, const Byte *data, size_t size) 179 | { 180 | UInt32 curBufferPos = (UInt32)p->count & 0x3F; 181 | while (size > 0) 182 | { 183 | p->buffer[curBufferPos++] = *data++; 184 | p->count++; 185 | size--; 186 | if (curBufferPos == 64) 187 | { 188 | curBufferPos = 0; 189 | sha256_write_byte_block(p); 190 | } 191 | } 192 | } 193 | 194 | void sha256_finalize(sha256* p, uint8_t* digest) 195 | { 196 | UInt64 lenInBits = (p->count << 3); 197 | UInt32 curBufferPos = (UInt32)p->count & 0x3F; 198 | unsigned i; 199 | p->buffer[curBufferPos++] = 0x80; 200 | while (curBufferPos != (64 - 8)) 201 | { 202 | curBufferPos &= 0x3F; 203 | if (curBufferPos == 0) 204 | sha256_write_byte_block(p); 205 | p->buffer[curBufferPos++] = 0; 206 | } 207 | for (i = 0; i < 8; i++) 208 | { 209 | p->buffer[curBufferPos++] = (Byte)(lenInBits >> 56); 210 | lenInBits <<= 8; 211 | } 212 | sha256_write_byte_block(p); 213 | 214 | for (i = 0; i < 8; i++) 215 | { 216 | *digest++ = (Byte)(p->state[i] >> 24); 217 | *digest++ = (Byte)(p->state[i] >> 16); 218 | *digest++ = (Byte)(p->state[i] >> 8); 219 | *digest++ = (Byte)(p->state[i]); 220 | } 221 | sha256_init(p); 222 | } 223 | 224 | void sha256_hash(const uint8_t* data, size_t size, uint8_t* result) 225 | { 226 | sha256 context; 227 | sha256_init(&context); 228 | sha256_update(&context, data, size); 229 | sha256_finalize(&context, result); 230 | } 231 | 232 | void sha256_hmac(const uint8_t* key, size_t keySize, const uint8_t* message, size_t messageSize, uint8_t* result) 233 | { 234 | sha256 context; 235 | sha256_init(&context); 236 | uint8_t hashKey[SHA256_BLOCK_SIZE]; 237 | if(keySize > SHA256_BLOCK_SIZE) 238 | { 239 | sha256_update(&context, key, keySize); 240 | sha256_finalize(&context, hashKey); 241 | memset(hashKey + 32, 0, 32); 242 | } 243 | else 244 | { 245 | memcpy(hashKey, key, keySize); 246 | if(keySize < SHA256_BLOCK_SIZE) 247 | memset(hashKey + keySize, 0, SHA256_BLOCK_SIZE - keySize); 248 | } 249 | 250 | uint8_t oKeyPad[SHA256_BLOCK_SIZE]; 251 | uint8_t iKeyPad[SHA256_BLOCK_SIZE]; 252 | int i; 253 | for(i = 0; i < SHA256_BLOCK_SIZE; ++i) 254 | { 255 | oKeyPad[i] = hashKey[i] ^ 0x5c; 256 | iKeyPad[i] = hashKey[i] ^ 0x36; 257 | } 258 | uint8_t hash[SHA256_DIGEST_SIZE]; 259 | sha256_update(&context, iKeyPad, SHA256_BLOCK_SIZE); 260 | sha256_update(&context, message, messageSize); 261 | sha256_finalize(&context, hash); 262 | sha256_update(&context, oKeyPad, SHA256_BLOCK_SIZE); 263 | sha256_update(&context, hash, SHA256_DIGEST_SIZE); 264 | sha256_finalize(&context, result); 265 | } 266 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /src/zlimdbclient.c: -------------------------------------------------------------------------------- 1 | 2 | #ifdef _WIN32 3 | #include 4 | #else 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #endif 15 | #include 16 | #include 17 | #include 18 | 19 | #include "zlimdbclient.h" 20 | #include "sha256.h" 21 | 22 | #ifdef _WIN32 23 | #define ERRNO WSAGetLastError() 24 | #define SET_ERRNO(e) WSASetLastError(e) 25 | #ifdef EWOULDBLOCK 26 | #undef EWOULDBLOCK 27 | #endif 28 | #define EWOULDBLOCK WSAEWOULDBLOCK 29 | #ifdef EINPROGRESS 30 | #undef EINPROGRESS 31 | #endif 32 | #define EINPROGRESS WSAEINPROGRESS 33 | #ifdef EINVAL 34 | #undef EINVAL 35 | #endif 36 | #define EINVAL WSAEINVAL 37 | #define CLOSE closesocket 38 | typedef int socklen_t; 39 | #define MSG_NOSIGNAL 0 40 | #else 41 | typedef int SOCKET; 42 | #define INVALID_SOCKET (-1) 43 | #define ERRNO errno 44 | #define SET_ERRNO(e) (errno = e) 45 | #define CLOSE close 46 | #define SOCKET_ERROR (-1) 47 | #endif 48 | 49 | typedef enum 50 | { 51 | _zlimdb_state_disconnected, 52 | _zlimdb_state_connected, 53 | _zlimdb_state_error, 54 | } _zlimdb_state; 55 | 56 | typedef struct _zlimdb_messageData_ _zlimdb_messageData; 57 | struct _zlimdb_messageData_ 58 | { 59 | _zlimdb_messageData* next; 60 | }; 61 | 62 | typedef enum 63 | { 64 | _zlimdb_requestState_receiving, 65 | _zlimdb_requestState_finished, 66 | } _zlimdb_requestState; 67 | 68 | typedef struct _zlimdb_requestData_ _zlimdb_requestData; 69 | struct _zlimdb_requestData_ 70 | { 71 | uint32_t requestId; 72 | _zlimdb_requestState state; 73 | _zlimdb_messageData* response; 74 | _zlimdb_messageData* lastResponse; 75 | _zlimdb_requestData* next; 76 | }; 77 | 78 | struct _zlimdb_ 79 | { 80 | _zlimdb_state state; 81 | SOCKET socket; 82 | #ifdef _WIN32 83 | HANDLE hInterruptEvent; 84 | HANDLE hReadEvent; 85 | DWORD selectedEvents; 86 | #else 87 | int interruptEventFd; 88 | #endif 89 | zlimdb_callback callback; 90 | void* userData; 91 | _zlimdb_messageData* queuedMessage; 92 | _zlimdb_messageData* lastQueuedMessage; 93 | uint32_t lastRequestId; 94 | _zlimdb_requestData* openRequest; 95 | _zlimdb_requestData* unusedRequest; 96 | _zlimdb_requestData requestData; 97 | }; 98 | 99 | #ifdef _MSC_VER 100 | static int __declspec(thread) zlimdbErrno = zlimdb_local_error_none; 101 | #else 102 | static int __thread zlimdbErrno = zlimdb_local_error_none; 103 | #endif 104 | 105 | static volatile long zlimdbInitCalls = 0; 106 | 107 | static void _zlimdb_freeMessages(_zlimdb_messageData* message) 108 | { 109 | _zlimdb_messageData* next; 110 | for(; message; message = next) 111 | { 112 | next = message->next; 113 | free(message); 114 | } 115 | } 116 | 117 | static int _zlimdb_sendRequest(zlimdb* zdb, zlimdb_header* header) 118 | { 119 | assert(zdb); 120 | assert(header->size >= sizeof(zlimdb_header)); 121 | 122 | header->flags = 0; 123 | 124 | #ifdef _WIN32 125 | unsigned int sentSize = 0; 126 | do 127 | { 128 | int res = send(zdb->socket, (const char*)header + sentSize, header->size - sentSize, 0); 129 | if(res < 0) 130 | { 131 | if(ERRNO == WSAEWOULDBLOCK) 132 | { 133 | if(zdb->selectedEvents) 134 | { 135 | WSAEventSelect(zdb->socket, zdb->hReadEvent, 0); 136 | zdb->selectedEvents = 0; 137 | } 138 | u_long val = 0; 139 | if(ioctlsocket(zdb->socket, FIONBIO, &val) != 0) 140 | { 141 | zdb->state = _zlimdb_state_error; 142 | return zlimdbErrno = zlimdb_local_error_system, -1; 143 | } 144 | continue; 145 | } 146 | zdb->state = _zlimdb_state_error; 147 | return zlimdbErrno = zlimdb_local_error_system, -1; 148 | } 149 | sentSize += res; 150 | } while(sentSize < header->size); 151 | #else 152 | int res = send(zdb->socket, (const char*)header, header->size, 0); 153 | if(res < 0) 154 | { 155 | zdb->state = _zlimdb_state_error; 156 | return zlimdbErrno = zlimdb_local_error_system, -1; 157 | } 158 | assert(res == header->size); 159 | #endif 160 | return 0; 161 | } 162 | 163 | static int _zlimdb_receiveData(zlimdb* zdb, void* data, size_t size) 164 | { 165 | assert(zdb); 166 | assert(data); 167 | 168 | unsigned int receivedSize = 0; 169 | while(receivedSize < size) 170 | { 171 | int res = recv(zdb->socket, (char*)data + receivedSize, size - receivedSize, 0); 172 | if(res == 0) 173 | { 174 | zdb->state = _zlimdb_state_error; 175 | return zlimdbErrno = zlimdb_local_error_connection_closed, -1; 176 | } 177 | else if(res < 0) 178 | { 179 | #ifdef _WIN32 180 | if(ERRNO == WSAEWOULDBLOCK) 181 | { 182 | if(zdb->selectedEvents) 183 | { 184 | WSAEventSelect(zdb->socket, zdb->hReadEvent, 0); 185 | zdb->selectedEvents = 0; 186 | } 187 | u_long val = 0; 188 | if(ioctlsocket(zdb->socket, FIONBIO, &val) != 0) 189 | { 190 | zdb->state = _zlimdb_state_error; 191 | return zlimdbErrno = zlimdb_local_error_system, -1; 192 | } 193 | continue; 194 | } 195 | #endif 196 | zdb->state = _zlimdb_state_error; 197 | return zlimdbErrno = zlimdb_local_error_system, -1; 198 | } 199 | receivedSize += res; 200 | } 201 | return 0; 202 | } 203 | 204 | static int _zlimdb_receiveHeader(zlimdb* zdb, zlimdb_header* header) 205 | { 206 | assert(zdb); 207 | assert(header); 208 | 209 | if(_zlimdb_receiveData(zdb, header, sizeof(zlimdb_header)) != 0) 210 | return -1; 211 | if(header->size < sizeof(zlimdb_header) || header->size > ZLIMDB_MAX_MESSAGE_SIZE) 212 | { 213 | zdb->state = _zlimdb_state_error; 214 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 215 | } 216 | return 0; 217 | } 218 | 219 | static int _zlimdb_receiveResponseData(zlimdb* zdb, const zlimdb_header* header, void* data, size_t maxSize) 220 | { 221 | assert(zdb); 222 | assert(header); 223 | assert(data); 224 | 225 | if(header->message_type == zlimdb_message_error_response) 226 | { 227 | if(header->size != sizeof(zlimdb_error_response)) 228 | { 229 | zdb->state = _zlimdb_state_error; 230 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 231 | } 232 | zlimdb_error_response errorResponse; 233 | if(_zlimdb_receiveData(zdb, &errorResponse.header + 1, sizeof(errorResponse) - sizeof(zlimdb_header)) != 0) 234 | return -1; 235 | return zlimdbErrno = errorResponse.error, -1; 236 | } 237 | size_t dataSize = header->size - sizeof(zlimdb_header); 238 | if(dataSize > 0) 239 | { 240 | if(dataSize > maxSize) 241 | { 242 | zdb->state = _zlimdb_state_error; 243 | return zlimdbErrno = zlimdb_local_error_buffer_size, -1; 244 | } 245 | if(_zlimdb_receiveData(zdb, data, dataSize) != 0) 246 | return -1; 247 | } 248 | return 0; 249 | } 250 | 251 | static int _zlimdb_copyResponse(zlimdb* zdb, const _zlimdb_messageData* response, zlimdb_header* message, size_t maxSize) 252 | { 253 | assert(zdb); 254 | assert(response); 255 | assert(message); 256 | assert(maxSize >= sizeof(zlimdb_header)); 257 | 258 | const zlimdb_header* header = (const zlimdb_header*)(response + 1); 259 | if(header->message_type == zlimdb_message_error_response) 260 | { 261 | if(header->size != sizeof(zlimdb_error_response)) 262 | { 263 | zdb->state = _zlimdb_state_error; 264 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 265 | } 266 | return zlimdbErrno = ((const zlimdb_error_response*)header)->error, -1; 267 | } 268 | if(header->size > maxSize) 269 | { 270 | zdb->state = _zlimdb_state_error; 271 | return zlimdbErrno = zlimdb_local_error_buffer_size, -1; 272 | } 273 | memcpy(message, header, header->size); 274 | return 0; 275 | } 276 | 277 | static int _zlimdb_receiveLoginResponse(zlimdb* zdb, void* message, size_t size) 278 | { 279 | assert(zdb); 280 | assert(message); 281 | assert(size >= sizeof(zlimdb_header)); 282 | 283 | zlimdb_header* header = message; 284 | if(_zlimdb_receiveHeader(zdb, header) != 0) 285 | return -1; 286 | if(header->request_id != 1 || header->flags) 287 | { 288 | zdb->state = _zlimdb_state_error; 289 | return zlimdbErrno = zlimdb_local_error_invalid_response, -1; 290 | } 291 | if(_zlimdb_receiveResponseData(zdb, header, header + 1, size - sizeof(zlimdb_header)) != 0) 292 | return -1; 293 | return 0; 294 | } 295 | 296 | static int _zlimdb_receiveResponse(zlimdb* zdb, uint32_t requestId, void* message, size_t maxSize) 297 | { 298 | assert(zdb); 299 | assert(requestId); 300 | assert(message); 301 | assert(maxSize >= sizeof(zlimdb_header)); 302 | 303 | // receive new response 304 | zlimdb_header* header = message; 305 | for(;;) 306 | { 307 | if(_zlimdb_receiveHeader(zdb, header) != 0) 308 | return -1; 309 | if(header->request_id == requestId) 310 | return _zlimdb_receiveResponseData(zdb, header, header + 1, maxSize - sizeof(zlimdb_header)); 311 | else if(header->request_id && header->message_type != zlimdb_message_control_request) 312 | { 313 | _zlimdb_requestData* request; 314 | for(request = zdb->openRequest; request; request = request->next) 315 | if(request->requestId == header->request_id) 316 | goto receiveResponse; 317 | zdb->state = _zlimdb_state_error; 318 | return zlimdbErrno = zlimdb_local_error_invalid_response, -1; 319 | receiveResponse: ; 320 | 321 | _zlimdb_messageData* response = malloc(sizeof(_zlimdb_messageData) + header->size); 322 | if(!response) 323 | { 324 | zdb->state = _zlimdb_state_error; 325 | return zlimdbErrno = zlimdb_local_error_system, -1; 326 | } 327 | void* buffer = response + 1; 328 | if(_zlimdb_receiveData(zdb, (zlimdb_header*)buffer + 1, header->size - sizeof(zlimdb_header)) != 0) 329 | return -1; 330 | *(zlimdb_header*)buffer = *header; 331 | response->next = 0; 332 | if(request->response) 333 | request->lastResponse->next = response; 334 | else 335 | request->response = response; 336 | request->lastResponse = response; 337 | } 338 | else 339 | { 340 | size_t bufferSize = header->size; 341 | void* buffer = malloc(sizeof(_zlimdb_messageData) + bufferSize); 342 | if(!buffer) 343 | { 344 | zdb->state = _zlimdb_state_error; 345 | return zlimdbErrno = zlimdb_local_error_system, -1; 346 | } 347 | if(_zlimdb_receiveData(zdb, (zlimdb_header*)((_zlimdb_messageData*)buffer + 1) + 1, bufferSize - sizeof(zlimdb_header)) != 0) 348 | return -1; 349 | *(zlimdb_header*)((_zlimdb_messageData*)buffer + 1) = *header; 350 | ((_zlimdb_messageData*)buffer)->next = 0; 351 | if(zdb->queuedMessage) 352 | zdb->lastQueuedMessage->next = buffer; 353 | else 354 | zdb->queuedMessage = buffer; 355 | zdb->lastQueuedMessage = buffer; 356 | } 357 | } 358 | } 359 | 360 | 361 | int zlimdb_init() 362 | { 363 | #ifdef _WIN32 364 | if(InterlockedIncrement(&zlimdbInitCalls) == 1) 365 | { 366 | WORD wVersionRequested = MAKEWORD(2, 2); 367 | WSADATA wsaData; 368 | if(WSAStartup(wVersionRequested, &wsaData) != 0) 369 | { 370 | InterlockedDecrement(&zlimdbInitCalls); 371 | return zlimdbErrno = zlimdb_local_error_system, -1; 372 | } 373 | } 374 | #else 375 | __sync_add_and_fetch(&zlimdbInitCalls, 1); 376 | #endif 377 | return zlimdbErrno = zlimdb_local_error_none, 0; 378 | } 379 | 380 | int zlimdb_cleanup() 381 | { 382 | #ifdef _WIN32 383 | if(InterlockedDecrement(&zlimdbInitCalls) == 0) 384 | { 385 | if(WSACleanup() != 0) 386 | { 387 | InterlockedIncrement(&zlimdbInitCalls); 388 | return zlimdbErrno = zlimdb_local_error_system, -1; 389 | } 390 | } 391 | #else 392 | __sync_add_and_fetch(&zlimdbInitCalls, -1); 393 | #endif 394 | return zlimdbErrno = zlimdb_local_error_none, 0; 395 | } 396 | 397 | zlimdb* zlimdb_create(zlimdb_callback callback, void* userData) 398 | { 399 | if(zlimdbInitCalls == 0) 400 | return zlimdbErrno = zlimdb_local_error_not_initialized, (zlimdb*)0; 401 | 402 | zlimdb* zdb = malloc(sizeof(zlimdb)); 403 | if(!zdb) 404 | return zlimdbErrno = zlimdb_local_error_system, (zlimdb*)0; 405 | 406 | zdb->lastRequestId = 0; 407 | zdb->openRequest = 0; 408 | zdb->requestData.next = 0; 409 | zdb->unusedRequest = &zdb->requestData; 410 | zdb->socket = INVALID_SOCKET; 411 | zdb->queuedMessage = 0; 412 | #ifdef _WIN32 413 | zdb->hInterruptEvent = WSA_INVALID_EVENT; 414 | zdb->hReadEvent = WSA_INVALID_EVENT; 415 | if((zdb->hInterruptEvent = WSACreateEvent()) == WSA_INVALID_EVENT || 416 | (zdb->hReadEvent = WSACreateEvent()) == WSA_INVALID_EVENT) 417 | { 418 | zlimdb_free(zdb); 419 | return zlimdbErrno = zlimdb_local_error_system, 0; 420 | } 421 | zdb->selectedEvents = 0; 422 | #else 423 | zdb->interruptEventFd = eventfd(0, EFD_CLOEXEC); 424 | if(zdb->interruptEventFd == INVALID_SOCKET) 425 | { 426 | zlimdb_free(zdb); 427 | return zlimdbErrno = zlimdb_local_error_system, (zlimdb*)0; 428 | } 429 | #endif 430 | zdb->state = _zlimdb_state_disconnected; 431 | zdb->callback = callback; 432 | zdb->userData = userData; 433 | return zlimdbErrno = zlimdb_local_error_none, zdb; 434 | } 435 | 436 | int zlimdb_free(zlimdb* zdb) 437 | { 438 | if(!zdb) 439 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 440 | 441 | if(zdb->socket != INVALID_SOCKET) 442 | CLOSE(zdb->socket); 443 | #ifdef _WIN32 444 | if(zdb->hInterruptEvent != WSA_INVALID_EVENT) 445 | WSACloseEvent(zdb->hInterruptEvent); 446 | if(zdb->hReadEvent != WSA_INVALID_EVENT) 447 | WSACloseEvent(zdb->hReadEvent); 448 | #else 449 | if(zdb->interruptEventFd != INVALID_SOCKET) 450 | CLOSE(zdb->interruptEventFd); 451 | #endif 452 | { 453 | _zlimdb_requestData* i, *next; 454 | for(i = zdb->openRequest; i; i = next) 455 | { 456 | next = i->next; 457 | _zlimdb_freeMessages(i->response); 458 | if(i != &zdb->requestData) 459 | free(i); 460 | } 461 | for(i = zdb->unusedRequest; i; i = next) 462 | { 463 | next = i->next; 464 | if(i != &zdb->requestData) 465 | free(i); 466 | } 467 | } 468 | _zlimdb_freeMessages(zdb->queuedMessage); 469 | free(zdb); 470 | return zlimdbErrno = zlimdb_local_error_none, 0; 471 | } 472 | 473 | int zlimdb_connect(zlimdb* zdb, const char* server, uint16_t port, const char* userName, const char* password) 474 | { 475 | if(!zdb || !userName || !password) 476 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 477 | size_t userNameSize = strlen(userName) + 1; 478 | if(sizeof(zlimdb_login_request) + userNameSize > ZLIMDB_MAX_MESSAGE_SIZE) 479 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 480 | 481 | if(zdb->state != _zlimdb_state_disconnected) 482 | return zlimdbErrno = zlimdb_local_error_state, -1; 483 | 484 | assert(zdb->socket == INVALID_SOCKET); 485 | #ifdef _WIN32 486 | zdb->socket = socket(AF_INET, SOCK_STREAM, 0); 487 | #else 488 | zdb->socket = socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); 489 | #endif 490 | if(zdb->socket == INVALID_SOCKET) 491 | return zlimdbErrno = zlimdb_local_error_system, -1; 492 | 493 | struct sockaddr_in sin; 494 | memset(&sin, 0, sizeof(sin)); 495 | sin.sin_family = AF_INET; 496 | sin.sin_port = htons(port ? port : ZLIMDB_DEFAULT_PORT); 497 | sin.sin_addr.s_addr = server ? inet_addr(server) : htonl(INADDR_LOOPBACK); 498 | if(ntohl(sin.sin_addr.s_addr) == INADDR_NONE) 499 | { 500 | int err = ERRNO; 501 | CLOSE(zdb->socket); 502 | SET_ERRNO(err); 503 | zdb->socket = INVALID_SOCKET; 504 | return zlimdbErrno = zlimdb_local_error_resolve, -1; 505 | } 506 | 507 | if(connect(zdb->socket, (struct sockaddr*)&sin, sizeof(sin)) != 0) 508 | { 509 | int err = ERRNO; 510 | CLOSE(zdb->socket); 511 | SET_ERRNO(err); 512 | zdb->socket = INVALID_SOCKET; 513 | return zlimdbErrno = zlimdb_local_error_system, -1; 514 | } 515 | 516 | // send login request 517 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 518 | zlimdb_login_request* loginRequest = (zlimdb_login_request*)buffer; 519 | loginRequest->header.size = sizeof(zlimdb_login_request) + userNameSize; 520 | loginRequest->header.message_type = zlimdb_message_login_request; 521 | loginRequest->header.request_id = 1; 522 | loginRequest->user_name_size = (uint16_t)userNameSize; 523 | memcpy(loginRequest + 1, userName, userNameSize); 524 | if(_zlimdb_sendRequest(zdb, &loginRequest->header) != 0) 525 | { 526 | int err = ERRNO; 527 | CLOSE(zdb->socket); 528 | SET_ERRNO(err); 529 | zdb->socket = INVALID_SOCKET; 530 | return -1; 531 | } 532 | 533 | // receive login response 534 | zlimdb_login_response loginResponse; 535 | if(_zlimdb_receiveLoginResponse(zdb, &loginResponse, sizeof(zlimdb_login_response)) != 0) 536 | { 537 | int err = ERRNO; 538 | CLOSE(zdb->socket); 539 | SET_ERRNO(err); 540 | zdb->socket = INVALID_SOCKET; 541 | return -1; 542 | } 543 | 544 | // send auth request 545 | size_t passwordLen = strlen(password); 546 | zlimdb_auth_request authRequest; 547 | authRequest.header.size = sizeof(zlimdb_auth_request); 548 | authRequest.header.message_type = zlimdb_message_auth_request; 549 | authRequest.header.request_id = 1; 550 | uint8_t pwHash[32]; 551 | sha256_hmac(loginResponse.pw_salt, sizeof(loginResponse.pw_salt), (const uint8_t*)password, passwordLen , pwHash); 552 | sha256_hmac(loginResponse.auth_salt, sizeof(loginResponse.auth_salt), pwHash, sizeof(pwHash), authRequest.signature); 553 | if(_zlimdb_sendRequest(zdb, &authRequest.header) != 0) 554 | { 555 | int err = ERRNO; 556 | CLOSE(zdb->socket); 557 | SET_ERRNO(err); 558 | zdb->socket = INVALID_SOCKET; 559 | return -1; 560 | } 561 | 562 | // receive auth response 563 | zlimdb_header authReponse; 564 | if(_zlimdb_receiveLoginResponse(zdb, &authReponse, sizeof(zlimdb_header)) != 0) 565 | { 566 | int err = ERRNO; 567 | CLOSE(zdb->socket); 568 | SET_ERRNO(err); 569 | zdb->socket = INVALID_SOCKET; 570 | return -1; 571 | } 572 | 573 | zdb->state = _zlimdb_state_connected; 574 | return zlimdbErrno = zlimdb_local_error_none, 0; 575 | } 576 | 577 | int zlimdb_is_connected(zlimdb* zdb) 578 | { 579 | if(!zdb) 580 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 581 | 582 | zlimdbErrno = zlimdb_local_error_none; 583 | if(zdb->state != _zlimdb_state_connected) 584 | return -1; 585 | return 0; 586 | } 587 | 588 | int zlimdb_errno() 589 | { 590 | return zlimdbErrno; 591 | } 592 | 593 | void zlimdb_seterrno(int errnum) 594 | { 595 | zlimdbErrno = errnum; 596 | } 597 | 598 | const char* zlimdb_strerror(int errnum) 599 | { 600 | switch(errnum) 601 | { 602 | // libzlimdbclient errors 603 | case zlimdb_local_error_none: return "Success"; 604 | case zlimdb_local_error_system: return "System error"; 605 | case zlimdb_local_error_invalid_parameter: return "Invalid parameter"; 606 | case zlimdb_local_error_not_initialized: return "Not initialized"; 607 | case zlimdb_local_error_state: return "State error"; 608 | case zlimdb_local_error_resolve: return "Hostname could not be resolved"; 609 | case zlimdb_local_error_interrupted: return "Operation was interrupted"; 610 | case zlimdb_local_error_timeout: return "Operation has timed out"; 611 | case zlimdb_local_error_invalid_message_data: return "Received invalid message data"; 612 | case zlimdb_local_error_invalid_response: return "Received invalid response"; 613 | case zlimdb_local_error_buffer_size: return "Buffer was too small"; 614 | case zlimdb_local_error_connection_closed: return "Connection was closed"; 615 | 616 | // client protocol errors: 617 | case zlimdb_error_invalid_message_data: return "Invalid message data"; 618 | case zlimdb_error_invalid_message_type: return "invalid message type"; 619 | case zlimdb_error_entity_not_found: return "Entity not found"; 620 | case zlimdb_error_table_not_found: return "Table not found"; 621 | case zlimdb_error_not_implemented: return "Operation not implemented"; 622 | case zlimdb_error_invalid_request: return "Invalid request"; 623 | case zlimdb_error_invalid_login: return "Invalid login data"; 624 | case zlimdb_error_open_file: return "Could not open file"; 625 | case zlimdb_error_read_file: return "Could not read from file"; 626 | case zlimdb_error_write_file: return "Could not write to file"; 627 | case zlimdb_error_subscription_not_found: return "Subscription not found"; 628 | case zlimdb_error_entity_id: return "Invalid entity id"; 629 | case zlimdb_error_table_already_exists: return "Table already exists"; 630 | case zlimdb_error_responder_not_available: return "Responder not available"; 631 | case zlimdb_error_responder_already_present: return "Responder already present"; 632 | 633 | default: return "Unknown error"; 634 | } 635 | } 636 | 637 | int zlimdb_add_table(zlimdb* zdb, const char* name, uint32_t* tableId) 638 | { 639 | if(!zdb || !name) 640 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 641 | size_t nameSize = strlen(name) + 1; 642 | if(sizeof(zlimdb_add_request) + sizeof(zlimdb_table_entity) + nameSize > ZLIMDB_MAX_MESSAGE_SIZE) 643 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 644 | 645 | if(zdb->state != _zlimdb_state_connected) 646 | return zlimdbErrno = zlimdb_local_error_state, -1; 647 | 648 | // create message 649 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 650 | zlimdb_add_request* addRequest = (zlimdb_add_request*)buffer; 651 | addRequest->header.size = sizeof(zlimdb_add_request) + sizeof(zlimdb_table_entity) + nameSize; 652 | addRequest->header.message_type = zlimdb_message_add_request; 653 | addRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 654 | addRequest->table_id = zlimdb_table_tables; 655 | zlimdb_table_entity* tableEntity = (zlimdb_table_entity*)(addRequest + 1); 656 | tableEntity->entity.id = 0; 657 | tableEntity->entity.time = 0; 658 | tableEntity->entity.size = (uint16_t)(sizeof(zlimdb_table_entity) + nameSize); 659 | tableEntity->name_size = (uint16_t)nameSize; 660 | tableEntity->flags = 0; 661 | memcpy(tableEntity + 1, name, nameSize); 662 | 663 | // send message 664 | if(_zlimdb_sendRequest(zdb, &addRequest->header) != 0) 665 | return -1; 666 | 667 | // receive response 668 | zlimdb_add_response addResponse; 669 | if(_zlimdb_receiveResponse(zdb, addRequest->header.request_id, &addResponse, sizeof(zlimdb_add_response)) != 0) 670 | return -1; 671 | if(tableId) 672 | *tableId = (uint32_t)addResponse.id; 673 | return zlimdbErrno = zlimdb_local_error_none, 0; 674 | } 675 | 676 | int zlimdb_find_table(zlimdb* zdb, const char* name, uint32_t* tableId) 677 | { 678 | if(!zdb || !name) 679 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 680 | size_t nameSize = strlen(name) + 1; 681 | if(sizeof(zlimdb_find_request) + sizeof(zlimdb_table_entity) + nameSize > ZLIMDB_MAX_MESSAGE_SIZE) 682 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 683 | 684 | if(zdb->state != _zlimdb_state_connected) 685 | return zlimdbErrno = zlimdb_local_error_state, -1; 686 | 687 | // create message 688 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 689 | zlimdb_find_request* findRequest = (zlimdb_find_request*)buffer; 690 | findRequest->header.size = sizeof(zlimdb_find_request) + sizeof(zlimdb_table_entity) + nameSize; 691 | findRequest->header.message_type = zlimdb_message_find_request; 692 | findRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 693 | findRequest->table_id = zlimdb_table_tables; 694 | zlimdb_table_entity* tableEntity = (zlimdb_table_entity*)(findRequest + 1); 695 | tableEntity->entity.id = 0; 696 | tableEntity->entity.time = 0; 697 | tableEntity->entity.size = (uint16_t)(sizeof(zlimdb_table_entity) + nameSize); 698 | tableEntity->name_size = (uint16_t)nameSize; 699 | tableEntity->flags = 0; 700 | memcpy(tableEntity + 1, name, nameSize); 701 | 702 | // send message 703 | if(_zlimdb_sendRequest(zdb, &findRequest->header) != 0) 704 | return -1; 705 | 706 | // receive response 707 | zlimdb_find_response findResponse; 708 | if(_zlimdb_receiveResponse(zdb, findRequest->header.request_id, &findResponse, sizeof(zlimdb_find_response)) != 0) 709 | return -1; 710 | if(tableId) 711 | *tableId = (uint32_t)findResponse.id; 712 | return zlimdbErrno = zlimdb_local_error_none, 0; 713 | } 714 | 715 | int zlimdb_copy_table(zlimdb* zdb, uint32_t tableId, const char* name, uint32_t* new_table_id) 716 | { 717 | if(!zdb || !tableId || !name) 718 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 719 | size_t nameSize = strlen(name) + 1; 720 | if(sizeof(zlimdb_copy_request) + sizeof(zlimdb_table_entity) + nameSize > ZLIMDB_MAX_MESSAGE_SIZE) 721 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 722 | 723 | if(zdb->state != _zlimdb_state_connected) 724 | return zlimdbErrno = zlimdb_local_error_state, -1; 725 | 726 | // create message 727 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 728 | zlimdb_copy_request* copyRequest = (zlimdb_copy_request*)buffer; 729 | copyRequest->header.size = sizeof(zlimdb_copy_request) + sizeof(zlimdb_table_entity) + nameSize; 730 | copyRequest->header.message_type = zlimdb_message_copy_request; 731 | copyRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 732 | copyRequest->table_id = tableId; 733 | copyRequest->destination_table_id = 0; 734 | zlimdb_table_entity* tableEntity = (zlimdb_table_entity*)(copyRequest + 1); 735 | tableEntity->entity.id = 0; 736 | tableEntity->entity.time = 0; 737 | tableEntity->entity.size = (uint16_t)(sizeof(zlimdb_table_entity) + nameSize); 738 | tableEntity->name_size = (uint16_t)nameSize; 739 | tableEntity->flags = 0; 740 | memcpy(tableEntity + 1, name, nameSize); 741 | 742 | // send message 743 | if(_zlimdb_sendRequest(zdb, ©Request->header) != 0) 744 | return -1; 745 | 746 | // receive response 747 | zlimdb_copy_response copyResponse; 748 | if(_zlimdb_receiveResponse(zdb, copyRequest->header.request_id, ©Response, sizeof(zlimdb_copy_response)) != 0) 749 | return -1; 750 | if(new_table_id) 751 | *new_table_id = (uint32_t)copyResponse.id; 752 | return zlimdbErrno = zlimdb_local_error_none, 0; 753 | } 754 | 755 | int zlimdb_copy_table_replace(zlimdb* zdb, uint32_t tableId, uint32_t destinationTableId) 756 | { 757 | if(!zdb || !tableId || !destinationTableId) 758 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 759 | 760 | if(zdb->state != _zlimdb_state_connected) 761 | return zlimdbErrno = zlimdb_local_error_state, -1; 762 | 763 | // create message 764 | zlimdb_copy_request copyRequest; 765 | copyRequest.header.size = sizeof(zlimdb_copy_request); 766 | copyRequest.header.message_type = zlimdb_message_copy_request; 767 | copyRequest.header.request_id = ++zdb->lastRequestId << 1 | 1; 768 | copyRequest.table_id = tableId; 769 | copyRequest.destination_table_id = destinationTableId; 770 | 771 | // send message 772 | if(_zlimdb_sendRequest(zdb, ©Request.header) != 0) 773 | return -1; 774 | 775 | // receive response 776 | zlimdb_copy_response copyResponse; 777 | if(_zlimdb_receiveResponse(zdb, copyRequest.header.request_id, ©Response, sizeof(zlimdb_copy_response)) != 0) 778 | return -1; 779 | return zlimdbErrno = zlimdb_local_error_none, 0; 780 | } 781 | 782 | int zlimdb_rename_table(zlimdb* zdb, uint32_t tableId, const char* name, uint32_t* new_table_id) 783 | { 784 | if(!zdb || !tableId || !name) 785 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 786 | size_t nameSize = strlen(name) + 1; 787 | if(sizeof(zlimdb_rename_request) + sizeof(zlimdb_table_entity) + nameSize > ZLIMDB_MAX_MESSAGE_SIZE) 788 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 789 | 790 | if(zdb->state != _zlimdb_state_connected) 791 | return zlimdbErrno = zlimdb_local_error_state, -1; 792 | 793 | // create message 794 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 795 | zlimdb_rename_request* renameRequest = (zlimdb_rename_request*)buffer; 796 | renameRequest->header.size = sizeof(zlimdb_rename_request) + sizeof(zlimdb_table_entity) + nameSize; 797 | renameRequest->header.message_type = zlimdb_message_rename_request; 798 | renameRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 799 | renameRequest->table_id = tableId; 800 | renameRequest->destination_table_id = 0; 801 | zlimdb_table_entity* tableEntity = (zlimdb_table_entity*)(renameRequest + 1); 802 | tableEntity->entity.id = 0; 803 | tableEntity->entity.time = 0; 804 | tableEntity->entity.size = (uint16_t)(sizeof(zlimdb_table_entity) + nameSize); 805 | tableEntity->name_size = (uint16_t)nameSize; 806 | tableEntity->flags = 0; 807 | memcpy(tableEntity + 1, name, nameSize); 808 | 809 | // send message 810 | if(_zlimdb_sendRequest(zdb, &renameRequest->header) != 0) 811 | return -1; 812 | 813 | // receive response 814 | zlimdb_rename_response renameResponse; 815 | if(_zlimdb_receiveResponse(zdb, renameRequest->header.request_id, &renameResponse, sizeof(zlimdb_rename_response)) != 0) 816 | return -1; 817 | if(new_table_id) 818 | *new_table_id = (uint32_t)renameResponse.id; 819 | return zlimdbErrno = zlimdb_local_error_none, 0; 820 | } 821 | 822 | int zlimdb_rename_table_replace(zlimdb* zdb, uint32_t tableId, uint32_t destinationTableId) 823 | { 824 | if(!zdb || !tableId || !destinationTableId) 825 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 826 | 827 | if(zdb->state != _zlimdb_state_connected) 828 | return zlimdbErrno = zlimdb_local_error_state, -1; 829 | 830 | // create message 831 | zlimdb_rename_request renameRequest; 832 | renameRequest.header.size = sizeof(zlimdb_rename_request); 833 | renameRequest.header.message_type = zlimdb_message_rename_request; 834 | renameRequest.header.request_id = ++zdb->lastRequestId << 1 | 1; 835 | renameRequest.table_id = tableId; 836 | renameRequest.destination_table_id = destinationTableId; 837 | 838 | // send message 839 | if(_zlimdb_sendRequest(zdb, &renameRequest.header) != 0) 840 | return -1; 841 | 842 | // receive response 843 | zlimdb_rename_response renameResponse; 844 | if(_zlimdb_receiveResponse(zdb, renameRequest.header.request_id, &renameResponse, sizeof(zlimdb_rename_response)) != 0) 845 | return -1; 846 | return zlimdbErrno = zlimdb_local_error_none, 0; 847 | } 848 | 849 | int zlimdb_remove_table(zlimdb* zdb, uint32_t tableId) 850 | { 851 | return zlimdb_remove(zdb, zlimdb_table_tables, tableId); 852 | } 853 | 854 | int zlimdb_add_user(zlimdb* zdb, const char* userName, const char* password) 855 | { 856 | if(!zdb || !userName || !password) 857 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 858 | size_t userNameSize = strlen(userName) + 1; 859 | if(sizeof(zlimdb_add_request) + sizeof(zlimdb_table_entity) + 11 + userNameSize > ZLIMDB_MAX_MESSAGE_SIZE) 860 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 861 | 862 | // create user table 863 | char tableName[ZLIMDB_MAX_MESSAGE_SIZE]; 864 | memcpy(tableName, "users/", 6); 865 | memcpy(tableName + 6, userName, userNameSize - 1); 866 | memcpy(tableName + 6 + userNameSize - 1, "/user", 5); 867 | tableName[11 + userNameSize - 1] = '\0'; 868 | uint32_t tableId; 869 | if(zlimdb_add_table(zdb, tableName, &tableId) != 0) 870 | return -1; 871 | 872 | // add user entity 873 | zlimdb_user_entity userEntity; 874 | userEntity.entity.size = sizeof(zlimdb_user_entity); 875 | userEntity.entity.id = 1; 876 | userEntity.entity.time = 0; 877 | srand((unsigned int)time(0)); 878 | uint16_t* i = (uint16_t*)userEntity.pw_salt, * end = (uint16_t*)(userEntity.pw_salt + sizeof(userEntity.pw_salt)); 879 | for(; i < end; ++i) 880 | *i = rand(); 881 | sha256_hmac(userEntity.pw_salt, sizeof(userEntity.pw_salt), (const uint8_t*)password, strlen(password), userEntity.pw_hash); 882 | if(zlimdb_add(zdb, tableId, &userEntity.entity, 0) != 0) 883 | return -1; 884 | return 0; 885 | } 886 | 887 | int zlimdb_add(zlimdb* zdb, uint32_t tableId, const zlimdb_entity* data, uint64_t* id) 888 | { 889 | if(!zdb || !tableId || !data || data->size > ZLIMDB_MAX_MESSAGE_SIZE - sizeof(zlimdb_add_request)) 890 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 891 | 892 | if(zdb->state != _zlimdb_state_connected) 893 | return zlimdbErrno = zlimdb_local_error_state, -1; 894 | 895 | // create message 896 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 897 | zlimdb_add_request* addRequest = (zlimdb_add_request*)buffer; 898 | addRequest->header.size = sizeof(zlimdb_add_request) + data->size; 899 | addRequest->header.message_type = zlimdb_message_add_request; 900 | addRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 901 | addRequest->table_id = tableId; 902 | memcpy(addRequest + 1, data, data->size); 903 | 904 | // send message 905 | if(_zlimdb_sendRequest(zdb, &addRequest->header) != 0) 906 | return -1; 907 | 908 | // receive response 909 | zlimdb_add_response addResponse; 910 | if(_zlimdb_receiveResponse(zdb, addRequest->header.request_id, &addResponse, sizeof(zlimdb_add_response)) != 0) 911 | return -1; 912 | if(id) 913 | *id = addResponse.id; 914 | return zlimdbErrno = zlimdb_local_error_none, 0; 915 | } 916 | 917 | int zlimdb_update(zlimdb* zdb, uint32_t tableId, const zlimdb_entity* data) 918 | { 919 | if(!zdb || !tableId || data->size > ZLIMDB_MAX_MESSAGE_SIZE - sizeof(zlimdb_update_request)) 920 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 921 | 922 | if(zdb->state != _zlimdb_state_connected) 923 | return zlimdbErrno = zlimdb_local_error_state, -1; 924 | 925 | // create message 926 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 927 | zlimdb_update_request* updateRequest = (zlimdb_update_request*)buffer; 928 | updateRequest->header.size = sizeof(zlimdb_update_request) + data->size; 929 | updateRequest->header.message_type = zlimdb_message_update_request; 930 | updateRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 931 | updateRequest->table_id = tableId; 932 | memcpy(updateRequest + 1, data, data->size); 933 | 934 | // send message 935 | if(_zlimdb_sendRequest(zdb, &updateRequest->header) != 0) 936 | return -1; 937 | 938 | // receive response 939 | zlimdb_header updateResponse; 940 | if(_zlimdb_receiveResponse(zdb, updateRequest->header.request_id, &updateResponse, sizeof(zlimdb_header)) != 0) 941 | return -1; 942 | return zlimdbErrno = zlimdb_local_error_none, 0; 943 | } 944 | 945 | int zlimdb_remove(zlimdb* zdb, uint32_t tableId, uint64_t entityId) 946 | { 947 | if(!zdb || !tableId || !entityId) 948 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 949 | 950 | if(zdb->state != _zlimdb_state_connected) 951 | return zlimdbErrno = zlimdb_local_error_state, -1; 952 | 953 | // create message 954 | zlimdb_remove_request removeRequest; 955 | removeRequest.header.size = sizeof(zlimdb_remove_request); 956 | removeRequest.header.message_type = zlimdb_message_remove_request; 957 | removeRequest.header.request_id = ++zdb->lastRequestId << 1 | 1; 958 | removeRequest.table_id = tableId; 959 | removeRequest.id = entityId; 960 | 961 | // send message 962 | if(_zlimdb_sendRequest(zdb, &removeRequest.header) != 0) 963 | return -1; 964 | 965 | // receive response 966 | zlimdb_header removeResponse; 967 | if(_zlimdb_receiveResponse(zdb, removeRequest.header.request_id, &removeResponse, sizeof(zlimdb_header)) != 0) 968 | return -1; 969 | return zlimdbErrno = zlimdb_local_error_none, 0; 970 | } 971 | 972 | int zlimdb_clear(zlimdb* zdb, uint32_t tableId) 973 | { 974 | if(!zdb || !tableId) 975 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 976 | 977 | if(zdb->state != _zlimdb_state_connected) 978 | return zlimdbErrno = zlimdb_local_error_state, -1; 979 | 980 | // create message 981 | zlimdb_clear_request clearRequest; 982 | clearRequest.header.size = sizeof(zlimdb_clear_request); 983 | clearRequest.header.message_type = zlimdb_message_clear_request; 984 | clearRequest.header.request_id = ++zdb->lastRequestId << 1 | 1; 985 | clearRequest.table_id = tableId; 986 | 987 | // send message 988 | if(_zlimdb_sendRequest(zdb, &clearRequest.header) != 0) 989 | return -1; 990 | 991 | // receive response 992 | zlimdb_header clearResponse; 993 | if(_zlimdb_receiveResponse(zdb, clearRequest.header.request_id, &clearResponse, sizeof(zlimdb_header)) != 0) 994 | return -1; 995 | return zlimdbErrno = zlimdb_local_error_none, 0; 996 | } 997 | 998 | int zlimdb_query(zlimdb* zdb, uint32_t tableId, zlimdb_query_type type, uint64_t param) 999 | { 1000 | if(!zdb || !tableId || type == zlimdb_query_type_since_next) 1001 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1002 | 1003 | if(zdb->state != _zlimdb_state_connected) 1004 | return zlimdbErrno = zlimdb_local_error_state, -1; 1005 | 1006 | // create request data 1007 | _zlimdb_requestData* requestData = zdb->unusedRequest; 1008 | if(requestData) 1009 | zdb->unusedRequest = requestData->next; 1010 | else 1011 | { 1012 | requestData = malloc(sizeof(_zlimdb_requestData)); 1013 | if(!requestData) 1014 | return zlimdbErrno = zlimdb_local_error_system, -1; 1015 | } 1016 | requestData->next = zdb->openRequest; 1017 | requestData->requestId = ++zdb->lastRequestId << 1 | 1; 1018 | requestData->response = 0; 1019 | requestData->state = _zlimdb_requestState_receiving; 1020 | zdb->openRequest = requestData; 1021 | 1022 | // create message 1023 | zlimdb_query_request queryRequest; 1024 | queryRequest.header.size = sizeof(zlimdb_query_request); 1025 | queryRequest.header.message_type = zlimdb_message_query_request; 1026 | queryRequest.header.request_id = requestData->requestId; 1027 | queryRequest.table_id = tableId; 1028 | queryRequest.type = type; 1029 | queryRequest.param = param; 1030 | 1031 | // send message 1032 | if(_zlimdb_sendRequest(zdb, &queryRequest.header) != 0) 1033 | { 1034 | zdb->openRequest = requestData->next; 1035 | requestData->next = zdb->unusedRequest; 1036 | zdb->unusedRequest = requestData; 1037 | return -1; 1038 | } 1039 | 1040 | return zlimdbErrno = zlimdb_local_error_none, 0; 1041 | } 1042 | 1043 | int zlimdb_query_entity(zlimdb* zdb, uint32_t tableId, uint64_t entityId, zlimdb_entity* entity, uint32_t minSize, uint32_t maxSize) 1044 | { 1045 | if(!zdb || !tableId || !entityId || !entity || minSize < sizeof(zlimdb_entity) || maxSize < sizeof(zlimdb_entity) || maxSize < minSize) 1046 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1047 | 1048 | if(zlimdb_query(zdb, tableId, zlimdb_query_type_by_id, entityId) != 0) 1049 | return -1; 1050 | char message[ZLIMDB_MAX_MESSAGE_SIZE]; 1051 | if(zlimdb_get_response(zdb, (zlimdb_header*)message, ZLIMDB_MAX_MESSAGE_SIZE) != 0) 1052 | return -1; 1053 | if(zdb->openRequest->state != _zlimdb_requestState_finished) 1054 | { 1055 | zdb->state = _zlimdb_state_error; 1056 | return zlimdbErrno = zlimdb_local_error_invalid_response, -1; 1057 | } 1058 | _zlimdb_requestData* request = zdb->openRequest; 1059 | zdb->openRequest = request->next; 1060 | _zlimdb_freeMessages(request->response); 1061 | request->next = zdb->unusedRequest; 1062 | zdb->unusedRequest = request; 1063 | 1064 | const zlimdb_entity* data = zlimdb_get_first_entity((const zlimdb_header*)message, minSize); 1065 | if(!data) 1066 | { 1067 | zdb->state = _zlimdb_state_error; 1068 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 1069 | } 1070 | if(data->size > maxSize) 1071 | { 1072 | zdb->state = _zlimdb_state_error; 1073 | return zlimdbErrno = zlimdb_local_error_buffer_size, -1; 1074 | } 1075 | memcpy(entity, data, data->size); 1076 | return zlimdbErrno = zlimdb_local_error_none, 0; 1077 | } 1078 | 1079 | int zlimdb_subscribe(zlimdb* zdb, uint32_t tableId, zlimdb_query_type type, uint64_t param, uint8_t flags) 1080 | { 1081 | if(!zdb || !tableId) 1082 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1083 | 1084 | if(zdb->state != _zlimdb_state_connected) 1085 | return zlimdbErrno = zlimdb_local_error_state, -1; 1086 | 1087 | // create request data 1088 | _zlimdb_requestData* requestData = zdb->unusedRequest; 1089 | if(requestData) 1090 | zdb->unusedRequest = requestData->next; 1091 | else 1092 | { 1093 | requestData = malloc(sizeof(_zlimdb_requestData)); 1094 | if(!requestData) 1095 | return zlimdbErrno = zlimdb_local_error_system, -1; 1096 | } 1097 | requestData->next = zdb->openRequest; 1098 | requestData->requestId = ++zdb->lastRequestId << 1 | 1; 1099 | requestData->response = 0; 1100 | requestData->state = _zlimdb_requestState_receiving; 1101 | zdb->openRequest = requestData; 1102 | 1103 | // create message 1104 | zlimdb_subscribe_request subscribeRequest; 1105 | subscribeRequest.query.header.size = sizeof(zlimdb_subscribe_request); 1106 | subscribeRequest.query.header.message_type = zlimdb_message_subscribe_request; 1107 | subscribeRequest.query.header.request_id = requestData->requestId; 1108 | subscribeRequest.query.table_id = tableId; 1109 | subscribeRequest.query.type = type; 1110 | subscribeRequest.query.param = param; 1111 | subscribeRequest.flags = flags; 1112 | 1113 | // send message 1114 | if(_zlimdb_sendRequest(zdb, &subscribeRequest.query.header) != 0) 1115 | { 1116 | zdb->openRequest = requestData->next; 1117 | requestData->next = zdb->unusedRequest; 1118 | zdb->unusedRequest = requestData; 1119 | return -1; 1120 | } 1121 | 1122 | return zlimdbErrno = zlimdb_local_error_none, 0; 1123 | } 1124 | 1125 | 1126 | int zlimdb_get_response(zlimdb* zdb, zlimdb_header* message, uint32_t maxSize) 1127 | { 1128 | if(!zdb || !message || maxSize < sizeof(zlimdb_header)) 1129 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1130 | 1131 | if(zdb->state != _zlimdb_state_connected) 1132 | return zlimdbErrno = zlimdb_local_error_state, -1; 1133 | 1134 | _zlimdb_requestData* request = zdb->openRequest; 1135 | if(!request) 1136 | return zlimdbErrno = zlimdb_local_error_state, -1; 1137 | 1138 | switch(request->state) 1139 | { 1140 | case _zlimdb_requestState_receiving: 1141 | break; 1142 | case _zlimdb_requestState_finished: 1143 | { 1144 | _zlimdb_freeMessages(request->response); 1145 | zdb->openRequest = request->next; 1146 | request->next = zdb->unusedRequest; 1147 | zdb->unusedRequest = request; 1148 | } 1149 | return zlimdbErrno = zlimdb_local_error_none, -1; 1150 | default: 1151 | return zlimdbErrno = zlimdb_local_error_state, -1; 1152 | } 1153 | 1154 | for(;;) 1155 | { 1156 | // return already received response 1157 | _zlimdb_messageData* response = request->response; 1158 | if(response) 1159 | { 1160 | const zlimdb_header* header = (const zlimdb_header*)(response + 1); 1161 | if(header->message_type == zlimdb_message_error_response) 1162 | { 1163 | zdb->state = _zlimdb_state_connected; 1164 | zlimdbErrno = zlimdb_local_error_none; 1165 | _zlimdb_copyResponse(zdb, response, message, maxSize); // get errno 1166 | _zlimdb_freeMessages(response); 1167 | zdb->openRequest = request->next; 1168 | request->next = zdb->unusedRequest; 1169 | zdb->unusedRequest = request; 1170 | return -1; 1171 | } 1172 | if(header->flags & zlimdb_header_flag_compressed) 1173 | { 1174 | const void* buffer = header + 1; 1175 | size_t dataSize = header->size - sizeof(zlimdb_header); 1176 | if(dataSize < sizeof(uint16_t)) 1177 | { 1178 | zdb->state = _zlimdb_state_error; 1179 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 1180 | } 1181 | uint16_t rawDataSize = *(const uint16_t*)buffer; 1182 | if(rawDataSize > 0) 1183 | { 1184 | if(sizeof(zlimdb_header) + rawDataSize > maxSize) 1185 | { 1186 | zdb->state = _zlimdb_state_error; 1187 | return zlimdbErrno = zlimdb_local_error_buffer_size, -1; 1188 | } 1189 | if(LZ4_decompress_safe((const char*)buffer + sizeof(uint16_t), (char*)(message + 1), dataSize - sizeof(uint16_t), rawDataSize) != rawDataSize) 1190 | { 1191 | zdb->state = _zlimdb_state_error; 1192 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 1193 | } 1194 | } 1195 | *message = *header; 1196 | message->size = sizeof(zlimdb_header) + rawDataSize; 1197 | message->flags &= ~zlimdb_header_flag_compressed; 1198 | } 1199 | else 1200 | { 1201 | if(header->size > maxSize) 1202 | { 1203 | zdb->state = _zlimdb_state_error; 1204 | return zlimdbErrno = zlimdb_local_error_buffer_size, -1; 1205 | } 1206 | memcpy(message, header, header->size); 1207 | } 1208 | if(!(header->flags & zlimdb_header_flag_fragmented)) 1209 | request->state = _zlimdb_requestState_finished; 1210 | request->response = response->next; 1211 | free(response); 1212 | return zlimdbErrno = zlimdb_local_error_none, 0; 1213 | } 1214 | 1215 | // receive new response 1216 | for(;;) 1217 | { 1218 | if(_zlimdb_receiveHeader(zdb, message) != 0) 1219 | return -1; 1220 | if(message->request_id == zdb->openRequest->requestId) 1221 | { 1222 | if(message->message_type == zlimdb_message_error_response) 1223 | { 1224 | zdb->state = _zlimdb_state_connected; 1225 | zlimdbErrno = zlimdb_local_error_none; 1226 | _zlimdb_receiveResponseData(zdb, message, message + 1, maxSize - sizeof(zlimdb_header)); // get errno 1227 | return -1; 1228 | } 1229 | if(message->flags & zlimdb_header_flag_compressed) 1230 | { 1231 | size_t dataSize = message->size - sizeof(zlimdb_header); 1232 | if(dataSize < sizeof(uint16_t)) 1233 | { 1234 | zdb->state = _zlimdb_state_error; 1235 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 1236 | } 1237 | char compressedData[ZLIMDB_MAX_MESSAGE_SIZE]; 1238 | if(_zlimdb_receiveResponseData(zdb, message, compressedData, dataSize) != 0) 1239 | return -1; 1240 | uint16_t rawDataSize = *(const uint16_t*)compressedData; 1241 | if(rawDataSize > 0) 1242 | { 1243 | if(sizeof(zlimdb_header) + rawDataSize > maxSize) 1244 | { 1245 | zdb->state = _zlimdb_state_error; 1246 | return zlimdbErrno = zlimdb_local_error_buffer_size, -1; 1247 | } 1248 | if(LZ4_decompress_safe((char*)compressedData + sizeof(uint16_t), (char*)(message + 1), dataSize - sizeof(uint16_t), rawDataSize) != rawDataSize) 1249 | { 1250 | zdb->state = _zlimdb_state_error; 1251 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, -1; 1252 | } 1253 | } 1254 | message->size = sizeof(zlimdb_header) + rawDataSize; 1255 | message->flags &= ~zlimdb_header_flag_compressed; 1256 | } 1257 | else 1258 | { 1259 | if(_zlimdb_receiveResponseData(zdb, message, message + 1, maxSize - sizeof(zlimdb_header)) != 0) 1260 | return -1; 1261 | } 1262 | if(!(message->flags & zlimdb_header_flag_fragmented)) 1263 | request->state = _zlimdb_requestState_finished; 1264 | return zlimdbErrno = zlimdb_local_error_none, 0; 1265 | } 1266 | else if(message->request_id && message->message_type != zlimdb_message_control_request) 1267 | { 1268 | _zlimdb_requestData* request; 1269 | for(request = zdb->openRequest->next; request; request = request->next) 1270 | if(request->requestId == message->request_id) 1271 | goto receiveResponse; 1272 | zdb->state = _zlimdb_state_error; 1273 | return zlimdbErrno = zlimdb_local_error_invalid_response, -1; 1274 | receiveResponse: ; 1275 | 1276 | _zlimdb_messageData* response = malloc(sizeof(_zlimdb_messageData) + message->size); 1277 | if(!response) 1278 | { 1279 | zdb->state = _zlimdb_state_error; 1280 | return zlimdbErrno = zlimdb_local_error_system, -1; 1281 | } 1282 | void* buffer = response + 1; 1283 | if(_zlimdb_receiveData(zdb, (zlimdb_header*)buffer + 1, message->size - sizeof(zlimdb_header)) != 0) 1284 | return -1; 1285 | *(zlimdb_header*)buffer = *message; 1286 | response->next = 0; 1287 | if(request->response) 1288 | request->lastResponse->next = response; 1289 | else 1290 | request->response = response; 1291 | request->lastResponse = response; 1292 | } 1293 | else 1294 | { 1295 | size_t bufferSize = message->size; 1296 | void* buffer = malloc(sizeof(_zlimdb_messageData) + bufferSize); 1297 | if(!buffer) 1298 | { 1299 | zdb->state = _zlimdb_state_error; 1300 | return zlimdbErrno = zlimdb_local_error_system, -1; 1301 | } 1302 | if(_zlimdb_receiveData(zdb, (zlimdb_header*)((_zlimdb_messageData*)buffer + 1) + 1, bufferSize - sizeof(zlimdb_header)) != 0) 1303 | return -1; 1304 | *(zlimdb_header*)((_zlimdb_messageData*)buffer + 1) = *message; 1305 | ((_zlimdb_messageData*)buffer)->next = 0; 1306 | if(zdb->queuedMessage) 1307 | zdb->lastQueuedMessage->next = buffer; 1308 | else 1309 | zdb->queuedMessage = buffer; 1310 | zdb->lastQueuedMessage = buffer; 1311 | break; 1312 | } 1313 | } 1314 | } 1315 | } 1316 | 1317 | const zlimdb_entity* zlimdb_get_first_entity(const zlimdb_header* header, uint32_t minSize) 1318 | { 1319 | if(header->size < sizeof(zlimdb_header) + sizeof(zlimdb_entity)) 1320 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1321 | const zlimdb_entity* result = (const zlimdb_entity*)(header + 1); 1322 | if(result->size < minSize || (const char*)result + result->size > (const char*)header + header->size) 1323 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1324 | return result; 1325 | } 1326 | 1327 | const zlimdb_entity* zlimdb_get_next_entity(const zlimdb_header* header, uint32_t minSize, const zlimdb_entity* entity) 1328 | { 1329 | const char* end = (const char*)header + header->size; 1330 | if((const char*)entity + entity->size + sizeof(zlimdb_entity) > end) 1331 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1332 | const zlimdb_entity* result = (const zlimdb_entity*)((const char*)entity + entity->size); 1333 | if(result->size < minSize || (const char*)result + result->size > end) 1334 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1335 | return result; 1336 | } 1337 | 1338 | const void* zlimdb_get_request_data(const zlimdb_header* header, uint32_t minSize) 1339 | { 1340 | if(header->size < sizeof(zlimdb_control_request) + minSize) 1341 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const void*)0; 1342 | return ((const zlimdb_control_request*)header) + 1; 1343 | } 1344 | 1345 | const void* zlimdb_get_response_data(const zlimdb_header* header, uint32_t minSize) 1346 | { 1347 | if(header->size < sizeof(zlimdb_header) + minSize) 1348 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const void*)0; 1349 | return header + 1; 1350 | } 1351 | 1352 | const zlimdb_entity* zlimdb_data_get_first_entity(const void* data, uint32_t size, uint32_t minSize) 1353 | { 1354 | if(size < sizeof(zlimdb_entity)) 1355 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1356 | const zlimdb_entity* result = (const zlimdb_entity*)data; 1357 | if(result->size < minSize || result->size > size) 1358 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1359 | return result; 1360 | } 1361 | 1362 | const zlimdb_entity* zlimdb_data_get_next_entity(const void* data, uint32_t size, uint32_t minSize, const zlimdb_entity* entity) 1363 | { 1364 | const char* end = (const char*)data + size; 1365 | if((const char*)entity + entity->size + sizeof(zlimdb_entity) > end) 1366 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1367 | const zlimdb_entity* result = (const zlimdb_entity*)((const char*)entity + entity->size); 1368 | if(result->size < minSize || (const char*)result + result->size > end) 1369 | return zlimdbErrno = zlimdb_local_error_invalid_message_data, (const zlimdb_entity*)0; 1370 | return result; 1371 | } 1372 | 1373 | /* 1374 | zlimdb_entity* zlimdb_get_single_entity(const zlimdb_header* header, uint32_t offset, uint32_t minSize) 1375 | { 1376 | if(offset + minSize > header->size) 1377 | return 0; 1378 | zlimdb_entity* result = (const char*)header + offset; 1379 | if((const char*)result + result->size > (const char*)header + header->size) 1380 | return 0; 1381 | return result; 1382 | } 1383 | */ 1384 | int zlimdb_unsubscribe(zlimdb* zdb, uint32_t tableId) 1385 | { 1386 | if(!zdb || !tableId) 1387 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1388 | 1389 | if(zdb->state != _zlimdb_state_connected) 1390 | return zlimdbErrno = zlimdb_local_error_state, -1; 1391 | 1392 | // create message 1393 | zlimdb_unsubscribe_request unsubscribeRequest; 1394 | unsubscribeRequest.header.size = sizeof(zlimdb_unsubscribe_request); 1395 | unsubscribeRequest.header.message_type = zlimdb_message_unsubscribe_request; 1396 | unsubscribeRequest.header.request_id = ++zdb->lastRequestId << 1 | 1; 1397 | unsubscribeRequest.table_id = tableId; 1398 | 1399 | // send message 1400 | if(_zlimdb_sendRequest(zdb, &unsubscribeRequest.header) != 0) 1401 | return -1; 1402 | 1403 | // receive response 1404 | zlimdb_header unsubscribeResponse; 1405 | if(_zlimdb_receiveResponse(zdb, unsubscribeRequest.header.request_id, &unsubscribeResponse, sizeof(zlimdb_header)) != 0) 1406 | return -1; 1407 | return zlimdbErrno = zlimdb_local_error_none, 0; 1408 | } 1409 | 1410 | int zlimdb_sync(zlimdb* zdb, uint32_t tableId, int64_t* serverTime, int64_t* tableTime) 1411 | { 1412 | if(!zdb || !tableId) 1413 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1414 | 1415 | if(zdb->state != _zlimdb_state_connected) 1416 | return zlimdbErrno = zlimdb_local_error_state, -1; 1417 | 1418 | // create message 1419 | zlimdb_sync_request syncRequest; 1420 | syncRequest.header.size = sizeof(zlimdb_sync_request); 1421 | syncRequest.header.message_type = zlimdb_message_sync_request; 1422 | syncRequest.header.request_id = ++zdb->lastRequestId << 1 | 1; 1423 | syncRequest.table_id = tableId; 1424 | 1425 | // send message 1426 | if(_zlimdb_sendRequest(zdb, &syncRequest.header) != 0) 1427 | return -1; 1428 | 1429 | // receive response 1430 | zlimdb_sync_response syncResponse; 1431 | if(_zlimdb_receiveResponse(zdb, syncRequest.header.request_id, &syncResponse, sizeof(zlimdb_sync_response)) != 0) 1432 | return -1; 1433 | if(serverTime) 1434 | *serverTime = syncResponse.server_time; 1435 | if(tableTime) 1436 | *tableTime = syncResponse.table_time; 1437 | return zlimdbErrno = zlimdb_local_error_none, 0; 1438 | } 1439 | 1440 | int zlimdb_control(zlimdb* zdb, uint32_t tableId, uint64_t entityId, uint32_t controlCode, const void* data, uint32_t size, zlimdb_header* message, uint32_t maxSize) 1441 | { 1442 | if(!zdb || !tableId || (size && !data) || size > ZLIMDB_MAX_MESSAGE_SIZE - sizeof(zlimdb_control_request) || maxSize < sizeof(zlimdb_header)) 1443 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1444 | 1445 | if(zdb->state != _zlimdb_state_connected) 1446 | return zlimdbErrno = zlimdb_local_error_state, -1; 1447 | 1448 | // create message 1449 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 1450 | zlimdb_control_request* controlRequest = (zlimdb_control_request*)buffer; 1451 | controlRequest->header.size = sizeof(zlimdb_control_request) + size; 1452 | controlRequest->header.message_type = zlimdb_message_control_request; 1453 | controlRequest->header.request_id = ++zdb->lastRequestId << 1 | 1; 1454 | controlRequest->table_id = tableId; 1455 | controlRequest->id = entityId; 1456 | controlRequest->control_code = controlCode; 1457 | memcpy(controlRequest + 1, data, size); 1458 | 1459 | // send message 1460 | if(_zlimdb_sendRequest(zdb, &controlRequest->header) != 0) 1461 | return -1; 1462 | 1463 | // receive response 1464 | if(_zlimdb_receiveResponse(zdb, controlRequest->header.request_id, message, maxSize) != 0) 1465 | return -1; 1466 | return zlimdbErrno = zlimdb_local_error_none, 0; 1467 | } 1468 | 1469 | int zlimdb_control_respond(zlimdb* zdb, uint32_t requestId, const void* data, uint32_t size) 1470 | { 1471 | if(!zdb || (size && !data) || size > ZLIMDB_MAX_MESSAGE_SIZE - sizeof(zlimdb_header)) 1472 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1473 | 1474 | // create message 1475 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 1476 | zlimdb_header* response = (zlimdb_header*)buffer; 1477 | response->size = sizeof(zlimdb_header) + size; 1478 | response->message_type = zlimdb_message_control_response; 1479 | response->request_id = requestId; 1480 | if(size) 1481 | memcpy(response + 1, data, size); 1482 | 1483 | // send message 1484 | if(_zlimdb_sendRequest(zdb, response) != 0) 1485 | return -1; 1486 | return zlimdbErrno = zlimdb_local_error_none, 0; 1487 | } 1488 | 1489 | int zlimdb_control_respond_error(zlimdb* zdb, uint32_t requestId, uint16_t error) 1490 | { 1491 | if(!zdb) 1492 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1493 | 1494 | // create message 1495 | zlimdb_error_response response; 1496 | response.header.size = sizeof(zlimdb_error_response); 1497 | response.header.message_type = zlimdb_message_error_response; 1498 | response.header.request_id = requestId; 1499 | response.error = error; 1500 | 1501 | // send message 1502 | if(_zlimdb_sendRequest(zdb, &response.header) != 0) 1503 | return -1; 1504 | return zlimdbErrno = zlimdb_local_error_none, 0; 1505 | } 1506 | 1507 | int zlimdb_exec(zlimdb* zdb, unsigned int timeout) 1508 | { 1509 | if(!zdb) 1510 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1511 | 1512 | if(zdb->state != _zlimdb_state_connected) 1513 | return zlimdbErrno = zlimdb_local_error_state, -1; 1514 | 1515 | #ifdef _WIN32 1516 | DWORD currentTick = GetTickCount(); 1517 | DWORD startTick = currentTick; 1518 | do 1519 | { 1520 | while(zdb->queuedMessage) 1521 | { 1522 | _zlimdb_messageData* message = zdb->queuedMessage; 1523 | zdb->queuedMessage = message->next; 1524 | if(zdb->callback) 1525 | zdb->callback(zdb->userData, (zlimdb_header*)(message + 1)); 1526 | free(message); 1527 | } 1528 | 1529 | if(zdb->selectedEvents == 0) 1530 | { 1531 | if(WSAEventSelect(zdb->socket, zdb->hReadEvent, FD_READ | FD_CLOSE) == SOCKET_ERROR) 1532 | { 1533 | zdb->state = _zlimdb_state_error; 1534 | return zlimdbErrno = zlimdb_local_error_system, -1; 1535 | } 1536 | zdb->selectedEvents = FD_READ | FD_CLOSE; 1537 | } 1538 | 1539 | HANDLE handles[] = {zdb->hReadEvent, zdb->hInterruptEvent}; 1540 | DWORD passedTicks = currentTick - startTick; 1541 | switch(passedTicks <= timeout ? WaitForMultipleObjects(2, handles, FALSE, timeout - passedTicks) : WAIT_TIMEOUT) 1542 | { 1543 | case WAIT_OBJECT_0: 1544 | break; 1545 | case WAIT_OBJECT_0 + 1: 1546 | WSAResetEvent(zdb->hInterruptEvent); 1547 | return zlimdbErrno = zlimdb_local_error_interrupted, -1; 1548 | case WAIT_TIMEOUT: 1549 | return zlimdbErrno = zlimdb_local_error_timeout, -1; 1550 | } 1551 | WSANETWORKEVENTS events; 1552 | if(WSAEnumNetworkEvents(zdb->socket, zdb->hReadEvent, &events) == SOCKET_ERROR) 1553 | { 1554 | zdb->state = _zlimdb_state_error; 1555 | return zlimdbErrno = zlimdb_local_error_system, -1; 1556 | } 1557 | if(events.lNetworkEvents) 1558 | { 1559 | zlimdb_header header; 1560 | if(_zlimdb_receiveHeader(zdb, &header) != 0) 1561 | return -1; 1562 | assert(!(header.flags & zlimdb_header_flag_compressed)); 1563 | size_t bufferSize = header.size; 1564 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 1565 | if(_zlimdb_receiveData(zdb, (zlimdb_header*)buffer + 1, bufferSize - sizeof(zlimdb_header)) != 0) 1566 | return -1; 1567 | if(zdb->callback) 1568 | { 1569 | *(zlimdb_header*)buffer = header; 1570 | zdb->callback(zdb->userData, (zlimdb_header*)buffer); 1571 | } 1572 | } 1573 | currentTick = GetTickCount(); 1574 | } while(zdb->state == _zlimdb_state_connected); 1575 | #else 1576 | struct timespec ts; 1577 | clock_gettime(CLOCK_MONOTONIC, &ts); 1578 | int64_t currentTick = (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; 1579 | int64_t startTick = currentTick; 1580 | do 1581 | { 1582 | while(zdb->queuedMessage) 1583 | { 1584 | _zlimdb_messageData* message = zdb->queuedMessage; 1585 | zdb->queuedMessage = message->next; 1586 | if(zdb->callback) 1587 | zdb->callback(zdb->userData, (zlimdb_header*)(message + 1)); 1588 | free(message); 1589 | } 1590 | 1591 | int64_t passedTicks = currentTick - startTick; 1592 | struct pollfd fds[] = { 1593 | { zdb->socket, POLLIN /*| POLLRDHUP*/ | POLLHUP, 0}, 1594 | { zdb->interruptEventFd, POLLIN /*| POLLRDHUP*/ | POLLHUP, 0} 1595 | }; 1596 | int ret = passedTicks <= timeout ? poll(fds, 2, timeout - passedTicks) : 0; 1597 | if(ret < 0) 1598 | { 1599 | zdb->state = _zlimdb_state_error; 1600 | return zlimdbErrno = zlimdb_local_error_system, -1; 1601 | } 1602 | if(fds[0].revents) 1603 | { 1604 | zlimdb_header header; 1605 | if(_zlimdb_receiveHeader(zdb, &header) != 0) 1606 | return -1; 1607 | assert(!(header.flags & zlimdb_header_flag_compressed)); 1608 | size_t bufferSize = header.size; 1609 | char buffer[ZLIMDB_MAX_MESSAGE_SIZE]; 1610 | if(_zlimdb_receiveData(zdb, (zlimdb_header*)buffer + 1, bufferSize - sizeof(zlimdb_header)) != 0) 1611 | return -1; 1612 | if(zdb->callback) 1613 | { 1614 | *(zlimdb_header*)buffer = header; 1615 | zdb->callback(zdb->userData, (zlimdb_header*)buffer); 1616 | } 1617 | } 1618 | if(fds[1].revents) 1619 | { 1620 | uint64_t val; 1621 | if(read(zdb->interruptEventFd, &val, sizeof(val)) == -1) 1622 | { 1623 | zdb->state = _zlimdb_state_error; 1624 | return zlimdbErrno = zlimdb_local_error_system, -1; 1625 | } 1626 | return zlimdbErrno = zlimdb_local_error_interrupted, -1; 1627 | } 1628 | if(ret == 0) 1629 | return zlimdbErrno = zlimdb_local_error_timeout, -1; 1630 | clock_gettime(CLOCK_MONOTONIC, &ts); 1631 | currentTick = (int64_t)ts.tv_sec * 1000 + ts.tv_nsec / 1000000; 1632 | } while(zdb->state == _zlimdb_state_connected); 1633 | #endif 1634 | return -1; 1635 | } 1636 | 1637 | int zlimdb_interrupt(zlimdb* zdb) 1638 | { 1639 | if(!zdb) 1640 | return zlimdbErrno = zlimdb_local_error_invalid_parameter, -1; 1641 | #ifdef _WIN32 1642 | if(!WSASetEvent(zdb->hInterruptEvent)) 1643 | return zlimdbErrno = zlimdb_local_error_system, -1; 1644 | #else 1645 | uint64_t val = 1; 1646 | if(write(zdb->interruptEventFd, &val, sizeof(val)) == -1) 1647 | return zlimdbErrno = zlimdb_local_error_system, -1; 1648 | #endif 1649 | return zlimdbErrno = zlimdb_local_error_none, 0; 1650 | } 1651 | --------------------------------------------------------------------------------