-
Notifications
You must be signed in to change notification settings - Fork 874
Expand file tree
/
Copy pathNpgsqlConnector.cs
More file actions
3176 lines (2683 loc) · 125 KB
/
NpgsqlConnector.cs
File metadata and controls
3176 lines (2683 loc) · 125 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
using System;
using System.Buffers;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Npgsql.BackendMessages;
using Npgsql.Util;
using Microsoft.Extensions.Logging;
using Npgsql.Properties;
using static Npgsql.Util.Statics;
namespace Npgsql.Internal;
/// <summary>
/// Represents a connection to a PostgreSQL backend. Unlike NpgsqlConnection objects, which are
/// exposed to users, connectors are internal to Npgsql and are recycled by the connection pool.
/// </summary>
[Experimental(NpgsqlDiagnostics.ConvertersExperimental)]
public sealed partial class NpgsqlConnector
{
#region Fields and Properties
/// <summary>
/// The physical connection socket to the backend.
/// </summary>
Socket _socket = default!;
/// <summary>
/// The physical connection stream to the backend, without anything on top.
/// </summary>
NetworkStream _baseStream = default!;
/// <summary>
/// The physical connection stream to the backend, layered with an SSL/TLS stream if in secure mode.
/// </summary>
Stream _stream = default!;
/// <summary>
/// The parsed connection string.
/// </summary>
public NpgsqlConnectionStringBuilder Settings { get; }
Action<SslClientAuthenticationOptions>? SslClientAuthenticationOptionsCallback { get; }
#pragma warning disable CS0618 // ProvidePasswordCallback is obsolete
ProvidePasswordCallback? ProvidePasswordCallback { get; }
#pragma warning restore CS0618
Action<NegotiateAuthenticationClientOptions>? NegotiateOptionsCallback { get; }
public Encoding TextEncoding { get; private set; } = default!;
/// <summary>
/// Same as <see cref="TextEncoding"/>, except that it does not throw an exception if an invalid char is
/// encountered (exception fallback), but rather replaces it with a question mark character (replacement
/// fallback).
/// </summary>
internal Encoding RelaxedTextEncoding { get; private set; } = default!;
/// <summary>
/// Buffer used for reading data.
/// </summary>
internal NpgsqlReadBuffer ReadBuffer { get; private set; } = default!;
/// <summary>
/// If we read a data row that's bigger than <see cref="ReadBuffer"/>, we allocate an oversize buffer.
/// The original (smaller) buffer is stored here, and restored when the connection is reset.
/// </summary>
NpgsqlReadBuffer? _origReadBuffer;
/// <summary>
/// Buffer used for writing data.
/// </summary>
internal NpgsqlWriteBuffer WriteBuffer { get; private set; } = default!;
/// <summary>
/// The secret key of the backend for this connector, used for query cancellation.
/// </summary>
int _backendSecretKey;
/// <summary>
/// The process ID of the backend for this connector.
/// </summary>
internal int BackendProcessId { get; private set; }
string? _inferredUserName;
/// <summary>
/// The user name that has been inferred when the connector was opened
/// </summary>
internal string InferredUserName
{
get => _inferredUserName ?? throw new InvalidOperationException($"{nameof(InferredUserName)} cannot be accessed before the connector has been opened.");
private set => _inferredUserName = value;
}
bool SupportsPostgresCancellation => BackendProcessId != 0;
/// <summary>
/// A unique ID identifying this connector, used for logging. Currently mapped to BackendProcessId
/// </summary>
internal int Id => BackendProcessId;
internal NpgsqlDataSource.ReloadableState ReloadableState = null!;
/// <summary>
/// Information about PostgreSQL and PostgreSQL-like databases (e.g. type definitions, capabilities...).
/// </summary>
public NpgsqlDatabaseInfo DatabaseInfo => ReloadableState.DatabaseInfo;
internal PgSerializerOptions SerializerOptions => ReloadableState.SerializerOptions;
internal IDbTypeResolver? DbTypeResolver => ReloadableState.DbTypeResolver;
/// <summary>
/// The current transaction status for this connector.
/// </summary>
internal TransactionStatus TransactionStatus { get; set; }
/// <summary>
/// A transaction object for this connector. Since only one transaction can be in progress at any given time,
/// this instance is recycled. To check whether a transaction is currently in progress on this connector,
/// see <see cref="TransactionStatus"/>.
/// </summary>
internal NpgsqlTransaction? Transaction { get; set; }
internal NpgsqlTransaction? UnboundTransaction { get; set; }
/// <summary>
/// The NpgsqlConnection that (currently) owns this connector. Null if the connector isn't
/// owned (i.e. idle in the pool)
/// </summary>
internal NpgsqlConnection? Connection { get; set; }
/// <summary>
/// The number of messages that were prepended to the current message chain, but not yet sent.
/// Note that this only tracks messages which produce a ReadyForQuery message
/// </summary>
internal int PendingPrependedResponses { get; set; }
/// <summary>
/// A ManualResetEventSlim used to make sure a cancellation request doesn't run
/// while we're reading responses for the prepended query
/// as we can't gracefully handle their cancellation.
/// </summary>
readonly ManualResetEventSlim ReadingPrependedMessagesMRE = new(initialState: true);
internal NpgsqlDataReader? CurrentReader;
internal PreparedStatementManager PreparedStatementManager { get; }
internal SqlQueryParser SqlQueryParser { get; } = new();
/// <summary>
/// If the connector is currently in COPY mode, holds a reference to the importer/exporter object.
/// Otherwise null.
/// </summary>
internal ICancelable? CurrentCopyOperation;
/// <summary>
/// Holds all run-time parameters received from the backend (via ParameterStatus messages)
/// </summary>
internal Dictionary<string, string> PostgresParameters { get; }
/// <summary>
/// Holds all run-time parameters in raw, binary format for efficient handling without allocations.
/// </summary>
readonly List<(byte[] Name, byte[] Value)> _rawParameters = [];
/// <summary>
/// If this connector was broken, this contains the exception that caused the break.
/// </summary>
volatile Exception? _breakReason;
/// <summary>
/// A lock that's taken while a cancellation is being delivered; new queries are blocked until the
/// cancellation is delivered. This reduces the chance that a cancellation meant for a previous
/// command will accidentally cancel a later one, see #615.
/// </summary>
object CancelLock { get; } = new();
/// <summary>
/// A lock that's taken to make sure no other concurrent operation is running.
/// Break takes it to set the state of the connector.
/// Anyone else should immediately check the state and exit
/// if the connector is closed.
/// </summary>
object SyncObj { get; } = new();
/// <summary>
/// A lock that's used to wait for the Cleanup to complete while breaking the connection.
/// </summary>
object CleanupLock { get; } = new();
readonly bool _isKeepAliveEnabled;
readonly Timer? _keepAliveTimer;
/// <summary>
/// The command currently being executed by the connector, null otherwise.
/// Used only for concurrent use error reporting purposes.
/// </summary>
NpgsqlCommand? _currentCommand;
bool _sendResetOnClose;
/// <summary>
/// The connector source (e.g. pool) from where this connector came, and to which it will be returned.
/// Note that in multi-host scenarios, this references the host-specific <see cref="PoolingDataSource"/> rather than the
/// <see cref="NpgsqlMultiHostDataSource"/>.
/// </summary>
internal NpgsqlDataSource DataSource { get; }
internal string UserFacingConnectionString => DataSource.ConnectionString;
/// <summary>
/// Contains the UTC timestamp when this connector was opened, used to implement
/// <see cref="NpgsqlConnectionStringBuilder.ConnectionLifetime"/>.
/// </summary>
internal DateTime OpenTimestamp { get; private set; }
internal int ClearCounter { get; set; }
volatile bool _postgresCancellationPerformed;
internal bool PostgresCancellationPerformed
{
get => _postgresCancellationPerformed;
private set => _postgresCancellationPerformed = value;
}
volatile bool _userCancellationRequested;
CancellationTokenRegistration _cancellationTokenRegistration;
internal bool UserCancellationRequested => _userCancellationRequested;
internal CancellationToken UserCancellationToken { get; set; }
internal bool AttemptPostgresCancellation { get; private set; }
static readonly TimeSpan _cancelImmediatelyTimeout = TimeSpan.Zero;
static readonly SslApplicationProtocol _alpnProtocol = new("postgresql");
#pragma warning disable CA1859
// We're casting to IDisposable to not explicitly reference X509Certificate2 for NativeAOT
// TODO: probably pointless now, needs to be rechecked
List<IDisposable>? _certificates;
#pragma warning restore CA1859
internal NpgsqlLoggingConfiguration LoggingConfiguration { get; }
internal ILogger ConnectionLogger { get; }
internal ILogger CommandLogger { get; }
internal ILogger TransactionLogger { get; }
internal ILogger CopyLogger { get; }
internal readonly Stopwatch QueryLogStopWatch = new();
internal EndPoint? ConnectedEndPoint { get; private set; }
#endregion
#region Constants
/// <summary>
/// The minimum timeout that can be set on internal commands such as COMMIT, ROLLBACK.
/// </summary>
/// <remarks>Precision is seconds</remarks>
internal const int MinimumInternalCommandTimeout = 3;
#endregion
#region Reusable Message Objects
byte[]? _resetWithoutDeallocateMessage;
int _resetWithoutDeallocateResponseCount;
// Backend
readonly CommandCompleteMessage _commandCompleteMessage = new();
readonly ReadyForQueryMessage _readyForQueryMessage = new();
readonly ParameterDescriptionMessage _parameterDescriptionMessage = new();
readonly DataRowMessage _dataRowMessage = new();
readonly RowDescriptionMessage _rowDescriptionMessage = new(connectorOwned: true);
// Since COPY is rarely used, allocate these lazily
CopyInResponseMessage? _copyInResponseMessage;
CopyOutResponseMessage? _copyOutResponseMessage;
CopyDataMessage? _copyDataMessage;
CopyBothResponseMessage? _copyBothResponseMessage;
#endregion
internal NpgsqlDataReader DataReader { get; set; }
internal NpgsqlDataReader? UnboundDataReader { get; set; }
#region Constructors
internal NpgsqlConnector(NpgsqlDataSource dataSource, NpgsqlConnection conn)
: this(dataSource)
{
var sslClientAuthenticationOptionsCallback = conn.SslClientAuthenticationOptionsCallback;
#pragma warning disable CS0618 // Obsolete
var provideClientCertificatesCallback = conn.ProvideClientCertificatesCallback;
var userCertificateValidationCallback = conn.UserCertificateValidationCallback;
if (provideClientCertificatesCallback is not null ||
userCertificateValidationCallback is not null)
{
if (sslClientAuthenticationOptionsCallback is not null)
throw new NotSupportedException(NpgsqlStrings.SslClientAuthenticationOptionsCallbackWithOtherCallbacksNotSupported);
sslClientAuthenticationOptionsCallback = options =>
{
if (provideClientCertificatesCallback is not null)
{
options.ClientCertificates ??= new X509Certificate2Collection();
provideClientCertificatesCallback.Invoke(options.ClientCertificates);
}
if (userCertificateValidationCallback is not null)
{
options.RemoteCertificateValidationCallback = userCertificateValidationCallback;
}
};
}
if (sslClientAuthenticationOptionsCallback is not null)
SslClientAuthenticationOptionsCallback = sslClientAuthenticationOptionsCallback;
ProvidePasswordCallback = conn.ProvidePasswordCallback;
#pragma warning restore CS0618
}
NpgsqlConnector(NpgsqlConnector connector)
: this(connector.DataSource)
{
SslClientAuthenticationOptionsCallback = connector.SslClientAuthenticationOptionsCallback;
ProvidePasswordCallback = connector.ProvidePasswordCallback;
}
NpgsqlConnector(NpgsqlDataSource dataSource)
{
Debug.Assert(dataSource.OwnsConnectors);
DataSource = dataSource;
LoggingConfiguration = dataSource.LoggingConfiguration;
ConnectionLogger = LoggingConfiguration.ConnectionLogger;
CommandLogger = LoggingConfiguration.CommandLogger;
TransactionLogger = LoggingConfiguration.TransactionLogger;
CopyLogger = LoggingConfiguration.CopyLogger;
SslClientAuthenticationOptionsCallback = dataSource.SslClientAuthenticationOptionsCallback;
NegotiateOptionsCallback = dataSource.Configuration.NegotiateOptionsCallback;
State = ConnectorState.Closed;
TransactionStatus = TransactionStatus.Idle;
Settings = dataSource.Settings;
PostgresParameters = new Dictionary<string, string>();
_isKeepAliveEnabled = Settings.KeepAlive > 0;
if (_isKeepAliveEnabled)
{
using (ExecutionContext.SuppressFlow()) // Don't capture the current ExecutionContext and its AsyncLocals onto the timer causing them to live forever
_keepAliveTimer = new Timer(PerformKeepAlive, null, Timeout.Infinite, Timeout.Infinite);
}
DataReader = new NpgsqlDataReader(this);
// TODO: Not just for automatic preparation anymore...
PreparedStatementManager = new PreparedStatementManager(this);
}
#endregion
#region Configuration settings
internal string Host => Settings.Host!;
internal int Port => Settings.Port;
internal string Database => Settings.Database!;
string KerberosServiceName => Settings.KerberosServiceName;
int ConnectionTimeout => Settings.Timeout;
#endregion Configuration settings
#region State management
int _state;
/// <summary>
/// Gets the current state of the connector
/// </summary>
internal ConnectorState State
{
get => (ConnectorState)_state;
set
{
var newState = (int)value;
if (newState == _state)
return;
if (newState is < 0 or > (int)ConnectorState.Replication)
ThrowHelper.ThrowArgumentOutOfRangeException(nameof(value), "Unknown state: " + value);
Interlocked.Exchange(ref _state, newState);
}
}
/// <summary>
/// Returns whether the connector is open, regardless of any task it is currently performing
/// </summary>
internal bool IsConnected => State is not (ConnectorState.Closed or ConnectorState.Connecting or ConnectorState.Broken);
internal bool IsReady => State == ConnectorState.Ready;
internal bool IsClosed => State == ConnectorState.Closed;
internal bool IsBroken => State == ConnectorState.Broken;
#endregion
#region Open
/// <summary>
/// Opens the physical connection to the server.
/// </summary>
/// <remarks>Usually called by the RequestConnector
/// Method of the connection pool manager.</remarks>
internal async Task Open(NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
Debug.Assert(State == ConnectorState.Closed);
State = ConnectorState.Connecting;
LogMessages.OpeningPhysicalConnection(ConnectionLogger, Host, Port, Database, UserFacingConnectionString);
var startOpenTimestamp = Stopwatch.GetTimestamp();
Activity? activity = null;
try
{
var username = await GetUsernameAsync(async, cancellationToken).ConfigureAwait(false);
activity = NpgsqlActivitySource.PhysicalConnectionOpen(this);
var gssEncMode = GetGssEncMode(Settings);
await OpenCore(this, username, Settings.SslMode, gssEncMode, timeout, async, cancellationToken).ConfigureAwait(false);
if (activity is not null)
NpgsqlActivitySource.Enrich(activity, this);
await DataSource.Bootstrap(this, timeout, forceReload: false, async, cancellationToken).ConfigureAwait(false);
// The connector directly references the current reloadable state reference, to protect it against changes by a concurrent
// ReloadTypes. We update them here before returning the connector from the pool.
ReloadableState = DataSource.CurrentReloadableState;
if (Settings.Pooling && Settings is { NoResetOnClose: false } && DatabaseInfo.SupportsDiscard)
{
_sendResetOnClose = true;
GenerateResetMessage();
}
OpenTimestamp = DateTime.UtcNow;
if (_isKeepAliveEnabled)
{
// Start the keep alive mechanism to work by scheduling the timer.
// Otherwise, it doesn't work for cases when no query executed during
// the connection lifetime in case of a new connector.
lock (SyncObj)
{
var keepAlive = Settings.KeepAlive * 1000;
_keepAliveTimer!.Change(keepAlive, keepAlive);
}
}
if (DataSource.ConnectionInitializerAsync is not null)
{
Debug.Assert(DataSource.ConnectionInitializer is not null);
var tempConnection = new NpgsqlConnection(DataSource, this);
try
{
if (async)
await DataSource.ConnectionInitializerAsync(tempConnection).ConfigureAwait(false);
else
DataSource.ConnectionInitializer(tempConnection);
}
finally
{
// Note that we can't just close/dispose the NpgsqlConnection, since that puts the connector back in the pool.
// But we transition it to disposed immediately, in case the user decides to capture the NpgsqlConnection and use it
// later.
Connection?.MakeDisposed();
Connection = null;
}
}
activity?.Dispose();
LogMessages.OpenedPhysicalConnection(
ConnectionLogger, Host, Port, Database, UserFacingConnectionString,
(long)Stopwatch.GetElapsedTime(startOpenTimestamp).TotalMilliseconds, Id);
}
catch (Exception e)
{
if (activity is not null)
NpgsqlActivitySource.SetException(activity, e);
Break(e, markHostAsOfflineOnConnecting: true);
throw;
}
static async Task OpenCore(
NpgsqlConnector conn,
string username,
SslMode sslMode,
GssEncryptionMode gssEncMode,
NpgsqlTimeout timeout,
bool async,
CancellationToken cancellationToken)
{
// If we fail to connect to the socket, there is no reason to retry even if SslMode/GssEncryption allows it
await conn.RawOpen(timeout, async, cancellationToken).ConfigureAwait(false);
try
{
await conn.SetupEncryption(sslMode, gssEncMode, timeout, async, cancellationToken).ConfigureAwait(false);
timeout.CheckAndApply(conn);
conn.WriteStartupMessage(username);
await conn.Flush(async, cancellationToken).ConfigureAwait(false);
using var cancellationRegistration = conn.StartCancellableOperation(cancellationToken, attemptPgCancellation: false);
await conn.Authenticate(username, timeout, async, cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
throw;
}
// We handle any exception here because on Windows while receiving a response from Postgres
// We might hit connection reset, in which case the actual error will be lost
// And we only read some IO error
// In addition, this behavior mimics libpq, where it retries as long as GssEncryptionMode and SslMode allows it
catch (Exception e) when
// We might also get here OperationCancelledException/TimeoutException
// But it's fine to fall down and retry because we'll immediately exit with the exact same exception
//
// Any error after trying with GSS encryption
(gssEncMode == GssEncryptionMode.Prefer ||
// Auth error with/without SSL
(sslMode == SslMode.Prefer && conn.IsSslEncrypted || sslMode == SslMode.Allow && !conn.IsSslEncrypted))
{
if (gssEncMode == GssEncryptionMode.Prefer)
{
conn.ConnectionLogger.LogTrace(e, "Error while opening physical connection with GSS encryption, retrying without it");
gssEncMode = GssEncryptionMode.Disable;
}
else
sslMode = sslMode == SslMode.Prefer ? SslMode.Disable : SslMode.Require;
conn.Cleanup();
// If Prefer was specified and we failed (with SSL), retry without SSL.
// If Allow was specified and we failed (without SSL), retry with SSL
await OpenCore(
conn,
username,
sslMode,
gssEncMode,
timeout,
async,
cancellationToken).ConfigureAwait(false);
return;
}
// We treat BackendKeyData as optional because some PostgreSQL-like database
// don't send it (CockroachDB, CrateDB)
var msg = await conn.ReadMessage(async).ConfigureAwait(false);
if (msg.Code == BackendMessageCode.BackendKeyData)
{
var keyDataMsg = (BackendKeyDataMessage)msg;
conn.BackendProcessId = keyDataMsg.BackendProcessId;
conn._backendSecretKey = keyDataMsg.BackendSecretKey;
msg = await conn.ReadMessage(async).ConfigureAwait(false);
}
if (msg.Code != BackendMessageCode.ReadyForQuery)
throw new NpgsqlException($"Received backend message {msg.Code} while expecting ReadyForQuery. Please file a bug.");
conn.State = ConnectorState.Ready;
}
}
internal async ValueTask<GssEncryptionResult> GSSEncrypt(bool async, bool isRequired, CancellationToken cancellationToken)
{
ConnectionLogger.LogTrace("Negotiating GSS encryption");
var targetName = $"{KerberosServiceName}/{Host}";
var clientOptions = new NegotiateAuthenticationClientOptions { TargetName = targetName };
NegotiateOptionsCallback?.Invoke(clientOptions);
var authentication = new NegotiateAuthentication(clientOptions);
try
{
byte[]? data;
NegotiateAuthenticationStatusCode statusCode;
try
{
data = authentication.GetOutgoingBlob(ReadOnlySpan<byte>.Empty, out statusCode)!;
}
catch (TypeInitializationException)
{
// On UNIX .NET throws TypeInitializationException if it's unable to load the native library
if (isRequired)
throw new NpgsqlException("Unable to load native library to negotiate GSS encryption");
return GssEncryptionResult.GetCredentialFailure;
}
if (statusCode != NegotiateAuthenticationStatusCode.ContinueNeeded)
{
// Unable to retrieve credentials
// If it's required, throw an appropriate exception
if (isRequired)
throw new NpgsqlException($"Unable to negotiate GSS encryption: {statusCode}");
return GssEncryptionResult.GetCredentialFailure;
}
WriteGSSEncryptRequest();
await Flush(async, cancellationToken).ConfigureAwait(false);
await ReadBuffer.Ensure(1, async).ConfigureAwait(false);
var response = (char)ReadBuffer.ReadByte();
// TODO: Server can respond with an error here
// but according to documentation we shouldn't display this error to the user/application
// since the server has not been authenticated (CVE-2024-10977)
// See https://www.postgresql.org/docs/current/protocol-flow.html#PROTOCOL-FLOW-GSSAPI
switch (response)
{
default:
throw new NpgsqlException($"Received unknown response {response} for GSSEncRequest (expecting G or N)");
case 'N':
if (isRequired)
throw new NpgsqlException("GGS encryption requested. No GSS encryption enabled connection from this host is configured.");
return GssEncryptionResult.NegotiateFailure;
case 'G':
break;
}
if (ReadBuffer.ReadBytesLeft > 0)
throw new NpgsqlException(
"Additional unencrypted data received after GSS encryption negotiation - this should never happen, and may be an indication of a man-in-the-middle attack.");
var lengthBuffer = new byte[4];
await WriteGssEncryptMessage(async, data, lengthBuffer, cancellationToken).ConfigureAwait(false);
while (true)
{
if (async)
await _stream.ReadExactlyAsync(lengthBuffer, cancellationToken).ConfigureAwait(false);
else
_stream.ReadExactly(lengthBuffer);
var messageLength = BitConverter.IsLittleEndian
? BinaryPrimitives.ReverseEndianness(Unsafe.ReadUnaligned<int>(ref lengthBuffer[0]))
: Unsafe.ReadUnaligned<int>(ref lengthBuffer[0]);
var buffer = ArrayPool<byte>.Shared.Rent(messageLength);
if (async)
await _stream.ReadExactlyAsync(buffer.AsMemory(0, messageLength), cancellationToken).ConfigureAwait(false);
else
_stream.ReadExactly(buffer.AsSpan(0, messageLength));
data = authentication.GetOutgoingBlob(buffer.AsSpan(0, messageLength), out statusCode);
ArrayPool<byte>.Shared.Return(buffer, clearArray: true);
if (statusCode is not NegotiateAuthenticationStatusCode.Completed and not NegotiateAuthenticationStatusCode.ContinueNeeded)
throw new NpgsqlException($"Error while negotiating GSS encryption: {statusCode}");
// TODO: the code below is the copy from GSS/SSPI auth
// It's unknown whether it holds true here or not
// We might get NegotiateAuthenticationStatusCode.Completed but the data will not be null
// This can happen if it's the first cycle, in which case we have to send that data to complete handshake (#4888)
if (data is null)
{
Debug.Assert(statusCode == NegotiateAuthenticationStatusCode.Completed);
break;
}
await WriteGssEncryptMessage(async, data, lengthBuffer, cancellationToken).ConfigureAwait(false);
}
_stream = new GSSStream(_stream, authentication);
ReadBuffer.Underlying = _stream;
WriteBuffer.Underlying = _stream;
IsGssEncrypted = true;
authentication = null;
ConnectionLogger.LogTrace("GSS encryption successful");
return GssEncryptionResult.Success;
async ValueTask WriteGssEncryptMessage(bool async, byte[] data, byte[] lengthBuffer, CancellationToken cancellationToken)
{
BinaryPrimitives.WriteInt32BigEndian(lengthBuffer, data.Length);
if (async)
{
await _stream.WriteAsync(lengthBuffer, cancellationToken).ConfigureAwait(false);
await _stream.WriteAsync(data, cancellationToken).ConfigureAwait(false);
await _stream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
else
{
_stream.Write(lengthBuffer);
_stream.Write(data);
_stream.Flush();
}
}
}
catch (Exception e) when (e is not OperationCanceledException)
{
throw new NpgsqlException("Exception while performing GSS encryption", e);
}
finally
{
authentication?.Dispose();
}
}
internal async ValueTask<DatabaseState> QueryDatabaseState(
NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken = default)
{
using var batch = CreateBatch();
batch.BatchCommands.Add(new NpgsqlBatchCommand("select pg_is_in_recovery()"));
batch.BatchCommands.Add(new NpgsqlBatchCommand("SHOW default_transaction_read_only"));
batch.Timeout = (int)timeout.CheckAndGetTimeLeft().TotalSeconds;
var reader = async ? await batch.ExecuteReaderAsync(cancellationToken).ConfigureAwait(false) : batch.ExecuteReader();
try
{
if (async)
{
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
_isHotStandBy = reader.GetBoolean(0);
await reader.NextResultAsync(cancellationToken).ConfigureAwait(false);
await reader.ReadAsync(cancellationToken).ConfigureAwait(false);
}
else
{
reader.Read();
_isHotStandBy = reader.GetBoolean(0);
reader.NextResult();
reader.Read();
}
_isTransactionReadOnly = reader.GetString(0) != "off";
var databaseState = UpdateDatabaseState();
Debug.Assert(databaseState.HasValue);
return databaseState.Value;
}
finally
{
if (async)
await reader.DisposeAsync().ConfigureAwait(false);
else
reader.Dispose();
}
}
void WriteStartupMessage(string username)
{
var startupParams = new Dictionary<string, string>
{
["user"] = username,
["client_encoding"] = Settings.ClientEncoding ??
PostgresEnvironment.ClientEncoding ??
"UTF8"
};
if (Settings.Database is not null)
startupParams["database"] = Settings.Database;
var applicationName = Settings.ApplicationName ?? PostgresEnvironment.AppName;
if (applicationName?.Length > 0)
startupParams["application_name"] = applicationName;
if (Settings.SearchPath?.Length > 0)
startupParams["search_path"] = Settings.SearchPath;
var timezone = Settings.Timezone ?? PostgresEnvironment.TimeZone;
if (timezone != null)
startupParams["TimeZone"] = timezone;
var options = Settings.Options ?? PostgresEnvironment.Options;
if (options?.Length > 0)
startupParams["options"] = options;
switch (Settings.ReplicationMode)
{
case ReplicationMode.Logical:
startupParams["replication"] = "database";
break;
case ReplicationMode.Physical:
startupParams["replication"] = "true";
break;
}
WriteStartup(startupParams);
}
ValueTask<string> GetUsernameAsync(bool async, CancellationToken cancellationToken)
{
var username = Settings.Username;
if (username?.Length > 0)
{
InferredUserName = username;
return new(username);
}
username = PostgresEnvironment.User;
if (username?.Length > 0)
{
InferredUserName = username;
return new(username);
}
return GetUsernameAsyncInternal();
async ValueTask<string> GetUsernameAsyncInternal()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
username = await DataSource.IntegratedSecurityHandler.GetUsername(async, Settings.IncludeRealm, ConnectionLogger,
cancellationToken).ConfigureAwait(false);
if (username?.Length > 0)
{
InferredUserName = username;
return username;
}
}
username = Environment.UserName;
if (username?.Length > 0)
{
InferredUserName = username;
return username;
}
throw new NpgsqlException("No username could be found, please specify one explicitly");
}
}
async Task RawOpen(NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
try
{
if (async)
await ConnectAsync(timeout, cancellationToken).ConfigureAwait(false);
else
Connect(timeout);
ConnectionLogger.LogTrace("Socket connected to {Host}:{Port}", Host, Port);
_baseStream = new NetworkStream(_socket, true);
_stream = _baseStream;
if (Settings.Encoding == "UTF8")
{
TextEncoding = NpgsqlWriteBuffer.UTF8Encoding;
RelaxedTextEncoding = NpgsqlWriteBuffer.RelaxedUTF8Encoding;
}
else
{
TextEncoding = Encoding.GetEncoding(Settings.Encoding, EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback);
RelaxedTextEncoding = Encoding.GetEncoding(Settings.Encoding, EncoderFallback.ReplacementFallback, DecoderFallback.ReplacementFallback);
}
ReadBuffer = new NpgsqlReadBuffer(this, _stream, _socket, Settings.ReadBufferSize, TextEncoding, RelaxedTextEncoding);
WriteBuffer = new NpgsqlWriteBuffer(this, _stream, _socket, Settings.WriteBufferSize, TextEncoding);
timeout.CheckAndApply(this);
IsSslEncrypted = false;
IsGssEncrypted = false;
}
catch
{
_stream?.Dispose();
_stream = null!;
_baseStream?.Dispose();
_baseStream = null!;
_socket?.Dispose();
_socket = null!;
throw;
}
}
async Task SetupEncryption(SslMode sslMode, GssEncryptionMode gssEncryptionMode, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
var gssEncryptResult = await TryNegotiateGssEncryption(gssEncryptionMode, async, cancellationToken).ConfigureAwait(false);
if (gssEncryptResult == GssEncryptionResult.Success)
return;
// TryNegotiateGssEncryption should already throw a much more meaningful exception
// if GSS encryption is required but for some reason we can't negotiate it.
// But since we have to return a specific result instead of generic true/false
// To make absolutely sure we didn't miss anything, recheck again
if (gssEncryptionMode == GssEncryptionMode.Require)
throw new NpgsqlException($"Unable to negotiate GSS encryption: {gssEncryptResult}");
timeout.CheckAndApply(this);
if (GetSslNegotiation(Settings) == SslNegotiation.Direct)
{
// We already check that in NpgsqlConnectionStringBuilder.PostProcessAndValidate, but since we also allow environment variables...
if (Settings.SslMode is not SslMode.Require and not SslMode.VerifyCA and not SslMode.VerifyFull)
throw new ArgumentException("SSL Mode has to be Require or higher to be used with direct SSL Negotiation");
if (gssEncryptResult == GssEncryptionResult.NegotiateFailure)
{
// We can be here only if it's fallback from preferred (but failed) gss encryption
// In this case, direct encryption isn't going to work anymore, so we throw a bogus exception to retry again without gss
// Alternatively, we can instead just go with the usual route of writing SslRequest, ignoring direct ssl
// But this is how libpq works
Debug.Assert(gssEncryptionMode == GssEncryptionMode.Prefer);
// The exception message doesn't matter since we're going to retry again
throw new NpgsqlException();
}
await DataSource.TransportSecurityHandler.NegotiateEncryption(async, this, sslMode, timeout, cancellationToken).ConfigureAwait(false);
if (ReadBuffer.ReadBytesLeft > 0)
throw new NpgsqlException("Additional unencrypted data received after SSL negotiation - this should never happen, and may be an indication of a man-in-the-middle attack.");
}
else if ((sslMode is SslMode.Prefer && DataSource.TransportSecurityHandler.SupportEncryption) ||
sslMode is SslMode.Require or SslMode.VerifyCA or SslMode.VerifyFull)
{
WriteSslRequest();
await Flush(async, cancellationToken).ConfigureAwait(false);
await ReadBuffer.Ensure(1, async).ConfigureAwait(false);
var response = (char)ReadBuffer.ReadByte();
timeout.CheckAndApply(this);
switch (response)
{
default:
throw new NpgsqlException($"Received unknown response {response} for SSLRequest (expecting S or N)");
case 'N':
if (sslMode != SslMode.Prefer)
throw new NpgsqlException("SSL connection requested. No SSL enabled connection from this host is configured.");
break;
case 'S':
await DataSource.TransportSecurityHandler.NegotiateEncryption(async, this, sslMode, timeout, cancellationToken).ConfigureAwait(false);
break;
}
if (ReadBuffer.ReadBytesLeft > 0)
throw new NpgsqlException("Additional unencrypted data received after SSL negotiation - this should never happen, and may be an indication of a man-in-the-middle attack.");
}
}
async ValueTask<GssEncryptionResult> TryNegotiateGssEncryption(GssEncryptionMode gssEncryptionMode, bool async, CancellationToken cancellationToken)
{
// GetCredentialFailure is essentially a nop (since we didn't send anything over the wire)
// So we can proceed further as if gss encryption wasn't even attempted
if (gssEncryptionMode == GssEncryptionMode.Disable) return GssEncryptionResult.GetCredentialFailure;
// Same thing as above, though in this case user doesn't require GSS encryption but didn't enable encryption
// Most of the time they're using the default value, in which case also exit without throwing an error
if (gssEncryptionMode == GssEncryptionMode.Prefer && !DataSource.TransportSecurityHandler.SupportEncryption)
return GssEncryptionResult.GetCredentialFailure;
if (ConnectedEndPoint!.AddressFamily == AddressFamily.Unix)
{
if (gssEncryptionMode == GssEncryptionMode.Prefer)
return GssEncryptionResult.GetCredentialFailure;
Debug.Assert(gssEncryptionMode == GssEncryptionMode.Require);
throw new NpgsqlException("GSS encryption isn't supported over unix socket");
}