-
Notifications
You must be signed in to change notification settings - Fork 9k
Expand file tree
/
Copy pathPostgreSQLHandler.cpp
More file actions
1611 lines (1444 loc) · 67.8 KB
/
Copy pathPostgreSQLHandler.cpp
File metadata and controls
1611 lines (1444 loc) · 67.8 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 <algorithm>
#include <memory>
#include <optional>
#include <string_view>
#include <vector>
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
#include <Server/PostgreSQLHandler.h>
#include <IO/ReadBufferFromPocoSocket.h>
#include <IO/ReadBufferFromString.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteBufferFromPocoSocket.h>
#include <IO/WriteBuffer.h>
#include <IO/WriteHelpers.h>
#include <Interpreters/Context.h>
#include <Interpreters/ProcessList.h>
#include <Interpreters/executeQuery.h>
#include <Parsers/Lexer.h>
#include <Parsers/parseQuery.h>
#include <Poco/Util/LayeredConfiguration.h>
#include <Server/TCPServer.h>
#include <base/scope_guard.h>
#include <Common/Exception.h>
#include <Common/ErrnoException.h>
#include <Common/CurrentThread.h>
#include <Common/QueryScope.h>
#include <Common/SettingSource.h>
#include <Common/SettingsChanges.h>
#include <Common/StringUtils.h>
#include <Common/config_version.h>
#include <Common/setThreadName.h>
#include <Core/PostgreSQLProtocol.h>
#include <IO/WriteBufferFromString.h>
#include <Parsers/ASTCopyQuery.h>
#include <Parsers/ParserCopyQuery.h>
#include <Core/ServerSettings.h>
#include <Core/Settings.h>
#include <Interpreters/InterpreterInsertQuery.h>
#include <Parsers/ASTIdentifier.h>
#include <Parsers/ParserQuery.h>
#include <fmt/format.h>
#include <Formats/FormatFactory.h>
#include <Processors/Executors/PullingPipelineExecutor.h>
#include <Processors/Executors/PushingPipelineExecutor.h>
#include <Processors/Formats/IInputFormat.h>
#include <Processors/Formats/IOutputFormat.h>
#if USE_SSL
# include <Common/OpenSSLHelpers.h>
# include <Server/CertificateReloader.h>
# include <Poco/Net/SSLManager.h>
# include <Poco/Net/SecureStreamSocket.h>
# include <Poco/Net/Utility.h>
# include <Poco/StringTokenizer.h>
# include <openssl/rand.h>
#endif
namespace DB
{
namespace Setting
{
extern const SettingsBool allow_settings_after_format_in_insert;
extern const SettingsUInt64 max_parser_backtracks;
extern const SettingsUInt64 max_parser_depth;
extern const SettingsUInt64 max_query_size;
extern const SettingsBool implicit_select;
extern const SettingsNonZeroUInt64 max_insert_block_size;
extern const SettingsUInt64 max_insert_block_size_bytes;
extern const SettingsUInt64 min_insert_block_size_rows;
extern const SettingsUInt64 min_insert_block_size_bytes;
}
namespace ServerSetting
{
extern const ServerSettingsString default_session_user;
}
namespace ErrorCodes
{
extern const int AUTHENTICATION_FAILED;
extern const int BAD_ARGUMENTS;
extern const int CANNOT_OPEN_FILE;
extern const int CANNOT_READ_ALL_DATA;
extern const int NOT_IMPLEMENTED;
extern const int SYNTAX_ERROR;
extern const int OPENSSL_ERROR;
extern const int UNEXPECTED_PACKET_FROM_CLIENT;
extern const int UNKNOWN_PACKET_FROM_CLIENT;
}
namespace
{
UInt32 generateRandomUInt32()
{
UInt32 secret_key = 0;
#if USE_SSL
if (RAND_bytes(reinterpret_cast<unsigned char *>(&secret_key), sizeof(secret_key)) != 1)
throw Exception(ErrorCodes::OPENSSL_ERROR, "RAND_bytes failed: {}", getOpenSSLErrors());
#else
const int random_fd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);
if (random_fd == -1)
throw ErrnoException(ErrorCodes::CANNOT_OPEN_FILE, "Cannot open /dev/urandom");
SCOPE_EXIT({ [[maybe_unused]] int err = ::close(random_fd); });
auto * position = reinterpret_cast<char *>(&secret_key);
size_t bytes_remaining = sizeof(secret_key);
while (bytes_remaining > 0)
{
ssize_t bytes_read = ::read(random_fd, position, bytes_remaining);
if (bytes_read == -1)
{
if (errno == EINTR)
continue;
throw ErrnoException(ErrorCodes::CANNOT_READ_ALL_DATA, "Cannot read from /dev/urandom");
}
if (bytes_read == 0)
throw Exception(ErrorCodes::CANNOT_READ_ALL_DATA, "Unexpected end of /dev/urandom");
position += bytes_read;
bytes_remaining -= bytes_read;
}
#endif
return secret_key;
}
/// Some PostgreSQL drivers issue session-management commands during connection
/// setup or teardown that have no ClickHouse equivalent, for example `RESET ALL`
/// and `UNLISTEN *` sent by the Skunk driver. Instead of failing such a command
/// with a syntax error, ClickHouse accepts it as a no-op and replies with a
/// `CommandComplete` carrying the matching PostgreSQL command tag. See issue
/// https://github.com/ClickHouse/ClickHouse/issues/12476.
///
/// Returns the command tag to report if `query` is such a no-op command, or
/// std::nullopt if the query must be executed normally. None of the recognized
/// keywords (`UNLISTEN`, `RESET`, `DISCARD`) is a valid ClickHouse statement
/// start, so there are no false positives.
///
/// This is applied only in the simple-query (`Q`) protocol path, consistent with the other
/// driver-compatibility no-ops (`BEGIN` / `COMMIT` / `SET application_name`): drivers emit these
/// session-management commands as plain, unparameterized statements, so there is no reason to run
/// them through the extended `Parse` / `Bind` / `Execute` flow, and the extended path deliberately
/// performs no such driver-specific rewriting.
std::optional<String> classifyNoOpDriverCommand(const String & query)
{
/// Only treat the packet as a no-op when it consists of a single statement. A simple-query
/// packet may contain several `;`-separated statements; if we shortcut on the leading keyword
/// we would acknowledge the whole packet and silently skip the rest (e.g. `RESET ALL; SELECT 1`
/// or, worse, `RESET ALL; DROP TABLE t`). An interior `;` — anything other than trailing
/// whitespace after it — means there is more than one statement, so bail out and let the normal
/// multi-statement splitter handle it.
if (const size_t semicolon = query.find(';'); semicolon != String::npos)
{
for (size_t i = semicolon + 1; i < query.size(); ++i)
{
const char c = query[i];
if (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != '\f' && c != '\v')
return std::nullopt;
}
}
/// Enough to cover the longest recognized command plus its argument: a PostgreSQL identifier
/// is at most 63 bytes, and a qualified `RESET extension.setting` name consists of two of them.
/// If the normalized prefix fills this budget completely, the statement may continue beyond it,
/// so we could not verify that nothing trails the argument — treat it as not recognized.
static constexpr size_t max_prefix_len = 160;
String prefix = PostgreSQLProtocol::Messaging::CommandComplete::extractNormalizedPrefix(query, max_prefix_len);
if (prefix.size() == max_prefix_len)
return std::nullopt;
/// The multi-statement guard above rejected any statement after an interior `;`, so the only
/// `;` that can remain is a single trailing one (with trailing whitespace already collapsed).
/// Drop it so it is not mistaken for a command argument below.
while (!prefix.empty() && (prefix.back() == ';' || prefix.back() == ' '))
prefix.pop_back();
/// `extractNormalizedPrefix` already uppercased the text and collapsed runs of
/// whitespace to single spaces, so a keyword is a run of 'A'..'Z'. Take the next
/// such run, skipping a leading space; this also stops at a `;` or `*`.
size_t pos = 0;
const auto take_word = [&]() -> String
{
while (pos < prefix.size() && prefix[pos] == ' ')
++pos;
const size_t start = pos;
while (pos < prefix.size() && prefix[pos] >= 'A' && prefix[pos] <= 'Z')
++pos;
return prefix.substr(start, pos - start);
};
const auto has_more = [&]() -> bool
{
while (pos < prefix.size() && prefix[pos] == ' ')
++pos;
return pos < prefix.size();
};
/// An argument in the normalized prefix: an identifier — a letter or `_` followed by letters,
/// digits, `_` or `$` (the text is already uppercased). With `allow_dots`, a qualified name
/// such as `EXTENSION.SETTING` (for `RESET`) is a single token as well.
const auto take_identifier = [&](bool allow_dots) -> String
{
while (pos < prefix.size() && prefix[pos] == ' ')
++pos;
const size_t start = pos;
if (pos < prefix.size() && ((prefix[pos] >= 'A' && prefix[pos] <= 'Z') || prefix[pos] == '_'))
{
++pos;
while (pos < prefix.size()
&& ((prefix[pos] >= 'A' && prefix[pos] <= 'Z') || (prefix[pos] >= '0' && prefix[pos] <= '9')
|| prefix[pos] == '_' || prefix[pos] == '$' || (allow_dots && prefix[pos] == '.')))
++pos;
}
return prefix.substr(start, pos - start);
};
/// Not `const`: the early returns below move it out, and `performance-no-automatic-move`
/// (clang-tidy) rejects returning a `const` local because constness prevents the move.
String command = take_word();
/// The keyword must end at a word boundary: `RESET1FOO` must not be taken for `RESET`.
if (pos < prefix.size() && prefix[pos] != ' ')
return std::nullopt;
/// Accept the connection-cleanup commands the Skunk driver actually sends: `RESET { name | ALL }`
/// and `UNLISTEN { channel | * }`, reporting the bare keyword as the tag. `LISTEN` and `NOTIFY`
/// are deliberately NOT accepted here: unlike `UNLISTEN` (idempotent unsubscribe-all cleanup),
/// they are application-visible PostgreSQL pub/sub operations, and this handler never delivers a
/// `NotificationResponse`, so acknowledging them would turn an unsupported feature into a silent
/// false success instead of a plain error. Issue #12476 only asks for `UNLISTEN *` / `RESET ALL`.
///
/// Accept exactly one argument — an identifier (for `RESET` possibly a qualified
/// `extension.setting` name; `ALL` is itself covered as an identifier), or `*` for `UNLISTEN` —
/// and require the statement to end right after it, so that malformed variants such as a bare
/// `RESET`, `RESET foo bar` or `UNLISTEN * garbage` are not acknowledged as success but fall
/// through to the normal error path. Valid forms that no driver is known to emit — quoted
/// identifiers and multi-word variants such as `RESET SESSION AUTHORIZATION` — likewise fall
/// through, as before this change.
if (command == "UNLISTEN" || command == "RESET")
{
String arg;
if (command == "UNLISTEN" && has_more() && prefix[pos] == '*')
{
arg = "*";
++pos;
}
else
{
arg = take_identifier(/* allow_dots = */ command == "RESET");
}
if (arg.empty() || has_more())
return std::nullopt;
return command;
}
if (command == "DISCARD")
{
/// PostgreSQL accepts only `DISCARD { ALL | PLANS | SEQUENCES | TEMP | TEMPORARY }`
/// (with `TEMPORARY` normalized to `TEMP`). Reject a bare `DISCARD` or an unknown
/// subcommand such as `DISCARD FOO` instead of claiming success for a command we were
/// never asked to emulate.
String arg = take_word();
if (arg == "TEMPORARY")
arg = "TEMP";
if ((arg == "ALL" || arg == "PLANS" || arg == "SEQUENCES" || arg == "TEMP") && !has_more())
return command + " " + arg;
return std::nullopt;
}
return std::nullopt;
}
}
PostgreSQLHandler::PostgreSQLHandler(
const Poco::Net::StreamSocket & socket_,
#if USE_SSL
const std::string & prefix_,
#endif
IServer & server_,
TCPServer & tcp_server_,
bool ssl_enabled_,
bool secure_required_,
Int32 connection_id_,
std::optional<String> default_session_user_,
VectorWithMemoryTracking<std::shared_ptr<PostgreSQLProtocol::PGAuthentication::AuthenticationMethod>> & auth_methods_,
const ProfileEvents::Event & read_event_,
const ProfileEvents::Event & write_event_)
: Poco::Net::TCPServerConnection(socket_)
#if USE_SSL
, config(server_.config())
, prefix(prefix_)
#endif
, server(server_)
, tcp_server(tcp_server_)
, ssl_enabled(ssl_enabled_)
, secure_required(secure_required_)
, connection_id(connection_id_)
, default_session_user(std::move(default_session_user_))
, read_event(read_event_)
, write_event(write_event_)
, authentication_manager(auth_methods_)
, prepared_statements_manager(std::nullopt)
{
/// `BackendKeyData` identifies every statement on this connection for cancellation.
secret_key = generateRandomUInt32();
query_id_token = generateRandomUInt32();
changeIO(socket());
#if USE_SSL
params.privateKeyFile = config.getString(prefix + Poco::Net::SSLManager::CFG_PRIV_KEY_FILE, "");
params.certificateFile = config.getString(prefix + Poco::Net::SSLManager::CFG_CERTIFICATE_FILE, params.privateKeyFile);
if (!params.privateKeyFile.empty() && !params.certificateFile.empty())
{
params.caLocation = config.getString(prefix + Poco::Net::SSLManager::CFG_CA_LOCATION, "");
if (params.caLocation.empty())
{
auto ctx = Poco::Net::SSLManager::instance().defaultServerContext();
params.caLocation = ctx->getCAPaths().caLocation;
}
params.verificationMode = Poco::Net::SSLManager::VAL_VER_MODE;
if (config.hasProperty(prefix + Poco::Net::SSLManager::CFG_VER_MODE))
{
std::string mode = config.getString(prefix + Poco::Net::SSLManager::CFG_VER_MODE);
params.verificationMode = Poco::Net::Utility::convertVerificationMode(mode);
}
params.verificationDepth = config.getInt(prefix + Poco::Net::SSLManager::CFG_VER_DEPTH, Poco::Net::SSLManager::VAL_VER_DEPTH);
params.loadDefaultCAs
= config.getBool(prefix + Poco::Net::SSLManager::CFG_ENABLE_DEFAULT_CA, Poco::Net::SSLManager::VAL_ENABLE_DEFAULT_CA);
params.cipherList = config.getString(prefix + Poco::Net::SSLManager::CFG_CIPHER_LIST, Poco::Net::SSLManager::VAL_CIPHER_LIST);
params.cipherList
= config.getString(prefix + Poco::Net::SSLManager::CFG_CYPHER_LIST, params.cipherList); // for backwards compatibility
bool require_tlsv1 = config.getBool(prefix + Poco::Net::SSLManager::CFG_REQUIRE_TLSV1, false);
bool require_tlsv1_1 = config.getBool(prefix + Poco::Net::SSLManager::CFG_REQUIRE_TLSV1_1, false);
bool require_tlsv1_2 = config.getBool(prefix + Poco::Net::SSLManager::CFG_REQUIRE_TLSV1_2, false);
if (require_tlsv1_2)
usage = Poco::Net::Context::TLSV1_2_SERVER_USE;
else if (require_tlsv1_1)
usage = Poco::Net::Context::TLSV1_1_SERVER_USE;
else if (require_tlsv1)
usage = Poco::Net::Context::TLSV1_SERVER_USE;
else
usage = Poco::Net::Context::SERVER_USE;
params.dhParamsFile = config.getString(prefix + Poco::Net::SSLManager::CFG_DH_PARAMS_FILE, "");
params.ecdhCurve = config.getString(prefix + Poco::Net::SSLManager::CFG_ECDH_CURVE, "");
std::string disabled_protocols_list = config.getString(prefix + Poco::Net::SSLManager::CFG_DISABLE_PROTOCOLS, "");
Poco::StringTokenizer dp_tok(
disabled_protocols_list, ";,", Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY);
disabled_protocols = 0;
for (const auto & token : dp_tok)
{
if (token == "sslv2")
disabled_protocols |= Poco::Net::Context::PROTO_SSLV2;
else if (token == "sslv3")
disabled_protocols |= Poco::Net::Context::PROTO_SSLV3;
else if (token == "tlsv1")
disabled_protocols |= Poco::Net::Context::PROTO_TLSV1;
else if (token == "tlsv1_1")
disabled_protocols |= Poco::Net::Context::PROTO_TLSV1_1;
else if (token == "tlsv1_2")
disabled_protocols |= Poco::Net::Context::PROTO_TLSV1_2;
else if (token == "tlsv1_3")
disabled_protocols |= Poco::Net::Context::PROTO_TLSV1_3;
}
extended_verification = config.getBool(prefix + Poco::Net::SSLManager::CFG_EXTENDED_VERIFICATION, false);
prefer_server_ciphers = config.getBool(prefix + Poco::Net::SSLManager::CFG_PREFER_SERVER_CIPHERS, false);
}
#endif
}
void PostgreSQLHandler::changeIO(Poco::Net::StreamSocket & socket)
{
in = std::make_shared<ReadBufferFromPocoSocket>(socket, read_event);
out = std::make_shared<AutoCanceledWriteBuffer<WriteBufferFromPocoSocket>>(socket, write_event);
message_transport = std::make_shared<PostgreSQLProtocol::Messaging::MessageTransport>(in.get(), out.get());
}
void PostgreSQLHandler::run()
{
DB::setThreadName(ThreadName::POSTGRES_HANDLER);
session = std::make_unique<Session>(server.context(), ClientInfo::Interface::POSTGRESQL);
SCOPE_EXIT({ session.reset(); });
session->setClientConnectionId(connection_id);
/// A `CancelRequest` for this connection arrives on a different connection, so the secret has
/// to be reachable from the whole server for as long as this one is open.
server.context()->getProcessList().registerPostgreSQLCancellationKey(connection_id, secret_key, currentQueryId());
SCOPE_EXIT({ server.context()->getProcessList().unregisterPostgreSQLCancellationKey(connection_id, secret_key); });
try
{
if (!startup())
return;
/// Emit `ReadyForQuery` only at explicit protocol boundaries.
need_ready_for_query = true;
while (tcp_server.isOpen())
{
if (need_ready_for_query)
{
message_transport->send(PostgreSQLProtocol::Messaging::ReadyForQuery(), true);
need_ready_for_query = false;
}
constexpr size_t connection_check_timeout = 1; // 1 second
while (!in->poll(1000000 * connection_check_timeout))
if (!tcp_server.isOpen())
return;
PostgreSQLProtocol::Messaging::FrontMessageType message_type = message_transport->receiveMessageType();
if (!tcp_server.isOpen())
return;
/// After an extended-query error, discard through `Sync` but honor `Terminate`.
if (ignore_until_sync
&& message_type != PostgreSQLProtocol::Messaging::FrontMessageType::SYNC
&& message_type != PostgreSQLProtocol::Messaging::FrontMessageType::TERMINATE)
{
message_transport->dropMessage();
continue;
}
switch (message_type)
{
case PostgreSQLProtocol::Messaging::FrontMessageType::QUERY:
/// A simple query is a complete protocol cycle, and it also destroys the
/// unnamed prepared statement and the unnamed portal.
in_extended_query_cycle = false;
prepared_statements_manager.dropUnnamedStatementAndPortal();
processQuery();
need_ready_for_query = true;
message_transport->flush();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::TERMINATE:
LOG_DEBUG(log, "Client closed the connection");
return;
case PostgreSQLProtocol::Messaging::FrontMessageType::PARSE:
/// An extended-query cycle ends at its `Sync` or at a simple query.
in_extended_query_cycle = true;
processParseQuery();
message_transport->flush();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::BIND:
in_extended_query_cycle = true;
processBindQuery();
message_transport->flush();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::EXECUTE:
in_extended_query_cycle = true;
processExecuteQuery();
message_transport->flush();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::SYNC:
/// `Sync` ends the cycle and produces one `ReadyForQuery`.
in_extended_query_cycle = false;
processSyncQuery();
need_ready_for_query = true;
message_transport->flush();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::DESCRIBE:
in_extended_query_cycle = true;
processDescribeQuery();
message_transport->flush();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::FLUSH:
message_transport->send(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::ERROR,
"0A000",
"ClickHouse doesn't support extended query mechanism"),
true);
LOG_ERROR(log, "Client tried to access via extended query protocol");
message_transport->dropMessage();
recoverFromRejectedMessage();
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::CLOSE:
in_extended_query_cycle = true;
processCloseQuery();
message_transport->flush();
break;
default:
message_transport->send(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::ERROR,
"0A000",
"Command is not supported"),
true);
LOG_ERROR(log, "Command is not supported. Command code {:d}", static_cast<Int32>(message_type));
message_transport->dropMessage();
recoverFromRejectedMessage();
}
}
}
catch (const Poco::Exception &exc)
{
log->log(exc);
}
}
void PostgreSQLHandler::recoverFromRejectedMessage()
{
/// A rejected message belonging to an extended-query cycle is recovered at that
/// cycle's `Sync`, which is where its `ReadyForQuery` comes from. Without an open
/// cycle there is no `Sync` to wait for, so the client is owed one right away.
if (in_extended_query_cycle)
ignore_until_sync = true;
else
need_ready_for_query = true;
}
bool PostgreSQLHandler::startup()
{
Int32 payload_size = 0;
Int32 info = 0;
establishSecureConnection(payload_size, info);
if (static_cast<PostgreSQLProtocol::Messaging::FrontMessageType>(info) == PostgreSQLProtocol::Messaging::FrontMessageType::CANCEL_REQUEST)
{
LOG_DEBUG(log, "Client issued request canceling");
cancelRequest();
return false;
}
std::unique_ptr<PostgreSQLProtocol::Messaging::StartupMessage> start_up_msg = receiveStartupMessage(payload_size);
/// 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 (start_up_msg->user.empty())
start_up_msg->user = default_session_user
? *default_session_user
: String(server.context()->getServerSettings()[ServerSetting::default_session_user]);
const auto & user_name = start_up_msg->user;
if (user_name.empty())
{
auto exception = Exception(ErrorCodes::AUTHENTICATION_FAILED, "Got an empty user name from PostgreSQL startup message");
session->onAuthenticationFailure(user_name, socket().peerAddress(), exception);
message_transport->send(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::ERROR, "28P01", "Invalid user or password"),
true);
return false;
}
authentication_manager.authenticate(user_name, *session, *message_transport, socket().peerAddress());
try
{
session->makeSessionContext();
session->sessionContext()->setDefaultFormat("PostgreSQLWire");
if (!start_up_msg->database.empty())
{
/// `database` is a real setting, so enforce its constraints on the startup-message
/// database too, consistently with `USE`, `SET database = ...` and the HTTP
/// `?database=...` parameter.
SettingsChanges database_change;
database_change.setSetting("database", start_up_msg->database);
session->sessionContext()->checkSettingsConstraints(database_change, SettingSource::QUERY);
session->sessionContext()->setCurrentDatabase(start_up_msg->database);
}
}
catch (const Exception & exc)
{
message_transport->send(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::ERROR, "XX000", exc.message()),
true);
throw;
}
sendParameterStatusData(*start_up_msg);
message_transport->send(
PostgreSQLProtocol::Messaging::BackendKeyData(connection_id, secret_key), true);
LOG_DEBUG(log, "Successfully finished Startup stage");
return true;
}
void PostgreSQLHandler::establishSecureConnection(Int32 & payload_size, Int32 & info)
{
bool was_secure_connection = false;
bool was_encryption_req = true;
readBinaryBigEndian(payload_size, *in);
readBinaryBigEndian(info, *in);
switch (static_cast<PostgreSQLProtocol::Messaging::FrontMessageType>(info))
{
case PostgreSQLProtocol::Messaging::FrontMessageType::SSL_REQUEST:
LOG_DEBUG(log, "Client requested SSL");
if (ssl_enabled)
{
was_secure_connection = true;
makeSecureConnectionSSL();
}
else
message_transport->send('N', true);
break;
case PostgreSQLProtocol::Messaging::FrontMessageType::GSSENC_REQUEST:
LOG_DEBUG(log, "Client requested GSSENC");
message_transport->send('N', true);
break;
default:
was_encryption_req = false;
}
if (was_encryption_req)
{
readBinaryBigEndian(payload_size, *in);
readBinaryBigEndian(info, *in);
}
if (secure_required && !was_secure_connection)
{
message_transport->send(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::ERROR, "XX000", "SSL connection required."),
true);
throw Exception(ErrorCodes::OPENSSL_ERROR, "SSL connection required.");
}
}
#if USE_SSL
void PostgreSQLHandler::makeSecureConnectionSSL()
{
message_transport->send('S', true);
Poco::Net::Context::Ptr ctx;
if (!params.privateKeyFile.empty() && !params.certificateFile.empty())
{
ctx = Poco::Net::SSLManager::instance().getCustomServerContext(prefix);
if (!ctx)
{
ctx = new Poco::Net::Context(usage, params);
ctx->disableProtocols(disabled_protocols);
ctx->enableExtendedCertificateVerification(extended_verification);
if (prefer_server_ciphers)
ctx->preferServerCiphers();
CertificateReloader::instance().tryLoad(config, ctx->sslContext(), prefix);
ctx = Poco::Net::SSLManager::instance().setCustomServerContext(prefix, ctx);
}
}
else
{
ctx = Poco::Net::SSLManager::instance().defaultServerContext();
}
ss = std::make_shared<Poco::Net::SecureStreamSocket>(Poco::Net::SecureStreamSocket::attach(socket(), ctx));
changeIO(*ss);
}
#else
void PostgreSQLHandler::makeSecureConnectionSSL() {}
#endif
void PostgreSQLHandler::sendParameterStatusData(PostgreSQLProtocol::Messaging::StartupMessage & start_up_message)
{
auto & parameters = start_up_message.parameters;
if (parameters.contains("application_name"))
message_transport->send(PostgreSQLProtocol::Messaging::ParameterStatus("application_name", parameters["application_name"]));
if (parameters.contains("client_encoding"))
message_transport->send(PostgreSQLProtocol::Messaging::ParameterStatus("client_encoding", parameters["client_encoding"]));
else
message_transport->send(PostgreSQLProtocol::Messaging::ParameterStatus("client_encoding", "UTF8"));
message_transport->send(PostgreSQLProtocol::Messaging::ParameterStatus("server_version", VERSION_STRING));
message_transport->send(PostgreSQLProtocol::Messaging::ParameterStatus("server_encoding", "UTF8"));
message_transport->send(PostgreSQLProtocol::Messaging::ParameterStatus("DateStyle", "ISO"));
message_transport->flush();
}
String PostgreSQLHandler::queryIdFor(Int32 connection_id_, UInt32 query_id_token_)
{
/// The random component is a token of its own and never the secret from `BackendKeyData`:
/// `system.processes` and `system.query_log` expose query IDs verbatim, while the secret
/// authenticates `CancelRequest`. It still has to be here, because a query ID that another
/// interface can predict can be occupied to keep a PostgreSQL statement from starting.
return fmt::format("postgres:{:d}:{:d}", connection_id_, query_id_token_);
}
String PostgreSQLHandler::currentQueryId() const
{
return queryIdFor(connection_id, query_id_token);
}
void PostgreSQLHandler::assignStatementQueryId(ContextMutablePtr query_context)
{
/// One statement, one query ID: a query ID may be held by only one query at a time across the
/// whole server, so an ID that outlived its statement would keep the next one from starting.
query_id_token = generateRandomUInt32();
const String query_id = currentQueryId();
query_context->setCurrentQueryId(query_id);
/// `CancelRequest` names the connection, so its entry has to follow the current statement.
server.context()->getProcessList().registerPostgreSQLCancellationKey(connection_id, secret_key, query_id);
}
void PostgreSQLHandler::cancelRequest()
{
std::unique_ptr<PostgreSQLProtocol::Messaging::CancelRequest> msg =
message_transport->receiveWithPayloadSize<PostgreSQLProtocol::Messaging::CancelRequest>(8);
/// The process ID and secret key authenticate this otherwise unauthenticated request.
/// PostgreSQL exposes no response, so report the outcome only to the log.
CancellationCode code = server.context()->getProcessList().sendCancelToPostgreSQLQuery(msg->process_id, msg->secret_key);
LOG_DEBUG(log, "Cancellation request for connection {}: {}", msg->process_id,
code == CancellationCode::CancelSent ? "sent" : "not sent");
}
inline std::unique_ptr<PostgreSQLProtocol::Messaging::StartupMessage> PostgreSQLHandler::receiveStartupMessage(int payload_size)
{
/// The declared size is read from the wire before any authentication, and the message is read
/// into memory in full, so it has to be bounded. PostgreSQL uses the same limit.
static constexpr Int32 max_startup_message_size = 10000;
std::unique_ptr<PostgreSQLProtocol::Messaging::StartupMessage> message;
try
{
if (payload_size < 8 || payload_size > max_startup_message_size)
throw Exception(ErrorCodes::UNKNOWN_PACKET_FROM_CLIENT,
"Startup message declares a size of {} bytes, while it must be between 8 and {} bytes",
payload_size, max_startup_message_size);
message = message_transport->receiveWithPayloadSize<PostgreSQLProtocol::Messaging::StartupMessage>(payload_size - 8);
}
catch (const Exception &)
{
message_transport->send(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse(
PostgreSQLProtocol::Messaging::ErrorOrNoticeResponse::ERROR, "08P01", "Can't correctly handle Startup message"),
true);
throw;
}
LOG_DEBUG(log, "Successfully received Startup message");
return message;
}
/// PostgreSQL clients qualify catalog tables and functions with the `pg_catalog`
/// schema, e.g. `pg_catalog.pg_class` or `pg_catalog.pg_table_is_visible(c.oid)`
/// (psql does so for the `\d` command). ClickHouse has no `pg_catalog` database:
/// the catalog tables are emulated with per-session temporary views
/// (see `initializeSystemTables`) and the functions are registered globally.
/// Removing the qualifier at the token level maps such queries onto them.
/// String literals are left intact - only a `pg_catalog` identifier that is not
/// itself qualified and is followed by a dot and another identifier is removed.
/// PostgreSQL folds unquoted identifiers to lower case, so a bare `PG_CATALOG` names
/// the same schema and is matched case-insensitively; a quoted identifier keeps its
/// case in PostgreSQL, so only the exact `"pg_catalog"` spelling is matched there.
static String removePgCatalogQualifier(const String & query)
{
static constexpr std::string_view pg_catalog = "pg_catalog";
/// A fast path for the common case of a query that does not mention the schema at all.
if (std::search(query.begin(), query.end(), pg_catalog.begin(), pg_catalog.end(),
[](char a, char b) { return equalsCaseInsensitive(a, b); }) == query.end())
return query;
std::vector<Token> tokens;
Lexer lexer(query.data(), query.data() + query.size());
for (Token token = lexer.nextToken(); !token.isEnd(); token = lexer.nextToken())
tokens.push_back(token);
auto is_pg_catalog = [](const Token & token)
{
std::string_view text(token.begin, token.size());
return (token.type == TokenType::BareWord && equalsCaseInsensitive(text, pg_catalog))
|| (token.type == TokenType::QuotedIdentifier && text == "\"pg_catalog\"");
};
auto next_significant = [&](size_t i) -> std::optional<size_t>
{
for (size_t j = i + 1; j < tokens.size(); ++j)
if (tokens[j].isSignificant())
return j;
return std::nullopt;
};
String result;
result.reserve(query.size());
std::optional<size_t> prev_emitted_significant;
for (size_t i = 0; i < tokens.size(); ++i)
{
const Token & token = tokens[i];
if (is_pg_catalog(token)
&& (!prev_emitted_significant || tokens[*prev_emitted_significant].type != TokenType::Dot))
{
auto dot = next_significant(i);
if (dot && tokens[*dot].type == TokenType::Dot)
{
auto after_dot = next_significant(*dot);
if (after_dot
&& (tokens[*after_dot].type == TokenType::BareWord || tokens[*after_dot].type == TokenType::QuotedIdentifier))
{
/// Skip the qualifier and the dot (and anything insignificant in between).
i = *dot;
continue;
}
}
}
result.append(token.begin, token.end);
if (token.isSignificant())
prev_emitted_significant = i;
}
return result;
}
bool PostgreSQLHandler::processCopyQuery(const String & query)
{
ParserCopyQuery parser_copy;
ASTPtr copy_query_parsed;
try
{
copy_query_parsed = parseQuery(parser_copy, query, 0, DBMS_DEFAULT_MAX_PARSER_DEPTH, DBMS_DEFAULT_MAX_PARSER_BACKTRACKS);
}
catch (const Exception &)
{
copy_query_parsed.reset();
}
/* The Postgres protocol for a copy query is different from simple queries such as SELECT.
* In the case of a COPY FROM request, the server sends CopyInResponse - a sign of readiness to receive data from the client.
* The client then sends CopyInData until all data has been sent.
* After this, the server sends a CommandComplete response.
* For more detailes see https://www.dolthub.com/blog/2024-09-17-tabular-data-imports/
*/
if (copy_query_parsed && copy_query_parsed->as<ASTCopyQuery>()->type == ASTCopyQuery::QueryType::COPY_FROM)
{
auto * copy_query = copy_query_parsed->as<ASTCopyQuery>();
auto query_context = session->makeQueryContext();
assignStatementQueryId(query_context);
QueryScope query_scope = QueryScope::create(query_context);
String columns_to_insert;
if (!copy_query->column_names.empty())
{
for (const auto & column_name : copy_query->column_names)
columns_to_insert += fmt::format("{}, ", column_name);
columns_to_insert.pop_back();
columns_to_insert.pop_back();
columns_to_insert = "(" + columns_to_insert + ")";
}
/// The parser has already quoted each part of `table_name`.
auto [ast, io] = executeQuery(fmt::format("INSERT INTO {} {} FROM INFILE 'psql_copy'", copy_query->table_name, columns_to_insert), query_context, {}, QueryProcessingStage::Enum::Complete);
chassert(io.pipeline.pushing());
auto executor = std::make_unique<PushingPipelineExecutor>(io.pipeline);
String format;
switch (copy_query->format)
{
case ASTCopyQuery::Formats::TSV:
format = "TSV";
break;
case ASTCopyQuery::Formats::CSV:
format = "CSV";
break;
case ASTCopyQuery::Formats::Binary:
format = "RowBinary";
break;
}
const Settings & settings = query_context->getSettingsRef();
message_transport->send(PostgreSQLProtocol::Messaging::CopyInResponse(), true);
executor->start();
while (true)
{
message_transport->flush();
PostgreSQLProtocol::Messaging::FrontMessageType message_type = message_transport->receiveMessageType();
if (message_type == PostgreSQLProtocol::Messaging::FrontMessageType::COPY_DATA)
{
std::unique_ptr<PostgreSQLProtocol::Messaging::CopyInData> data_query =
message_transport->receive<PostgreSQLProtocol::Messaging::CopyInData>();
ReadBufferFromString buf(data_query->query);
auto format_ptr = FormatFactory::instance().getInput(
format,
buf,
io.pipeline.getHeader(),
query_context,
settings[Setting::max_insert_block_size],
std::nullopt,
nullptr,
nullptr,
false,
CompressionMethod::None,
false,
settings[Setting::max_insert_block_size_bytes],
settings[Setting::min_insert_block_size_rows],
settings[Setting::min_insert_block_size_bytes]);
while (true)
{
auto chunk = format_ptr->generate();
if (chunk.empty())
break;
executor->push(std::move(chunk));
}
}
else if (message_type == PostgreSQLProtocol::Messaging::FrontMessageType::COPY_COMPLETION)
{
message_transport->receive<PostgreSQLProtocol::Messaging::CopyDone>();
executor->finish();
break;
}
else
{
executor->cancel();
throw Exception(ErrorCodes::BAD_ARGUMENTS, "Received incorrect message type - expected {} or {}, got {}", PostgreSQLProtocol::Messaging::FrontMessageType::COPY_DATA, PostgreSQLProtocol::Messaging::FrontMessageType::COPY_COMPLETION, message_type);
}
}
auto command = PostgreSQLProtocol::Messaging::CommandComplete::Command::COPY;
message_transport->send(PostgreSQLProtocol::Messaging::CommandComplete(command, 0), true);
return true;
}
/* In the case of a COPY TO request, the server calculates the number of columns and then sends it to the client in CopyOutResponse.
* After this, the server sends the data in a CopyOutData message, and when the data runs out, it sends a CopyCompletionResponse.
* For more detailes see https://www.dolthub.com/blog/2024-09-17-tabular-data-imports/
*/
if (copy_query_parsed && copy_query_parsed->as<ASTCopyQuery>()->type == ASTCopyQuery::QueryType::COPY_TO)
{
auto * copy_query = copy_query_parsed->as<ASTCopyQuery>();
auto query_context = session->makeQueryContext();
assignStatementQueryId(query_context);
QueryScope query_scope = QueryScope::create(query_context);
String columns_to_select = "*";
if (!copy_query->column_names.empty())
{
columns_to_select.clear();
for (const auto & column_name : copy_query->column_names)
columns_to_select += fmt::format("{}, ", column_name);
columns_to_select.pop_back();
columns_to_select.pop_back();
}
auto select_query = fmt::format("SELECT {} FROM {};", columns_to_select, copy_query->table_name);
auto [ast, io] = executeQuery(select_query, query_context, {}, QueryProcessingStage::Enum::Complete);
chassert(io.pipeline.pulling());
message_transport->send(PostgreSQLProtocol::Messaging::CopyOutResponse(static_cast<Int32>(io.pipeline.getHeader().columns())));
VectorWithMemoryTracking<char> result_buf;
WriteBufferFromVectorImpl<decltype(result_buf)> output_buffer(result_buf);
auto format_ptr = FormatFactory::instance().getOutputFormat(toString(copy_query->format), output_buffer, io.pipeline.getHeader(), query_context);
auto executor = std::make_unique<PullingPipelineExecutor>(io.pipeline);
Block block;
while (executor->pull(block))
{
output_buffer.restart(DBMS_DEFAULT_BUFFER_SIZE); // This will recreate moved vector
format_ptr->write(materializeBlock(block));
format_ptr->flush();
output_buffer.finalize();
message_transport->send(PostgreSQLProtocol::Messaging::CopyOutData(result_buf));
result_buf.clear();
}
message_transport->send(PostgreSQLProtocol::Messaging::CopyCompletionResponse(), true);
return true;
}
return false;
}
void PostgreSQLHandler::processQuery()
{
/// Output position before the currently executing statement. If a statement
/// fails when nothing has been sent for it yet, the session can be kept alive.
size_t out_bytes_before_statement = out->count();
try
{
std::unique_ptr<PostgreSQLProtocol::Messaging::Query> query =
message_transport->receive<PostgreSQLProtocol::Messaging::Query>();
if (isEmptyQuery(query->query))
{
message_transport->send(PostgreSQLProtocol::Messaging::EmptyQueryResponse());
return;
}
bool psycopg2_cond = query->query == "BEGIN" || query->query == "COMMIT"; // psycopg2 starts and ends queries with BEGIN/COMMIT commands
bool jdbc_cond = query->query.contains("SET extra_float_digits") || query->query.contains("SET application_name"); // jdbc starts with setting this parameter