-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
protocol_classic.cc
4113 lines (3405 loc) · 140 KB
/
protocol_classic.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, 2024, 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 designed to work 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 either included with
the program or referenced in the documentation.
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
Low level functions for storing data to be send to the MySQL client.
The actual communication is handled by the net_xxx functions in net_serv.cc
*/
/* clang-format off */
/**
@page page_protocol_basics Protocol Basics
This is a description of the basic building blocks used by the MySQL protocol:
- @subpage page_protocol_basic_data_types
- @subpage page_protocol_basic_packets
- @subpage page_protocol_basic_response_packets
- @subpage page_protocol_basic_character_set
- @subpage page_protocol_basic_compression
- @subpage page_protocol_basic_tls
- @subpage page_protocol_basic_expired_passwords
*/
/**
@page page_protocol_basic_data_types Basic Data Types
The protocol has a few basic types that are used throughout the protocol:
- @subpage page_protocol_basic_dt_integers
- @subpage page_protocol_basic_dt_strings
*/
/**
@page page_protocol_basic_dt_integers Integer Types
The MySQL %Protocol has a set of possible encodings for integers.
@section sect_protocol_basic_dt_int_fixed Protocol::FixedLengthInteger
Fixed-Length Integer Types
============================
A fixed-length unsigned integer stores its value in a series of
bytes with the least significant byte first.
The MySQL uses the following fixed-length unsigned integer variants:
- @anchor a_protocol_type_int1 int\<1>:
1 byte @ref sect_protocol_basic_dt_int_fixed.
- @anchor a_protocol_type_int2 int\<2\>:
2 byte @ref sect_protocol_basic_dt_int_fixed. See int2store()
- @anchor a_protocol_type_int3 int\<3\>:
3 byte @ref sect_protocol_basic_dt_int_fixed. See int3store()
- @anchor a_protocol_type_int4 int\<4\>:
4 byte @ref sect_protocol_basic_dt_int_fixed. See int4store()
- @anchor a_protocol_type_int6 int\<6\>:
6 byte @ref sect_protocol_basic_dt_int_fixed. See int6store()
- @anchor a_protocol_type_int8 int\<8\>:
8 byte @ref sect_protocol_basic_dt_int_fixed. See int8store()
See int3store() for an example.
@section sect_protocol_basic_dt_int_le Protocol::LengthEncodedInteger
Length-Encoded Integer Type
==============================
An integer that consumes 1, 3, 4, or 9 bytes, depending on its numeric value
To convert a number value into a length-encoded integer:
Greater or equal | Lower than | Stored as
-----------------|----------------|-------------------------
0 | 251 | `1-byte integer`
251 | 2<sup>16</sup> | `0xFC + 2-byte integer`
2<sup>16</sup> | 2<sup>24</sup> | `0xFD + 3-byte integer`
2<sup>24</sup> | 2<sup>64</sup> | `0xFE + 8-byte integer`
Similarly, to convert a length-encoded integer into its numeric value
check the first byte.
@warning
If the first byte of a packet is a length-encoded integer and
its byte value is `0xFE`, you must check the length of the packet to
verify that it has enough space for a 8-byte integer.
If not, it may be an EOF_Packet instead.
*/
/**
@page page_protocol_basic_dt_strings String Types
Strings are sequences of bytes and appear in a few forms in the protocol.
@section sect_protocol_basic_dt_string_fix Protocol::FixedLengthString
Fixed-length strings have a known, hardcoded length.
An example is the sql-state of the @ref page_protocol_basic_err_packet
which is always 5 bytes long.
@section sect_protocol_basic_dt_string_null Protocol::NullTerminatedString
Strings that are terminated by a `00` byte.
@section sect_protocol_basic_dt_string_var Protocol::VariableLengthString
The length of the string is determined by another field or is calculated
at runtime
@section sect_protocol_basic_dt_string_le Protocol::LengthEncodedString
A length encoded string is a string that is prefixed with length encoded
integer describing the length of the string.
It is a special case of @ref sect_protocol_basic_dt_string_var
@section sect_protocol_basic_dt_string_eof Protocol::RestOfPacketString
If a string is the last component of a packet, its length can be calculated
from the overall packet length minus the current position.
*/
/**
@page page_protocol_basic_response_packets Generic Response Packets
For most commands the client sends to the server, the server returns one
of these packets in response:
- @subpage page_protocol_basic_ok_packet
- @subpage page_protocol_basic_err_packet
- @subpage page_protocol_basic_eof_packet
*/
/**
@page page_protocol_command_phase %Command Phase
In the command phase, the client sends a command packet with
the sequence-id [00]:
~~~~~~~~
13 00 00 00 03 53 ...
01 00 00 00 01
^^- command-byte
^^---- sequence-id == 0
~~~~~~~~
The first byte of the payload describes the command-type.
See ::enum_server_command for the list of commands supported.
The commands belong to one of the following sub-protocols
- @subpage page_protocol_command_phase_text
- @subpage page_protocol_command_phase_utility
- @subpage page_protocol_command_phase_ps
- @subpage page_protocol_command_phase_sp
@sa ::dispatch_command
*/
/**
@page page_protocol_command_phase_utility Utility Commands
- @subpage page_protocol_com_quit
- @subpage page_protocol_com_init_db
- @subpage page_protocol_com_field_list
- @subpage page_protocol_com_refresh
- @subpage page_protocol_com_statistics
- @subpage page_protocol_com_process_info
- @subpage page_protocol_com_process_kill
- @subpage page_protocol_com_debug
- @subpage page_protocol_com_ping
- @subpage page_protocol_com_change_user
- @subpage page_protocol_com_reset_connection
- @subpage page_protocol_com_set_option
*/
/**
@page page_protocol_command_phase_text Text Protocol
- @subpage page_protocol_com_query
*/
/**
@page page_protocol_command_phase_ps Prepared Statements
The prepared statement protocol was introduced in MySQL 4.1 and adds a
few new commands:
- @subpage page_protocol_com_stmt_prepare
- @subpage page_protocol_com_stmt_execute
- @subpage page_protocol_com_stmt_fetch
- @subpage page_protocol_com_stmt_close
- @subpage page_protocol_com_stmt_reset
- @subpage page_protocol_com_stmt_send_long_data
It also defines a more compact resultset format that is used instead of
@ref page_protocol_com_query_response_text_resultset to return the results.
@note Keep in mind that not all SQL statements can be prepared.
@sa [WL#2871](https://dev.mysql.com/worklog/task/?id=2871)
*/
/**
@page page_protocol_command_phase_sp Stored Programs
In MySQL 5.0 the protocol was extended to handle:
- @ref sect_protocol_command_phase_sp_multi_resultset
- @ref sect_protocol_command_phase_sp_multi_statement
@section sect_protocol_command_phase_sp_multi_resultset Multi-Resultset
Multi-resultsets are sent by a stored program if more than one resultset was
generated inside of it. e.g.:
~~~~~~~~~~~~
CREATE TEMPORARY TABLE ins ( id INT );
DROP PROCEDURE IF EXISTS multi;
DELIMITER $$
CREATE PROCEDURE multi() BEGIN
SELECT 1;
SELECT 1;
INSERT INTO ins VALUES (1);
INSERT INTO ins VALUES (2);
END$$
DELIMITER ;
CALL multi();
DROP TABLE ins;
~~~~~~~~~~~~
results in:
- a resultset
~~~~~~~~~~~~~
01 00 00 01 01 17 00 00 02 03 64 65 66 00 00 00 ..........def...
01 31 00 0c 3f 00 01 00 00 00 08 81 00 00 00 00 .1..?...........
05 00 00 03 fe 00 00 0a 00 02 00 00 04 01 31 05 ..............1.
00 00 05 fe 00 00 0a 00 ........
~~~~~~~~~~~~~
- see the @ref page_protocol_basic_eof_packet
`05 00 00 03 fe 00 00 0a 00` with its status-flag being `0x0A`
- another resultset:
~~~~~~~~~~~~~
01 00 00 06 01 17 00 00 07 03 64 65 66 00 00 00 ..........def...
01 31 00 0c 3f 00 01 00 00 00 08 81 00 00 00 00 .1..?...........
05 00 00 08 fe 00 00 0a 00 02 00 00 09 01 31 05 ..............1.
00 00 0a fe 00 00 0a 00 ........
~~~~~~~~~~~~~
- see the @ref page_protocol_basic_eof_packet
`05 00 00 03 fe 00 00 0a 00` with its status-flag being `0x0A`
- and a closing empty resultset, an @ref page_protocol_basic_ok_packet
~~~~~~~~~~~~~
07 00 00 0b 00 01 00 02 00 00 00 ...........
~~~~~~~~~~~~~
If the ::SERVER_MORE_RESULTS_EXISTS flag ise set, that indicates more
resultsets will follow.
The trailing @ref page_protocol_basic_ok_packet is the response to the
`CALL` statement and contains the `affected_rows` count of the last
statement. In our case we inserted 2 rows, but only the `affected_rows`
of the last `INSERT` statement is returned as part of the
@ref page_protocol_basic_ok_packet. If the last statement is a `SELECT`,
the `affected_rows` count is 0.
As of MySQL 5.7.5, the resultset is followed by an
@ref page_protocol_basic_ok_packet, and this
@ref page_protocol_basic_ok_packet has the ::SERVER_MORE_RESULTS_EXISTS
flag set to start the processing of the next resultset.
The client has to announce that it wants multi-resultsets by either setting
the ::CLIENT_MULTI_RESULTS or ::CLIENT_PS_MULTI_RESULTS capability flags.
@subsection sect_protocol_command_phase_sp_multi_resultset_out_params OUT Parameter Set
Starting with MySQL 5.5.3, prepared statements can bind OUT parameters of
stored procedures. They are returned as an extra resultset in the
multi-resultset response. The client announces it can handle OUT parameters
by setting the ::CLIENT_PS_MULTI_RESULTS capability.
To distinguish a normal resultset from an OUT parameter set, the
@ref page_protocol_basic_eof_packet or (if ::CLIENT_DEPRECATE_EOF capability
flag is set) @ref page_protocol_basic_ok_packet that follows its field
definition has the ::SERVER_PS_OUT_PARAMS flag set.
@note The closing @ref page_protocol_basic_eof_packet does NOT have either
::SERVER_PS_OUT_PARAMS flag nor the ::SERVER_MORE_RESULTS_EXISTS flag set.
Only the first @ref page_protocol_basic_eof_packet has.
@section sect_protocol_command_phase_sp_multi_statement Multi-Statement
A multi-statement is permitting ::COM_QUERY to send more than one query to
the server, separated by `;` characters.
The client musst announce that it wants multi-statements by either setting
the ::CLIENT_MULTI_STATEMENTS capability or by using
@ref page_protocol_com_set_option
*/
/**
@page page_protocol_com_set_option COM_SET_OPTION
@brief Sets options for the current connection
::COM_SET_OPTION enables and disables server capabilities for the current
connection.
@note Only ::CLIENT_MULTI_STATEMENTS can be set to a
value defined in ::enum_mysql_set_option.
@return @ref page_protocol_basic_ok_packet on success,
@ref page_protocol_basic_err_packet otherwise.
<table>
<caption>Payload</caption>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref a_protocol_type_int1 "int<1>"</td>
<td>status</td>
<td>[0x1A] COM_SET_OPTION</td></tr>
<tr><td>@ref a_protocol_type_int2 "int<2>"</td>
<td>option_operation</td>
<td>One of ::enum_mysql_set_option</td></tr>
</table>
@sa ::mysql_set_server_option, ::dispatch_sql_command
*/
/**
@page page_protocol_connection_lifecycle Connection Lifecycle
The MySQL protocol is a stateful protocol. When a connection is established
the server initiates a @ref page_protocol_connection_phase. Once that is
performed the connection enters the \ref page_protocol_command_phase. The
@ref page_protocol_command_phase ends when the connection terminates.
The connection can also enter @ref page_protocol_replication from
@ref page_protocol_connection_phase if one of the replication commands
is sent.
@startuml
[*] --> ConnectionState : client connects
ConnectionState: Authentication
ConnectionState --> [*] : Error or client disconnects
ConnectionState --> CommandState : Successful authentication
CommandState: RPC commands read/execute loop
CommandState --> [*] : client or server closes the connection
CommandState --> ReplicationMode : Replication command received
ReplicationMode: binlog data streamed
ReplicationMode --> [*] : client or server closes the connection
@enduml
Further reading:
- @subpage page_protocol_connection_phase
- @subpage page_protocol_command_phase
- @subpage page_protocol_replication
*/
/**
@page page_protocol_basic_character_set Character Set
MySQL has a very flexible character set support as documented in
[Character Set Support](http://dev.mysql.com/doc/refman/5.7/en/charset.html).
The list of character sets and their IDs can be queried as follows:
<pre>
SELECT id, collation_name FROM information_schema.collations ORDER BY id;
+----+-------------------+
| id | collation_name |
+----+-------------------+
| 1 | big5_chinese_ci |
| 2 | latin2_czech_cs |
| 3 | dec8_swedish_ci |
| 4 | cp850_general_ci |
| 5 | latin1_german1_ci |
| 6 | hp8_english_ci |
| 7 | koi8r_general_ci |
| 8 | latin1_swedish_ci |
| 9 | latin2_general_ci |
| 10 | swe7_swedish_ci |
+----+-------------------+
</pre>
The following table shows a few common character sets.
Number | Hex | Character Set Name
-------|-------|-------------------
8 | 0x08 | @ref my_charset_latin1 "latin1_swedish_ci"
33 | 0x21 | @ref my_charset_utf8mb3_general_ci "utf8mb3_general_ci"
63 | 0x3f | @ref my_charset_bin "binary"
@anchor a_protocol_character_set Protocol::CharacterSet
----------------------
A character set is defined in the protocol as a integer.
Fields:
- charset_nr (2) -- number of the character set and collation
*/
/* clang-format on */
/**
@defgroup group_cs Client/Server Protocol
Client/server protocol related structures,
macros, globals and functions
*/
#include "sql/protocol_classic.h"
#include <openssl/ssl.h>
#include <string.h>
#include <algorithm>
#include <limits>
#include "decimal.h"
#include "lex_string.h"
#include "m_ctype.h"
#include "m_string.h"
#include "my_byteorder.h"
#include "my_compiler.h"
#include "my_dbug.h"
#include "my_inttypes.h"
#include "my_loglevel.h"
#include "my_sys.h"
#include "my_time.h"
#include "mysql/com_data.h"
#include "mysql/psi/mysql_socket.h"
#include "mysqld_error.h"
#include "mysys_err.h"
#include "sql/field.h"
#include "sql/item.h"
#include "sql/item_func.h" // Item_func_set_user_var
#include "sql/my_decimal.h"
#include "sql/mysqld.h" // global_system_variables
#include "sql/session_tracker.h"
#include "sql/sql_class.h" // THD
#include "sql/sql_error.h"
#include "sql/sql_lex.h"
#include "sql/sql_list.h"
#include "sql/sql_prepare.h" // Prepared_statement
#include "sql/system_variables.h"
#include "sql_string.h"
#include "template_utils.h"
using std::max;
using std::min;
static const unsigned int PACKET_BUFFER_EXTRA_ALLOC = 1024;
static bool net_send_error_packet(THD *, uint, const char *, const char *);
static bool net_send_error_packet(NET *, uint, const char *, const char *, bool,
ulong, const CHARSET_INFO *);
static bool write_eof_packet(THD *, NET *, uint, uint);
static ulong get_ps_param_len(enum enum_field_types, uchar *, ulong, ulong *,
bool *);
/**
Ensures that the packet buffer has enough capacity to hold a string of the
given length.
@param length the length of the string
@param[in,out] packet the buffer
@return true if memory could not be allocated, false on success
*/
static bool ensure_packet_capacity(size_t length, String *packet) {
size_t packet_length = packet->length();
/*
The +9 comes from that strings of length longer than 16M require
9 bytes to be stored (see net_store_length).
*/
return packet_length + 9 + length > packet->alloced_length() &&
packet->mem_realloc(packet_length + 9 + length);
}
/**
Store length and data in a network packet buffer.
@param from the data to store
@param length the length of the data
@param[in,out] packet the buffer
@return true if there is not enough memory, false on success
*/
static inline bool net_store_data(const uchar *from, size_t length,
String *packet) {
if (ensure_packet_capacity(length, packet)) return true;
size_t packet_length = packet->length();
uchar *to = net_store_length((uchar *)packet->ptr() + packet_length, length);
if (length > 0) memcpy(to, from, length);
packet->length((uint)(to + length - (uchar *)packet->ptr()));
return false;
}
/**
Stores a string in the network buffer. The string is padded with zeros if it
is shorter than the specified padded length.
@param data the string to store
@param data_length the length of the string
@param padded_length the length of the zero-padded string
@param[in,out] packet the network buffer
*/
static bool net_store_zero_padded_data(const char *data, size_t data_length,
size_t padded_length, String *packet) {
const size_t zeros =
padded_length > data_length ? padded_length - data_length : 0;
const size_t full_length = data_length + zeros;
if (ensure_packet_capacity(full_length, packet)) return true;
uchar *to = net_store_length(
pointer_cast<uchar *>(packet->ptr()) + packet->length(), full_length);
memset(to, '0', zeros);
if (data_length > 0)
memcpy(to + zeros, pointer_cast<const uchar *>(data), data_length);
packet->length(pointer_cast<char *>(to) + full_length - packet->ptr());
return false;
}
/**
net_store_data() - extended version with character set conversion.
It is optimized for short strings whose length after
conversion is guaranteed to be less than 251, which occupies
exactly one byte to store length. It allows not to use
the "convert" member as a temporary buffer, conversion
is done directly to the "packet" member.
The limit 251 is good enough to optimize send_result_set_metadata()
because column, table, database names fit into this limit.
*/
bool Protocol_classic::net_store_data_with_conversion(
const uchar *from, size_t length, const CHARSET_INFO *from_cs,
const CHARSET_INFO *to_cs) {
uint dummy_errors;
/* Calculate maximum possible result length */
size_t conv_length = to_cs->mbmaxlen * length / from_cs->mbminlen;
if (conv_length > 250) {
/*
For strings with conv_length greater than 250 bytes
we don't know how many bytes we will need to store length: one or two,
because we don't know result length until conversion is done.
For example, when converting from utf8 (mbmaxlen=3) to latin1,
conv_length=300 means that the result length can vary between 100 to 300.
length=100 needs one byte, length=300 needs to bytes.
Thus conversion directly to "packet" is not worthy.
Let's use "convert" as a temporary buffer.
*/
return (convert.copy(pointer_cast<const char *>(from), length, from_cs,
to_cs, &dummy_errors) ||
net_store_data(pointer_cast<const uchar *>(convert.ptr()),
convert.length(), packet));
}
size_t packet_length = packet->length();
size_t new_length = packet_length + conv_length + 1;
if (new_length > packet->alloced_length() && packet->mem_realloc(new_length))
return true;
char *length_pos = packet->ptr() + packet_length;
char *to = length_pos + 1;
to += copy_and_convert(to, conv_length, to_cs, (const char *)from, length,
from_cs, &dummy_errors);
net_store_length((uchar *)length_pos, to - length_pos - 1);
packet->length((uint)(to - packet->ptr()));
return false;
}
/**
Send a error string to client.
Design note:
net_printf_error and net_send_error are low-level functions
that shall be used only when a new connection is being
established or at server startup.
For SIGNAL/RESIGNAL and GET DIAGNOSTICS functionality it's
critical that every error that can be intercepted is issued in one
place only, my_message_sql.
@param thd Thread handler
@param sql_errno The error code to send
@param err A pointer to the error message
@retval false The message was sent to the client
@retval true An error occurred and the message wasn't sent properly
*/
bool net_send_error(THD *thd, uint sql_errno, const char *err) {
bool error;
DBUG_TRACE;
assert(!thd->sp_runtime_ctx);
assert(sql_errno);
assert(err);
DBUG_PRINT("enter", ("sql_errno: %d err: %s", sql_errno, err));
/*
It's one case when we can push an error even though there
is an OK or EOF already.
*/
thd->get_stmt_da()->set_overwrite_status(true);
/* Abort multi-result sets */
thd->server_status &= ~SERVER_MORE_RESULTS_EXISTS;
error = net_send_error_packet(thd, sql_errno, err,
mysql_errno_to_sqlstate(sql_errno));
thd->get_stmt_da()->set_overwrite_status(false);
return error;
}
/**
Send a error string to client using net struct.
This is used initial connection handling code.
@param net Low-level net struct
@param sql_errno The error code to send
@param err A pointer to the error message
@retval false The message was sent to the client
@retval true An error occurred and the message wasn't sent properly
*/
bool net_send_error(NET *net, uint sql_errno, const char *err) {
DBUG_TRACE;
assert(sql_errno && err);
DBUG_PRINT("enter", ("sql_errno: %d err: %s", sql_errno, err));
bool error = net_send_error_packet(
net, sql_errno, err, mysql_errno_to_sqlstate(sql_errno), false, 0,
global_system_variables.character_set_results);
return error;
}
/* clang-format off */
/**
@page page_protocol_basic_ok_packet OK_Packet
An OK packet is sent from the server to the client to signal successful
completion of a command. As of MySQL 5.7.5, OK packets are also used to
indicate EOF, and EOF packets are deprecated.
if ::CLIENT_PROTOCOL_41 is set, the packet contains a warning count.
<table>
<caption>The Payload of an OK Packet</caption>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref a_protocol_type_int1 "int<1>"</td>
<td>header</td>
<td>`0x00` or `0xFE` the OK packet header</td></tr>
<tr><td>@ref sect_protocol_basic_dt_int_le "int<lenenc>"</td>
<td>affected_rows</td>
<td>affected rows</td></tr>
<tr><td>@ref sect_protocol_basic_dt_int_le "int<lenenc>"</td>
<td>last_insert_id</td>
<td>last insert-id</td></tr>
<tr><td colspan="3">if capabilities @& ::CLIENT_PROTOCOL_41 {</td></tr>
<tr><td>@ref a_protocol_type_int2 "int<2>"</td>
<td>status_flags</td>
<td>@ref SERVER_STATUS_flags_enum</td></tr>
<tr><td>@ref a_protocol_type_int2 "int<2>"</td>
<td>warnings</td>
<td>number of warnings</td></tr>
<tr><td colspan="3">} else if capabilities @& ::CLIENT_TRANSACTIONS {</td></tr>
<tr><td>@ref a_protocol_type_int2 "int<2>"</td>
<td>status_flags</td>
<td>@ref SERVER_STATUS_flags_enum</td></tr>
<tr><td colspan="3">}</td></tr>
<tr><td colspan="3">if capabilities @& ::CLIENT_SESSION_TRACK</td></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>info</td>
<td>human readable status information</td></tr>
<tr><td colspan="3"> if status_flags @& ::SERVER_SESSION_STATE_CHANGED {</td></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>session state info</td>
<td>@anchor a_protocol_basic_ok_packet_sessinfo
@ref sect_protocol_basic_ok_packet_sessinfo</td></tr>
<tr><td colspan="3"> }</td></tr>
<tr><td colspan="3">} else {</td></tr>
<tr><td>@ref sect_protocol_basic_dt_string_eof "string<EOF>"</td>
<td>info</td>
<td>human readable status information</td></tr>
<tr><td colspan="3">}</td></tr>
</table>
These rules distinguish whether the packet represents OK or EOF:
- OK: header = 0 and length of packet > 7
- EOF: header = 0xfe and length of packet < 9
To ensure backward compatibility between old (prior to 5.7.5) and
new (5.7.5 and up) versions of MySQL, new clients advertise
the ::CLIENT_DEPRECATE_EOF flag:
- Old clients do not know about this flag and do not advertise it.
Consequently, the server does not send OK packets that represent EOF.
(Old servers never do this, anyway. New servers recognize the absence
of the flag to mean they should not.)
- New clients advertise this flag. Old servers do not know this flag and
do not send OK packets that represent EOF. New servers recognize the flag
and can send OK packets that represent EOF.
Example
=======
OK with ::CLIENT_PROTOCOL_41. 0 affected rows, last-insert-id was 0,
AUTOCOMMIT enabled, 0 warnings. No further info.
~~~~~~~~~~~~~~~~~~~~~
07 00 00 02 00 00 00 02 00 00 00
~~~~~~~~~~~~~~~~~~~~~
@section sect_protocol_basic_ok_packet_sessinfo Session State Information
State-change information is sent in the OK packet as a array of state-change
blocks which are made up of:
<table>
<caption>Layout of Session State Information</caption>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref a_protocol_type_int1 "int<1>"</td>
<td>type</td>
<td>type of data. See enum_session_state_type</td></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>data</td>
<td>data of the changed session info</td></tr>
</table>
Interpretation of the data field depends on the type value:
@subsection sect_protocol_basic_ok_packet_sessinfo_SESSION_TRACK_SYSTEM_VARIABLES SESSION_TRACK_SYSTEM_VARIABLES
<table>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>name</td>
<td>name of the changed system variable</td></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>value</td>
<td>value of the changed system variable</td></tr>
</table>
Example:
After a SET autocommit = OFF statement:
<table><tr>
<td>
~~~~~~~~~~~~~~~~~~~~~
00 00 0f1 0a 61 75 74 6f 63 6f 6d 6d 69 74 03 4f 46 46
~~~~~~~~~~~~~~~~~~~~~
</td><td>
~~~~~~~~~~~~~~~~~~~~~
....autocommit.OFF
~~~~~~~~~~~~~~~~~~~~~
</td></tr></table>
@subsection sect_protocol_basic_ok_packet_sessinfo_SESSION_TRACK_SCHEMA SESSION_TRACK_SCHEMA
<table>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>name</td>
<td>name of the changed schema</td></tr>
</table>
Example:
After a USE test statement:
<table><tr>
<td>
~~~~~~~~~~~~~~~~~~~~~
01 00 05 04 74 65 73 74
~~~~~~~~~~~~~~~~~~~~~
</td><td>
~~~~~~~~~~~~~~~~~~~~~
...test
~~~~~~~~~~~~~~~~~~~~~
</td></tr></table>
@subsection sect_protocol_basic_ok_packet_sessinfo_SESSION_TRACK_STATE_CHANGE SESSION_TRACK_STATE_CHANGE
A flag byte that indicates whether session state changes occurred.
This flag is represented as an ASCII value.
<table>
<tr><th>Type</th><th>Name</th><th>Description</th></tr>
<tr><td>@ref sect_protocol_basic_dt_string_le "string<lenenc>"</td>
<td>is_tracked</td>
<td>`0x31` ("1") if state tracking got enabled.</td></tr>
</table>
Example:
After a SET SESSION session_track_state_change = 1 statement:
<table><tr>
<td>
~~~~~~~~~~~~~~~~~~~~~
03 02 00 01 31
~~~~~~~~~~~~~~~~~~~~~
</td><td>
~~~~~~~~~~~~~~~~~~~~~
...1
~~~~~~~~~~~~~~~~~~~~~
</td></tr></table>
See also net_send_ok()
*/
/* clang-format on */
/**
Return OK to the client.
See @ref page_protocol_basic_ok_packet for the OK packet structure.
@param thd Thread handler
@param server_status The server status
@param statement_warn_count Total number of warnings
@param affected_rows Number of rows changed by statement
@param id Auto_increment id for first row (if used)
@param message Message to send to the client
(Used by mysql_status)
@param eof_identifier when true [FE] will be set in OK header
else [00] will be used
@retval false The message was successfully sent
@retval true An error occurred and the messages wasn't sent properly
*/
static bool net_send_ok(THD *thd, uint server_status, uint statement_warn_count,
ulonglong affected_rows, ulonglong id,
const char *message, bool eof_identifier) {
Protocol *protocol = thd->get_protocol();
NET *net = thd->get_protocol_classic()->get_net();
uchar buff[MYSQL_ERRMSG_SIZE + 10];
uchar *pos, *start;
/*
To be used to manage the data storage in case session state change
information is present.
*/
String store;
bool state_changed = false;
bool error = false;
DBUG_TRACE;
if (!net->vio) // hack for re-parsing queries
{
DBUG_PRINT("info", ("vio present: NO"));
return false;
}
start = buff;
/*
Use 0xFE packet header if eof_identifier is true
unless we are talking to old client
*/
if (eof_identifier && (protocol->has_client_capability(CLIENT_DEPRECATE_EOF)))
buff[0] = 254;
else
buff[0] = 0;
/* affected rows */
pos = net_store_length(buff + 1, affected_rows);
/* last insert id */
pos = net_store_length(pos, id);
if (protocol->has_client_capability(CLIENT_SESSION_TRACK) &&
thd->session_tracker.enabled_any() &&
thd->session_tracker.changed_any()) {
server_status |= SERVER_SESSION_STATE_CHANGED;
state_changed = true;
}
if (protocol->has_client_capability(CLIENT_PROTOCOL_41)) {
DBUG_PRINT("info",
("affected_rows: %lu id: %lu status: %u warning_count: %u",
(ulong)affected_rows, (ulong)id, (uint)(server_status & 0xffff),
(uint)statement_warn_count));
/* server status */
int2store(pos, server_status);
pos += 2;
/* warning count: we can only return up to 65535 warnings in two bytes. */
uint tmp = min(statement_warn_count, 65535U);
int2store(pos, tmp);
pos += 2;
} else if (net->return_status) // For 4.0 protocol
{
int2store(pos, server_status);
pos += 2;
}
thd->get_stmt_da()->set_overwrite_status(true);
if (protocol->has_client_capability(CLIENT_SESSION_TRACK)) {
/* the info field */
if (state_changed || (message && message[0]))
pos = net_store_data(pos, pointer_cast<const uchar *>(message),
message ? strlen(message) : 0);
/* session state change information */
if (unlikely(state_changed)) {
store.set_charset(thd->variables.collation_database);
/*
First append the fields collected so far. In case of malloc, memory
for message is also allocated here.
*/
store.append((const char *)start, (pos - start), MYSQL_ERRMSG_SIZE);
/* .. and then the state change information. */
thd->session_tracker.store(thd, store);
start = (uchar *)store.ptr();
pos = start + store.length();
}
} else if (message && message[0]) {
/* the info field, if there is a message to store */
pos = net_store_data(pos, pointer_cast<const uchar *>(message),
strlen(message));
}
/* OK packet length will be restricted to 16777215 bytes */
if (((size_t)(pos - start)) > MAX_PACKET_LENGTH) {
net->error = NET_ERROR_SOCKET_RECOVERABLE;
net->last_errno = ER_NET_OK_PACKET_TOO_LARGE;
my_error(ER_NET_OK_PACKET_TOO_LARGE, MYF(0));
DBUG_PRINT("info", ("OK packet too large"));
return true;
}
error = my_net_write(net, start, (size_t)(pos - start));
if (!error) error = net_flush(net);
thd->get_stmt_da()->set_overwrite_status(false);
DBUG_PRINT("info", ("OK sent, so no more error sending allowed"));
return error;
}
static uchar eof_buff[1] = {(uchar)254}; /* Marker for end of fields */
/* clang-format off */
/**
@page page_protocol_basic_eof_packet EOF_Packet
If ::CLIENT_PROTOCOL_41 is enabled, the EOF packet contains a
warning count and status flags.
@note
In the MySQL client/server protocol, the
@ref page_protocol_basic_eof_packet and
@ref page_protocol_basic_ok_packet packets serve
the same purpose, to mark the end of a query execution result.
Due to changes in MySQL 5.7 in
the @ref page_protocol_basic_ok_packet packets (such as session
state tracking), and to avoid repeating the changes in
the @ref page_protocol_basic_eof_packet packet, the
@ref page_protocol_basic_ok_packet is deprecated as of MySQL 5.7.5.
@warning
The @ref page_protocol_basic_eof_packet packet may appear in places where
a @ref sect_protocol_basic_dt_int_le "Protocol::LengthEncodedInteger"
may appear. You must check whether the packet length is less than 9 to
make sure that it is a @ref page_protocol_basic_eof_packet packet.
<table>
<caption>The Payload of an EOF Packet</caption>