-
Notifications
You must be signed in to change notification settings - Fork 4k
/
Copy pathnet_serv.cc
2265 lines (1945 loc) · 74.2 KB
/
net_serv.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
/* Copyright (c) 2000, 2022, Oracle and/or its affiliates.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License, version 2.0,
as published by the Free Software Foundation.
This program is also distributed with certain software (including
but not limited to OpenSSL) that is licensed under separate terms,
as designated in a particular file or component or in included license
documentation. The authors of MySQL hereby grant you an additional
permission to link the program and your derivative works with the
separately licensed software that they have included with MySQL.
Without limiting anything contained in the foregoing, this file,
which is part of C Driver for MySQL (Connector/C), is also subject to the
Universal FOSS Exception, version 1.0, a copy of which can be found at
http://oss.oracle.com/licenses/universal-foss-exception.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License, version 2.0, for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
/**
@file
This file is the net layer API for the MySQL client/server protocol.
Write and read of logical packets to/from socket.
Writes are cached into net_buffer_length big packets.
Read packets are reallocated dynamically when reading big packets.
Each logical packet has the following pre-info:
3 byte length & 1 byte package-number.
*/
#include <string.h>
#include <sys/types.h>
#include <algorithm>
#include <mysql/components/services/log_builtins.h>
#include <mysql/thread_pool_priv.h>
#include "../sql/current_thd.h"
#include "../sql/sql_class.h"
#include "../sql/sql_thd_internal_api.h"
#include "my_byteorder.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_io.h"
#include "my_macros.h"
#include "my_sys.h"
#include "mysql.h"
#include "mysql/service_mysql_alloc.h"
#include "mysql_async.h"
#include "mysql_com.h"
#include "mysqld_error.h"
#include "violite.h"
using std::max;
using std::min;
#ifdef MYSQL_SERVER
#include "sql/psi_memory_key.h"
#else
#define key_memory_NET_buff 0
#define key_memory_NET_compress_packet 0
#endif
/*
The following handles the differences when this is linked between the
client and the server.
This gives an error if a too big packet is found.
The server can change this, but because the client can't normally do this
the client should have a bigger max_allowed_packet.
*/
#ifdef MYSQL_SERVER
/*
The following variables/functions should really not be declared
extern, but as it's hard to include sql_class.h here, we have to
live with this for a while.
*/
extern void thd_increment_bytes_sent(size_t length);
extern void thd_increment_bytes_received(size_t length);
/* Additional instrumentation hooks for the server */
#include "mysql_com_server.h"
#endif
static bool net_write_buff(NET *, const uchar *, size_t);
static uchar *compress_packet(NET *net, const uchar *packet, size_t *length);
NET_EXTENSION *net_extension_init() {
NET_EXTENSION *ext = static_cast<NET_EXTENSION *>(my_malloc(
PSI_NOT_INSTRUMENTED, sizeof(NET_EXTENSION), MYF(MY_WME | MY_ZEROFILL)));
ext->net_async_context = static_cast<NET_ASYNC *>(my_malloc(
PSI_NOT_INSTRUMENTED, sizeof(NET_ASYNC), MYF(MY_WME | MY_ZEROFILL)));
ext->compress_ctx.algorithm = enum_compression_algorithm::MYSQL_UNCOMPRESSED;
return ext;
}
void net_extension_free(NET *net) {
NET_EXTENSION *ext = NET_EXTENSION_PTR(net);
if (ext) {
#ifndef MYSQL_SERVER
if (ext->net_async_context) {
my_free(ext->net_async_context);
ext->net_async_context = nullptr;
}
mysql_compress_context_deinit(&ext->compress_ctx);
my_free(ext);
net->extension = nullptr;
#endif
}
}
/**
Returns the appropriate compression_context based on caller.
If the caller is server then fetch is from the server extension
structure.
@param[in] net NET structure
@returns mysql_compress_context structure pointer
*/
static mysql_compress_context *compress_context(NET *net) {
mysql_compress_context *mysql_compress_ctx = nullptr;
#ifdef MYSQL_SERVER
NET_SERVER *server_extension = static_cast<NET_SERVER *>(net->extension);
if (server_extension != nullptr) {
mysql_compress_ctx = &server_extension->compress_ctx;
}
#else
NET_EXTENSION *ext = NET_EXTENSION_PTR(net);
if (ext != nullptr) mysql_compress_ctx = &ext->compress_ctx;
#endif
return mysql_compress_ctx;
}
/** Init with packet info. */
bool my_net_init(NET *net, Vio *vio) {
DBUG_TRACE;
net->vio = vio;
my_net_local_init(net); /* Set some limits */
if (!(net->buff = (uchar *)my_malloc(
key_memory_NET_buff,
(size_t)net->max_packet + NET_HEADER_SIZE + COMP_HEADER_SIZE,
MYF(MY_WME))))
return true;
net->buff_end = net->buff + net->max_packet;
net->error = NET_ERROR_UNSET;
net->return_status = nullptr;
net->pkt_nr = net->compress_pkt_nr = 0;
net->write_pos = net->read_pos = net->buff;
net->last_error[0] = 0;
net->compress = false;
net->reading_or_writing = 0;
net->where_b = net->remain_in_buf = 0;
net->last_errno = 0;
#ifdef MYSQL_SERVER
net->extension = nullptr;
#else
NET_EXTENSION *ext = net_extension_init();
ext->net_async_context->cur_pos = net->buff + net->where_b;
ext->net_async_context->read_rows_is_first_read = true;
ext->net_async_context->async_operation = NET_ASYNC_OP_IDLE;
ext->net_async_context->async_send_command_status =
NET_ASYNC_SEND_COMMAND_IDLE;
ext->net_async_context->async_read_query_result_status =
NET_ASYNC_READ_QUERY_RESULT_IDLE;
ext->net_async_context->async_packet_read_state = NET_ASYNC_PACKET_READ_IDLE;
ext->compress_ctx.algorithm = enum_compression_algorithm::MYSQL_UNCOMPRESSED;
net->extension = ext;
#endif
if (vio) {
/* For perl DBI/DBD. */
net->fd = vio_fd(vio);
vio_fastsend(vio);
}
return false;
}
void net_end(NET *net) {
DBUG_TRACE;
#ifdef MYSQL_SERVER
NET_SERVER *server_extension = static_cast<NET_SERVER *>(net->extension);
if (server_extension != nullptr)
mysql_compress_context_deinit(&server_extension->compress_ctx);
#else
net_extension_free(net);
#endif
my_free(net->buff);
net->buff = nullptr;
}
void net_claim_memory_ownership(NET *net, bool claim) {
my_claim(net->buff, claim);
}
/** Realloc the packet buffer. */
bool net_realloc(NET *net, size_t length) {
uchar *buff;
size_t pkt_length;
DBUG_TRACE;
DBUG_PRINT("enter", ("length: %lu", (ulong)length));
if (length >= net->max_packet_size) {
DBUG_PRINT("error",
("Packet too large. Max size: %lu", net->max_packet_size));
/* Error, but no need to stop using the socket. */
net->error = NET_ERROR_SOCKET_RECOVERABLE;
net->last_errno = ER_NET_PACKET_TOO_LARGE;
#ifdef MYSQL_SERVER
my_error(ER_NET_PACKET_TOO_LARGE, MYF(0));
#endif
return true;
}
pkt_length = (length + IO_SIZE - 1) & ~(IO_SIZE - 1);
/*
We must allocate some extra bytes for the end 0 and to be able to
read big compressed blocks in
net_read_packet() may actually read 4 bytes depending on build flags and
platform.
*/
if (!(buff = (uchar *)my_realloc(
key_memory_NET_buff, (char *)net->buff,
pkt_length + NET_HEADER_SIZE + COMP_HEADER_SIZE, MYF(MY_WME)))) {
/* Error, but no need to stop using the socket. */
net->error = NET_ERROR_SOCKET_RECOVERABLE;
net->last_errno = ER_OUT_OF_RESOURCES;
/* In the server the error is reported by MY_WME flag. */
return true;
}
#ifdef MYSQL_SERVER
net->buff = net->write_pos = buff;
#else
size_t cur_pos_offset = NET_ASYNC_DATA(net)->cur_pos - net->buff;
net->buff = net->write_pos = buff;
NET_ASYNC_DATA(net)->cur_pos = net->buff + cur_pos_offset;
#endif
net->buff_end = buff + (net->max_packet = (ulong)pkt_length);
return false;
}
/**
Clear (reinitialize) the NET structure for a new command.
@remark Performs debug checking of the socket buffer to
ensure that the protocol sequence is correct.
@param net NET handler
@param check_buffer Whether to check the socket buffer.
*/
void net_clear(NET *net, bool check_buffer [[maybe_unused]]) {
DBUG_TRACE;
DBUG_EXECUTE_IF("simulate_bad_field_length_1", {
net->pkt_nr = net->compress_pkt_nr = 0;
net->write_pos = net->buff;
return;
});
DBUG_EXECUTE_IF("simulate_bad_field_length_2", {
net->pkt_nr = net->compress_pkt_nr = 0;
net->write_pos = net->buff;
return;
});
/* Ready for new command */
net->pkt_nr = net->compress_pkt_nr = 0;
net->write_pos = net->buff;
}
/** Flush write_buffer if not empty. */
bool net_flush(NET *net) {
bool error = false;
DBUG_TRACE;
if (net->buff != net->write_pos) {
error =
net_write_packet(net, net->buff, (size_t)(net->write_pos - net->buff));
net->write_pos = net->buff;
}
/* Sync packet number if using compression */
if (net->compress) net->pkt_nr = net->compress_pkt_nr;
return error;
}
/**
Whether a I/O operation should be retried later.
@param net NET handler.
@param retry_count Maximum number of interrupted operations.
@retval true Operation should be retried.
@retval false Operation should not be retried. Fatal error.
*/
static bool net_should_retry(NET *net, uint *retry_count [[maybe_unused]]) {
bool retry;
#ifndef MYSQL_SERVER
/*
In the client library, interrupted I/O operations are always retried.
Otherwise, it's either a timeout or an unrecoverable error.
*/
retry = vio_should_retry(net->vio);
#else
/*
In the server, interrupted I/O operations are retried up to a limit.
In this scenario, pthread_kill can be used to wake up
(interrupt) threads waiting for I/O.
*/
retry = vio_should_retry(net->vio) && ((*retry_count)++ < net->retry_count);
#endif
return retry;
}
/* clang-format off */
/**
@page page_protocol_basic_packets MySQL Packets
If a MySQL client or server wants to send data, it:
- Splits the data into packets of size 2<sup>24</sup> bytes
- Prepends to each chunk a packet header
@section sect_protocol_basic_packets_packet Protocol::Packet
Data between client and server is exchanged in packets of max 16MByte size.
<table>
<caption>Payload</caption>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref a_protocol_type_int1 "int<3>"</td>
<td>payload_length</td>
<td>Length of the payload. The number of bytes in the packet beyond
the initial 4 bytes that make up the packet header.</td></tr>
<tr><td>@ref a_protocol_type_int1 "int<1>"</td>
<td>sequence_id</td>
<td>@ref sect_protocol_basic_packets_sequence_id</td></tr>
<tr><td>@ref sect_protocol_basic_dt_string_var "string<var>"</td>
<td>payload</td>
<td>payload of the packet</td></tr>
</table>
Example:
@todo: Reference COM_QUIT
A COM_QUIT looks like this:
<table><tr>
<td>
~~~~~~~~~~~~~~~~~~~~~
01 00 00 00 01
~~~~~~~~~~~~~~~~~~~~~
</td><td>
- length: 1
- sequence_id: x00
- payload: 0x01
</td></tr></table>
@sa my_net_write(), net_write_command(), net_write_buff(), my_net_read(),
net_send_ok()
@section sect_protocol_basic_packets_sending_mt_16mb Sending More Than 16Mb
If the payload is larger than or equal to 2<sup>24</sup>-1 bytes the length
is set to 2<sup>24</sup>-1 (`ff ff ff`) and a additional packets are sent
with the rest of the payload until the payload of a packet is less
than 2<sup>24</sup>-1 bytes.
Sending a payload of 16 777 215 (2<sup>24</sup>-1) bytes looks like:
~~~~~~~~~~~~~~~~
ff ff ff 00 ...
00 00 00 01
~~~~~~~~~~~~~~~~
@section sect_protocol_basic_packets_sequence_id Sequence ID
The sequence-id is incremented with each packet and may wrap around.
It starts at 0 and is reset to 0 when a new command begins in the
@ref page_protocol_command_phase.
@section sect_protocol_basic_packets_describing_packets Describing Packets
In this document we describe each packet by first defining its payload and
provide an example showing each packet that is sent, including its packet
header:
<pre>
<packetname>
<description>
direction: client -> server
response: <response>
payload:
<type> <description>
</pre>
Example:
~~~~~~~~~~~~~~~~~~~~~
01 00 00 00 01
~~~~~~~~~~~~~~~~~~~~~
@note Some packets have optional fields or a different layout depending on
the @ref group_cs_capabilities_flags.
If a field has a fixed value, its description shows it as a hex value in
brackets like this: `[00]`
*/
/* clang-format on */
/*****************************************************************************
** Write something to server/client buffer
*****************************************************************************/
/**
Write a logical packet with packet header.
Format: Packet length (3 bytes), packet number (1 byte)
When compression is used, a 3 byte compression length is added.
@note If compression is used, the original packet is modified!
*/
bool my_net_write(NET *net, const uchar *packet, size_t len) {
uchar buff[NET_HEADER_SIZE];
DBUG_DUMP("net write", packet, len);
if (unlikely(!net->vio)) /* nowhere to write */
return false;
DBUG_EXECUTE_IF("simulate_net_write_failure", {
my_error(ER_NET_ERROR_ON_WRITE, MYF(0));
return 1;
};);
/* turn off non blocking operations */
if (!vio_is_blocking(net->vio)) vio_set_blocking_flag(net->vio, true);
/*
Big packets are handled by splitting them in packets of MAX_PACKET_LENGTH
length. The last packet is always a packet that is < MAX_PACKET_LENGTH.
(The last packet may even have a length of 0)
*/
while (len >= MAX_PACKET_LENGTH) {
const ulong z_size = MAX_PACKET_LENGTH;
int3store(buff, z_size);
buff[3] = (uchar)net->pkt_nr++;
if (net_write_buff(net, buff, NET_HEADER_SIZE) ||
net_write_buff(net, packet, z_size)) {
return true;
}
packet += z_size;
len -= z_size;
}
/* Write last packet */
int3store(buff, static_cast<uint>(len));
buff[3] = (uchar)net->pkt_nr++;
if (net_write_buff(net, buff, NET_HEADER_SIZE)) {
return true;
}
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("packet_header", buff, NET_HEADER_SIZE);
#endif
return net_write_buff(net, packet, len);
}
static void reset_packet_write_state(NET *net) {
DBUG_TRACE;
NET_ASYNC *net_async = NET_ASYNC_DATA(net);
if (net_async->async_write_vector) {
if (net_async->async_write_vector != net_async->inline_async_write_vector) {
my_free(net_async->async_write_vector);
}
net_async->async_write_vector = nullptr;
}
if (net_async->async_write_headers) {
if (net_async->async_write_headers !=
net_async->inline_async_write_header) {
my_free(net_async->async_write_headers);
}
net_async->async_write_headers = nullptr;
}
net_async->async_write_vector_size = 0;
net_async->async_write_vector_current = 0;
if (net_async->compressed_write_buffers) {
/*
There are two entries per packet, one for header and one for payload.
We only need to free payloads as headers have their own buffer. If the
last packet was size 0, the vector size will be 1 lower and due to int
truncation for odd numbers will be correctly accounted for.
*/
for (size_t i = 0; i < net_async->compressed_buffers_size; ++i) {
my_free(net_async->compressed_write_buffers[i]);
}
my_free(net_async->compressed_write_buffers);
net_async->compressed_write_buffers = nullptr;
net_async->compressed_buffers_size = 0;
}
}
/*
Construct the proper buffers for our nonblocking write. What we do
here is we make an iovector for the entire write (header, command,
and payload). We then continually call writev on this vector,
consuming parts from it as bytes are successfully written. Headers
for the message are all stored inside one buffer, separate from the
payload; this lets us avoid copying the entire query just to insert
the headers every 2**24 bytes.
The most common case is the query fits in a packet. In that case,
we don't construct the iovector dynamically, instead using one we
pre-allocated inside the net structure. This avoids allocations in
the common path, but requires special casing with our iovec and
header buffer.
*/
static int begin_packet_write_state(NET *net, uchar command,
const uchar *packet, size_t packet_len,
const uchar *optional_prefix,
size_t prefix_len) {
DBUG_TRACE;
size_t header_len = NET_HEADER_SIZE;
if (net->compress) {
header_len += NET_HEADER_SIZE + COMP_HEADER_SIZE;
}
NET_ASYNC *net_async = NET_ASYNC_DATA(net);
size_t total_len = packet_len + prefix_len;
bool include_command = (command < COM_END);
if (include_command) {
++total_len;
}
size_t packet_count = 1 + total_len / MAX_PACKET_LENGTH;
reset_packet_write_state(net);
struct io_vec *vec;
uchar *headers;
uchar **compressed_buffers = nullptr;
if (total_len < MAX_PACKET_LENGTH) {
/*
Most writes hit this case, ie, less than MAX_PACKET_LENGTH of
query text.
*/
vec = net_async->inline_async_write_vector;
headers = net_async->inline_async_write_header;
} else {
/* Large query, create the vector and header buffer dynamically. */
vec = (struct io_vec *)my_malloc(
PSI_NOT_INSTRUMENTED, sizeof(struct io_vec) * (packet_count * 2 + 1),
MYF(MY_ZEROFILL));
if (!vec) {
return 0;
}
headers =
(uchar *)my_malloc(PSI_NOT_INSTRUMENTED,
packet_count * (header_len + 1), MYF(MY_ZEROFILL));
if (!headers) {
my_free(vec);
return 0;
}
}
/*
Regardless of where vec and headers come from, these are what we
feed to writev and populate below.
*/
net_async->async_write_vector = vec;
net_async->async_write_headers = headers;
if (net->compress) {
// Will need to hand compress and manage at most 1 buffer per packet
compressed_buffers =
(uchar **)my_malloc(key_memory_NET_compress_packet,
sizeof(uchar *) * packet_count, MYF(MY_ZEROFILL));
if (!compressed_buffers) {
reset_packet_write_state(net);
return 0;
}
}
net_async->compressed_write_buffers = compressed_buffers;
/*
We sneak the command into the first header, so the special casing
below about packet_num == 0 relates to that. This lets us avoid
an extra allocation and copying the input buffers again.
Every chunk of MAX_PACKET_LENGTH results in a header and a
payload, so we have twice as many entries in the IO
vector as we have packet_count. The first packet may be prefixed with a
small amount of data, so that one actually might
consume *three* iovec entries.
*/
for (size_t packet_num = 0; packet_num < packet_count; ++packet_num) {
/*
The first iovec contains the headers only and command if it is provided
*/
uchar *buf = headers + packet_num * (header_len + 1);
size_t bytes_queued = 0;
(*vec).iov_base = buf;
(*vec).iov_len = header_len;
/*
if using compression, add the compression header. Usually, we would rely on
compress_packet to add compression headers, but here we assume
that headers do not compress well due to their short length and send them
as is by constructing our own packat and incrementing compress_pkt_nr
manually.
We don't compress the headers together with the payload because that
would mean extra memcpy's to concatenate the buffers to pass into
compress_packet.
*/
if (net->compress) {
size_t comp_packet_len = NET_HEADER_SIZE;
if (packet_num == 0) {
comp_packet_len += prefix_len + (include_command ? 1 : 0);
}
int3store(buf, comp_packet_len);
buf[3] = (uchar)net->compress_pkt_nr++;
/*
The bytes in COMP_HEADER_SIZE are implicitly zero because they were
zero filled. A zero length means that the contents are uncompressed.
*/
buf += NET_HEADER_SIZE + COMP_HEADER_SIZE;
}
size_t packet_size = min<size_t>(MAX_PACKET_LENGTH, total_len);
int3store(buf, packet_size);
buf[3] = (uchar)net->pkt_nr++;
/*
We sneak the command byte into the header, even though
technically it is payload. This lets us avoid an allocation
or separate one-byte entry in our iovec.
*/
if (packet_num == 0 && include_command) {
buf[4] = command;
(*vec).iov_len++;
/* Our command byte counts against the packet size. */
++bytes_queued;
}
++vec;
/* Second iovec (if any), our optional prefix. */
if (packet_num == 0 && optional_prefix != nullptr) {
(*vec).iov_base = const_cast<uchar *>(optional_prefix);
(*vec).iov_len = prefix_len;
bytes_queued += prefix_len;
++vec;
}
/*
Final iovec, the payload itself. Send however many bytes from
packet we have left, and advance our packet pointer.
*/
size_t remaining_bytes = packet_size - bytes_queued;
(*vec).iov_base = const_cast<uchar *>(packet);
(*vec).iov_len = remaining_bytes;
bytes_queued += remaining_bytes;
packet += remaining_bytes;
total_len -= bytes_queued;
/* clang-format off */
/*
If we have a payload to compress, then compress_packet will add
compression headers for us. This is what we have at this point where
each line is an iovec.
| len |cpn|uncompress len| len | pn | command |
| prefix + command | 0 |0 | total_len = command + prefix + payload | 0 |COM_* |
| prefix |
|... |
|payload |
|... |
We want to transform into this:
| len |cpn|uncompress len| len | pn | command |
| prefix +command | 0 |0 | total_len = command + prefix + payload | 0 |COM_* |
| prefix |
|... |
| len |cpn|uncompress len| compressed payload |
| len(compressed payload) | 1| len(payload)| compress(payload) |
*/
/* clang-format on */
if (net->compress && remaining_bytes) {
(*vec).iov_base =
compress_packet(net, (uchar *)(*vec).iov_base, &(*vec).iov_len);
if (!(*vec).iov_base) {
reset_packet_write_state(net);
return 0;
}
compressed_buffers[net_async->compressed_buffers_size++] =
(uchar *)(*vec).iov_base;
}
++vec;
/* Make sure we sent entire packets. */
if (total_len > 0) {
assert(packet_size == MAX_PACKET_LENGTH);
}
}
/* Make sure we don't have anything left to send. */
assert(total_len == 0);
net_async->async_write_vector_size = (vec - net_async->async_write_vector);
net_async->async_write_vector_current = 0;
/*
This is needed because the packet reading code in the net_read_packet_header
uses pkt_nr for verification.
*/
if (net->compress) net->pkt_nr = net->compress_pkt_nr;
return 1;
}
static net_async_status net_write_vector_nonblocking(NET *net, ssize_t *res) {
NET_ASYNC *net_async = NET_ASYNC_DATA(net);
struct io_vec *vec =
net_async->async_write_vector + net_async->async_write_vector_current;
DBUG_TRACE;
while (net_async->async_write_vector_current !=
net_async->async_write_vector_size) {
if (vio_is_blocking(net->vio)) {
vio_set_blocking_flag(net->vio, false);
}
*res = vio_write(net->vio, (uchar *)vec->iov_base, vec->iov_len);
if (*res < 0) {
if (socket_errno == SOCKET_EAGAIN ||
(SOCKET_EAGAIN != SOCKET_EWOULDBLOCK &&
socket_errno == SOCKET_EWOULDBLOCK)) {
/*
In the unlikely event that there is a renegotiation and
SSL_ERROR_WANT_READ is returned, set blocking state to read.
*/
if (static_cast<size_t>(*res) == VIO_SOCKET_WANT_READ) {
net_async->async_blocking_state = NET_NONBLOCKING_READ;
} else {
net_async->async_blocking_state = NET_NONBLOCKING_WRITE;
}
return NET_ASYNC_NOT_READY;
}
return NET_ASYNC_COMPLETE;
}
size_t bytes_written = static_cast<size_t>(*res);
vec->iov_len -= bytes_written;
vec->iov_base = (char *)vec->iov_base + bytes_written;
if (vec->iov_len != 0) break;
++net_async->async_write_vector_current;
vec++;
}
if (net_async->async_write_vector_current ==
net_async->async_write_vector_size) {
return NET_ASYNC_COMPLETE;
}
net_async->async_blocking_state = NET_NONBLOCKING_WRITE;
return NET_ASYNC_NOT_READY;
}
/**
Send a command to the server in asynchronous way. This function will first
populate all headers in NET::async_write_headers, followed by payload in
NET::async_write_vector. Once header and payload is populated in NET, were
call net_write_vector_nonblocking to send the packets to server in an
asynchronous way.
*/
net_async_status net_write_command_nonblocking(NET *net, uchar command,
const uchar *prefix,
size_t prefix_len,
const uchar *packet,
size_t packet_len, bool *res) {
net_async_status status;
NET_ASYNC *net_async = NET_ASYNC_DATA(net);
ssize_t rc;
DBUG_TRACE;
DBUG_DUMP("net write prefix", prefix, prefix_len);
DBUG_DUMP("net write pkt", packet, packet_len);
if (unlikely(!net->vio)) {
/* nowhere to write */
*res = false;
goto done;
}
switch (net_async->async_operation) {
case NET_ASYNC_OP_IDLE:
if (!begin_packet_write_state(net, command, packet, packet_len, prefix,
prefix_len)) {
*res = false;
goto done;
}
net_async->async_operation = NET_ASYNC_OP_WRITING;
[[fallthrough]];
case NET_ASYNC_OP_WRITING:
status = net_write_vector_nonblocking(net, &rc);
if (status == NET_ASYNC_COMPLETE) {
if (rc < 0) {
*res = true;
} else {
*res = false;
}
goto done;
}
return NET_ASYNC_NOT_READY;
default:
assert(false);
*res = true;
return NET_ASYNC_COMPLETE;
}
done:
reset_packet_write_state(net);
net_async->async_operation = NET_ASYNC_OP_IDLE;
return NET_ASYNC_COMPLETE;
}
/*
Non blocking version of my_net_write().
*/
net_async_status my_net_write_nonblocking(NET *net, const uchar *packet,
size_t len, bool *res) {
return net_write_command_nonblocking(net, COM_END, packet, len, nullptr, 0,
res);
}
/**
Send a command to the server.
The reason for having both header and packet is so that libmysql
can easy add a header to a special command (like prepared statements)
without having to re-alloc the string.
As the command is part of the first data packet, we have to do some data
juggling to put the command in there, without having to create a new
packet.
This function will split big packets into sub-packets if needed.
(Each sub packet can only be 2^24 bytes)
@param net NET handler
@param command Command in MySQL server (enum enum_server_command)
@param header Header to write after command
@param head_len Length of header
@param packet Query or parameter to query
@param len Length of packet
@retval
0 ok
@retval
1 error
*/
bool net_write_command(NET *net, uchar command, const uchar *header,
size_t head_len, const uchar *packet, size_t len) {
/* turn off non blocking operations */
if (!vio_is_blocking(net->vio)) vio_set_blocking_flag(net->vio, true);
size_t length = len + 1 + head_len; /* 1 extra byte for command */
uchar buff[NET_HEADER_SIZE + 1];
uint header_size = NET_HEADER_SIZE + 1;
DBUG_TRACE;
DBUG_PRINT("enter", ("length: %lu", (ulong)len));
buff[4] = command; /* For first packet */
if (length >= MAX_PACKET_LENGTH) {
/* Take into account that we have the command in the first header */
len = MAX_PACKET_LENGTH - 1 - head_len;
do {
int3store(buff, MAX_PACKET_LENGTH);
buff[3] = (uchar)net->pkt_nr++;
if (net_write_buff(net, buff, header_size) ||
net_write_buff(net, header, head_len) ||
net_write_buff(net, packet, len)) {
return true;
}
packet += len;
length -= MAX_PACKET_LENGTH;
len = MAX_PACKET_LENGTH;
head_len = 0;
header_size = NET_HEADER_SIZE;
} while (length >= MAX_PACKET_LENGTH);
len = length; /* Data left to be written */
}
int3store(buff, static_cast<uint>(length));
buff[3] = (uchar)net->pkt_nr++;
bool rc = net_write_buff(net, buff, header_size) ||
(head_len && net_write_buff(net, header, head_len)) ||
net_write_buff(net, packet, len) || net_flush(net);
return rc;
}
/**
Caching the data in a local buffer before sending it.
Fill up net->buffer and send it to the client when full.
If the rest of the to-be-sent-packet is bigger than buffer,
send it in one big block (to avoid copying to internal buffer).
If not, copy the rest of the data to the buffer and return without
sending data.
@param net Network handler
@param packet Packet to send
@param len Length of packet
@note
The cached buffer can be sent as it is with 'net_flush()'.
In this code we have to be careful to not send a packet longer than
MAX_PACKET_LENGTH to net_write_packet() if we are using the compressed
protocol as we store the length of the compressed packet in 3 bytes.
@retval
0 ok
@retval
1
*/
static bool net_write_buff(NET *net, const uchar *packet, size_t len) {
DBUG_TRACE;
ulong left_length;
if (net->compress && net->max_packet > MAX_PACKET_LENGTH)
left_length = (ulong)(MAX_PACKET_LENGTH - (net->write_pos - net->buff));
else
left_length = (ulong)(net->buff_end - net->write_pos);
#ifdef DEBUG_DATA_PACKETS
DBUG_DUMP("data", packet, len);
#endif
if (len > left_length) {
if (net->write_pos != net->buff) {
/* Fill up already used packet and write it */
memcpy(net->write_pos, packet, left_length);
if (net_write_packet(net, net->buff,
(size_t)(net->write_pos - net->buff) + left_length))
return true;
net->write_pos = net->buff;
packet += left_length;
len -= left_length;
}
if (net->compress) {
/*
We can't have bigger packets than 16M with compression
Because the uncompressed length is stored in 3 bytes
*/
left_length = MAX_PACKET_LENGTH;
while (len > left_length) {
if (net_write_packet(net, packet, left_length)) return true;
packet += left_length;
len -= left_length;
}
}
if (len > net->max_packet) return net_write_packet(net, packet, len);
/* Send out rest of the blocks as full sized blocks */
}
if (len > 0) memcpy(net->write_pos, packet, len);
net->write_pos += len;
return false;
}
/**
Write a determined number of bytes to a network handler.
@param net NET handler.
@param buf Buffer containing the data to be written.
@param count The length, in bytes, of the buffer.
@return true on error, false on success.
*/
static bool net_write_raw_loop(NET *net, const uchar *buf, size_t count) {
unsigned int retry_count = 0;
while (count) {
size_t sentcnt = vio_write(net->vio, buf, count);
/* VIO_SOCKET_ERROR (-1) indicates an error. */
if (sentcnt == VIO_SOCKET_ERROR) {
/* A recoverable I/O error occurred? */
if (net_should_retry(net, &retry_count))
continue;
else