-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathMySQLHandler.cpp
More file actions
1107 lines (987 loc) · 48.4 KB
/
Copy pathMySQLHandler.cpp
File metadata and controls
1107 lines (987 loc) · 48.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <Server/MySQLHandler.h>
#include <algorithm>
#include <array>
#include <optional>
#include <Access/Common/AccessFlags.h>
#include <Core/MySQL/Authentication.h>
#include <Core/MySQL/PacketsConnection.h>
#include <Core/MySQL/PacketsGeneric.h>
#include <Core/MySQL/PacketsPreparedStatements.h>
#include <Core/MySQL/PacketsProtocolText.h>
#include <Core/NamesAndTypes.h>
#include <Core/ServerSettings.h>
#include <Core/Settings.h>
#include <Core/UUID.h>
#include <IO/LimitReadBuffer.h>
#include <IO/ReadBufferFromPocoSocket.h>
#include <IO/ReadBufferFromString.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteBufferFromPocoSocket.h>
#include <IO/WriteBuffer.h>
#include <IO/copyData.h>
#include <Interpreters/DatabaseCatalog.h>
#include <Interpreters/Session.h>
#include <Interpreters/executeQuery.h>
#include <Interpreters/Context.h>
#include <Parsers/ASTFunction.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ASTLiteral.h>
#include <Parsers/CommonParsers.h>
#include <Parsers/ExpressionElementParsers.h>
#include <Parsers/ExpressionListParsers.h>
#include <Parsers/IParser.h>
#include <Parsers/TokenIterator.h>
#include <Server/TCPServer.h>
#include <Storages/IStorage.h>
#include <base/scope_guard.h>
#include <Common/CurrentThread.h>
#include <Common/FieldVisitorToString.h>
#include <Common/QueryScope.h>
#include <Common/NetException.h>
#include <Common/OpenSSLHelpers.h>
#include <Common/SettingSource.h>
#include <Common/SettingsChanges.h>
#include <Common/StringUtils.h>
#include <Common/config_version.h>
#include <Common/logger_useful.h>
#include <Common/quoteString.h>
#include <Poco/String.h>
#include <Common/re2.h>
#include <Common/setThreadName.h>
#if USE_SSL
# include <Poco/Net/SSLManager.h>
# include <Poco/Net/SecureStreamSocket.h>
#endif
namespace DB
{
namespace Setting
{
extern const SettingsBool allow_experimental_analyzer;
extern const SettingsBool prefer_column_name_to_alias;
extern const SettingsSeconds receive_timeout;
extern const SettingsSeconds send_timeout;
}
namespace ServerSetting
{
extern const ServerSettingsString default_session_user;
}
using namespace MySQLProtocol;
using namespace MySQLProtocol::Generic;
using namespace MySQLProtocol::ProtocolText;
using namespace MySQLProtocol::ConnectionPhase;
using namespace MySQLProtocol::PreparedStatements;
#if USE_SSL
using Poco::Net::SecureStreamSocket;
using Poco::Net::SSLManager;
#endif
namespace ErrorCodes
{
extern const int AUTHENTICATION_FAILED;
extern const int CANNOT_READ_ALL_DATA;
extern const int NOT_IMPLEMENTED;
extern const int MYSQL_CLIENT_INSUFFICIENT_CAPABILITIES;
extern const int SUPPORT_IS_DISABLED;
extern const int UNSUPPORTED_METHOD;
extern const int OPENSSL_ERROR;
extern const int SYNTAX_ERROR;
extern const int UNKNOWN_PACKET_FROM_CLIENT;
}
static const size_t PACKET_HEADER_SIZE = 4;
static const size_t SSL_REQUEST_PAYLOAD_SIZE = 32;
/** The handshake response is read before the client is authenticated, so its size has to be bounded.
* The fields it carries are a user name, a database name, an authentication plugin name and an
* authentication response, so this is generous: a real client sends a few hundred bytes.
* Without a bound, a peer can make the server grow memory while sending a response that never ends:
* `MySQLPacketPayloadReadBuffer` follows a chain of maximum-size (16 MiB) packets as one logical
* message, and the fields inside the response are read up to a terminator.
*/
static const size_t MAX_HANDSHAKE_RESPONSE_PAYLOAD_SIZE = 64 * 1024;
static bool checkShouldReplaceQuery(const String & query, const String & prefix)
{
return query.length() >= prefix.length()
&& std::equal(prefix.begin(), prefix.end(), query.begin(), [](char a, char b) { return std::tolower(a) == std::tolower(b); });
}
static bool isFederatedServerSetupSetCommand(const String & query)
{
re2::RE2::Options regexp_options;
regexp_options.set_case_sensitive(false);
static const re2::RE2 expr(
"(^(SET NAMES(.*)))"
"|(^(SET character_set_results(.*)))"
"|(^(SET FOREIGN_KEY_CHECKS(.*)))"
"|(^(SET AUTOCOMMIT(.*)))"
"|(^(SET sql_mode(.*)))"
"|(^(SET @@(.*)))"
"|(^(SET SESSION TRANSACTION ISOLATION LEVEL(.*)))", regexp_options);
chassert(expr.ok());
return re2::RE2::FullMatch(query, expr);
}
/// Always return an empty set with appropriate column definitions for SHOW WARNINGS queries
/// See also: https://dev.mysql.com/doc/refman/8.0/en/show-warnings.html
static String showWarningsReplacementQuery([[maybe_unused]] const String & query)
{
return "SELECT '' AS Level, 0::UInt32 AS Code, '' AS Message WHERE false";
}
static String showCountWarningsReplacementQuery([[maybe_unused]] const String & query)
{
return "SELECT 0::UInt64 AS `@@session.warning_count`";
}
/// Replace "[query(such as SHOW VARIABLES...)]" into "".
static String selectEmptyReplacementQuery(const String & query)
{
std::ignore = query;
return "select ''";
}
/// Parse `text` as exactly one string literal (and nothing else) and return its unescaped value.
/// Returns nullopt if `text` is not a single string literal, so callers can reject client input
/// instead of concatenating it into a query (which would allow SQL injection over the MySQL wire).
static std::optional<String> tryParseSingleStringLiteral(const String & text)
{
Tokens tokens(text.data(), text.data() + text.size(), DBMS_DEFAULT_MAX_QUERY_SIZE);
IParser::Pos pos(tokens, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS);
Expected expected;
ASTPtr ast;
if (!ParserStringLiteral().parse(pos, ast, expected))
return std::nullopt;
/// Accept one optional trailing ';' then end-of-stream: executeQuery treats ';' as
/// end-of-query, so a benign programmatic client may send "SHOW TABLE STATUS LIKE 'x';".
/// A second statement after the ';' leaves pos before end -> rejected, so this stays injection-safe.
ParserToken(TokenType::Semicolon).ignore(pos, expected);
if (!pos->isEnd())
return std::nullopt;
return ast->as<ASTLiteral &>().value.safeGet<String>();
}
/// Replace "SHOW TABLE STATUS LIKE 'xx'" into a SELECT from INFORMATION_SCHEMA.TABLES.
/// Both statements describe the same MySQL metadata family, so they must share one mapping:
/// a client mixing the two introspection paths has to see identical values for one object.
static String showTableStatusReplacementQuery(const String & query)
{
const String prefix = "SHOW TABLE STATUS LIKE ";
String pattern;
/// The dispatcher matched the key "SHOW TABLE STATUS LIKE" (22 chars, no separator) but we slice
/// at prefix.length() (23, includes the space). Require that separator byte to be whitespace,
/// else "SHOW TABLE STATUS LIKEx'a'" would skip the stray byte and be coerced into a lookup.
if (query.size() > prefix.size() && isWhitespaceASCII(query[prefix.size() - 1]))
{
/// Parse the LIKE argument as a single string literal and re-quote it. The raw client
/// suffix must never be concatenated verbatim: that allowed injecting an arbitrary tail
/// (e.g. "" UNION SELECT ... FROM system.users) into the generated query. If the suffix
/// is not exactly one string literal, match nothing rather than risk injection.
if (auto parsed = tryParseSingleStringLiteral(query.data() + prefix.length()))
pattern = *parsed;
}
return (
"SELECT"
" table_name AS Name,"
" engine AS Engine,"
" version AS Version,"
" row_format AS Row_format,"
" table_rows AS Rows,"
" avg_row_length AS Avg_row_length,"
" data_length AS Data_length,"
" max_data_length AS Max_data_length,"
" index_length AS Index_length,"
" data_free AS Data_free,"
" auto_increment AS Auto_increment,"
" create_time AS Create_time,"
" update_time AS Update_time,"
" check_time AS Check_time,"
" table_collation AS Collation,"
" checksum AS Checksum,"
" create_options AS Create_options,"
" table_comment AS Comment"
" FROM INFORMATION_SCHEMA.TABLES"
/// MySQL scopes SHOW TABLE STATUS to the session's default database, so the translation
/// must constrain table_schema too, or a lookup would also return same-named tables from
/// other databases. The replacement is executed with the session's query context, so
/// currentDatabase() resolves to that session database (it also tracks later USE
/// statements). MySQL's "No database selected" state cannot arise here: a ClickHouse
/// session always has a current database (the server default when the client sent none).
" WHERE table_schema = currentDatabase() AND table_name LIKE "
+ quoteString(pattern));
}
static std::optional<String> setSettingReplacementQuery(const String & query, const String & mysql_setting, const String & clickhouse_setting)
{
const String prefix = "SET " + mysql_setting;
if (!checkShouldReplaceQuery(query, prefix))
return std::nullopt;
/// checkShouldReplaceQuery is only a byte-prefix check, so it also matches a longer variable
/// that merely starts with the mapped name (e.g. "SET SQL_SELECT_LIMITED=1" matches the
/// "SET SQL_SELECT_LIMIT" prefix). Require a word boundary after the name: the next character
/// must not continue an identifier. Otherwise this is a different variable, so leave the query
/// untranslated (it passes through and errors safely as an unknown setting) instead of resetting
/// the unrelated mapped setting below.
if (query.length() > prefix.length() && isWordCharASCII(query[prefix.length()]))
return std::nullopt;
/// Parse the "= <value>" tail and re-serialize the value rather than concatenating the raw
/// client suffix. Concatenation let a client smuggle a tail into the generated query
/// (e.g. "SET SQL_SELECT_LIMIT=1, max_threads=42" became "SET limit=1, max_threads=42").
/// Only translate when the full tail is exactly "= <literal|DEFAULT>" with an optional single
/// trailing ';' (executeQuery treats ';' as end-of-query, so a benign programmatic client may
/// send "SET SQL_SELECT_LIMIT=2;"). Anything else (a malformed value, or an injected tail such
/// as ", max_threads=42" or a second statement after ';') is rejected: throw instead of
/// silently resetting the mapped setting to DEFAULT, which would change the caller's session
/// state on a malformed input and report success.
const String tail = query.data() + prefix.length();
Tokens tokens(tail.data(), tail.data() + tail.size(), DBMS_DEFAULT_MAX_QUERY_SIZE);
IParser::Pos pos(tokens, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS);
Expected expected;
if (!ParserToken(TokenType::Equals).ignore(pos, expected))
throw Exception(ErrorCodes::SYNTAX_ERROR, "Expected '=' after '{}'", prefix);
String value;
ASTPtr ast;
if (ParserKeyword(Keyword::DEFAULT).ignore(pos, expected))
value = "DEFAULT";
else if (ParserLiteral().parse(pos, ast, expected))
value = applyVisitor(FieldVisitorToString(), ast->as<ASTLiteral &>().value);
else
throw Exception(ErrorCodes::SYNTAX_ERROR, "Expected a single value after '{} ='", prefix);
ParserToken(TokenType::Semicolon).ignore(pos, expected);
if (!pos->isEnd())
throw Exception(ErrorCodes::SYNTAX_ERROR, "Unexpected trailing tokens after '{} = <value>'", prefix);
return "SET " + clickhouse_setting + " = " + value;
}
/// Replace "KILL QUERY [connection_id]" into "KILL QUERY WHERE query_id LIKE 'mysql:[connection_id]:xxx'".
static String killConnectionIdReplacementQuery(const String & query)
{
const String prefix = "KILL QUERY ";
/// The dispatcher matched the key "KILL QUERY" (10 chars, no separator) but we slice at
/// prefix.length() (11, includes the space). Require that separator byte to be whitespace,
/// else "KILL QUERY;12"/"KILL QUERYx12" would skip the stray byte and be coerced into a cancel.
if (query.size() > prefix.size() && isWhitespaceASCII(query[prefix.size() - 1]))
{
String suffix = query.data() + prefix.length();
/// Capture the digits of the connection id and accept one optional trailing ';' plus
/// surrounding whitespace: "^[0-9]" accepted only a single digit and silently dropped every
/// multi-digit id (e.g. "KILL QUERY 12"), and a benign programmatic client may send
/// "KILL QUERY 12;" (executeQuery treats ';' as end-of-query). Only the captured digits are
/// substituted, so any other tail (a non-numeric id, or a second statement after ';') fails
/// the match and stays injection-safe.
static const re2::RE2 expr(R"(^\s*([0-9]+)\s*;?\s*$)");
String connection_id_str;
if (re2::RE2::FullMatch(suffix, expr, &connection_id_str))
{
String replacement = fmt::format("KILL QUERY WHERE query_id LIKE 'mysql:{}:%'", connection_id_str);
return replacement;
}
}
return query;
}
/// Lowercase every string literal reachable through this node (a plain literal, a literal
/// tuple/array, or a tuple/array function of literals, as on the right side of IN).
/// Returns whether at least one string was lowercased.
static bool lowercaseStringLiterals(ASTPtr & node)
{
if (auto * literal = node->as<ASTLiteral>())
{
if (literal->value.getType() == Field::Types::String)
{
literal->value = Poco::toLower(literal->value.safeGet<String>());
return true;
}
if (literal->value.getType() == Field::Types::Tuple || literal->value.getType() == Field::Types::Array)
{
bool lowered = false;
auto lower_elements = [&](auto & elements)
{
for (auto & element : elements)
{
if (element.getType() == Field::Types::String)
{
element = Poco::toLower(element.template safeGet<String>());
lowered = true;
}
}
};
if (literal->value.getType() == Field::Types::Tuple)
{
auto elements = literal->value.safeGet<Tuple>();
lower_elements(elements);
literal->value = std::move(elements);
}
else
{
auto elements = literal->value.safeGet<Array>();
lower_elements(elements);
literal->value = std::move(elements);
}
return lowered;
}
return false;
}
if (const auto * function = node->as<ASTFunction>();
function && (function->name == "tuple" || function->name == "array") && function->arguments)
{
bool lowered = false;
for (auto & argument : function->arguments->children)
lowered |= lowercaseStringLiterals(argument);
return lowered;
}
return false;
}
/// Whether this column of the synthetic SHOW COLLATION result set is string-valued.
/// Only these participate in case-insensitive matching: wrapping a numeric column
/// (`Id`, `Sortlen`) in `lower` would throw instead of comparing.
static bool isStringValuedCollationColumn(const String & name)
{
static constexpr std::array string_columns{"Collation", "Charset", "Default", "Compiled", "Pad_attribute"};
return std::any_of(string_columns.begin(), string_columns.end(), [&](const auto * column) { return name == column; });
}
/// MySQL matches collation and charset names case-insensitively and resolves column names in the
/// WHERE clause of SHOW statements case-insensitively, while ClickHouse compares strings bytewise
/// and resolves identifiers case-sensitively. Rewrite the parsed "SHOW COLLATION WHERE ..." filter
/// so that the comparison forms MySQL clients use keep their MySQL semantics: canonicalize
/// identifiers to the column names of the synthetic result set, and for "=", "!=", "LIKE" and "IN"
/// comparisons of a string-valued column against string literals, lowercase both sides (every
/// string value in the synthetic set has a single known spelling, so this is lossless). Numeric
/// columns are left untouched: ClickHouse already coerces string literals to numbers there.
static void makeShowCollationsFilterCaseInsensitive(ASTPtr & node)
{
if (auto * identifier = node->as<ASTIdentifier>())
{
static constexpr std::array canonical_columns{"Collation", "Charset", "Id", "Default", "Compiled", "Sortlen", "Pad_attribute"};
for (const auto * column : canonical_columns)
{
if (Poco::icompare(identifier->name(), column) == 0)
{
node = make_intrusive<ASTIdentifier>(String(column));
break;
}
}
return;
}
if (auto * function = node->as<ASTFunction>();
function && function->arguments && function->arguments->children.size() == 2
&& (function->name == "equals" || function->name == "notEquals" || function->name == "like"
|| function->name == "notLike" || function->name == "ilike" || function->name == "notILike"
|| function->name == "in" || function->name == "notIn"))
{
/// Canonicalize identifiers first, then decide by the canonical name whether this
/// comparison targets a string-valued column.
for (auto & argument : function->arguments->children)
makeShowCollationsFilterCaseInsensitive(argument);
bool string_column = false;
for (const auto & argument : function->arguments->children)
if (const auto * argument_identifier = argument->as<ASTIdentifier>();
argument_identifier && isStringValuedCollationColumn(argument_identifier->name()))
string_column = true;
if (string_column)
{
bool lowered_literal = false;
for (auto & argument : function->arguments->children)
lowered_literal |= lowercaseStringLiterals(argument);
if (lowered_literal)
for (auto & argument : function->arguments->children)
if (argument->as<ASTIdentifier>())
argument = makeASTFunction("lower", argument);
}
return;
}
for (auto & child : node->children)
makeShowCollationsFilterCaseInsensitive(child);
}
/// Replace "SHOW COLLATION [LIKE 'pattern' | WHERE <expr>]" with a response enumerating every
/// collation the server actually puts on the wire, in the shape MySQL uses for this statement:
/// `utf8mb4_0900_ai_ci` (advertised in the handshake and stamped on string columns in result-set
/// metadata) and `binary` (stamped on numeric and other non-string columns). The set must be
/// complete: MySQL Connector/NET builds its charset-id dictionary from this result and fails on
/// any `ColumnDefinition41.character_set` id missing from it (an empty result makes it skip the
/// lookup, a partial one makes it throw).
static String showCollationsReplacementQuery(const String & query)
{
static constexpr auto collations = "SELECT"
" 'utf8mb4_0900_ai_ci' AS `Collation`,"
" 'utf8mb4' AS `Charset`,"
" 255 AS `Id`,"
" 'Yes' AS `Default`,"
" 'Yes' AS `Compiled`,"
" 0 AS `Sortlen`,"
" 'NO PAD' AS `Pad_attribute`"
" UNION ALL SELECT"
" 'binary' AS `Collation`,"
" 'binary' AS `Charset`,"
" 63 AS `Id`,"
" 'Yes' AS `Default`,"
" 'Yes' AS `Compiled`,"
" 1 AS `Sortlen`,"
" 'NO PAD' AS `Pad_attribute`";
const String prefix = "SHOW COLLATION";
const String tail = query.size() > prefix.size() ? String(query.data() + prefix.size()) : String();
/// The dispatcher is only a byte-prefix check; a word character right after the prefix means
/// a different statement (e.g. "SHOW COLLATIONX"), so leave it untranslated to error naturally.
if (!tail.empty() && isWordCharASCII(tail[0]))
return query;
/// The dispatcher routes every prefix match here, so the filtered forms of the statement
/// ("SHOW COLLATION LIKE 'pattern'", "SHOW COLLATION WHERE <expr>") also land in this
/// function and their filter must be honored, not dropped. Parse the tail and re-serialize
/// the filter instead of concatenating the raw client suffix (which would allow SQL injection
/// over the MySQL wire). Any malformed tail is left untranslated so the client gets a syntax
/// error rather than a silently unfiltered result.
Tokens tokens(tail.data(), tail.data() + tail.size(), DBMS_DEFAULT_MAX_QUERY_SIZE);
IParser::Pos pos(tokens, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS);
Expected expected;
String filter;
if (ParserKeyword(Keyword::LIKE).ignore(pos, expected))
{
ASTPtr ast;
if (!ParserStringLiteral().parse(pos, ast, expected))
return query;
/// MySQL matches collation names case-insensitively, so use ILIKE.
filter = " WHERE `Collation` ILIKE " + quoteString(ast->as<ASTLiteral &>().value.safeGet<String>());
}
else if (ParserKeyword(Keyword::WHERE).ignore(pos, expected))
{
ASTPtr ast;
if (!ParserExpression().parse(pos, ast, expected))
return query;
makeShowCollationsFilterCaseInsensitive(ast);
filter = " WHERE " + ast->formatWithSecretsOneLine();
}
/// Accept one optional trailing ';' then end-of-stream (executeQuery treats ';' as
/// end-of-query). Anything else is a tail this translation does not understand.
ParserToken(TokenType::Semicolon).ignore(pos, expected);
if (!pos->isEnd())
return query;
return "SELECT * FROM (" + String(collations) + ")" + filter;
}
/** MySQL returns this error code, HY000, so should we.
*
* These error codes represent the worst legacy practices in software engineering from 1970s
* (fixed-size fields, short variable names, cryptic abbreviations, lack of documentation, made-up alphabets)
* We should never ever fall into these practices, and having this compatibility error code is probably the only exception.
*
* You might be wondering, why it is HY000, and more precisely, what do the letters H and Y mean?
* The history does not know. The best answer I found is:
* https://dba.stackexchange.com/questions/241506/what-does-hy-stand-for-in-error-code
* Also, https://en.wikipedia.org/wiki/SQLSTATE
*
* Apparently, they decide to allocate alphanumeric characters for some meaning,
* then split their range (0..9A..Z) to some intervals for the system, user, and other categories,
* and the letter H appeared to be the first in some category.
*
* Also, the letter Y is chosen, because it is the highest, but someone afraid to took letter Z,
* and decided that the second highest letter is good enough.
*
* This will forever remind us about the mistakes made by previous generations of software engineers.
*/
static constexpr const char * mysql_error_code = "HY000";
MySQLHandler::MySQLHandler(
IServer & server_,
TCPServer & tcp_server_,
const Poco::Net::StreamSocket & socket_,
bool ssl_enabled, bool secure_required_,
uint32_t connection_id_,
std::optional<String> default_session_user_,
const ProfileEvents::Event & read_event_,
const ProfileEvents::Event & write_event_)
: Poco::Net::TCPServerConnection(socket_)
, server(server_)
, tcp_server(tcp_server_)
, log(getLogger("MySQLHandler"))
, secure_required(secure_required_)
, connection_id(connection_id_)
, default_session_user(std::move(default_session_user_))
, auth_plugin(new MySQLProtocol::Authentication::Native41())
, read_event(read_event_)
, write_event(write_event_)
{
server_capabilities = CLIENT_PROTOCOL_41 | CLIENT_SECURE_CONNECTION | CLIENT_PLUGIN_AUTH | CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA | CLIENT_CONNECT_WITH_DB | CLIENT_DEPRECATE_EOF;
if (ssl_enabled)
server_capabilities |= CLIENT_SSL;
queries_replacements.emplace("SHOW WARNINGS", showWarningsReplacementQuery);
queries_replacements.emplace("SHOW COUNT(*) WARNINGS", showCountWarningsReplacementQuery);
queries_replacements.emplace("KILL QUERY", killConnectionIdReplacementQuery);
queries_replacements.emplace("SHOW TABLE STATUS LIKE", showTableStatusReplacementQuery);
queries_replacements.emplace("SHOW VARIABLES", selectEmptyReplacementQuery);
queries_replacements.emplace("SHOW COLLATION", showCollationsReplacementQuery);
settings_replacements.emplace("SQL_SELECT_LIMIT", "limit");
settings_replacements.emplace("NET_WRITE_TIMEOUT", "send_timeout");
settings_replacements.emplace("NET_READ_TIMEOUT", "receive_timeout");
}
MySQLHandler::~MySQLHandler() = default;
void MySQLHandler::run()
{
DB::setThreadName(ThreadName::MYSQL_HANDLER);
session = std::make_unique<Session>(server.context(), ClientInfo::Interface::MYSQL);
SCOPE_EXIT({ session.reset(); });
session->setClientConnectionId(connection_id);
const Settings & settings = server.context()->getSettingsRef();
socket().setReceiveTimeout(settings[Setting::receive_timeout]);
socket().setSendTimeout(settings[Setting::send_timeout]);
in = std::make_shared<ReadBufferFromPocoSocket>(socket(), read_event);
out = std::make_shared<AutoCanceledWriteBuffer<WriteBufferFromPocoSocket>>(socket(), write_event);
packet_endpoint = std::make_shared<MySQLProtocol::PacketEndpoint>(*in, *out, sequence_id);
try
{
Handshake handshake(server_capabilities, connection_id, VERSION_STRING + String("-") + VERSION_NAME,
auth_plugin->getName(), auth_plugin->getAuthPluginData(), CharacterSet::utf8mb4_0900_ai_ci);
packet_endpoint->sendPacket<Handshake>(handshake);
LOG_TRACE(log, "Sent handshake");
HandshakeResponse handshake_response;
finishHandshake(handshake_response);
client_capabilities = handshake_response.capability_flags;
max_packet_size = handshake_response.max_packet_size ? handshake_response.max_packet_size : MAX_PACKET_LENGTH;
LOG_TRACE(log,
"Capabilities: {}, max_packet_size: {}, character_set: {}, user: {}, auth_response length: {}, database: {}, auth_plugin_name: {}",
handshake_response.capability_flags,
handshake_response.max_packet_size,
static_cast<int>(handshake_response.character_set),
handshake_response.username,
handshake_response.auth_response.length(),
handshake_response.database,
handshake_response.auth_plugin_name);
if (!(client_capabilities & CLIENT_PROTOCOL_41))
throw Exception(ErrorCodes::MYSQL_CLIENT_INSUFFICIENT_CAPABILITIES, "Required capability: CLIENT_PROTOCOL_41.");
/// Check the actual state of the transport, not the capability bit advertised by the client:
/// a client can set `CLIENT_SSL` in a plaintext `HandshakeResponse` without ever sending an
/// `SSLRequest`, and then the connection stays unencrypted.
if (secure_required && !secure_connection)
throw Exception(ErrorCodes::OPENSSL_ERROR, "SSL connection required.");
/// An empty user name means the default session user: the `default_session_user`
/// server setting, possibly overridden for this listener in the `protocols` section.
/// If the resolved name is empty too (explicitly configured to prohibit connections
/// without a user name), authentication fails on the empty user name below.
if (handshake_response.username.empty())
handshake_response.username = default_session_user
? *default_session_user
: String(server.context()->getServerSettings()[ServerSetting::default_session_user]);
if (handshake_response.username.empty())
{
auto exception = Exception(ErrorCodes::AUTHENTICATION_FAILED, "Got an empty user name from MySQL handshake");
session->onAuthenticationFailure(handshake_response.username, socket().peerAddress(), exception);
packet_endpoint->sendPacket(ERRPacket(exception.code(), mysql_error_code, exception.message()));
return;
}
authenticate(handshake_response.username, handshake_response.auth_plugin_name, handshake_response.auth_response);
try
{
session->makeSessionContext();
session->sessionContext()->setDefaultFormat("MySQLWire");
if (!handshake_response.database.empty())
{
/// `database` is a real setting, so enforce its constraints on the handshake database
/// too, consistently with `USE`, `SET database = ...` and the HTTP `?database=...`
/// parameter.
SettingsChanges database_change;
database_change.setSetting("database", handshake_response.database);
session->sessionContext()->checkSettingsConstraints(database_change, SettingSource::QUERY);
session->sessionContext()->setCurrentDatabase(handshake_response.database);
}
}
catch (const Exception & exc)
{
log->log(exc);
packet_endpoint->sendPacket(ERRPacket(exc.code(), mysql_error_code, exc.message()));
}
OKPacket ok_packet(0, handshake_response.capability_flags, 0, 0, 0);
packet_endpoint->sendPacket(ok_packet);
while (tcp_server.isOpen())
{
packet_endpoint->resetSequenceId();
MySQLPacketPayloadReadBuffer payload = packet_endpoint->getPayload();
while (!in->poll(1000000))
if (!tcp_server.isOpen())
return;
char command = 0;
payload.readStrict(command);
// For commands which are executed without MemoryTracker.
LimitReadBuffer limited_payload(payload, {.read_no_more = 1000, .expect_eof = true, .excetion_hint = "too long MySQL packet."});
LOG_DEBUG(log, "Received command: {}. Connection id: {}.",
static_cast<int>(static_cast<unsigned char>(command)), connection_id);
if (!tcp_server.isOpen())
return;
try
{
switch (command)
{
case COM_QUIT:
return;
case COM_INIT_DB:
comInitDB(limited_payload);
break;
case COM_QUERY:
comQuery(payload, false);
break;
case COM_FIELD_LIST:
comFieldList(limited_payload);
break;
case COM_PING:
comPing();
break;
case COM_STMT_PREPARE:
comStmtPrepare(payload);
break;
case COM_STMT_EXECUTE:
comStmtExecute(payload);
break;
case COM_STMT_CLOSE:
comStmtClose(payload);
break;
default:
throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Command {} is not implemented.", command);
}
}
catch (const NetException & exc)
{
log->log(exc);
throw;
}
catch (...)
{
tryLogCurrentException(log, "MySQLHandler: Cannot read packet: ");
packet_endpoint->sendPacket(ERRPacket(getCurrentExceptionCode(), mysql_error_code, getCurrentExceptionMessage(false)));
}
}
}
catch (const Poco::Exception & exc)
{
log->log(exc);
}
}
/** Reads 3 bytes, finds out whether it is SSLRequest or HandshakeResponse packet, starts secure connection, if it is SSLRequest.
* Reading is performed from socket instead of ReadBuffer to prevent reading part of SSL handshake.
* If we read it from socket, it will be impossible to start SSL connection using Poco. Size of SSLRequest packet payload is 32 bytes, thus we can read at most 36 bytes.
*/
void MySQLHandler::finishHandshake(MySQLProtocol::ConnectionPhase::HandshakeResponse & packet)
{
size_t packet_size = PACKET_HEADER_SIZE + SSL_REQUEST_PAYLOAD_SIZE;
/// Buffer for SSLRequest or part of HandshakeResponse.
std::vector<char> buf(packet_size);
size_t pos = 0;
/// Reads at least count and at most packet_size bytes.
auto read_bytes = [this, &buf, &pos, &packet_size](size_t count) -> void {
while (pos < count)
{
int ret = socket().receiveBytes(buf.data() + pos, static_cast<uint32_t>(packet_size - pos));
if (ret == 0)
{
throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read all data. Bytes read: {}. Bytes expected: 3", std::to_string(pos));
}
pos += ret;
}
};
read_bytes(3); /// We can find out whether it is SSLRequest of HandshakeResponse by first 3 bytes.
size_t payload_size = unalignedLoad<uint32_t>(buf.data()) & 0xFFFFFFu;
LOG_TRACE(log, "payload size: {}", payload_size);
if (payload_size == SSL_REQUEST_PAYLOAD_SIZE)
{
finishHandshakeSSL(packet_size, buf.data(), pos, read_bytes, packet);
}
else
{
if (payload_size > MAX_HANDSHAKE_RESPONSE_PAYLOAD_SIZE)
throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT,
"Handshake response declares a payload of {} bytes, while it must be at most {} bytes",
payload_size, MAX_HANDSHAKE_RESPONSE_PAYLOAD_SIZE);
/// Reading rest of HandshakeResponse.
packet_size = PACKET_HEADER_SIZE + payload_size;
WriteBufferFromOwnString buf_for_handshake_response;
buf_for_handshake_response.write(buf.data(), pos);
copyData(*packet_endpoint->in, buf_for_handshake_response, packet_size - pos);
ReadBufferFromString payload(buf_for_handshake_response.str());
payload.ignore(PACKET_HEADER_SIZE);
packet.readPayloadWithUnpacked(payload);
packet_endpoint->sequence_id++;
}
}
void MySQLHandler::authenticate(const String & user_name, const String & auth_plugin_name, const String & initial_auth_response)
{
try
{
const auto user_authentication_types = session->getAuthenticationTypesOrLogInFailure(user_name);
for (const auto user_authentication_type : user_authentication_types)
{
// For compatibility with JavaScript MySQL client, Native41 authentication plugin is used when possible
// (if password is specified using double SHA1). Otherwise, SHA256 plugin is used.
if (user_authentication_type == DB::AuthenticationType::SHA256_PASSWORD)
{
authPluginSSL();
}
}
std::optional<String> auth_response = auth_plugin_name == auth_plugin->getName() ? std::make_optional<String>(initial_auth_response) : std::nullopt;
auth_plugin->authenticate(user_name, *session, auth_response, packet_endpoint, secure_connection, socket().peerAddress());
}
catch (const Exception & exc)
{
LOG_ERROR(log, "Authentication for user {} failed.", user_name);
packet_endpoint->sendPacket(ERRPacket(exc.code(), mysql_error_code, exc.message()));
throw;
}
LOG_DEBUG(log, "Authentication for user {} succeeded.", user_name);
}
void MySQLHandler::comInitDB(ReadBuffer & payload)
{
String database;
readStringUntilEOF(database, payload);
LOG_DEBUG(log, "Setting current database to {}", database);
/// Mirror the access check of the SQL `USE database` statement (InterpreterUseQuery).
session->sessionContext()->checkAccess(AccessType::SHOW_DATABASES, database);
/// ... and its settings-constraint check on the `database` setting.
SettingsChanges database_change;
database_change.setSetting("database", database);
session->sessionContext()->checkSettingsConstraints(database_change, SettingSource::QUERY);
session->sessionContext()->setCurrentDatabase(database);
packet_endpoint->sendPacket(OKPacket(0, client_capabilities, 0, 0, 1));
}
void MySQLHandler::comFieldList(ReadBuffer & payload)
{
ComFieldList packet;
packet.readPayloadWithUnpacked(payload);
const auto session_context = session->sessionContext();
String database = session_context->getCurrentDatabase();
/// Mirror the access check of the SQL `DESCRIBE`/`SHOW COLUMNS` statements (InterpreterDescribeQuery).
/// Check before getTable() so this command does not become a table-existence oracle.
session_context->checkAccess(AccessType::SHOW_COLUMNS, database, packet.table);
StoragePtr table_ptr = DatabaseCatalog::instance().getTable({database, packet.table}, session_context);
auto metadata_snapshot = table_ptr->getInMemoryMetadataPtr(session_context, false);
for (const NameAndTypePair & column : metadata_snapshot->getColumns().getAll())
{
/// Report the same type, charset and flags as result-set metadata (`getColumnDefinition`) does
/// for this column, so `COM_FIELD_LIST` and a plain `SELECT` describe the column identically:
/// string columns as `utf8mb4_0900_ai_ci` strings (matching the handshake collation),
/// numeric and other non-string columns as `binary` with their native wire types.
ColumnDefinition type_definition = getColumnDefinition(column.name, column.type);
ColumnDefinition column_definition(
database, packet.table, packet.table, column.name, column.name,
type_definition.character_set, type_definition.column_length, type_definition.column_type,
type_definition.flags, type_definition.decimals, true
);
packet_endpoint->sendPacket(column_definition);
}
packet_endpoint->sendPacket(OKPacket(0xfe, client_capabilities, 0, 0, 0));
}
void MySQLHandler::comPing()
{
packet_endpoint->sendPacket(OKPacket(0x0, client_capabilities, 0, 0, 0));
}
void MySQLHandler::comQuery(ReadBuffer & payload, bool binary_protocol)
{
String query = String(payload.position(), payload.buffer().end());
// This is a workaround in order to support adding ClickHouse to MySQL using federated server.
// As ClickHouse doesn't support these statements, we just send OK packet in response.
if (isFederatedServerSetupSetCommand(query))
{
packet_endpoint->sendPacket(OKPacket(0x00, client_capabilities, 0, 0, 0));
}
else
{
String replacement_query;
bool should_replace = false;
bool with_output = false;
// Queries replacements
for (auto const & [query_to_replace, replacement_fn] : queries_replacements)
{
if (checkShouldReplaceQuery(query, query_to_replace))
{
should_replace = true;
replacement_query = replacement_fn(query);
break;
}
}
// Settings replacements
if (!should_replace)
{
for (auto const & [mysql_setting, clickhouse_setting] : settings_replacements)
{
const auto replacement_query_opt = setSettingReplacementQuery(query, mysql_setting, clickhouse_setting);
if (replacement_query_opt.has_value())
{
should_replace = true;
replacement_query = replacement_query_opt.value();
break;
}
}
}
auto query_context = session->makeQueryContext();
query_context->setCurrentQueryId(fmt::format("mysql:{}:{}", connection_id, toString(UUIDHelpers::generateV4())));
/// --- Workaround for Bug 56173.
auto settings = query_context->getSettingsCopy();
if (!settings[Setting::allow_experimental_analyzer])
{
settings[Setting::prefer_column_name_to_alias] = true;
query_context->setSettings(settings);
}
/// Update timeouts
socket().setReceiveTimeout(settings[Setting::receive_timeout]);
socket().setSendTimeout(settings[Setting::send_timeout]);
QueryScope query_scope = QueryScope::create(query_context);
std::atomic<size_t> affected_rows {0};
auto prev = query_context->getProgressCallback();
query_context->setProgressCallback([&, my_prev = prev](const Progress & progress)
{
if (my_prev)
my_prev(progress);
affected_rows += progress.written_rows;
});
FormatSettings format_settings;
format_settings.mysql_wire.client_capabilities = client_capabilities;
format_settings.mysql_wire.max_packet_size = max_packet_size;
format_settings.mysql_wire.sequence_id = &sequence_id;
format_settings.mysql_wire.binary_protocol = binary_protocol;
auto set_result_details = [&with_output](const QueryResultDetails & details)
{
if (details.format)
{
if (*details.format != "MySQLWire")
throw Exception(ErrorCodes::UNSUPPORTED_METHOD, "MySQL protocol does not support custom output formats");
with_output = true;
}
};
if (should_replace)
{
ReadBufferFromString replacement(replacement_query);
executeQuery(replacement, *out, query_context, set_result_details, QueryFlags{}, format_settings);
}
else
executeQuery(payload, *out, query_context, set_result_details, QueryFlags{}, format_settings);
if (!with_output)
packet_endpoint->sendPacket(OKPacket(0x00, client_capabilities, affected_rows, 0, 0));
}
}
void MySQLHandler::comStmtPrepare(DB::ReadBuffer & payload)
{
String statement;
readStringUntilEOF(statement, payload);
auto statement_id_opt = emplacePreparedStatement(std::move(statement));
if (statement_id_opt.has_value())
packet_endpoint->sendPacket(PreparedStatementResponseOK(statement_id_opt.value(), 0, 0, 0));
else
packet_endpoint->sendPacket(ERRPacket());
}
void MySQLHandler::comStmtExecute(ReadBuffer & payload)
{
uint32_t statement_id = 0;
payload.readStrict(reinterpret_cast<char *>(&statement_id), 4);
auto statement_opt = getPreparedStatement(statement_id);
if (statement_opt.has_value())
MySQLHandler::comQuery(statement_opt.value(), true);
else
packet_endpoint->sendPacket(ERRPacket());
};
void MySQLHandler::comStmtClose(ReadBuffer & payload)
{
uint32_t statement_id = 0;
payload.readStrict(reinterpret_cast<char *>(&statement_id), 4);
// https://dev.mysql.com/doc/dev/mysql-server/latest/page_protocol_com_stmt_close.html
// No response packet is sent back to the client.
erasePreparedStatement(statement_id);
};
std::optional<UInt32> MySQLHandler::emplacePreparedStatement(String statement)
{
static constexpr size_t MAX_PREPARED_STATEMENTS = 10'000;
std::lock_guard<std::mutex> lock(prepared_statements_mutex);
if (prepared_statements.size() > MAX_PREPARED_STATEMENTS) /// Shouldn't happen in reality as COM_STMT_CLOSE cleans up the elements
{
LOG_ERROR(log, "Too many prepared statements");
current_prepared_statement_id = 0;
prepared_statements.clear();
return {};
}
uint32_t statement_id = current_prepared_statement_id;
++current_prepared_statement_id;
// Key collisions should not happen here, as we remove the elements from the map with COM_STMT_CLOSE,
// and we have quite a big range of available identifiers with 32-bit unsigned integer
if (prepared_statements.contains(statement_id))
{
LOG_ERROR(
log,
"Failed to store a new statement `{}` with id {}; it is already taken by `{}`",
statement,
statement_id,
prepared_statements.at(statement_id));
return {};
}
prepared_statements.emplace(statement_id, statement);