-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqcloud.c
More file actions
3892 lines (3176 loc) · 134 KB
/
sqcloud.c
File metadata and controls
3892 lines (3176 loc) · 134 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// sqcloud.c
//
// Created by Marco Bambini on 08/02/21.
//
#include "lz4.h"
#include "sqcloud.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <assert.h>
#include <sys/time.h>
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "Ws2_32.lib")
#include <Shlwapi.h>
#include <io.h>
#include <float.h>
#include "pthread.h"
#else
#include <errno.h>
#include <netdb.h>
#include <signal.h>
#include <unistd.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <netinet/tcp.h>
#include <sys/ioctl.h>
#include <pthread.h>
#include <inttypes.h>
#endif
#ifndef SQLITECLOUD_DISABLE_TLS
#ifdef SQLITECLOUD_USE_TLS_HEADER
#include "tls.h"
#else
#ifndef HEADER_TLS_H
#define TLS_WANT_POLLIN -2
#define TLS_WANT_POLLOUT -3
struct tls;
struct tls_config;
struct tls *tls_client(void);
struct tls_config *tls_config_new(void);
void tls_config_free(struct tls_config *config);
int tls_init(void);
int tls_configure(struct tls *_ctx, struct tls_config *_config);
int tls_connect_socket(struct tls *_ctx, int _s, const char *_servername);
int tls_close(struct tls *_ctx);
void tls_config_insecure_noverifycert(struct tls_config *config);
void tls_config_insecure_noverifyname(struct tls_config *config);
int tls_config_set_ca_file(struct tls_config *_config, const char *_ca_file);
int tls_config_set_cert_file(struct tls_config *_config,const char *_cert_file);
int tls_config_set_key_file(struct tls_config *_config, const char *_key_file);
ssize_t tls_read(struct tls *_ctx, void *_buf, size_t _buflen);
ssize_t tls_write(struct tls *_ctx, const void *_buf, size_t _buflen);
const char *tls_error(struct tls *_ctx);
const char *tls_config_error(struct tls_config *_config);
void tls_free(struct tls *_ctx);
#endif
#endif
#endif
// MARK: MACROS -
#ifdef _WIN32
#pragma warning (disable: 4005)
#pragma warning (disable: 4068)
#define readsocket(a,b,c) recv((a), (b), (c), 0L)
#define writesocket(a,b,c) send((a), (b), (c), 0L)
#else
#define readsocket read
#define writesocket write
#define closesocket(s) close(s)
#endif
#ifndef mem_alloc
#define mem_realloc realloc
#define mem_zeroalloc(_s) calloc(1,_s)
#define mem_alloc(_s) malloc(_s)
#define mem_free(_s) free(_s)
#define mem_string_dup(_s) strdup(_s)
#define mem_string_ndup(_s,_n) strndup(_s,_n)
#endif
#ifndef MIN
#define MIN(a,b) (((a)<(b))?(a):(b))
#endif
#define MAX_SOCK_LIST 6 // maximum number of socket descriptor to try to connect to
// this change is required to support IPv4/IPv6 connections
#define DEFAULT_TIMEOUT 12 // default connection timeout in seconds
#define REPLY_OK "+2 OK" // default OK reply
#define REPLY_OK_LEN 5 // default OK reply string length
// https://levelup.gitconnected.com/8-ways-to-measure-execution-time-in-c-c-48634458d0f9
#define TIME_GET(_t1) struct timeval _t1; gettimeofday(&_t1, NULL)
#define TIME_VAL(_t1, _t2) ((double)(_t2.tv_sec - _t1.tv_sec) + (double)((_t2.tv_usec - _t1.tv_usec)*1e-6))
#define CMD_MINLEN 2
#define CONNSTRING_KEYVALUE_SEPARATOR '='
#define CONNSTRING_TOKEN_SEPARATOR ';'
#define DEFAULT_CHUCK_NBUFFERS 20
#define DEFAULT_CHUNK_MINROWS 2000
#define ARRAY_STATIC_COUNT 256
#define ARRAY_HEADER_BUFFER_SIZE 64
#ifndef TLS_DEFAULT_CA_FILE
#if CLI_WINDOWS
// windows
#elif __APPLE__
// macos
#define TLS_DEFAULT_CA_FILE "/etc/ssl/cert.pem"
#else
// linux
#define TLS_DEFAULT_CA_FILE "/etc/ssl/certs/ca-certificates.crt"
#endif
#endif
// MARK: - PROTOTYPES -
static SQCloudResult *internal_socket_read (SQCloudConnection *connection, bool mainfd);
static bool internal_socket_write (SQCloudConnection *connection, const char *buffer, size_t len, bool mainfd, bool compute_header);
static uint32_t internal_parse_number (char *buffer, uint32_t blen, uint32_t *cstart);
static SQCloudResult *internal_parse_buffer (SQCloudConnection *connection, char *buffer, uint32_t blen, uint32_t cstart, bool isstatic, bool externalbuffer);
static bool internal_connect (SQCloudConnection *connection, const char *hostname, int port, SQCloudConfig *config, bool mainfd);
static bool internal_set_error (SQCloudConnection *connection, int errcode, const char *format, ...);
static SQCloudResult *internal_array_exec (SQCloudConnection *connection, const char *r[], int64_t len[], uint32_t n, uint32_t count);
// MARK: -
struct SQCloudResult {
SQCLOUD_RESULT_TYPE tag; // RESULT_OK, RESULT_ERROR, RESULT_STRING, RESULT_INTEGER, RESULT_FLOAT, RESULT_ROWSET, RESULT_NULL
bool ischunk; // flag used to correctly access the union below
union {
struct {
char *buffer; // buffer used by the user (it could be a ptr inside rawbuffer)
char *rawbuffer; // ptr to the buffer to be freed
uint32_t balloc; // buffer allocation size
};
struct {
char **buffers; // array of buffers used by rowset sent in chunk
bool *bext; // array of flags, if true the buffer must not be freed
uint32_t *blens; // array of buffer len
uint32_t *nheads; // array of header len
uint32_t bcount; // number of buffers in the array
uint32_t bnum; // number of pre-allocated buffers
uint32_t brows; // number of pre-allocated rows
};
};
// common
uint32_t blen; // total buffer length (also the sum of buffers)
double time; // full execution time (latency + server side time)
bool externalbuffer; // true if the buffer is managed by the caller code
// false if the buffer can be freed by the SQCloudResultFree func
uint32_t nheader; // number of character in the first part of the header (which is usually skipped)
// used in TYPE_ROWSET only
uint32_t version; // rowset version
uint32_t nrows; // number of rows
uint32_t ncols; // number of columns
uint32_t ndata; // number of items stores in data
char **data; // data contained in the rowset
char **name; // column names
char **decltype; // column declared types
char **dbname; // column database names
char **tblname; // column table names
char **origname; // column origin names
int *notnull; // column is not null
int *prikey; // column is primary key
int *autoinc; // column is auto increment
uint32_t *clen; // max len for each column (used to display result)
uint32_t maxlen; // max len for each row/column
// vm related fields (reserved)
uint32_t n1;
uint32_t n2;
uint32_t n3;
uint32_t n4;
uint32_t n5;
} _SQCloudResult;
struct SQCloudConnection {
int fd;
char errmsg[1024];
int errcode; // error code
int extcode; // extended error code
int offcode; // offset error code
SQCloudResult *_chunk;
SQCloudConfig *_config;
bool isblob;
bool config_to_free;
// pub/sub
char *uuid;
int pubsubfd;
SQCloudPubSubCB callback;
void *data;
char *hostname;
int port;
pthread_t tid;
#ifndef SQLITECLOUD_DISABLE_TLS
struct tls *tls_context;
struct tls *tls_pubsub_context;
#endif
} _SQCloudConnection;
struct SQCloudVM {
SQCloudConnection *connection;
SQCloudResult *result;
int index;
int type;
bool finalized;
bool isreadonly;
int isexplain;
int rowindex;
int nparams;
int ncolumns;
int64_t lastrowid;
int64_t changes;
int64_t totalchanges;
char *errmsg;
int errcode;
int xerrcode;
} _SQCloudVM;
struct SQCloudBlob {
SQCloudConnection *connection;
int index;
int64_t bytes;
int rc;
} _SQCloudBlob;
struct SQCloudBackup {
SQCloudConnection *connection;
int index;
int page_size;
int page_total;
int page_remaining;
int counter;
int size;
void *data;
} _SQCloudBackup;
static SQCloudResult SQCloudResultOK = {RESULT_OK, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0};
static SQCloudResult SQCloudResultNULL = {RESULT_NULL, NULL, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0};
// MARK: - UTILS -
static uint32_t utf8_charbytes (const char *s, uint32_t i) {
unsigned char c = (unsigned char)s[i];
// determine bytes needed for character, based on RFC 3629
if ((c > 0) && (c <= 127)) return 1;
if ((c >= 194) && (c <= 223)) return 2;
if ((c >= 224) && (c <= 239)) return 3;
if ((c >= 240) && (c <= 244)) return 4;
// means error
return 0;
}
static uint32_t utf8_len (const char *s, uint32_t nbytes) {
uint32_t pos = 0;
uint32_t len = 0;
while (pos < nbytes) {
++len;
uint32_t n = utf8_charbytes(s, pos);
if (n == 0) return 0; // means error
pos += n;
}
return len;
}
#if 0
static char *extract_connection_token (const char *s, char *key, char buffer[256]) {
char *target = strstr(s, key);
if (!target) return NULL;
// find out = separator
char *p = target;
while (p[0]) {
if (p[0] == CONNSTRING_KEYVALUE_SEPARATOR) break;
++p;
}
// skip =
++p;
// skip spaces (if any)
while (p[0]) {
if (!isspace(p[0])) break;
++p;
}
// copy value to buffer
int len = 0;
while (p[0] && len < 255) {
if (isspace(p[0])) break;
if (p[0] == CONNSTRING_TOKEN_SEPARATOR) break;
buffer[len] = p[0];
++len;
++p;
}
// null-terminate returning value
buffer[len] = 0;
p = &buffer[0];
return p;
}
#endif
// MARK: - PRIVATE -
static int socket_geterror (int fd) {
int err;
socklen_t errlen = sizeof(err);
int sockerr = getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen);
if (sockerr < 0) return -1;
return ((err == 0 || err == EINTR || err == EAGAIN || err == EINPROGRESS)) ? 0 : err;
}
static void *pubsub_thread (void *arg) {
SQCloudConnection *connection = (SQCloudConnection *)arg;
int fd = connection->pubsubfd;
#ifndef SQLITECLOUD_DISABLE_TLS
struct tls *tls = connection->tls_pubsub_context;
#endif
size_t blen = 2048;
char *buffer = mem_alloc(blen);
if (buffer == NULL) return NULL;
char *original = buffer;
uint32_t tread = 0;
while (1) {
fd_set set;
FD_ZERO(&set);
FD_SET(fd, &set);
// wait for read event
int rc = select(fd + 1, &set, NULL, NULL, NULL);
if (rc <= 0) continue;
// read payload string
#ifndef SQLITECLOUD_DISABLE_TLS
ssize_t nread = (tls) ? tls_read(tls, buffer, blen) : readsocket(fd, buffer, blen);
if ((tls) && (nread == TLS_WANT_POLLIN || nread == TLS_WANT_POLLOUT)) continue;
#else
ssize_t nread = readsocket(fd, buffer, blen);
#endif
if (nread < 0) {
const char *msg = "";
#ifndef SQLITECLOUD_DISABLE_TLS
if (tls) msg = tls_error(tls);
#endif
internal_set_error(connection, INTERNAL_ERRCODE_NETWORK, "An error occurred while reading data: %s (%s).", strerror(errno), msg);
if (connection->callback) connection->callback(connection, NULL, connection->data);
break;
}
if (nread == 0) {
internal_set_error(connection, INTERNAL_ERRCODE_SOCKCLOSED, "PubSub connection closed.");
if (connection->callback) connection->callback(connection, NULL, connection->data);
break;
}
tread += (uint32_t)nread;
blen -= (uint32_t)nread;
buffer += nread;
uint32_t cstart = 0;
uint32_t clen = internal_parse_number (&original[1], tread-1, &cstart);
if (clen == 0) continue;
// check if read is complete
// clen is the lenght parsed in the buffer
// cstart is the index of the first space
// +1 because we skipped the first character in the internal_parse_number function
if (clen + cstart + 1 != tread) {
// check buffer allocation and continue reading
if (clen + cstart > blen) {
char *clone = mem_alloc(clen + cstart + 1);
if (!clone) {
internal_set_error(connection, INTERNAL_ERRCODE_MEMORY, "Unable to allocate memory: %d.", clen + cstart + 1);
if (connection->callback) connection->callback(connection, NULL, connection->data);
break;
}
memcpy(clone, original, tread);
buffer = original = clone;
blen = (clen + cstart + 1) - tread;
buffer += tread;
}
continue;
}
SQCloudResult *result = internal_parse_buffer(connection, original, tread, (clen) ? cstart : 0, false, false);
if (result->tag == RESULT_STRING) result->tag = RESULT_JSON;
if (!connection->callback) break;
connection->callback(connection, result, connection->data);
blen = 2048;
buffer = mem_alloc(blen);
if (!buffer) break;
original = buffer;
tread = 0;
}
if (buffer) mem_free(buffer);
return NULL;
}
// MARK: -
static bool internal_init (void) {
static bool inited = false;
if (inited) return true;
#ifdef _WIN32
WSADATA wsaData;
WSAStartup(MAKEWORD(2,2), &wsaData);
#else
// IGNORE SIGPIPE and SIGABORT
struct sigaction act;
act.sa_handler = SIG_IGN;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGPIPE, &act, (struct sigaction *)NULL);
sigaction(SIGABRT, &act, (struct sigaction *)NULL);
#endif
inited = true;
return true;
}
static bool internal_set_error (SQCloudConnection *connection, int errcode, const char *format, ...) {
connection->errcode = errcode;
va_list arg;
va_start (arg, format);
vsnprintf(connection->errmsg, sizeof(connection->errmsg), format, arg);
va_end (arg);
return false;
}
static void internal_clear_error (SQCloudConnection *connection) {
connection->errcode = 0;
connection->extcode = 0;
connection->offcode = -1; // If the most recent error does not reference a specific token in the input SQL, then the sqlite3_error_offset() function returns -1.
connection->errmsg[0] = 0;
}
static bool internal_setup_tls (SQCloudConnection *connection, SQCloudConfig *config, bool mainfd) {
#ifndef SQLITECLOUD_DISABLE_TLS
if (config && config->insecure) return true;
int rc = 0;
if (tls_init() < 0) {
return internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error while initializing TLS library.");
}
struct tls_config *tls_conf = tls_config_new();
if (!tls_conf) {
return internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error while initializing a new TLS configuration.");
}
if (config->no_verify_certificate) {
tls_config_insecure_noverifycert(tls_conf);
tls_config_insecure_noverifyname(tls_conf);
}
// loads a file containing the root certificates
if (config && config->tls_root_certificate) {
rc = tls_config_set_ca_file(tls_conf, config->tls_root_certificate);
if (rc < 0) {internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error in tls_config_set_ca_file: %s.", tls_config_error(tls_conf));}
#ifdef TLS_DEFAULT_CA_FILE
} else {
rc = tls_config_set_ca_file(tls_conf, TLS_DEFAULT_CA_FILE);
if (rc < 0) {internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error in tls_config_set_ca_file: %s.", tls_config_error(tls_conf));}
#endif
}
// loads a file containing the server certificate
if (config && config->tls_certificate) {
rc = tls_config_set_cert_file(tls_conf, config->tls_certificate);
if (rc < 0) {internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error in tls_config_set_cert_file: %s.", tls_config_error(tls_conf));}
}
// loads a file containing the private key
if (config && config->tls_certificate_key) {
rc = tls_config_set_key_file(tls_conf, config->tls_certificate_key);
if (rc < 0) {internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error in tls_config_set_key_file: %s.", tls_config_error(tls_conf));}
}
struct tls *tls_context = tls_client();
if (!tls_context) {
return internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error while initializing a new TLS client.");
}
// apply configuration to context
rc = tls_configure(tls_context, tls_conf);
tls_config_free(tls_conf);
if (rc < 0) {
return internal_set_error(connection, INTERNAL_ERRCODE_TLS, "Error in tls_configure: %s.", tls_error(tls_context));
}
// save context
if (mainfd) connection->tls_context = tls_context;
else connection->tls_pubsub_context = tls_context;
#endif
return true;
}
static SQCLOUD_VALUE_TYPE internal_type (char *buffer) {
// for VALUE_NULL values we don't return _ but the NULL value itself, so check for this special case
// internal_parse_value is used both internally to set the value inside a Rowset (1)
// and also from the public API SQCloudRowsetValue (2)
// to fix this misbehaviour, (1) should return _ while (2) should return NULL
// this is really just a convention so it is much more easier to just return NULL everytime
if (!buffer) return VALUE_NULL;
switch (buffer[0]) {
case CMD_STRING:
case CMD_ZEROSTRING: return VALUE_TEXT;
case CMD_INT: return VALUE_INTEGER;
case CMD_FLOAT: return VALUE_FLOAT;
case CMD_NULL: return VALUE_NULL;
case CMD_BLOB: return VALUE_BLOB;
}
return VALUE_NULL;
}
static bool internal_has_commandlen (int c) {
return ((c == CMD_INT) || (c == CMD_FLOAT) || (c == CMD_NULL)) ? false : true;
}
static bool internal_canbe_zerolength (int c) {
return ((c == CMD_BLOB) || (c == CMD_STRING));
}
static uint32_t internal_buffer_maxlen (SQCloudResult *result, char *value) {
if (!value) return 2;
// chunk case
if (result->ischunk) {
// lookup value index
int32_t index = -1;
char *buffer = NULL;
uint32_t blen = 0;
for (int32_t i=0; i < result->bcount; ++i) {
buffer = result->buffers[i];
blen = result->blens[i];
if ((value >= buffer) && (value <= buffer + blen)) {
index = i;
break;
}
}
// sanity check
if (index == -1) return 0;
return (uint32_t)(blen - (uint32_t)(value - buffer) + result->nheads[index]);
}
// default case
return (uint32_t)(result->blen - (uint32_t)(value - result->rawbuffer) + result->nheader);
}
static uint32_t internal_parse_number_extended (char *buffer, uint32_t blen, uint32_t *cstart, uint32_t *extcode, int32_t *offcode) {
uint32_t value = 0;
uint32_t extvalue = 0;
int32_t offvalue = -1;
bool isext = false;
bool isoff = false;
for (uint32_t i=0; i<blen; ++i) {
int c = buffer[i];
// check for optional extended error code (ERRCODE[:EXTCODE:OFFCODE])
if (c == ':') {
if (isext == false) isext = true;
else {isext = false; isoff = true; offvalue = 0;}
continue;
}
// check for end of value
if (c == ' ') {
if (cstart) *cstart = i+1;
if (extcode) *extcode = extvalue;
if (offcode) *offcode = offvalue;
return value;
}
// compute numeric value
if (isext) extvalue = (extvalue * 10) + (buffer[i] - '0');
else if (isoff) offvalue = (offvalue * 10) + (buffer[i] - '0');
else value = (value * 10) + (buffer[i] - '0');
}
return 0;
}
static uint32_t internal_parse_number (char *buffer, uint32_t blen, uint32_t *cstart) {
return internal_parse_number_extended(buffer, blen, cstart, NULL, NULL);
}
static int internal_parse_type (char *buffer) {
if (!buffer) return 0;
return buffer[0];
}
static char *internal_parse_value (char *buffer, uint32_t *len, uint32_t *cellsize) {
if (*len <= 0) return NULL;
// handle special NULL value case
if (!buffer || buffer[0] == CMD_NULL) {
*len = 0;
if (cellsize) *cellsize = 2;
return NULL;
}
// blen originally was hard coded to 24 because the max 64bit value is 20 characters long
uint32_t cstart = 0;
uint32_t blen = *len;
blen = internal_parse_number(&buffer[1], blen, &cstart);
// handle decimal/float cases
if ((buffer[0] == CMD_INT) || (buffer[0] == CMD_FLOAT)) {
*len = cstart - 1;
if (cellsize) *cellsize = cstart + 1;
return &buffer[1];
}
// sanity check
if (blen > *len) return NULL;
*len = (buffer[0] == CMD_ZEROSTRING) ? blen - 1 : blen;
if (cellsize) *cellsize = cstart + blen + 1;
return &buffer[1+cstart];
}
static SQCloudResult *internal_run_command (SQCloudConnection *connection, const char *buffer, size_t blen, bool mainfd) {
internal_clear_error(connection);
if (!buffer || blen < CMD_MINLEN) return NULL;
TIME_GET(tstart);
if (!internal_socket_write(connection, buffer, blen, mainfd, true)) return NULL;
SQCloudResult *result = internal_socket_read(connection, mainfd);
TIME_GET(tend);
if (result) result->time = TIME_VAL(tstart, tend);
return result;
}
static bool internal_send_blob(SQCloudConnection *connection, void *buffer, uint32_t blen) {
internal_clear_error(connection);
// set connection to be BLOB
connection->isblob = true;
// check zero-size BLOB
TIME_GET(tstart);
bool rc = internal_socket_write(connection, (blen) ? buffer : NULL, blen, true, true);
connection->isblob = false;
if (!rc) return false;
SQCloudResult *result = internal_socket_read(connection, true);
TIME_GET(tend);
if (result) result->time = TIME_VAL(tstart, tend);
rc = (SQCloudResultType(result) == RESULT_OK);
SQCloudResultFree(result);
return rc;
}
static SQCloudResult *internal_setup_pubsub (SQCloudConnection *connection, const char *buffer, size_t blen) {
// check if pubsub was already setup
if (connection->pubsubfd != 0) return &SQCloudResultOK;
if (!internal_setup_tls(connection, connection->_config, false)) return NULL;
if (internal_connect(connection, connection->hostname, connection->port, connection->_config, false)) {
SQCloudResult *result = internal_run_command(connection, buffer, blen, false);
if (!SQCloudResultIsOK(result)) return result;
pthread_create(&connection->tid, NULL, pubsub_thread, (void *)connection);
} else {
return NULL;
}
return &SQCloudResultOK;
}
static SQCloudResult *internal_reconnect (SQCloudConnection *connection, const char *buffer, size_t blen) {
// DO RE-CONNECT HERE
return NULL;
}
static int32_t internal_array_count (char *buffer, uint32_t blen) {
// =LEN N VALUE1 VALUE2 ... VALUEN
if (buffer[0] != CMD_ARRAY) return -1;
do {
++buffer;
--blen;
}
while (buffer[0] != ' ');
++buffer; --blen;
uint32_t size = 0;
return internal_parse_number(buffer, blen, &size);
}
static SQCloudResult *internal_parse_array (SQCloudConnection *connection, char *buffer, uint32_t blen, uint32_t bstart) {
SQCloudResult *rowset = (SQCloudResult *)mem_zeroalloc(sizeof(SQCloudResult));
if (!rowset) {
internal_set_error(connection, INTERNAL_ERRCODE_MEMORY, "Unable to allocate memory for SQCloudResult: %d.", sizeof(SQCloudResult));
return NULL;
}
rowset->tag = RESULT_ARRAY;
rowset->rawbuffer = buffer;
rowset->blen = blen;
rowset->nheader = bstart;
// =LEN N VALUE1 VALUE2 ... VALUEN
uint32_t start1 = 0;
uint32_t n = internal_parse_number(&buffer[bstart], blen-1, &start1);
rowset->ndata = n;
rowset->data = (char **) mem_alloc(rowset->ndata * sizeof(char *));
if (!rowset->data) {
internal_set_error(connection, INTERNAL_ERRCODE_MEMORY, "Unable to allocate memory for SQCloudResult: %d.", rowset->ndata * sizeof(char *));
mem_free(rowset);
return NULL;
}
// loop from i to n to parse each data
buffer += bstart + start1;
for (uint32_t i=0; i<n; ++i) {
uint32_t cellsize = 0;
uint32_t len = blen - start1;
char *value = internal_parse_value(buffer, &len, &cellsize);
rowset->data[i] = (value) ? buffer : NULL;
buffer += cellsize;
blen -= cellsize;
}
return rowset;
}
static SQCloudResult *internal_rowset_type (SQCloudConnection *connection, char *buffer, uint32_t blen, uint32_t bstart, SQCLOUD_RESULT_TYPE type) {
SQCloudResult *rowset = (SQCloudResult *)mem_zeroalloc(sizeof(SQCloudResult));
if (!rowset) {
internal_set_error(connection, INTERNAL_ERRCODE_MEMORY, "Unable to allocate memory for SQCloudResult: %d.", sizeof(SQCloudResult));
return NULL;
}
rowset->tag = type;
rowset->buffer = &buffer[bstart];
rowset->rawbuffer = buffer;
rowset->blen = blen;
rowset->balloc = blen;
return rowset;
}
static char *internal_get_rowset_header (SQCloudResult *result, char **header, uint32_t col, uint32_t *len) {
if (!result || result->tag != RESULT_ROWSET) return NULL;
if (col >= result->ncols) return NULL;
if (header == NULL) return NULL;
char *buffer = (result->ischunk) ? result->buffers[0] : result->rawbuffer;
*len = result->blen - (uint32_t)(header[col] - buffer);
return internal_parse_value(header[col], len, NULL);
}
static int internal_get_rowset_header_int (SQCloudResult *result, int *header, uint32_t col) {
if (!result || result->tag != RESULT_ROWSET) return -1;
if (col >= result->ncols) return -1;
if (header == NULL) return -1;
return header[col];
}
static bool internal_parse_rowset_header (SQCloudResult *rowset, char **pbuffer, uint32_t *pblen, uint32_t ncols, uint32_t version) {
if (version == ROWSET_TYPE_DATA_ONLY) return true;
char *buffer = *pbuffer;
uint32_t blen = *pblen;
/*
if (BITCHECK(flags, SQCLOUD_ROWSET_FLAG_METAVM)) {
uint32_t cstart1 = 0, cstart2 = 0, cstart3 = 0, cstart4 = 0, cstart5 = 0;
// bind parameter count
buffer += 1; blen -= 1;
uint32_t n1 = internal_parse_number(buffer, blen, &cstart1);
// vm is readonly
buffer += cstart1; blen -= cstart1;
uint32_t n2 = internal_parse_number(buffer, blen, &cstart2);
// column count
buffer += cstart2; blen -= cstart2;
uint32_t n3 = internal_parse_number(buffer, blen, &cstart3);
// vm is explain
buffer += cstart3; blen -= cstart3;
uint32_t n4 = internal_parse_number(buffer, blen, &cstart4);
// tail len
buffer += cstart4; blen -= cstart4;
uint32_t n5 = internal_parse_number(buffer, blen, &cstart5);
buffer += cstart5; blen -= cstart5;
rowset->n1 = n1;
rowset->n2 = n2;
rowset->n3 = n3;
rowset->n4 = n4;
rowset->n5 = n5;
}
*/
// header is guarantee to contain column names
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t len = internal_parse_number(&buffer[1], blen, &cstart);
rowset->name[i] = buffer;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
if (rowset->clen[i] < len) rowset->clen[i] = len;
if (rowset->maxlen < len) rowset->maxlen = len;
}
// check if additional metadata is contained
if (version == ROWSET_TYPE_METADATA_v1) {
rowset->decltype = (char **) mem_alloc(ncols * sizeof(char *));
if (!rowset->decltype) return false;
rowset->dbname = (char **) mem_alloc(ncols * sizeof(char *));
if (!rowset->dbname) return false;
rowset->tblname = (char **) mem_alloc(ncols * sizeof(char *));
if (!rowset->tblname) return false;
rowset->origname = (char **) mem_alloc(ncols * sizeof(char *));
if (!rowset->origname) return false;
rowset->notnull = (int *) mem_alloc(ncols * sizeof(int));
if (!rowset->notnull) return false;
rowset->prikey = (int *) mem_alloc(ncols * sizeof(int));
if (!rowset->prikey) return false;
rowset->autoinc = (int *) mem_alloc(ncols * sizeof(int));
if (!rowset->autoinc) return false;
// column declared types
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t len = internal_parse_number(&buffer[1], blen, &cstart);
rowset->decltype[i] = buffer;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
// column database names
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t len = internal_parse_number(&buffer[1], blen, &cstart);
rowset->dbname[i] = buffer;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
// column table names
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t len = internal_parse_number(&buffer[1], blen, &cstart);
rowset->tblname[i] = buffer;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
// column origin names
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t len = internal_parse_number(&buffer[1], blen, &cstart);
rowset->origname[i] = buffer;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
// column not null flag
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t value = internal_parse_number(&buffer[1], blen, &cstart);
rowset->notnull[i] = (int)value;
uint32_t len = 0;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
// column primary key flag
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t value = internal_parse_number(&buffer[1], blen, &cstart);
rowset->prikey[i] = (int)value;
uint32_t len = 0;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
// column autoincrement key flag
for (uint32_t i=0; i<ncols; ++i) {
uint32_t cstart = 0;
uint32_t value = internal_parse_number(&buffer[1], blen, &cstart);
rowset->autoinc[i] = (int)value;
uint32_t len = 0;
buffer += cstart + len + 1;
blen -= cstart + len + 1;
}
}
*pbuffer = buffer;
*pblen = blen;
return true;
}
static bool internal_parse_rowset_values (SQCloudResult *rowset, char **pbuffer, uint32_t *pblen, uint32_t index, uint32_t bound, uint32_t ncols, uint32_t version) {
if (version == ROWSET_TYPE_HEADER_ONLY) return true;
char *buffer = *pbuffer;
uint32_t blen = *pblen;
for (uint32_t i=index; i<bound; ++i) {
uint32_t len = blen, cellsize;
char *value = internal_parse_value(buffer, &len, &cellsize);
rowset->data[i] = (value) ? buffer : NULL;
buffer += cellsize;
blen -= cellsize;
++rowset->ndata;
if (rowset->clen[i % ncols] < len) rowset->clen[i % ncols] = len;
if (rowset->maxlen < len) rowset->maxlen = len;
}
return true;
}
static SQCloudResult *internal_parse_rowset (SQCloudConnection *connection, char *buffer, uint32_t blen, uint32_t bstart,
uint32_t nrows, uint32_t ncols, uint32_t version) {
SQCloudResult *rowset = (SQCloudResult *)mem_zeroalloc(sizeof(SQCloudResult));
if (!rowset) {
internal_set_error(connection, INTERNAL_ERRCODE_MEMORY, "Unable to allocate memory for SQCloudResult: %d.", sizeof(SQCloudResult));
return NULL;
}
rowset->tag = RESULT_ROWSET;
rowset->buffer = buffer;
rowset->rawbuffer = buffer;
rowset->blen = blen;
rowset->balloc = blen;
rowset->nheader = bstart;
rowset->version = version;
rowset->nrows = nrows;
rowset->ncols = ncols;
rowset->data = (char **) mem_alloc(nrows * ncols * sizeof(char *));
rowset->name = (char **) mem_alloc(ncols * sizeof(char *));
rowset->clen = (uint32_t *) mem_zeroalloc(ncols * sizeof(uint32_t));
if (!rowset->data || !rowset->name || !rowset->clen) goto abort_rowset;