-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
swoole_mysql_coro.cc
2520 lines (2320 loc) · 81.8 KB
/
swoole_mysql_coro.cc
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
/*
+----------------------------------------------------------------------+
| Swoole |
+----------------------------------------------------------------------+
| Copyright (c) 2012-2018 The Swoole Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.0 of the Apache license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.apache.org/licenses/LICENSE-2.0.html |
| If you did not receive a copy of the Apache2.0 license and are unable|
| to obtain it through the world-wide-web, please send a note to |
| license@swoole.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Twosee <twose@qq.com> |
| Author: Tianfeng Han <mikan.tenny@gmail.com> |
+----------------------------------------------------------------------+
*/
#include "php_swoole_cxx.h"
#include "swoole_mysql_proto.h"
// see mysqlnd 'L64' macro redefined
#undef L64
extern "C" {
#include "ext/hash/php_hash.h"
#include "ext/hash/php_hash_sha.h"
#include "ext/standard/php_math.h"
#ifdef SW_USE_MYSQLND
#include "ext/mysqlnd/mysqlnd.h"
#include "ext/mysqlnd/mysqlnd_charset.h"
#endif
}
#include <unordered_map>
using namespace swoole;
using swoole::coroutine::Socket;
/* keep same with pdo and mysqli */
#define MYSQLND_UNKNOWN_SQLSTATE "HY000"
#define MYSQLND_SERVER_GONE "MySQL server has gone away"
#define MYSQLND_CR_UNKNOWN_ERROR 2000
#define MYSQLND_CR_CONNECTION_ERROR 2002
#define MYSQLND_CR_SERVER_GONE_ERROR 2006
#define MYSQLND_CR_OUT_OF_MEMORY 2008
#define MYSQLND_CR_SERVER_LOST 2013
#define MYSQLND_CR_COMMANDS_OUT_OF_SYNC 2014
#define MYSQLND_CR_CANT_FIND_CHARSET 2019
#define MYSQLND_CR_MALFORMED_PACKET 2027
#define MYSQLND_CR_NOT_IMPLEMENTED 2054
#define MYSQLND_CR_NO_PREPARE_STMT 2030
#define MYSQLND_CR_PARAMS_NOT_BOUND 2031
#define MYSQLND_CR_INVALID_PARAMETER_NO 2034
#define MYSQLND_CR_INVALID_BUFFER_USE 2035
namespace swoole
{
class mysql_statement;
class mysql_client
{
public:
/* session related {{{ */
Socket *socket = nullptr;
Socket::timeout_controller *tc = nullptr;
enum sw_mysql_state state = SW_MYSQL_STATE_CLOSED;
bool quit = false;
mysql::result_info result;
std::unordered_map<uint32_t, mysql_statement*> statements;
mysql_statement* statement = nullptr;
/* }}} */
std::string host = SW_MYSQL_DEFAULT_HOST;
uint16_t port = SW_MYSQL_DEFAULT_PORT;
bool ssl = false;
std::string user = "root";
std::string password = "root";
std::string database = "test";
char charset = SW_MYSQL_DEFAULT_CHARSET;
double connect_timeout = Socket::default_connect_timeout;
bool strict_type = false;
inline int get_error_code()
{
return error_code;
}
inline const char* get_error_msg()
{
return error_msg.c_str();
}
inline void non_sql_error(int code, const char *msg)
{
error_code = code;
error_msg = cpp_string::format("SQLSTATE[" MYSQLND_UNKNOWN_SQLSTATE "] [%d] %s", code, msg);
}
template<typename ...Args>
inline void non_sql_error(int code, const char *format, Args ...args)
{
error_code = code;
error_msg = cpp_string::format(
"SQLSTATE[" MYSQLND_UNKNOWN_SQLSTATE "] [%d] %s",
code, cpp_string::format(format, args...).c_str()
);
}
void io_error()
{
if (state == SW_MYSQL_STATE_CLOSED)
{
non_sql_error(MYSQLND_CR_CONNECTION_ERROR, socket->errMsg);
}
else
{
non_sql_error(
MYSQLND_CR_SERVER_GONE_ERROR, MYSQLND_SERVER_GONE "%s%s",
socket->errCode ? " due to " : "", socket->errCode ? socket->errMsg : ""
);
}
/* don't send QUIT after IO error */
quit = true;
close();
}
void proto_error(const char *data, const enum sw_mysql_packet_types expected_type)
{
mysql::server_packet packet(data);
non_sql_error(
MYSQLND_CR_MALFORMED_PACKET, "Unexpected mysql packet length=%u, number=%u, type=%u, expected_type=%u",
packet.header.length, packet.header.number, (uint8_t) data[SW_MYSQL_PACKET_HEADER_SIZE], expected_type
);
close();
}
void server_error(const char *data)
{
mysql::err_packet err_packet(data);
error_code = err_packet.code;
error_msg = cpp_string::format("SQLSTATE[%s] [%d] %s", err_packet.sql_state, err_packet.code, err_packet.msg.c_str());
state = SW_MYSQL_STATE_IDLE;
}
inline bool get_fetch_mode()
{
return fetch_mode;
}
inline bool set_fetch_mode(bool v)
{
if (sw_unlikely(socket && v))
{
non_sql_error(ENOTSUP, "Can not use fetch mode after the connection is established");
return false;
}
fetch_mode = v;
return true;
}
inline bool get_defer()
{
return defer;
}
inline bool set_defer(bool v)
{
// if (sw_unlikely(fetch_mode && v))
// {
// non_sql_error(ENOTSUP, "Can not use defer mode when fetch mode is on");
// return false;
// }
defer = v;
return true;
}
void add_timeout_controller(double timeout, const enum swTimeout_type type)
{
if (sw_unlikely(!socket))
{
return;
}
// Notice: `timeout > 0` is wrong, maybe -1
if (timeout != 0)
{
SW_ASSERT(!tc);
tc = new Socket::timeout_controller(socket, timeout, type);
}
}
inline bool has_timedout(enum swTimeout_type type)
{
return tc && tc->has_timedout(type);
}
void del_timeout_controller()
{
if (tc)
{
delete tc;
tc = nullptr;
}
}
bool connect(std::string host, uint16_t port, bool ssl);
inline bool connect()
{
return connect(host, port, ssl);
}
inline bool is_connect()
{
return socket && socket->is_connect();
}
inline int get_fd()
{
return socket ? socket->get_fd() : -1;
}
inline bool check_connection()
{
if (sw_unlikely(!is_connect()))
{
non_sql_error(MYSQLND_CR_CONNECTION_ERROR, "%s or %s", strerror(ECONNRESET), strerror(ENOTCONN));
return false;
}
return true;
}
inline bool check_liveness()
{
if (sw_unlikely(!check_connection()))
{
return false;
}
if (sw_unlikely(!socket->check_liveness()))
{
non_sql_error(MYSQLND_CR_SERVER_GONE_ERROR, MYSQLND_SERVER_GONE);
close();
return false;
}
return true;
}
inline bool is_writable()
{
return is_connect() && !socket->has_bound(SW_EVENT_WRITE);
}
bool is_available_for_new_reuqest()
{
if (sw_unlikely(state != SW_MYSQL_STATE_IDLE && state != SW_MYSQL_STATE_CLOSED))
{
if (socket)
{
socket->check_bound_co(SW_EVENT_RDWR);
}
non_sql_error(
EINPROGRESS,
"MySQL client is busy now on state#%d, "
"please use recv/fetchAll/nextResult to get all unread data "
"and wait for response then try again",
state
);
return false;
}
if (sw_unlikely(!check_liveness()))
{
return false;
}
else
{
/* without unread data */
swString *buffer = socket->get_read_buffer();
SW_ASSERT(buffer->length == (size_t) buffer->offset);
swString_clear(buffer);
return true;
}
}
const char* recv_packet();
inline const char* recv_none_error_packet()
{
const char *data = recv_packet();
if (sw_unlikely(data && mysql::server_packet::is_err(data)))
{
server_error(data);
return nullptr;
}
return data;
}
inline const char* recv_eof_packet()
{
const char *data = recv_packet();
if (sw_unlikely(data && !mysql::server_packet::is_eof(data)))
{
proto_error(data, SW_MYSQL_PACKET_EOF);
return nullptr;
}
#ifdef SW_LOG_TRACE_OPEN
mysql::eof_packet eof_packet(data);
#endif
return data;
}
inline bool send_raw(const char *data, size_t length)
{
if (sw_unlikely(!check_connection()))
{
return false;
}
else
{
if (sw_unlikely(has_timedout(SW_TIMEOUT_WRITE)))
{
io_error();
return false;
}
if (sw_unlikely(socket->send_all(data, length) != (ssize_t ) length))
{
io_error();
return false;
}
return true;
}
}
bool send_packet(mysql::client_packet *packet);
bool send_command(enum sw_mysql_command command, const char* sql = nullptr, size_t length = 0);
// just for internal
void send_command_without_check(enum sw_mysql_command command, const char* sql = nullptr, size_t length = 0);
void query(zval *return_value, const char *statement, size_t statement_length);
void send_query_request(zval *return_value, const char *statement, size_t statement_length);
void recv_query_response(zval *return_value);
const char* handle_row_data_size(mysql::row_data *row_data, uint8_t size);
bool handle_row_data_lcb(mysql::row_data *row_data);
void handle_row_data_text(zval *return_value, mysql::row_data *row_data, mysql::field_packet *field);
void handle_strict_type(zval *ztext, mysql::field_packet *field);
void fetch(zval *return_value);
void fetch_all(zval *return_value);
void next_result(zval *return_value);
bool recv();
bool send_prepare_request(const char *statement, size_t statement_length);
mysql_statement* recv_prepare_response();
void close();
~mysql_client()
{
SW_ASSERT(statements.empty());
close();
}
private:
int error_code = 0;
std::string error_msg = "";
/* unable to support both features at the same time, so we have to set them by method {{{ */
bool fetch_mode = false;
bool defer = false;
/* }}} */
// recv data of specified length
const char* recv_length(size_t need_length, const bool try_to_recycle = false);
// usually mysql->connect = connect(TCP) + handshake
bool handshake();
};
class mysql_statement
{
public:
std::string statement;
mysql::statement info;
mysql::result_info result;
mysql_statement(mysql_client *client, const char *statement, size_t statement_length) :
client(client)
{
this->statement = std::string(statement, statement_length);
}
inline mysql_client* get_client()
{
return client;
}
inline int get_error_code()
{
return sw_likely(client) ? client->get_error_code() : error_code;
}
inline const char* get_error_msg()
{
return sw_likely(client) ? client->get_error_msg() : error_msg.c_str();
}
inline bool is_available()
{
if (sw_unlikely(!client))
{
error_code = ECONNRESET;
error_msg = "statement must to be recompiled after the connection is broken";
return false;
}
return true;
}
inline bool is_available_for_new_reuqest()
{
if (sw_unlikely(!is_available()))
{
return false;
}
if (sw_unlikely(!client->is_available_for_new_reuqest()))
{
return false;
}
return true;
}
inline void add_timeout_controller(double timeout, const enum swTimeout_type type)
{
if (sw_likely(client))
{
client->add_timeout_controller(timeout, type);
}
}
inline void del_timeout_controller()
{
if (sw_likely(client))
{
client->del_timeout_controller();
}
}
// [notify = false]: mysql_client actively close
inline void close(const bool notify = true)
{
if (client)
{
// if client point exists, socket is always available
if (notify)
{
if (sw_likely(client->is_writable()))
{
char id[4];
sw_mysql_int4store(id, info.id);
client->send_command_without_check(SW_MYSQL_COM_STMT_CLOSE, id, sizeof(id));
}
client->statements.erase(info.id);
}
else
{
error_code = client->get_error_code();
error_msg = client->get_error_msg();
}
client = nullptr;
}
}
~mysql_statement()
{
close();
}
bool send_prepare_request();
bool recv_prepare_response();
void execute(zval *return_value, zval *params);
void send_execute_request(zval *return_value, zval *params);
void recv_execute_response(zval *return_value);
void fetch(zval *return_value);
void fetch_all(zval *return_value);
void next_result(zval *return_value);
private:
mysql_client *client = nullptr;
int error_code = 0;
std::string error_msg;
};
}
static zend_class_entry *swoole_mysql_coro_ce;
static zend_object_handlers swoole_mysql_coro_handlers;
static zend_class_entry *swoole_mysql_coro_exception_ce;
static zend_object_handlers swoole_mysql_coro_exception_handlers;
static zend_class_entry *swoole_mysql_coro_statement_ce;
static zend_object_handlers swoole_mysql_coro_statement_handlers;
typedef struct {
mysql_client *client;
zend_object std;
} mysql_coro_t;
typedef struct {
mysql_statement *statement;
zend_object *zclient;
zend_object std;
} mysql_coro_statement_t;
static PHP_METHOD(swoole_mysql_coro, __construct);
static PHP_METHOD(swoole_mysql_coro, __destruct);
static PHP_METHOD(swoole_mysql_coro, connect);
static PHP_METHOD(swoole_mysql_coro, getDefer);
static PHP_METHOD(swoole_mysql_coro, setDefer);
static PHP_METHOD(swoole_mysql_coro, query);
static PHP_METHOD(swoole_mysql_coro, fetch);
static PHP_METHOD(swoole_mysql_coro, fetchAll);
static PHP_METHOD(swoole_mysql_coro, nextResult);
static PHP_METHOD(swoole_mysql_coro, prepare);
static PHP_METHOD(swoole_mysql_coro, recv);
static PHP_METHOD(swoole_mysql_coro, begin);
static PHP_METHOD(swoole_mysql_coro, commit);
static PHP_METHOD(swoole_mysql_coro, rollback);
#ifdef SW_USE_MYSQLND
static PHP_METHOD(swoole_mysql_coro, escape);
#endif
static PHP_METHOD(swoole_mysql_coro, close);
static PHP_METHOD(swoole_mysql_coro_statement, execute);
static PHP_METHOD(swoole_mysql_coro_statement, fetch);
static PHP_METHOD(swoole_mysql_coro_statement, fetchAll);
static PHP_METHOD(swoole_mysql_coro_statement, nextResult);
static PHP_METHOD(swoole_mysql_coro_statement, recv);
static PHP_METHOD(swoole_mysql_coro_statement, close);
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_void, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_optional_timeout, 0, 0, 0)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_mysql_coro_connect, 0, 0, 0)
ZEND_ARG_ARRAY_INFO(0, server_config, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_mysql_coro_query, 0, 0, 1)
ZEND_ARG_INFO(0, sql)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_mysql_coro_prepare, 0, 0, 1)
ZEND_ARG_INFO(0, query)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_mysql_coro_setDefer, 0, 0, 0)
ZEND_ARG_INFO(0, defer)
ZEND_END_ARG_INFO()
#ifdef SW_USE_MYSQLND
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_mysql_coro_escape, 0, 0, 1)
ZEND_ARG_INFO(0, string)
ZEND_ARG_INFO(0, flags)
ZEND_END_ARG_INFO()
#endif
ZEND_BEGIN_ARG_INFO_EX(arginfo_swoole_mysql_coro_statement_execute, 0, 0, 0)
ZEND_ARG_INFO(0, params)
ZEND_ARG_INFO(0, timeout)
ZEND_END_ARG_INFO()
static const zend_function_entry swoole_mysql_coro_methods[] =
{
PHP_ME(swoole_mysql_coro, __construct, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, __destruct, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, getDefer, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, setDefer, arginfo_swoole_mysql_coro_setDefer, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, connect, arginfo_swoole_mysql_coro_connect, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, query, arginfo_swoole_mysql_coro_query, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, fetch, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, fetchAll, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, nextResult, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, prepare, arginfo_swoole_mysql_coro_prepare, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, recv, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, begin, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, commit, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro, rollback, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
#ifdef SW_USE_MYSQLND
PHP_ME(swoole_mysql_coro, escape, arginfo_swoole_mysql_coro_escape, ZEND_ACC_PUBLIC)
#endif
PHP_ME(swoole_mysql_coro, close, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
static const zend_function_entry swoole_mysql_coro_statement_methods[] =
{
PHP_ME(swoole_mysql_coro_statement, execute, arginfo_swoole_mysql_coro_statement_execute, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro_statement, fetch, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro_statement, fetchAll, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro_statement, nextResult, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro_statement, recv, arginfo_swoole_optional_timeout, ZEND_ACC_PUBLIC)
PHP_ME(swoole_mysql_coro_statement, close, arginfo_swoole_void, ZEND_ACC_PUBLIC)
PHP_FE_END
};
void swoole_sha256(const char *str, int len, unsigned char *digest)
{
PHP_SHA256_CTX context;
PHP_SHA256Init(&context);
PHP_SHA256Update(&context, (unsigned char *) str, len);
PHP_SHA256Final(digest, &context);
}
bool mysql_client::connect(std::string host, uint16_t port, bool ssl)
{
if (socket && (host != this->host || port != this->port || ssl != this->ssl))
{
close();
}
if (!socket)
{
if (host.compare(0, 6, "unix:/", 0, 6) == 0)
{
host = host.substr(sizeof("unix:") - 1);
host.erase(0, host.find_first_not_of('/') - 1);
socket = new Socket(SW_SOCK_UNIX_STREAM);
}
else if (host.find(':') != std::string::npos)
{
socket = new Socket(SW_SOCK_TCP6);
}
else
{
socket = new Socket(SW_SOCK_TCP);
}
if (sw_unlikely(socket->get_fd() < 0))
{
php_swoole_fatal_error(E_WARNING, "new Socket() failed. Error: %s [%d]", strerror(errno), errno);
non_sql_error(MYSQLND_CR_CONNECTION_ERROR, strerror(errno));
delete socket;
socket = nullptr;
return false;
}
#ifdef SW_USE_OPENSSL
socket->open_ssl = ssl;
#endif
socket->set_timeout(connect_timeout, SW_TIMEOUT_CONNECT);
add_timeout_controller(connect_timeout, SW_TIMEOUT_ALL);
if (!socket->connect(host, port))
{
io_error();
return false;
}
this->host = host;
this->port = port;
#ifdef SW_USE_OPENSSL
this->ssl = ssl;
#endif
if (!handshake())
{
close();
return false;
}
state = SW_MYSQL_STATE_IDLE;
quit = false;
del_timeout_controller();
}
return true;
}
const char* mysql_client::recv_length(size_t need_length, const bool try_to_recycle)
{
if (sw_likely(check_connection()))
{
ssize_t retval;
swString *buffer = socket->get_read_buffer();
off_t offset = buffer->offset; // save offset instead of buffer point (due to realloc)
size_t read_n = buffer->length - buffer->offset; // readable bytes
if (try_to_recycle && read_n == 0)
{
swTraceLog(SW_TRACE_MYSQL_CLIENT, "mysql buffer will be recycled, length=%zu, offset=%jd", buffer->length, (intmax_t) offset);
swString_clear(buffer);
offset = 0;
}
while (read_n < need_length)
{
if (sw_unlikely(has_timedout(SW_TIMEOUT_READ)))
{
io_error();
return nullptr;
}
if (sw_unlikely(buffer->length == buffer->size))
{
/* offset + need_length = new size (min) */
if (sw_unlikely(swString_extend(buffer, SW_MEM_ALIGNED_SIZE_EX(offset + need_length, SwooleG.pagesize)) != SW_OK))
{
non_sql_error(MYSQLND_CR_OUT_OF_MEMORY, strerror(ENOMEM));
return nullptr;
}
else
{
swTraceLog(SW_TRACE_MYSQL_CLIENT, "mysql buffer extend to %zu", buffer->size);
}
}
retval = socket->recv(buffer->str + buffer->length, buffer->size - buffer->length);
if (sw_unlikely(retval <= 0))
{
io_error();
return nullptr;
}
read_n += retval;
buffer->length += retval;
}
buffer->offset += need_length;
return buffer->str + offset;
}
return nullptr;
}
const char* mysql_client::recv_packet()
{
const char *p;
uint32_t length;
p = recv_length(SW_MYSQL_PACKET_HEADER_SIZE, true);
if (sw_unlikely(!p))
{
return nullptr;
}
length = mysql::packet::get_length(p);
swTraceLog(SW_TRACE_MYSQL_CLIENT, "recv packet length=%u, number=%u", length, mysql::packet::get_number(p));
p = recv_length(length);
if (sw_unlikely(!p))
{
return nullptr;
}
/* Notice: why we do this? because buffer maybe reallocated when recv data */
return p - SW_MYSQL_PACKET_HEADER_SIZE;
}
bool mysql_client::send_packet(mysql::client_packet *packet)
{
const char *data = packet->get_data();
uint32_t length = SW_MYSQL_PACKET_HEADER_SIZE + packet->get_length();
if (sw_likely(send_raw(data, length)))
{
return true;
}
return false;
}
bool mysql_client::send_command(enum sw_mysql_command command, const char* sql, size_t length)
{
if (sw_likely(SW_MYSQL_PACKET_HEADER_SIZE + 1 + length <= SwooleG.pagesize))
{
mysql::command_packet command_packet(command, sql, length);
return send_raw(command_packet.get_data(), command_packet.get_data_length());
}
else
{
/* if the data is larger than page_size, copy memory to the kernel buffer multiple times is much faster */
size_t send_s = SW_MIN(length, SW_MYSQL_MAX_PACKET_BODY_SIZE - 1), send_n = send_s, number = 0;
mysql::command_packet command_packet(command);
command_packet.set_header(1 + send_s, number++);
if (sw_unlikely(
!send_raw(command_packet.get_data(), SW_MYSQL_PACKET_HEADER_SIZE + 1)) ||
!send_raw(sql, send_s)
)
{
return false;
}
/* MySQL single packet size is 16M, we must subpackage */
while (send_n < length)
{
send_s = length - send_n;
send_s = SW_MIN(send_s, SW_MYSQL_MAX_PACKET_BODY_SIZE);
command_packet.set_header(send_s, number++);
if (sw_unlikely(
!send_raw(command_packet.get_data(), SW_MYSQL_PACKET_HEADER_SIZE)) ||
!send_raw(sql + send_n, send_s)
)
{
return false;
}
send_n += send_s;
}
return true;
}
}
void mysql_client::send_command_without_check(enum sw_mysql_command command, const char* sql, size_t length)
{
mysql::command_packet command_packet(command, sql, length);
(void) (socket && socket->send(command_packet.get_data(), command_packet.get_data_length()));
}
bool mysql_client::handshake()
{
const char *data;
// recv greeting pakcet
if (sw_unlikely(!(data = recv_none_error_packet())))
{
return false;
}
mysql::greeting_packet greeting_packet(data);
// generate login packet
do {
mysql::login_packet login_packet(&greeting_packet, user, password, database, charset);
if (sw_unlikely(!send_packet(&login_packet)))
{
return false;
}
} while (0);
// recv auth switch request packet, 4 possible packet types
switch (mysql::server_packet::parse_type(data = recv_packet()))
{
case SW_MYSQL_PACKET_AUTH_SWITCH_REQUEST:
{
mysql::auth_switch_request_packet request(data);
mysql::auth_switch_response_packet response(&request, password);
if (sw_unlikely(!send_packet(&response)))
{
return false;
}
break;
}
case SW_MYSQL_PACKET_AUTH_SIGNATURE_REQUEST:
{
mysql::auth_signature_request_packet request(data);
if (sw_unlikely(!request.is_vaild()))
{
goto _proto_error;
}
if (sw_likely(!request.is_full_auth_required()))
{
break;
}
// no cache, need full auth with rsa key (openssl required)
#ifdef SW_MYSQL_RSA_SUPPORT
// tell the server we are prepared
do {
mysql::auth_signature_prepared_packet prepared(request.header.number + 1);
if (sw_unlikely(!send_packet(&prepared)))
{
return false;
}
} while (0);
// recv rsa key and encode the password
do {
if (sw_unlikely(!(data = recv_none_error_packet())))
{
return false;
}
mysql::raw_data_packet raw_data_packet(data);
mysql::auth_signature_response_packet response(&raw_data_packet, password, greeting_packet.auth_plugin_data);
if (sw_unlikely(!send_packet(&response)))
{
return false;
}
} while (0);
break;
#else
error_code = EPROTONOSUPPORT;
error_msg = SW_MYSQL_NO_RSA_ERROR;
return false;
#endif
}
case SW_MYSQL_PACKET_OK:
{
#ifdef SW_LOG_TRACE_OPEN
mysql::ok_packet ok_packet(data);
#endif
return true;
}
case SW_MYSQL_PACKET_ERR:
server_error(data);
return false;
case SW_MYSQL_PACKET_NULL:
// io_error
return false;
default:
_proto_error:
proto_error(data, SW_MYSQL_PACKET_AUTH_SWITCH_REQUEST);
return false;
}
// maybe ok packet or err packet
if (sw_unlikely(!(data = recv_none_error_packet())))
{
return false;
}
#ifdef SW_LOG_TRACE_OPEN
mysql::ok_packet ok_packet(data);
#endif
return true;
}
void mysql_client::query(zval *return_value, const char *statement, size_t statement_length)
{
send_query_request(return_value, statement, statement_length);
if (EXPECTED(!defer && Z_TYPE_P(return_value) == IS_TRUE))
{
recv_query_response(return_value);
}
}
void mysql_client::send_query_request(zval *return_value, const char *statement, size_t statement_length)
{
if (sw_unlikely(!is_available_for_new_reuqest()))
{
RETURN_FALSE;
}
if (sw_unlikely(!send_command(SW_MYSQL_COM_QUERY, statement, statement_length)))
{
RETURN_FALSE;
}
state = SW_MYSQL_STATE_QUERY;
RETURN_TRUE;
};
void mysql_client::recv_query_response(zval *return_value)
{
const char *data;
if (sw_unlikely(!(data = recv_none_error_packet())))
{
RETURN_FALSE;
}
if (mysql::server_packet::is_ok(data))
{
mysql::ok_packet ok_packet(data);
result.ok = ok_packet;
state = ok_packet.server_status.more_results_exists() ? SW_MYSQL_STATE_QUERY_MORE_RESULTS : SW_MYSQL_STATE_IDLE;
RETURN_TRUE;
}
do {
mysql::lcb_packet lcb_packet(data);
if (sw_unlikely(lcb_packet.length == 0))
{
// is it possible?
proto_error(data, SW_MYSQL_PACKET_FIELD);
RETURN_FALSE;
}
result.alloc_fields(lcb_packet.length);
for (uint32_t i = 0; i < lcb_packet.length; i++)
{
if (sw_unlikely(!(data = recv_packet())))
{
RETURN_FALSE;
}
result.set_field(i, data);
}
} while (0);
// expect eof
if (sw_unlikely(!(data = recv_eof_packet())))
{
RETURN_FALSE;
}
state = SW_MYSQL_STATE_QUERY_FETCH;
if (get_fetch_mode())
{
RETURN_TRUE;
}
fetch_all(return_value);
}
const char* mysql_client::handle_row_data_size(mysql::row_data *row_data, uint8_t size)
{
const char *p, *data;
SW_ASSERT(size < sizeof(row_data->stack_buffer));
if (sw_unlikely(!(p = row_data->read(size))))
{
uint8_t received = row_data->recv(row_data->stack_buffer, size);
if (sw_unlikely(!(data = recv_packet())))
{
return nullptr;
}
row_data->next_packet(data);
received += row_data->recv(row_data->stack_buffer + received, size - received);
if (sw_unlikely(received != size))
{
proto_error(data, SW_MYSQL_PACKET_ROW_DATA);
return nullptr;
}
p = row_data->stack_buffer;
}
return p;
}
bool mysql_client::handle_row_data_lcb(mysql::row_data *row_data)
{
const char *p, *data;
// recv 1 byte to get binary code size