-
Notifications
You must be signed in to change notification settings - Fork 72
/
cext.c
1275 lines (1013 loc) · 39 KB
/
cext.c
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
#include <arpa/inet.h>
#include <errno.h>
#include <ruby.h>
#include <ruby/encoding.h>
#include <ruby/io.h>
#include <ruby/thread.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <sys/un.h>
#include <unistd.h>
#include <fcntl.h>
#include <trilogy.h>
#include "trilogy-ruby.h"
VALUE Trilogy_CastError;
static VALUE Trilogy_BaseConnectionError, Trilogy_ProtocolError, Trilogy_SSLError, Trilogy_QueryError,
Trilogy_ConnectionClosedError,
Trilogy_TimeoutError, Trilogy_SyscallError, Trilogy_Result, Trilogy_EOFError, Trilogy_AuthPluginError;
static ID id_socket, id_host, id_port, id_username, id_password, id_found_rows, id_connect_timeout, id_read_timeout,
id_write_timeout, id_keepalive_enabled, id_keepalive_idle, id_keepalive_interval, id_keepalive_count,
id_ivar_affected_rows, id_ivar_fields, id_ivar_last_insert_id, id_ivar_rows, id_ivar_query_time, id_password,
id_database, id_enable_cleartext_plugin, id_ssl_ca, id_ssl_capath, id_ssl_cert, id_ssl_cipher, id_ssl_crl, id_ssl_crlpath, id_ssl_key,
id_ssl_mode, id_tls_ciphersuites, id_tls_min_version, id_tls_max_version, id_multi_statement, id_multi_result,
id_from_code, id_from_errno, id_connection_options, id_max_allowed_packet;
struct trilogy_ctx {
trilogy_conn_t conn;
char server_version[TRILOGY_SERVER_VERSION_SIZE + 1];
unsigned int query_flags;
VALUE encoding;
};
static void mark_trilogy(void *ptr)
{
struct trilogy_ctx *ctx = ptr;
rb_gc_mark(ctx->encoding);
}
static void free_trilogy(void *ptr)
{
struct trilogy_ctx *ctx = ptr;
trilogy_free(&ctx->conn);
xfree(ptr);
}
static size_t trilogy_memsize(const void *ptr) {
const struct trilogy_ctx *ctx = ptr;
size_t memsize = sizeof(struct trilogy_ctx);
if (ctx->conn.socket != NULL) {
memsize += sizeof(trilogy_sock_t);
}
memsize += ctx->conn.packet_buffer.cap;
return memsize;
}
static const rb_data_type_t trilogy_data_type = {
.wrap_struct_name = "trilogy",
.function = {
.dmark = mark_trilogy,
.dfree = free_trilogy,
.dsize = trilogy_memsize,
},
.flags = RUBY_TYPED_FREE_IMMEDIATELY | RUBY_TYPED_WB_PROTECTED
};
static struct trilogy_ctx *get_ctx(VALUE obj)
{
struct trilogy_ctx *ctx;
TypedData_Get_Struct(obj, struct trilogy_ctx, &trilogy_data_type, ctx);
return ctx;
}
static struct trilogy_ctx *get_open_ctx(VALUE obj)
{
struct trilogy_ctx *ctx = get_ctx(obj);
if (ctx->conn.socket == NULL) {
rb_raise(Trilogy_ConnectionClosedError, "Attempted to use closed connection");
}
return ctx;
}
NORETURN(static void trilogy_syserr_fail_str(int, VALUE));
static void trilogy_syserr_fail_str(int e, VALUE msg)
{
if (e == EPIPE) {
// Backwards compatibility: This error message is a bit odd, but includes "TRILOGY_CLOSED_CONNECTION" to match legacy string matching
rb_raise(Trilogy_EOFError, "%" PRIsVALUE ": TRILOGY_CLOSED_CONNECTION: EPIPE", msg);
} else {
VALUE exc = rb_funcall(Trilogy_SyscallError, id_from_errno, 2, INT2NUM(e), msg);
rb_exc_raise(exc);
}
}
static int trilogy_error_recoverable_p(int rc)
{
// TRILOGY_OPENSSL_ERR and TRILOGY_SYSERR (which can result from an SSL error) must shut down the socket, as further
// SSL calls would be invalid.
// TRILOGY_ERR, which represents an error message sent to us from the server, is recoverable.
// TRILOGY_MAX_PACKET_EXCEEDED is also recoverable as we do not send data when it occurs.
// For other exceptions we will also close the socket to prevent further use, as the connection is probably in an
// invalid state.
return rc == TRILOGY_ERR || rc == TRILOGY_MAX_PACKET_EXCEEDED;
}
NORETURN(static void handle_trilogy_error(struct trilogy_ctx *, int, const char *, ...));
static void handle_trilogy_error(struct trilogy_ctx *ctx, int rc, const char *msg, ...)
{
va_list args;
va_start(args, msg);
VALUE rbmsg = rb_vsprintf(msg, args);
va_end(args);
if (!trilogy_error_recoverable_p(rc)) {
if (ctx->conn.socket != NULL) {
// trilogy_sock_shutdown may affect errno
int errno_was = errno;
trilogy_sock_shutdown(ctx->conn.socket);
errno = errno_was;
}
}
switch (rc) {
case TRILOGY_SYSERR:
trilogy_syserr_fail_str(errno, rbmsg);
case TRILOGY_TIMEOUT:
rb_raise(Trilogy_TimeoutError, "%" PRIsVALUE, rbmsg);
case TRILOGY_ERR: {
VALUE conn_message = rb_str_new(ctx->conn.error_message, ctx->conn.error_message_len);
VALUE message = rb_sprintf("%" PRIsVALUE " (%" PRIsVALUE ")", conn_message, rbmsg);
VALUE exc = rb_funcall(Trilogy_ProtocolError, id_from_code, 2, message, INT2NUM(ctx->conn.error_code));
rb_exc_raise(exc);
}
case TRILOGY_OPENSSL_ERR: {
unsigned long ossl_error = ERR_get_error();
ERR_clear_error();
if (ERR_GET_LIB(ossl_error) == ERR_LIB_SYS) {
int err_reason = ERR_GET_REASON(ossl_error);
trilogy_syserr_fail_str(err_reason, rbmsg);
}
rb_raise(Trilogy_SSLError, "%" PRIsVALUE ": SSL Error: %s", rbmsg, ERR_reason_error_string(ossl_error));
}
case TRILOGY_DNS_ERR: {
rb_raise(Trilogy_BaseConnectionError, "%" PRIsVALUE ": TRILOGY_DNS_ERROR", rbmsg);
}
case TRILOGY_CLOSED_CONNECTION: {
rb_raise(Trilogy_EOFError, "%" PRIsVALUE ": TRILOGY_CLOSED_CONNECTION", rbmsg);
}
case TRILOGY_AUTH_PLUGIN_ERROR: {
rb_raise(Trilogy_AuthPluginError, "%" PRIsVALUE ": TRILOGY_AUTH_PLUGIN_ERROR", rbmsg);
}
case TRILOGY_UNSUPPORTED: {
rb_raise(Trilogy_BaseConnectionError, "%" PRIsVALUE ": TRILOGY_UNSUPPORTED", rbmsg);
}
default:
rb_raise(Trilogy_QueryError, "%" PRIsVALUE ": %s", rbmsg, trilogy_error(rc));
}
}
static VALUE allocate_trilogy(VALUE klass)
{
struct trilogy_ctx *ctx;
VALUE obj = TypedData_Make_Struct(klass, struct trilogy_ctx, &trilogy_data_type, ctx);
ctx->query_flags = TRILOGY_FLAGS_DEFAULT;
if (trilogy_init(&ctx->conn) < 0) {
VALUE rbmsg = rb_str_new("trilogy_init", 13);
trilogy_syserr_fail_str(errno, rbmsg);
}
return obj;
}
static int flush_writes(struct trilogy_ctx *ctx)
{
while (1) {
int rc = trilogy_flush_writes(&ctx->conn);
if (rc != TRILOGY_AGAIN) {
return rc;
}
rc = trilogy_sock_wait_write(ctx->conn.socket);
if (rc != TRILOGY_OK) {
return rc;
}
}
}
static struct timeval double_to_timeval(double secs)
{
double whole_secs = floor(secs);
return (struct timeval){
.tv_sec = whole_secs,
.tv_usec = floor((secs - whole_secs) * 1000000),
};
}
static double timeval_to_double(struct timeval tv)
{
return (double)tv.tv_sec + ((double)tv.tv_usec) / 1000000.0;
}
struct rb_trilogy_wait_args {
struct timeval *timeout;
int wait_flag;
int fd;
int rc;
};
static VALUE rb_trilogy_wait_protected(VALUE vargs) {
struct rb_trilogy_wait_args *args = (void *)vargs;
args->rc = rb_wait_for_single_fd(args->fd, args->wait_flag, args->timeout);
return Qnil;
}
static int _cb_ruby_wait(trilogy_sock_t *sock, trilogy_wait_t wait)
{
struct timeval *timeout = NULL;
int wait_flag = 0;
switch (wait) {
case TRILOGY_WAIT_READ:
timeout = &sock->opts.read_timeout;
wait_flag = RB_WAITFD_IN;
break;
case TRILOGY_WAIT_WRITE:
timeout = &sock->opts.write_timeout;
wait_flag = RB_WAITFD_OUT;
break;
case TRILOGY_WAIT_CONNECT:
// wait for connection to be writable
timeout = &sock->opts.connect_timeout;
if (timeout->tv_sec == 0 && timeout->tv_usec == 0) {
// We used to use the write timeout for this, so if a connect timeout isn't configured, default to that.
timeout = &sock->opts.write_timeout;
}
wait_flag = RB_WAITFD_OUT;
break;
case TRILOGY_WAIT_HANDSHAKE:
// wait for handshake packet on initial connection
timeout = &sock->opts.connect_timeout;
wait_flag = RB_WAITFD_IN;
break;
default:
return TRILOGY_ERR;
}
if (timeout->tv_sec == 0 && timeout->tv_usec == 0) {
timeout = NULL;
}
struct rb_trilogy_wait_args args;
args.fd = trilogy_sock_fd(sock);
args.wait_flag = wait_flag;
args.timeout = timeout;
args.rc = 0;
int state = 0;
rb_protect(rb_trilogy_wait_protected, (VALUE)&args, &state);
if (state) {
trilogy_sock_shutdown(sock);
rb_jump_tag(state);
}
// rc here comes from rb_wait_for_single_fd which (similar to poll(3)) returns 0 to indicate that the call timed out
// or -1 to indicate a system error with errno set.
if (args.rc < 0)
return TRILOGY_SYSERR;
if (args.rc == 0)
return TRILOGY_TIMEOUT;
return TRILOGY_OK;
}
struct nogvl_sock_args {
int rc;
trilogy_sock_t *sock;
};
static void *no_gvl_resolve(void *data)
{
struct nogvl_sock_args *args = data;
args->rc = trilogy_sock_resolve(args->sock);
return NULL;
}
static int try_connect(struct trilogy_ctx *ctx, trilogy_handshake_t *handshake, const trilogy_sockopt_t *opts)
{
trilogy_sock_t *sock = trilogy_sock_new(opts);
if (sock == NULL) {
return TRILOGY_ERR;
}
struct nogvl_sock_args args = {.rc = 0, .sock = sock};
// Do the DNS resolving with the GVL unlocked. At this point all
// configuration data is copied and available to the trilogy socket.
rb_thread_call_without_gvl(no_gvl_resolve, (void *)&args, RUBY_UBF_IO, NULL);
int rc = args.rc;
if (rc != TRILOGY_OK) {
trilogy_sock_close(sock);
return rc;
}
/* replace the default wait callback with our GVL-aware callback so we can
escape the GVL on each wait operation without going through call_without_gvl */
sock->wait_cb = _cb_ruby_wait;
rc = trilogy_connect_send_socket(&ctx->conn, sock);
if (rc < 0) {
trilogy_sock_close(sock);
return rc;
}
while (1) {
rc = trilogy_connect_recv(&ctx->conn, handshake);
if (rc == TRILOGY_OK) {
return rc;
}
if (rc != TRILOGY_AGAIN) {
return rc;
}
rc = trilogy_sock_wait(ctx->conn.socket, TRILOGY_WAIT_HANDSHAKE);
if (rc != TRILOGY_OK) {
return rc;
}
}
}
static void auth_switch(struct trilogy_ctx *ctx, trilogy_handshake_t *handshake)
{
int rc = trilogy_auth_switch_send(&ctx->conn, handshake);
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_auth_switch_send");
}
while (1) {
rc = trilogy_auth_recv(&ctx->conn, handshake);
if (rc == TRILOGY_OK) {
return;
}
if (rc != TRILOGY_AGAIN) {
handle_trilogy_error(ctx, rc, "trilogy_auth_recv");
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_auth_recv");
}
}
}
static void authenticate(struct trilogy_ctx *ctx, trilogy_handshake_t *handshake, trilogy_ssl_mode_t ssl_mode)
{
int rc;
if (ssl_mode != TRILOGY_SSL_DISABLED) {
if (handshake->capabilities & TRILOGY_CAPABILITIES_SSL) {
rc = trilogy_ssl_request_send(&ctx->conn);
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_ssl_request_send");
}
rc = trilogy_sock_upgrade_ssl(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_ssl_upgrade");
}
} else {
if (ssl_mode != TRILOGY_SSL_PREFERRED_NOVERIFY) {
rb_raise(Trilogy_SSLError, "SSL required, not supported by server");
}
}
}
rc = trilogy_auth_send(&ctx->conn, handshake);
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_auth_send");
}
while (1) {
rc = trilogy_auth_recv(&ctx->conn, handshake);
if (rc == TRILOGY_OK || rc == TRILOGY_AUTH_SWITCH) {
break;
}
if (rc != TRILOGY_AGAIN) {
if (rc == TRILOGY_UNSUPPORTED) {
handle_trilogy_error(ctx, rc, "trilogy_auth_recv: caching_sha2_password requires either TCP with TLS or a unix socket");
}
else {
handle_trilogy_error(ctx, rc, "trilogy_auth_recv");
}
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_auth_recv");
}
}
if (rc == TRILOGY_AUTH_SWITCH) {
auth_switch(ctx, handshake);
}
}
static VALUE rb_trilogy_connect(VALUE self, VALUE encoding, VALUE charset, VALUE opts)
{
struct trilogy_ctx *ctx = get_ctx(self);
trilogy_sockopt_t connopt = {0};
trilogy_handshake_t handshake;
VALUE val;
RB_OBJ_WRITE(self, &ctx->encoding, encoding);
connopt.encoding = NUM2INT(charset);
Check_Type(opts, T_HASH);
if ((val = rb_hash_lookup(opts, ID2SYM(id_ssl_mode))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.ssl_mode = (trilogy_ssl_mode_t)NUM2INT(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_connect_timeout))) != Qnil) {
connopt.connect_timeout = double_to_timeval(NUM2DBL(val));
}
if ((val = rb_hash_aref(opts, ID2SYM(id_read_timeout))) != Qnil) {
connopt.read_timeout = double_to_timeval(NUM2DBL(val));
}
if ((val = rb_hash_aref(opts, ID2SYM(id_write_timeout))) != Qnil) {
connopt.write_timeout = double_to_timeval(NUM2DBL(val));
}
if (RTEST(rb_hash_aref(opts, ID2SYM(id_keepalive_enabled)))) {
connopt.keepalive_enabled = true;
}
if ((val = rb_hash_lookup(opts, ID2SYM(id_keepalive_idle))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.keepalive_idle = NUM2USHORT(val);
}
if ((val = rb_hash_lookup(opts, ID2SYM(id_keepalive_count))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.keepalive_count = NUM2USHORT(val);
}
if ((val = rb_hash_lookup(opts, ID2SYM(id_keepalive_interval))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.keepalive_interval = NUM2USHORT(val);
}
if ((val = rb_hash_lookup(opts, ID2SYM(id_max_allowed_packet))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.max_allowed_packet = NUM2SIZET(val);
}
if ((val = rb_hash_lookup(opts, ID2SYM(id_host))) != Qnil) {
Check_Type(val, T_STRING);
connopt.hostname = StringValueCStr(val);
connopt.port = 3306;
if ((val = rb_hash_lookup(opts, ID2SYM(id_port))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.port = NUM2USHORT(val);
}
} else {
connopt.path = (char *)"/tmp/mysql.sock";
if ((val = rb_hash_lookup(opts, ID2SYM(id_socket))) != Qnil) {
Check_Type(val, T_STRING);
connopt.path = StringValueCStr(val);
}
}
if ((val = rb_hash_aref(opts, ID2SYM(id_username))) != Qnil) {
Check_Type(val, T_STRING);
connopt.username = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_password))) != Qnil) {
Check_Type(val, T_STRING);
connopt.password = RSTRING_PTR(val);
connopt.password_len = RSTRING_LEN(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_database))) != Qnil) {
Check_Type(val, T_STRING);
connopt.database = StringValueCStr(val);
connopt.flags |= TRILOGY_CAPABILITIES_CONNECT_WITH_DB;
}
if (RTEST(rb_hash_aref(opts, ID2SYM(id_enable_cleartext_plugin)))) {
connopt.enable_cleartext_plugin = true;
}
if (RTEST(rb_hash_aref(opts, ID2SYM(id_found_rows)))) {
connopt.flags |= TRILOGY_CAPABILITIES_FOUND_ROWS;
}
if (rb_hash_aref(opts, ID2SYM(id_multi_result)) != Qfalse) {
connopt.flags |= TRILOGY_CAPABILITIES_MULTI_RESULTS;
}
if (RTEST(rb_hash_aref(opts, ID2SYM(id_multi_statement)))) {
connopt.flags |= TRILOGY_CAPABILITIES_MULTI_STATEMENTS;
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_ca))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_ca = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_capath))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_capath = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_cert))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_cert = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_cipher))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_cipher = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_crl))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_crl = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_crlpath))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_crlpath = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_ssl_key))) != Qnil) {
Check_Type(val, T_STRING);
connopt.ssl_key = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_tls_ciphersuites))) != Qnil) {
Check_Type(val, T_STRING);
connopt.tls_ciphersuites = StringValueCStr(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_tls_min_version))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.tls_min_version = NUM2INT(val);
}
if ((val = rb_hash_aref(opts, ID2SYM(id_tls_max_version))) != Qnil) {
Check_Type(val, T_FIXNUM);
connopt.tls_max_version = NUM2INT(val);
}
int rc = try_connect(ctx, &handshake, &connopt);
if (rc != TRILOGY_OK) {
if (connopt.path) {
handle_trilogy_error(ctx, rc, "trilogy_connect - unable to connect to %s", connopt.path);
} else {
handle_trilogy_error(ctx, rc, "trilogy_connect - unable to connect to %s:%hu", connopt.hostname,
connopt.port);
}
}
memcpy(ctx->server_version, handshake.server_version, TRILOGY_SERVER_VERSION_SIZE);
ctx->server_version[TRILOGY_SERVER_VERSION_SIZE] = 0;
authenticate(ctx, &handshake, connopt.ssl_mode);
return Qnil;
}
static VALUE rb_trilogy_change_db(VALUE self, VALUE database)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
StringValue(database);
int rc = trilogy_change_db_send(&ctx->conn, RSTRING_PTR(database), RSTRING_LEN(database));
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_change_db_send");
}
while (1) {
rc = trilogy_change_db_recv(&ctx->conn);
if (rc == TRILOGY_OK) {
break;
}
if (rc != TRILOGY_AGAIN) {
handle_trilogy_error(ctx, rc, "trilogy_change_db_recv");
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_change_db_recv");
}
}
return Qtrue;
}
static VALUE rb_trilogy_set_server_option(VALUE self, VALUE option)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
int rc = trilogy_set_option_send(&ctx->conn, NUM2INT(option));
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_set_option_send");
}
while (1) {
rc = trilogy_set_option_recv(&ctx->conn);
if (rc == TRILOGY_OK) {
break;
}
if (rc != TRILOGY_AGAIN) {
handle_trilogy_error(ctx, rc, "trilogy_set_option_recv");
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_set_option_recv");
}
}
return Qtrue;
}
static void load_query_options(unsigned int query_flags, struct rb_trilogy_cast_options *cast_options)
{
cast_options->cast = (query_flags & TRILOGY_FLAGS_CAST) != 0;
cast_options->cast_booleans = (query_flags & TRILOGY_FLAGS_CAST_BOOLEANS) != 0;
cast_options->cast_decimals_to_bigdecimals = (query_flags & TRILOGY_FLAGS_CAST_ALL_DECIMALS_TO_BIGDECIMALS) != 0;
cast_options->database_local_time = (query_flags & TRILOGY_FLAGS_LOCAL_TIMEZONE) != 0;
cast_options->flatten_rows = (query_flags & TRILOGY_FLAGS_FLATTEN_ROWS) != 0;
}
struct read_query_response_state {
struct rb_trilogy_cast_options *cast_options;
struct trilogy_ctx *ctx;
// Error state for tracking
const char *msg;
int rc;
};
static void get_timespec_monotonic(struct timespec *ts)
{
#if defined(HAVE_CLOCK_GETTIME) && defined(CLOCK_MONOTONIC)
if (clock_gettime(CLOCK_MONOTONIC, ts) == -1) {
rb_sys_fail("clock_gettime");
}
#else
struct timeval tv;
if (gettimeofday(&tv, 0) < 0) {
rb_sys_fail("gettimeofday");
}
ts->tv_sec = tv.tv_sec;
ts->tv_nsec = tv.tv_usec * 1000;
#endif
}
static VALUE read_query_error(struct read_query_response_state *args, int rc, const char *msg)
{
args->rc = rc;
args->msg = msg;
return Qundef;
}
static VALUE read_query_response(VALUE vargs)
{
struct read_query_response_state *args = (void *)vargs;
struct trilogy_ctx *ctx = args->ctx;
struct timespec start;
get_timespec_monotonic(&start);
uint64_t column_count = 0;
int rc;
while (1) {
rc = trilogy_query_recv(&ctx->conn, &column_count);
if (rc == TRILOGY_OK || rc == TRILOGY_HAVE_RESULTS) {
break;
}
if (rc != TRILOGY_AGAIN) {
return read_query_error(args, rc, "trilogy_query_recv");
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_query_recv");
}
}
struct timespec finish;
get_timespec_monotonic(&finish);
double query_time = finish.tv_sec - start.tv_sec;
query_time += (double)(finish.tv_nsec - start.tv_nsec) / 1000000000.0;
VALUE result = rb_obj_alloc(Trilogy_Result);
VALUE column_names = rb_ary_new2(column_count);
rb_ivar_set(result, id_ivar_fields, column_names);
VALUE rows = rb_ary_new();
rb_ivar_set(result, id_ivar_rows, rows);
rb_ivar_set(result, id_ivar_query_time, DBL2NUM(query_time));
if (rc == TRILOGY_OK) {
rb_ivar_set(result, id_ivar_last_insert_id, ULL2NUM(ctx->conn.last_insert_id));
rb_ivar_set(result, id_ivar_affected_rows, ULL2NUM(ctx->conn.affected_rows));
return result;
} else {
rb_ivar_set(result, id_ivar_last_insert_id, Qnil);
rb_ivar_set(result, id_ivar_affected_rows, Qnil);
}
VALUE rb_column_info;
struct column_info *column_info = ALLOCV_N(struct column_info, rb_column_info, column_count);
for (uint64_t i = 0; i < column_count; i++) {
trilogy_column_t column;
while (1) {
rc = trilogy_read_column(&ctx->conn, &column);
if (rc == TRILOGY_OK) {
break;
}
if (rc != TRILOGY_AGAIN) {
return read_query_error(args, rc, "trilogy_read_column");
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
return read_query_error(args, rc, "trilogy_read_column");
}
}
#ifdef HAVE_RB_INTERNED_STR
VALUE column_name = rb_interned_str(column.name, column.name_len);
#else
VALUE column_name = rb_str_new(column.name, column.name_len);
OBJ_FREEZE(column_name);
#endif
rb_ary_push(column_names, column_name);
column_info[i].type = column.type;
column_info[i].flags = column.flags;
column_info[i].len = column.len;
column_info[i].charset = column.charset;
column_info[i].decimals = column.decimals;
}
VALUE rb_row_values;
trilogy_value_t *row_values = ALLOCV_N(trilogy_value_t, rb_row_values, column_count);
while (1) {
int rc = trilogy_read_row(&ctx->conn, row_values);
if (rc == TRILOGY_AGAIN) {
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
return read_query_error(args, rc, "trilogy_read_row");
}
continue;
}
if (rc == TRILOGY_EOF) {
break;
}
if (rc != TRILOGY_OK) {
return read_query_error(args, rc, "trilogy_read_row");
}
if (args->cast_options->flatten_rows) {
for (uint64_t i = 0; i < column_count; i++) {
rb_ary_push(rows, rb_trilogy_cast_value(row_values + i, column_info + i, args->cast_options));
}
} else {
VALUE row = rb_ary_new2(column_count);
for (uint64_t i = 0; i < column_count; i++) {
rb_ary_push(row, rb_trilogy_cast_value(row_values + i, column_info + i, args->cast_options));
}
rb_ary_push(rows, row);
}
}
return result;
}
static VALUE execute_read_query_response(struct trilogy_ctx *ctx)
{
struct rb_trilogy_cast_options cast_options;
load_query_options(ctx->query_flags, &cast_options);
struct read_query_response_state args = {
.cast_options = &cast_options,
.ctx = ctx,
.rc = TRILOGY_OK,
.msg = NULL,
};
int state = 0;
VALUE result = rb_protect(read_query_response, (VALUE)&args, &state);
// If we have seen an unexpected exception, jump to it so it gets raised.
if (state) {
trilogy_sock_shutdown(ctx->conn.socket);
rb_jump_tag(state);
}
// Handle errors we can gracefully recover from here that were due to
// errors signaled at the protocol level, not unexpected exceptions.
if (result == Qundef) {
handle_trilogy_error(ctx, args.rc, args.msg);
}
return result;
}
static VALUE rb_trilogy_next_result(VALUE self)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
if (!(ctx->conn.server_status & TRILOGY_SERVER_STATUS_MORE_RESULTS_EXISTS)) {
return Qnil;
}
return execute_read_query_response(ctx);
}
static VALUE rb_trilogy_more_results_exist(VALUE self)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
if (ctx->conn.server_status & TRILOGY_SERVER_STATUS_MORE_RESULTS_EXISTS) {
return Qtrue;
} else {
return Qfalse;
}
}
static VALUE rb_trilogy_query(VALUE self, VALUE query)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
StringValue(query);
query = rb_str_export_to_enc(query, rb_to_encoding(ctx->encoding));
int rc = trilogy_query_send(&ctx->conn, RSTRING_PTR(query), RSTRING_LEN(query));
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc < 0) {
handle_trilogy_error(ctx, rc, "trilogy_query_send");
}
return execute_read_query_response(ctx);
}
static VALUE rb_trilogy_ping(VALUE self)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
int rc = trilogy_ping_send(&ctx->conn);
if (rc == TRILOGY_AGAIN) {
rc = flush_writes(ctx);
}
if (rc < 0) {
handle_trilogy_error(ctx, rc, "trilogy_ping_send");
}
while (1) {
rc = trilogy_ping_recv(&ctx->conn);
if (rc == TRILOGY_OK) {
break;
}
if (rc != TRILOGY_AGAIN) {
handle_trilogy_error(ctx, rc, "trilogy_ping_recv");
}
rc = trilogy_sock_wait_read(ctx->conn.socket);
if (rc != TRILOGY_OK) {
handle_trilogy_error(ctx, rc, "trilogy_ping_recv");
}
}
return Qtrue;
}
static VALUE rb_trilogy_escape(VALUE self, VALUE str)
{
struct trilogy_ctx *ctx = get_open_ctx(self);
rb_encoding *str_enc = rb_enc_get(str);
StringValue(str);
if (!rb_enc_asciicompat(str_enc)) {
rb_raise(rb_eEncCompatError, "input string must be ASCII-compatible");
}
const char *escaped_str;
size_t escaped_len;
int rc = trilogy_escape(&ctx->conn, RSTRING_PTR(str), RSTRING_LEN(str), &escaped_str, &escaped_len);
if (rc < 0) {
handle_trilogy_error(ctx, rc, "trilogy_escape");
}
return rb_enc_str_new(escaped_str, escaped_len, str_enc);
}
static VALUE rb_trilogy_close(VALUE self)
{
struct trilogy_ctx *ctx = get_ctx(self);