-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathmysql_connection.cpp
3226 lines (3022 loc) · 107 KB
/
mysql_connection.cpp
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 "../deps/json/json.hpp"
using json = nlohmann::json;
#define PROXYJSON
#include "MySQL_HostGroups_Manager.h"
#include "proxysql.h"
#include "cpp.h"
//#include "SpookyV2.h"
#include <fcntl.h>
#include <sstream>
#include "MySQL_PreparedStatement.h"
#include "MySQL_Data_Stream.h"
#include "MySQL_Query_Processor.h"
#include "MySQL_Variables.h"
#include <atomic>
// some of the code that follows is from mariadb client library memory allocator
typedef int myf; // Type of MyFlags in my_funcs
#define MYF(v) (myf) (v)
#define MY_KEEP_PREALLOC 1
#define MY_ALIGN(A,L) (((A) + (L) - 1) & ~((L) - 1))
#define ALIGN_SIZE(A) MY_ALIGN((A),sizeof(double))
static void ma_free_root(MA_MEM_ROOT *root, myf MyFLAGS);
static void *ma_alloc_root(MA_MEM_ROOT *mem_root, size_t Size);
#define MAX(a,b) (((a) > (b)) ? (a) : (b))
static void * ma_alloc_root(MA_MEM_ROOT *mem_root, size_t Size)
{
size_t get_size;
void * point;
MA_USED_MEM *next= 0;
MA_USED_MEM **prev;
Size= ALIGN_SIZE(Size);
if ((*(prev= &mem_root->free)))
{
if ((*prev)->left < Size &&
mem_root->first_block_usage++ >= 16 &&
(*prev)->left < 4096)
{
next= *prev;
*prev= next->next;
next->next= mem_root->used;
mem_root->used= next;
mem_root->first_block_usage= 0;
}
for (next= *prev; next && next->left < Size; next= next->next)
prev= &next->next;
}
if (! next)
{ /* Time to alloc new block */
get_size= MAX(Size+ALIGN_SIZE(sizeof(MA_USED_MEM)),
(mem_root->block_size & ~1) * ( (mem_root->block_num >> 2) < 4 ? 4 : (mem_root->block_num >> 2) ) );
if (!(next = (MA_USED_MEM*) malloc(get_size)))
{
if (mem_root->error_handler)
(*mem_root->error_handler)();
return((void *) 0); /* purecov: inspected */
}
mem_root->block_num++;
next->next= *prev;
next->size= get_size;
next->left= get_size-ALIGN_SIZE(sizeof(MA_USED_MEM));
*prev=next;
}
point= (void *) ((char*) next+ (next->size-next->left));
if ((next->left-= Size) < mem_root->min_malloc)
{ /* Full block */
*prev=next->next; /* Remove block from list */
next->next=mem_root->used;
mem_root->used=next;
mem_root->first_block_usage= 0;
}
return(point);
}
static void ma_free_root(MA_MEM_ROOT *root, myf MyFlags)
{
MA_USED_MEM *next,*old;
if (!root)
return; /* purecov: inspected */
if (!(MyFlags & MY_KEEP_PREALLOC))
root->pre_alloc=0;
for ( next=root->used; next ;)
{
old=next; next= next->next ;
if (old != root->pre_alloc)
free(old);
}
for (next= root->free ; next ; )
{
old=next; next= next->next ;
if (old != root->pre_alloc)
free(old);
}
root->used=root->free=0;
if (root->pre_alloc)
{
root->free=root->pre_alloc;
root->free->left=root->pre_alloc->size-ALIGN_SIZE(sizeof(MA_USED_MEM));
root->free->next=0;
}
}
extern char * binary_sha1;
#include "proxysql_find_charset.h"
void Variable::fill_server_internal_session(json &j, int idx) {
if (idx == SQL_CHARACTER_SET_RESULTS || idx == SQL_CHARACTER_SET_CLIENT || idx == SQL_CHARACTER_SET_DATABASE) {
const MARIADB_CHARSET_INFO *ci = NULL;
if (!value) {
ci = proxysql_find_charset_name(mysql_tracked_variables[idx].default_value);
} else if (strcasecmp("NULL", value) && strcasecmp("binary", value)) {
ci = proxysql_find_charset_nr(atoi(value));
}
if (!ci) {
if (idx == SQL_CHARACTER_SET_RESULTS && (!strcasecmp("NULL", value) || !strcasecmp("binary", value))) {
if (!strcasecmp("NULL", value)) {
j[mysql_tracked_variables[idx].internal_variable_name] = "";
} else {
j[mysql_tracked_variables[idx].internal_variable_name] = value;
}
} else {
// LCOV_EXCL_START
proxy_error("Cannot find charset [%s] for variables %d\n", value, idx);
assert(0);
// LCOV_EXCL_STOP
}
} else {
j[mysql_tracked_variables[idx].internal_variable_name] = std::string((ci && ci->csname)?ci->csname:"");
}
} else if (idx == SQL_CHARACTER_SET_CONNECTION) {
const MARIADB_CHARSET_INFO *ci = NULL;
if (!value)
ci = proxysql_find_charset_name(mysql_tracked_variables[idx].default_value);
else
ci = proxysql_find_charset_nr(atoi(value));
j[mysql_tracked_variables[idx].internal_variable_name] = std::string((ci && ci->csname)?ci->csname:"");
} else if (idx == SQL_COLLATION_CONNECTION) {
const MARIADB_CHARSET_INFO *ci = NULL;
if (!value)
ci = proxysql_find_charset_collate(mysql_tracked_variables[idx].default_value);
else
ci = proxysql_find_charset_nr(atoi(value));
j[mysql_tracked_variables[idx].internal_variable_name] = std::string((ci && ci->name)?ci->name:"");
/*
// NOTE: it seems we treat SQL_LOG_BIN in a special way
// it doesn't seem necessary
} else if (idx == SQL_SQL_LOG_BIN) {
if (!value)
j["backends"][conn_num]["conn"][mysql_tracked_variables[idx].internal_variable_name] = mysql_tracked_variables[idx].default_value;
else
j["backends"][conn_num]["conn"][mysql_tracked_variables[idx].internal_variable_name] = std::string(!strcmp("1",value)?"ON":"OFF");
*/
} else {
j[mysql_tracked_variables[idx].internal_variable_name] = std::string(value?value:"");
}
}
void Variable::fill_client_internal_session(json &j, int idx) {
if (idx == SQL_CHARACTER_SET_RESULTS || idx == SQL_CHARACTER_SET_CLIENT || idx == SQL_CHARACTER_SET_DATABASE) {
const MARIADB_CHARSET_INFO *ci = NULL;
if (!value) {
ci = proxysql_find_charset_name(mysql_tracked_variables[idx].default_value);
} else if (strcasecmp("NULL", value) && strcasecmp("binary", value)) {
ci = proxysql_find_charset_nr(atoi(value));
}
if (!ci) {
if (idx == SQL_CHARACTER_SET_RESULTS && (!strcasecmp("NULL", value) || !strcasecmp("binary", value))) {
if (!strcasecmp("NULL", value)) {
j[mysql_tracked_variables[idx].internal_variable_name] = "";
} else {
j[mysql_tracked_variables[idx].internal_variable_name] = value;
}
} else {
// LCOV_EXCL_START
proxy_error("Cannot find charset [%s] for variables %d\n", value, idx);
assert(0);
// LCOV_EXCL_STOP
}
} else {
j[mysql_tracked_variables[idx].internal_variable_name] = (ci && ci->csname)?ci->csname:"";
}
} else if (idx == SQL_CHARACTER_SET_CONNECTION) {
const MARIADB_CHARSET_INFO *ci = NULL;
if (!value)
ci = proxysql_find_charset_collate(mysql_tracked_variables[idx].default_value);
else
ci = proxysql_find_charset_nr(atoi(value));
j[mysql_tracked_variables[idx].internal_variable_name] = (ci && ci->csname)?ci->csname:"";
} else if (idx == SQL_COLLATION_CONNECTION) {
const MARIADB_CHARSET_INFO *ci = NULL;
if (!value)
ci = proxysql_find_charset_collate(mysql_tracked_variables[idx].default_value);
else
ci = proxysql_find_charset_nr(atoi(value));
j[mysql_tracked_variables[idx].internal_variable_name] = (ci && ci->name)?ci->name:"";
/*
// NOTE: it seems we treat SQL_LOG_BIN in a special way
// it doesn't seem necessary
} else if (idx == SQL_LOG_BIN) {
if (!value)
j["conn"][mysql_tracked_variables[idx].internal_variable_name] = mysql_tracked_variables[idx].default_value;
else
j["conn"][mysql_tracked_variables[idx].internal_variable_name] = !strcmp("1", value)?"ON":"OFF";
*/
} else {
j[mysql_tracked_variables[idx].internal_variable_name] = value?value:"";
}
}
static int
mysql_status(short event, short cont) {
int status= 0;
if (event & POLLIN)
status|= MYSQL_WAIT_READ;
if (event & POLLOUT)
status|= MYSQL_WAIT_WRITE;
// if (event==0 && cont==true) {
// status |= MYSQL_WAIT_TIMEOUT;
// }
// FIXME: handle timeout
// if (event & PROXY_TIMEOUT)
// status|= MYSQL_WAIT_TIMEOUT;
return status;
}
/* deprecating session_vars[] because we are introducing a better algorithm
// Defining list of session variables for comparison with query digest to disable multiplexing for "SET <variable_name>" commands
static char * session_vars[]= {
// For issue #555 , multiplexing is disabled if --safe-updates is used
//(char *)"SQL_SAFE_UPDATES=?,SQL_SELECT_LIMIT=?,MAX_JOIN_SIZE=?",
// for issue #1832 , we are splitting the above into 3 variables
// (char *)"SQL_SAFE_UPDATES",
// (char *)"SQL_SELECT_LIMIT",
// (char *)"MAX_JOIN_SIZE",
(char *)"FOREIGN_KEY_CHECKS",
(char *)"UNIQUE_CHECKS",
(char *)"AUTO_INCREMENT_INCREMENT",
(char *)"AUTO_INCREMENT_OFFSET",
(char *)"TIMESTAMP",
(char *)"GROUP_CONCAT_MAX_LEN"
};
*/
MySQL_Connection_userinfo::MySQL_Connection_userinfo() {
username=NULL;
password=NULL;
passtype=PASSWORD_TYPE::PRIMARY;
sha1_pass=NULL;
schemaname=NULL;
fe_username=NULL;
hash=0;
}
MySQL_Connection_userinfo::~MySQL_Connection_userinfo() {
if (username) free(username);
if (fe_username) free(fe_username);
if (password) free(password);
if (sha1_pass) free(sha1_pass);
if (schemaname) free(schemaname);
}
void MySQL_Connection::compute_unknown_transaction_status() {
if (mysql) {
int _myerrno=mysql_errno(mysql);
if (_myerrno == 0) {
unknown_transaction_status = false; // no error
return;
}
if (_myerrno >= 2000 && _myerrno < 3000) { // client error
// do not change it
return;
}
if (_myerrno >= 1000 && _myerrno < 2000) { // server error
unknown_transaction_status = true;
return;
}
if (_myerrno >= 3000 && _myerrno < 4000) { // server error
unknown_transaction_status = true;
return;
}
// all other cases, server error
}
}
/**
* Computes a unique hash value for a user connection.
*
* This function generates a hash based on the concatenation of username, password, and schema name,
* interspersed with two predefined delimiters. It leverages the SpookyHash algorithm for hashing.
* The purpose of this hash could be for identifying unique user connections or sessions within ProxySQL.
*
* @return Returns the computed hash value.
*/
uint64_t MySQL_Connection_userinfo::compute_hash() {
int l=0;
if (username)
l+=strlen(username);
if (password)
l+=strlen(password);
if (schemaname)
l+=strlen(schemaname);
// two random seperator
#define _COMPUTE_HASH_DEL1_ "-ujhtgf76y576574fhYTRDF345wdt-"
#define _COMPUTE_HASH_DEL2_ "-8k7jrhtrgJHRgrefgreyhtRFewg6-"
l+=strlen(_COMPUTE_HASH_DEL1_);
l+=strlen(_COMPUTE_HASH_DEL2_);
char *buf=(char *)malloc(l+1);
l=0;
if (username) {
strcpy(buf+l,username);
l+=strlen(username);
}
strcpy(buf+l,_COMPUTE_HASH_DEL1_);
l+=strlen(_COMPUTE_HASH_DEL1_);
if (password) {
strcpy(buf+l,password);
l+=strlen(password);
}
if (schemaname) {
strcpy(buf+l,schemaname);
l+=strlen(schemaname);
}
strcpy(buf+l,_COMPUTE_HASH_DEL2_);
l+=strlen(_COMPUTE_HASH_DEL2_);
hash=SpookyHash::Hash64(buf,l,0);
free(buf);
return hash;
}
void MySQL_Connection_userinfo::set(char *u, char *p, char *s, char *sh1) {
if (u) {
if (username) {
if (strcmp(u,username)) {
free(username);
username=strdup(u);
}
} else {
username=strdup(u);
}
}
if (p) {
if (password) {
if (strcmp(p,password)) {
free(password);
password=strdup(p);
}
} else {
password=strdup(p);
}
}
if (s) {
if (schemaname) free(schemaname);
schemaname=strdup(s);
}
if (sh1) {
if (sha1_pass) {
free(sha1_pass);
}
sha1_pass=strdup(sh1);
}
compute_hash();
}
void MySQL_Connection_userinfo::set(MySQL_Connection_userinfo *ui) {
set(ui->username, ui->password, ui->schemaname, ui->sha1_pass);
}
/**
* Sets the schema name for the current connection.
*
* This function updates the schema name for a connection. If the new schema name differs
* from the current one, it updates the internal representation and recalculates any related hash or identifier
* for the session. This is typically used to switch contexts or databases within the same connection.
*
* @param _new The new schema name to be set.
* @param l Length of the schema name string.
* @return Returns true if the schema name was changed, false otherwise.
*/
bool MySQL_Connection_userinfo::set_schemaname(char *_new, int l) {
int _l=0;
if (schemaname) {
_l=strlen(schemaname); // bug fix for #609
}
if ((schemaname==NULL) || (l != _l) || (strncmp(_new,schemaname, l ))) {
if (schemaname) {
free(schemaname);
schemaname=NULL;
}
if (l) {
schemaname=(char *)malloc(l+1);
memcpy(schemaname,_new,l);
schemaname[l]=0;
} else {
int k=strlen(mysql_thread___default_schema);
schemaname=(char *)malloc(k+1);
memcpy(schemaname,mysql_thread___default_schema,k);
schemaname[k]=0;
}
compute_hash();
return true;
}
return false;
}
/**
* Constructor for MySQL_Connection.
*
* Initializes a new MySQL connection object. Sets up the initial state, allocates necessary resources,
* and prepares the connection for use. It initializes member variables to their default values, including
* setting up default options for the MySQL client library, and prepares the connection for database operations.
*/
MySQL_Connection::MySQL_Connection() {
mysql=NULL;
async_state_machine=ASYNC_CONNECT_START;
ret_mysql=NULL;
send_quit=true;
myds=NULL;
inserted_into_pool=0;
reusable=false;
parent=NULL;
userinfo=new MySQL_Connection_userinfo();
fd=-1;
status_flags=0;
last_time_used=0;
for (auto i = 0; i < SQL_NAME_LAST_HIGH_WM; i++) {
variables[i].value = NULL;
var_hash[i] = 0;
}
options.client_flag = 0;
options.compression_min_length=0;
options.server_version=NULL;
options.last_set_autocommit=-1; // -1 = never set
options.autocommit=true;
options.no_backslash_escapes=false;
options.init_connect=NULL;
options.init_connect_sent=false;
options.session_track_gtids = NULL;
options.session_track_gtids_sent = false;
options.ldap_user_variable=NULL;
options.ldap_user_variable_value=NULL;
options.ldap_user_variable_sent=false;
options.session_track_gtids_int=0;
options.server_capabilities=0;
compression_pkt_id=0;
mysql_result=NULL;
query.ptr=NULL;
query.length=0;
query.stmt=NULL;
query.stmt_meta=NULL;
query.stmt_result=NULL;
largest_query_length=0;
warning_count=0;
multiplex_delayed=false;
MyRS=NULL;
MyRS_reuse=NULL;
unknown_transaction_status = false;
creation_time=0;
auto_increment_delay_token = 0;
processing_multi_statement=false;
proxy_debug(PROXY_DEBUG_MYSQL_CONNPOOL, 4, "Creating new MySQL_Connection %p\n", this);
local_stmts=new MySQL_STMTs_local_v14(false); // false by default, it is a backend
bytes_info.bytes_recv = 0;
bytes_info.bytes_sent = 0;
statuses.questions = 0;
statuses.myconnpoll_get = 0;
statuses.myconnpoll_put = 0;
memset(gtid_uuid,0,sizeof(gtid_uuid));
memset(&connected_host_details, 0, sizeof(connected_host_details));
};
MySQL_Connection::~MySQL_Connection() {
proxy_debug(PROXY_DEBUG_MYSQL_CONNPOOL, 4, "Destroying MySQL_Connection %p\n", this);
if (options.server_version) free(options.server_version);
if (options.init_connect) free(options.init_connect);
if (options.ldap_user_variable) free(options.ldap_user_variable);
if (options.ldap_user_variable_value) free(options.ldap_user_variable_value);
if (userinfo) {
delete userinfo;
userinfo=NULL;
}
if (local_stmts) {
delete local_stmts;
}
if (mysql) {
// always decrease the counter
if (ret_mysql) {
__sync_fetch_and_sub(&MyHGM->status.server_connections_connected,1);
if (query.stmt_result) {
if (query.stmt_result->handle) {
query.stmt_result->handle->status = MYSQL_STATUS_READY; // avoid calling mthd_my_skip_result()
}
}
if (mysql_result) {
if (mysql_result->handle) {
mysql_result->handle->status = MYSQL_STATUS_READY; // avoid calling mthd_my_skip_result()
}
}
async_free_result();
}
close_mysql(); // this take care of closing mysql connection
mysql=NULL;
}
if (MyRS) {
delete MyRS;
MyRS = NULL;
}
if (MyRS_reuse) {
delete MyRS_reuse;
MyRS_reuse = NULL;
}
if (query.stmt) {
query.stmt=NULL;
}
if (options.session_track_gtids) {
free(options.session_track_gtids);
options.session_track_gtids=NULL;
}
for (auto i = 0; i < SQL_NAME_LAST_HIGH_WM; i++) {
if (variables[i].value) {
free(variables[i].value);
variables[i].value = NULL;
var_hash[i] = 0;
}
}
if (connected_host_details.hostname)
free(connected_host_details.hostname);
if (connected_host_details.ip)
free(connected_host_details.ip);
if (ssl_params != NULL) {
delete ssl_params;
ssl_params = NULL;
}
};
bool MySQL_Connection::set_autocommit(bool _ac) {
proxy_debug(PROXY_DEBUG_MYSQL_CONNPOOL, 4, "Setting autocommit %d\n", _ac);
options.autocommit=_ac;
return _ac;
}
bool MySQL_Connection::set_no_backslash_escapes(bool _ac) {
proxy_debug(PROXY_DEBUG_MYSQL_CONNPOOL, 4, "Setting no_backslash_escapes %d\n", _ac);
options.no_backslash_escapes=_ac;
return _ac;
}
void print_backtrace(void);
unsigned int MySQL_Connection::set_charset(unsigned int _c, enum charset_action action) {
proxy_debug(PROXY_DEBUG_MYSQL_CONNPOOL, 4, "Setting charset %d\n", _c);
// SQL_CHARACTER_SET should be set befor setting SQL_CHRACTER_ACTION
std::stringstream ss;
ss << _c;
mysql_variables.client_set_value(myds->sess, SQL_CHARACTER_SET, ss.str());
// When SQL_CHARACTER_ACTION is set character set variables are set according to
// SQL_CHRACTER_SET value
ss.str(std::string());
ss.clear();
ss << action;
mysql_variables.client_set_value(myds->sess, SQL_CHARACTER_ACTION, ss.str());
return _c;
}
void MySQL_Connection::update_warning_count_from_connection() {
// if a prepared statement was cached while 'mysql_thread_query_digest' was true, and subsequently,
// 'mysql_thread_query_digest' is set to false, fetching that statement from the cache may still contain the digest text.
// To prevent this, we will check the digest text in conjunction with 'mysql_thread_query_digest' to verify whether it
// is enabled or disabled.
if (myds && myds->sess && myds->sess->CurrentQuery.QueryParserArgs.digest_text) {
const char* dig_text = myds->sess->CurrentQuery.QueryParserArgs.digest_text;
const size_t dig_len = strlen(dig_text);
// SHOW WARNINGS doesn't have any impact warning count,
// so we are replication same behaviour here
if (parent->myhgc->handle_warnings_enabled() &&
(dig_len != 13 || strncasecmp(dig_text, "SHOW WARNINGS", 13) != 0)) {
warning_count = mysql_warning_count(mysql);
}
}
}
void MySQL_Connection::update_warning_count_from_statement() {
// if a prepared statement was cached while 'mysql_thread_query_digest' was true, and subsequently,
// 'mysql_thread_query_digest' is set to false, fetching that statement from the cache may still contain the digest text.
// To prevent this, we will check the digest text in conjunction with 'mysql_thread_query_digest' to verify whether it
// is enabled or disabled.
if (myds && myds->sess && myds->sess->CurrentQuery.stmt_info && myds->sess->CurrentQuery.stmt_info->digest_text &&
mysql_thread___query_digests == true) {
if (parent->myhgc->handle_warnings_enabled()) {
warning_count = mysql_stmt_warning_count(query.stmt);
}
}
}
bool MySQL_Connection::is_expired(unsigned long long timeout) {
// FIXME: here the check should be a sanity check
// FIXME: for now this is just a temporary (and stupid) check
return false;
}
void MySQL_Connection::set_status(bool set, uint32_t status_flag) {
if (set) {
this->status_flags |= status_flag;
} else {
this->status_flags &= ~status_flag;
}
}
bool MySQL_Connection::get_status(uint32_t status_flag) {
return this->status_flags & status_flag;
}
void MySQL_Connection::set_status_sql_log_bin0(bool v) {
if (v) {
status_flags |= STATUS_MYSQL_CONNECTION_SQL_LOG_BIN0;
} else {
status_flags &= ~STATUS_MYSQL_CONNECTION_SQL_LOG_BIN0;
}
}
bool MySQL_Connection::get_status_sql_log_bin0() {
return status_flags & STATUS_MYSQL_CONNECTION_SQL_LOG_BIN0;
}
bool MySQL_Connection::requires_CHANGE_USER(const MySQL_Connection *client_conn) {
char *username = client_conn->userinfo->username;
if (strcmp(userinfo->username,username)) {
// the two connections use different usernames
// The connection need to be reset with CHANGE_USER
return true;
}
for (auto i = 0; i < SQL_NAME_LAST_LOW_WM; i++) {
if (client_conn->var_hash[i] == 0) {
if (var_hash[i]) {
// this connection has a variable set that the
// client connection doesn't have.
// Since connection cannot be unset , this connection
// needs to be reset with CHANGE_USER
return true;
}
}
}
if (client_conn->dynamic_variables_idx.size() < dynamic_variables_idx.size()) {
// the server connection has more variables set than the client
return true;
}
std::vector<uint32_t>::const_iterator it_c = client_conn->dynamic_variables_idx.begin(); // client connection iterator
std::vector<uint32_t>::const_iterator it_s = dynamic_variables_idx.begin(); // server connection iterator
for ( ; it_s != dynamic_variables_idx.end() ; it_s++) {
while ( it_c != client_conn->dynamic_variables_idx.end() && ( *it_c < *it_s ) ) {
it_c++;
}
if ( it_c != client_conn->dynamic_variables_idx.end() && *it_c == *it_s) {
// the backend variable idx matches the frontend variable idx
} else {
// we are processing a backend variable but there are
// no more frontend variables
return true;
}
}
return false;
}
unsigned int MySQL_Connection::reorder_dynamic_variables_idx() {
dynamic_variables_idx.clear();
// note that we are inserting the index already ordered
for (auto i = SQL_NAME_LAST_LOW_WM + 1 ; i < SQL_NAME_LAST_HIGH_WM ; i++) {
if (var_hash[i] != 0) {
dynamic_variables_idx.push_back(i);
}
}
unsigned int r = dynamic_variables_idx.size();
return r;
}
unsigned int MySQL_Connection::number_of_matching_session_variables(const MySQL_Connection *client_conn, unsigned int& not_matching) {
unsigned int ret=0;
for (auto i = 0; i < SQL_NAME_LAST_LOW_WM; i++) {
if (client_conn->var_hash[i] && i != SQL_CHARACTER_ACTION) { // client has a variable set
if (var_hash[i] == client_conn->var_hash[i]) { // server conection has the variable set to the same value
ret++;
} else {
not_matching++;
}
}
}
// increse not_matching y the sum of client and server variables
// when a match is found the counter will be reduced by 2
not_matching += client_conn->dynamic_variables_idx.size();
not_matching += dynamic_variables_idx.size();
std::vector<uint32_t>::const_iterator it_c = client_conn->dynamic_variables_idx.begin(); // client connection iterator
std::vector<uint32_t>::const_iterator it_s = dynamic_variables_idx.begin(); // server connection iterator
for ( ; it_c != client_conn->dynamic_variables_idx.end() && it_s != dynamic_variables_idx.end() ; it_c++) {
while (it_s != dynamic_variables_idx.end() && *it_s < *it_c) {
it_s++;
}
if (it_s != dynamic_variables_idx.end()) {
if (*it_s == *it_c) {
if (var_hash[*it_s] == client_conn->var_hash[*it_c]) { // server conection has the variable set to the same value
// when a match is found the counter is reduced by 2
not_matching-=2;
ret++;
}
}
}
}
return ret;
}
bool MySQL_Connection::match_ff_req_options(const MySQL_Connection *c) {
// 'server_capabilities' is empty for backend connections
const MySQL_Connection* backend { !c->options.server_capabilities ? c : this };
const MySQL_Connection* frontend { c->options.server_capabilities ? c : this };
// Only required to be checked for fast_forward sessions
if (frontend->myds && frontend->myds->sess->session_fast_forward) {
return (frontend->options.client_flag & CLIENT_DEPRECATE_EOF) ==
(backend->mysql->server_capabilities & CLIENT_DEPRECATE_EOF);
} else {
return true;
}
}
bool MySQL_Connection::match_tracked_options(const MySQL_Connection *c) {
uint32_t cf1 = options.client_flag; // own client flags
uint32_t cf2 = c->options.client_flag; // other client flags
if ((cf1 & CLIENT_FOUND_ROWS) == (cf2 & CLIENT_FOUND_ROWS)) {
if ((cf1 & CLIENT_MULTI_STATEMENTS) == (cf2 & CLIENT_MULTI_STATEMENTS)) {
if ((cf1 & CLIENT_MULTI_RESULTS) == (cf2 & CLIENT_MULTI_RESULTS)) {
if ((cf1 & CLIENT_IGNORE_SPACE) == (cf2 & CLIENT_IGNORE_SPACE)) {
return true;
}
}
}
}
return false;
}
void MySQL_Connection::connect_start_SetAttributes() {
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "program_name", "proxysql");
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "_server_host", parent->address);
{
time_t __timer;
char __buffer[25];
struct tm *__tm_info;
time(&__timer);
__tm_info = localtime(&__timer);
strftime(__buffer, 25, "%Y-%m-%d %H:%M:%S", __tm_info);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "connection_creation_time", __buffer);
unsigned long long t1=monotonic_time();
sprintf(__buffer,"%llu",(t1-GloVars.global.start_time)/1000/1000);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "proxysql_uptime", __buffer);
sprintf(__buffer,"%d", parent->myhgc->hid);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "hostgroup_id", __buffer);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "compile_time", __TIMESTAMP__);
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "proxysql_version", PROXYSQL_VERSION);
if (binary_sha1) {
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "proxysql_sha1", binary_sha1);
} else {
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "proxysql_sha1", "unknown");
}
mysql_options4(mysql, MYSQL_OPT_CONNECT_ATTR_ADD, "mysql_bug_102266", "Avoid MySQL bug https://bugs.mysql.com/bug.php?id=102266 , https://github.com/sysown/proxysql/issues/3276");
}
}
void MySQL_Connection::connect_start_SetCharset() {
const char *csname = NULL;
/* Take client character set and use it to connect to backend */
if (myds && myds->sess) {
csname = mysql_variables.client_get_value(myds->sess, SQL_CHARACTER_SET);
}
MARIADB_CHARSET_INFO * c = NULL;
if (csname)
c = (MARIADB_CHARSET_INFO *)proxysql_find_charset_nr(atoi(csname));
else
c = (MARIADB_CHARSET_INFO *)proxysql_find_charset_name(mysql_thread___default_variables[SQL_CHARACTER_SET]);
if (!c) {
// LCOV_EXCL_START
proxy_error("Not existing charset number %s\n", mysql_thread___default_variables[SQL_CHARACTER_SET]);
assert(0);
// LCOV_EXCL_STOP
}
if (c->nr > 255) {
const char *csname_default = c->csname;
c = NULL;
c = (MARIADB_CHARSET_INFO *)proxysql_find_charset_name(csname_default);
if (!c) {
// LCOV_EXCL_START
proxy_error("Not existing charset number %s\n", mysql_thread___default_variables[SQL_CHARACTER_SET]);
assert(0);
// LCOV_EXCL_STOP
}
}
{
/* We are connecting to backend setting charset in mysql_options.
* Client already has sent us a character set and client connection variables have been already set.
* Now we store this charset in server connection variables to avoid updating this variables on backend.
*/
std::stringstream ss;
ss << c->nr;
mysql_variables.server_set_value(myds->sess, SQL_CHARACTER_SET, ss.str().c_str());
mysql_variables.server_set_value(myds->sess, SQL_CHARACTER_SET_RESULTS, ss.str().c_str());
mysql_variables.server_set_value(myds->sess, SQL_CHARACTER_SET_CLIENT, ss.str().c_str());
mysql_variables.server_set_value(myds->sess, SQL_CHARACTER_SET_CONNECTION, ss.str().c_str());
mysql_variables.server_set_value(myds->sess, SQL_COLLATION_CONNECTION, ss.str().c_str());
}
//mysql_options(mysql, MYSQL_SET_CHARSET_NAME, c->csname);
mysql->charset = c;
}
void MySQL_Connection::connect_start_SetClientFlag(unsigned long& client_flags) {
client_flags = 0;
if (parent->compression)
client_flags |= CLIENT_COMPRESS;
if (myds) {
if (myds->sess) {
if (myds->sess->client_myds) {
if (myds->sess->client_myds->myconn) {
uint32_t orig_client_flags = myds->sess->client_myds->myconn->options.client_flag;
if (orig_client_flags & CLIENT_FOUND_ROWS) {
client_flags |= CLIENT_FOUND_ROWS;
}
if (orig_client_flags & CLIENT_MULTI_STATEMENTS) {
client_flags |= CLIENT_MULTI_STATEMENTS;
}
if (orig_client_flags & CLIENT_MULTI_RESULTS) {
client_flags |= CLIENT_MULTI_RESULTS;
}
if (orig_client_flags & CLIENT_IGNORE_SPACE) {
client_flags |= CLIENT_IGNORE_SPACE;
}
}
}
}
}
// set 'CLIENT_DEPRECATE_EOF' flag if explicitly stated by 'mysql-enable_server_deprecate_eof'.
// Capability is disabled by default in 'mariadb_client', so setting this option is not optional
// for having 'CLIENT_DEPRECATE_EOF' in the connection to be stablished.
if (mysql_thread___enable_server_deprecate_eof) {
mysql->options.client_flag |= CLIENT_DEPRECATE_EOF;
}
if (myds != NULL) {
if (myds->sess != NULL) {
if (myds->sess->session_fast_forward) { // this is a fast_forward connection
assert(myds->sess->client_myds != NULL);
MySQL_Connection * c = myds->sess->client_myds->myconn;
assert(c != NULL);
mysql->options.client_flag &= ~(CLIENT_DEPRECATE_EOF); // we disable it by default
// if both client_flag and server_capabilities (used for client) , set CLIENT_DEPRECATE_EOF
if (c->options.client_flag & CLIENT_DEPRECATE_EOF) {
if (c->options.server_capabilities & CLIENT_DEPRECATE_EOF) {
mysql->options.client_flag |= CLIENT_DEPRECATE_EOF;
}
}
// In case of 'fast_forward', we only enable compression if both, client and backend matches. Otherwise,
// we honor the behavior of a regular connection of when a connection doesn't agree on using compression
// during handshake, and we fallback to an uncompressed connection.
client_flags &= ~(CLIENT_COMPRESS); // we disable it by default
if (c->options.client_flag & CLIENT_COMPRESS) {
if (c->options.server_capabilities & CLIENT_COMPRESS) {
client_flags |= CLIENT_COMPRESS;
}
}
}
}
}
}
char * MySQL_Connection::connect_start_DNS_lookup() {
char* host_ip = NULL;
const std::string& res_ip = MySQL_Monitor::dns_lookup(parent->address, false);
if (!res_ip.empty()) {
if (connected_host_details.hostname) {
if (strcmp(connected_host_details.hostname, parent->address) != 0) {
free(connected_host_details.hostname);
connected_host_details.hostname = strdup(parent->address);
}
}
else {
connected_host_details.hostname = strdup(parent->address);
}
if (connected_host_details.ip) {
if (strcmp(connected_host_details.ip, res_ip.c_str()) != 0) {
free(connected_host_details.ip);
connected_host_details.ip = strdup(res_ip.c_str());
}
}
else {
connected_host_details.ip = strdup(res_ip.c_str());
}
host_ip = connected_host_details.ip;
}
else {
host_ip = parent->address;
}
return host_ip;
}
void MySQL_Connection::connect_start_SetSslSettings() {
if (parent->use_ssl) {
if (ssl_params != NULL) {
delete ssl_params;
ssl_params = NULL;
}
ssl_params = MyHGM->get_Server_SSL_Params(parent->address, parent->port, userinfo->username);
MySQL_Connection::set_ssl_params(mysql, ssl_params);
mysql_options(mysql, MARIADB_OPT_SSL_KEYLOG_CALLBACK, (void*)proxysql_keylog_write_line_callback);
}
}
// non blocking API
void MySQL_Connection::connect_start() {
PROXY_TRACE();
mysql=mysql_init(NULL);
assert(mysql);
mysql_options(mysql, MYSQL_OPT_NONBLOCK, 0);
connect_start_SetAttributes();
connect_start_SetSslSettings();
unsigned int timeout= 1;
mysql_options(mysql, MYSQL_OPT_CONNECT_TIMEOUT, (void *)&timeout);
connect_start_SetCharset();
unsigned long client_flags = 0;
connect_start_SetClientFlag(client_flags);
char *auth_password=NULL;
if (userinfo->password) {
if (userinfo->password[0]=='*') { // we don't have the real password, let's pass sha1
auth_password=userinfo->sha1_pass;
} else {
auth_password=userinfo->password;
}
}
if (parent->port) {
char* host_ip = connect_start_DNS_lookup();
async_exit_status=mysql_real_connect_start(&ret_mysql, mysql, host_ip, userinfo->username, auth_password, userinfo->schemaname, parent->port, NULL, client_flags);
} else {
client_flags &= ~(CLIENT_COMPRESS); // disabling compression for connections made via Unix socket
async_exit_status=mysql_real_connect_start(&ret_mysql, mysql, "localhost", userinfo->username, auth_password, userinfo->schemaname, parent->port, parent->address, client_flags);
}
fd=mysql_get_socket(mysql);
// {
// // FIXME: THIS IS FOR TESTING PURPOSE ONLY
// // DO NOT ENABLE THIS CODE FOR PRODUCTION USE
// // we drastically reduce the receive buffer to make sure that
// // mysql_stmt_store_result_[start|continue] doesn't complete
// // in a single call
// int rcvbuf = 10240;
// if(setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf)) < 0) {
// proxy_error("Failed to call setsockopt\n");
// exit(EXIT_FAILURE);
// }
// }
}
void MySQL_Connection::connect_cont(short event) {
proxy_debug(PROXY_DEBUG_MYSQL_PROTOCOL, 6,"event=%d\n", event);
async_exit_status = mysql_real_connect_cont(&ret_mysql, mysql, mysql_status(event, true));