/
NpgsqlConnector.cs
2716 lines (2290 loc) · 107 KB
/
NpgsqlConnector.cs
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.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
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.Channels;
using System.Threading.Tasks;
using Npgsql.BackendMessages;
using Npgsql.TypeMapping;
using Npgsql.Util;
using static Npgsql.Util.Statics;
using System.Transactions;
using Microsoft.Extensions.Logging;
using Npgsql.Properties;
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>
public sealed partial class NpgsqlConnector : IDisposable
{
#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; }
ProvideClientCertificatesCallback? ProvideClientCertificatesCallback { get; }
RemoteCertificateValidationCallback? UserCertificateValidationCallback { get; }
ProvidePasswordCallback? ProvidePasswordCallback { get; }
#pragma warning disable CA2252 // Experimental API
PhysicalOpenCallback? PhysicalOpenCallback { get; }
PhysicalOpenAsyncCallback? PhysicalOpenAsyncCallback { get; }
#pragma warning restore CA2252
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; }
bool SupportsPostgresCancellation => BackendProcessId != 0;
/// <summary>
/// A unique ID identifying this connector, used for logging. Currently mapped to BackendProcessId
/// </summary>
internal int Id => BackendProcessId;
/// <summary>
/// Information about PostgreSQL and PostgreSQL-like databases (e.g. type definitions, capabilities...).
/// </summary>
public NpgsqlDatabaseInfo DatabaseInfo { get; internal set; } = default!;
internal ConnectorTypeMapper TypeMapper { get; set; } = default!;
/// <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; }
internal NpgsqlDataReader? CurrentReader;
internal PreparedStatementManager PreparedStatementManager;
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 readonly Dictionary<string, string> PostgresParameters;
/// <summary>
/// Holds all run-time parameters in raw, binary format for efficient handling without allocations.
/// </summary>
readonly List<(byte[] Name, byte[] Value)> _rawParameters = new();
/// <summary>
/// If this connector was broken, this contains the exception that caused the break.
/// </summary>
volatile Exception? _breakReason;
/// <summary>
/// Semaphore, used to synchronize DatabaseInfo between multiple connections, so it wouldn't be loaded in parallel.
/// </summary>
static readonly SemaphoreSlim DatabaseInfoSemaphore = new(1);
/// <summary>
/// <para>
/// Used by the pool to indicate that I/O is currently in progress on this connector, so that another write
/// isn't started concurrently. Note that since we have only one write loop, this is only ever usedto
/// protect against an over-capacity writes into a connector that's currently *asynchronously* writing.
/// </para>
/// <para>
/// It is guaranteed that the currently-executing
/// Specifically, reading may occur - and the connector may even be returned to the pool - before this is
/// released.
/// </para>
/// </summary>
internal volatile int MultiplexAsyncWritingLock;
/// <seealso cref="MultiplexAsyncWritingLock"/>
internal void FlagAsNotWritableForMultiplexing()
{
Debug.Assert(Settings.Multiplexing);
Debug.Assert(CommandsInFlightCount > 0 || IsBroken || IsClosed,
$"About to mark multiplexing connector as non-writable, but {nameof(CommandsInFlightCount)} is {CommandsInFlightCount}");
Interlocked.Exchange(ref MultiplexAsyncWritingLock, 1);
}
/// <seealso cref="MultiplexAsyncWritingLock"/>
internal void FlagAsWritableForMultiplexing()
{
Debug.Assert(Settings.Multiplexing);
if (Interlocked.CompareExchange(ref MultiplexAsyncWritingLock, 0, 1) != 1)
throw new Exception("Multiplexing lock was not taken when releasing. Please report a bug.");
}
/// <summary>
/// The timeout for reading messages that are part of the user's command
/// (i.e. which aren't internal prepended commands).
/// </summary>
/// <remarks>Precision is milliseconds</remarks>
internal int UserTimeout { private get; set; }
/// <summary>
/// A lock that's taken while a user action is in progress, e.g. a command being executed.
/// Only used when keepalive is enabled, otherwise null.
/// </summary>
SemaphoreSlim? _userLock;
/// <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>
internal object CancelLock { get; }
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="ConnectorPool"/> rather than the
/// <see cref="MultiHostConnectorPool"/>,
/// </summary>
readonly ConnectorSource _connectorSource;
internal string UserFacingConnectionString => _connectorSource.UserFacingConnectionString;
/// <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.FromMilliseconds(-1);
static readonly ILogger Logger = NpgsqlLoggingConfiguration.ConnectionLogger;
static readonly ILogger CommandLogger = NpgsqlLoggingConfiguration.CommandLogger;
static readonly ILogger CopyLogger = NpgsqlLoggingConfiguration.CopyLogger;
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();
// 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(ConnectorSource connectorSource, NpgsqlConnection conn)
: this(connectorSource)
{
ProvideClientCertificatesCallback = conn.ProvideClientCertificatesCallback;
UserCertificateValidationCallback = conn.UserCertificateValidationCallback;
ProvidePasswordCallback = conn.ProvidePasswordCallback;
#pragma warning disable CA2252 // Experimental API
PhysicalOpenCallback = conn.PhysicalOpenCallback;
PhysicalOpenAsyncCallback = conn.PhysicalOpenAsyncCallback;
#pragma warning restore CA2252
}
NpgsqlConnector(NpgsqlConnector connector)
: this(connector._connectorSource)
{
ProvideClientCertificatesCallback = connector.ProvideClientCertificatesCallback;
UserCertificateValidationCallback = connector.UserCertificateValidationCallback;
ProvidePasswordCallback = connector.ProvidePasswordCallback;
}
NpgsqlConnector(ConnectorSource connectorSource)
{
Debug.Assert(connectorSource.OwnsConnectors);
_connectorSource = connectorSource;
State = ConnectorState.Closed;
TransactionStatus = TransactionStatus.Idle;
Settings = connectorSource.Settings;
PostgresParameters = new Dictionary<string, string>();
CancelLock = new object();
_isKeepAliveEnabled = Settings.KeepAlive > 0;
if (_isKeepAliveEnabled)
{
_userLock = new SemaphoreSlim(1, 1);
_keepAliveTimer = new Timer(PerformKeepAlive, null, Timeout.Infinite, Timeout.Infinite);
}
DataReader = new NpgsqlDataReader(this);
// TODO: Not just for automatic preparation anymore...
PreparedStatementManager = new PreparedStatementManager(this);
if (Settings.Multiplexing)
{
// Note: It's OK for this channel to be unbounded: each command enqueued to it is accompanied by sending
// it to PostgreSQL. If we overload it, a TCP zero window will make us block on the networking side
// anyway.
// Note: the in-flight channel can probably be single-writer, but that doesn't actually do anything
// at this point. And we currently rely on being able to complete the channel at any point (from
// Break). We may want to revisit this if an optimized, SingleWriter implementation is introduced.
var commandsInFlightChannel = Channel.CreateUnbounded<NpgsqlCommand>(
new UnboundedChannelOptions { SingleReader = true });
CommandsInFlightReader = commandsInFlightChannel.Reader;
CommandsInFlightWriter = commandsInFlightChannel.Writer;
// TODO: Properly implement this
if (_isKeepAliveEnabled)
throw new NotImplementedException("Keepalive not yet implemented for multiplexing");
}
}
#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;
bool IntegratedSecurity => Settings.IntegratedSecurity;
/// <summary>
/// The actual command timeout value that gets set on internal commands.
/// </summary>
/// <remarks>Precision is milliseconds</remarks>
int InternalCommandTimeout
{
get
{
var internalTimeout = Settings.InternalCommandTimeout;
if (internalTimeout == -1)
return Math.Max(Settings.CommandTimeout, MinimumInternalCommandTimeout) * 1000;
// Todo: Decide what we really want here
// This assertion can easily fail if InternalCommandTimeout is set to 1 or 2 in the connection string
// We probably don't want to allow these values but in that case a Debug.Assert is the wrong way to enforce it.
Debug.Assert(internalTimeout == 0 || internalTimeout >= MinimumInternalCommandTimeout);
return internalTimeout * 1000;
}
}
#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;
Interlocked.Exchange(ref _state, newState);
}
}
/// <summary>
/// Returns whether the connector is open, regardless of any task it is currently performing
/// </summary>
bool IsConnected
=> State switch
{
ConnectorState.Ready => true,
ConnectorState.Executing => true,
ConnectorState.Fetching => true,
ConnectorState.Waiting => true,
ConnectorState.Copy => true,
ConnectorState.Replication => true,
ConnectorState.Closed => false,
ConnectorState.Connecting => false,
ConnectorState.Broken => false,
_ => throw new ArgumentOutOfRangeException("Unknown state: " + State)
};
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(Logger, Host, Port, Database, UserFacingConnectionString);
var stopwatch = Stopwatch.StartNew();
try
{
await OpenCore(this, Settings.SslMode, timeout, async, cancellationToken);
await LoadDatabaseInfo(forceReload: false, timeout, async, cancellationToken);
if (Settings.Pooling && !Settings.Multiplexing && !Settings.NoResetOnClose && DatabaseInfo.SupportsDiscard)
{
_sendResetOnClose = true;
GenerateResetMessage();
}
OpenTimestamp = DateTime.UtcNow;
#pragma warning disable CA2252 // Experimental API
if (async && PhysicalOpenAsyncCallback is not null)
await PhysicalOpenAsyncCallback(this);
else if (!async && PhysicalOpenCallback is not null)
PhysicalOpenCallback(this);
#pragma warning restore CA2252
if (Settings.Multiplexing)
{
// Start an infinite async loop, which processes incoming multiplexing traffic.
// It is intentionally not awaited and will run as long as the connector is alive.
// The CommandsInFlightWriter channel is completed in Cleanup, which should cause this task
// to complete.
_ = Task.Run(MultiplexingReadLoop, CancellationToken.None)
.ContinueWith(t =>
{
// Note that we *must* observe the exception if the task is faulted.
Logger.LogError(t.Exception!, "Exception bubbled out of multiplexing read loop", Id);
}, TaskContinuationOptions.OnlyOnFaulted);
}
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 (this)
{
var keepAlive = Settings.KeepAlive * 1000;
_keepAliveTimer!.Change(keepAlive, keepAlive);
}
}
LogMessages.OpenedPhysicalConnection(Logger, Host, Port, Database, UserFacingConnectionString, stopwatch.ElapsedMilliseconds, Id);
}
catch (Exception e)
{
Break(e);
throw;
}
static async Task OpenCore(NpgsqlConnector conn, SslMode sslMode, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
await conn.RawOpen(sslMode, timeout, async, cancellationToken);
var username = conn.GetUsername();
if (conn.Settings.Database == null)
conn.Settings.Database = username;
timeout.CheckAndApply(conn);
conn.WriteStartupMessage(username);
await conn.Flush(async, cancellationToken);
var cancellationRegistration = conn.StartCancellableOperation(cancellationToken, attemptPgCancellation: false);
try
{
await conn.Authenticate(username, timeout, async, cancellationToken);
}
catch (PostgresException e)
when (e.SqlState == PostgresErrorCodes.InvalidAuthorizationSpecification &&
(sslMode == SslMode.Prefer && conn.IsSecure || sslMode == SslMode.Allow && !conn.IsSecure))
{
cancellationRegistration.Dispose();
Debug.Assert(!conn.IsBroken);
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, sslMode == SslMode.Prefer ? SslMode.Disable : SslMode.Require, timeout, async, cancellationToken);
return;
}
using var _ = cancellationRegistration;
// We treat BackendKeyData as optional because some PostgreSQL-like database
// don't send it (CockroachDB, CrateDB)
var msg = await conn.ReadMessage(async);
if (msg.Code == BackendMessageCode.BackendKeyData)
{
var keyDataMsg = (BackendKeyDataMessage)msg;
conn.BackendProcessId = keyDataMsg.BackendProcessId;
conn._backendSecretKey = keyDataMsg.BackendSecretKey;
msg = await conn.ReadMessage(async);
}
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 LoadDatabaseInfo(bool forceReload, NpgsqlTimeout timeout, bool async,
CancellationToken cancellationToken = default)
{
// The type loading below will need to send queries to the database, and that depends on a type mapper being set up (even if its
// empty). So we set up here, and then later inject the DatabaseInfo.
// For multiplexing connectors, the type mapper is the shared pool-wide one (since when validating/binding parameters on
// multiplexing there's no connector yet). However, in the very first multiplexing connection (bootstrap phase) we create
// a connector-specific mapper, which will later become shared pool-wide one.
TypeMapper =
Settings.Multiplexing && ((MultiplexingConnectorPool)_connectorSource).MultiplexingTypeMapper is { } multiplexingTypeMapper
? multiplexingTypeMapper
: new ConnectorTypeMapper(this);
var key = new NpgsqlDatabaseInfoCacheKey(Settings);
if (forceReload || !NpgsqlDatabaseInfo.Cache.TryGetValue(key, out var database))
{
var hasSemaphore = async
? await DatabaseInfoSemaphore.WaitAsync(timeout.CheckAndGetTimeLeft(), cancellationToken)
: DatabaseInfoSemaphore.Wait(timeout.CheckAndGetTimeLeft(), cancellationToken);
// We've timed out - calling Check, to throw the correct exception
if (!hasSemaphore)
timeout.Check();
try
{
if (forceReload || !NpgsqlDatabaseInfo.Cache.TryGetValue(key, out database))
{
NpgsqlDatabaseInfo.Cache[key] = database = await NpgsqlDatabaseInfo.Load(this, timeout, async);
}
}
finally
{
DatabaseInfoSemaphore.Release();
}
}
DatabaseInfo = database;
TypeMapper.DatabaseInfo = database;
}
internal async ValueTask<ClusterState> QueryClusterState(
NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken = default)
{
using var cmd = CreateCommand("select pg_is_in_recovery(); SHOW default_transaction_read_only");
cmd.CommandTimeout = (int)timeout.CheckAndGetTimeLeft().TotalSeconds;
// We're taking the timestamp before the query is sent, because due to issues (IO, operation ordering, etc) we can receive an
// 'old' state. Otherwise, execution of the query shouldn't make notable difference.
var timeStamp = DateTime.UtcNow;
var reader = async ? await cmd.ExecuteReaderAsync(cancellationToken) : cmd.ExecuteReader();
try
{
if (async)
{
await reader.ReadAsync(cancellationToken);
_isHotStandBy = reader.GetBoolean(0);
await reader.NextResultAsync(cancellationToken);
await reader.ReadAsync(cancellationToken);
}
else
{
reader.Read();
_isHotStandBy = reader.GetBoolean(0);
reader.NextResult();
reader.Read();
}
_isTransactionReadOnly = reader.GetString(0) != "off";
var clusterState = UpdateClusterState(ignoreDatabaseVersion: false);
Debug.Assert(clusterState.HasValue);
return clusterState.Value;
}
finally
{
if (async)
await reader.DisposeAsync();
else
reader.Dispose();
}
}
void WriteStartupMessage(string username)
{
var startupParams = new Dictionary<string, string>
{
["user"] = username,
["client_encoding"] = Settings.ClientEncoding ??
PostgresEnvironment.ClientEncoding ??
"UTF8",
["database"] = Settings.Database!
};
if (Settings.ApplicationName?.Length > 0)
startupParams["application_name"] = Settings.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);
}
string GetUsername()
{
var username = Settings.Username;
if (username?.Length > 0)
return username;
username = PostgresEnvironment.User;
if (username?.Length > 0)
return username;
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
username = KerberosUsernameProvider.GetUsername(Settings.IncludeRealm);
if (username?.Length > 0)
return username;
}
username = Environment.UserName;
if (username?.Length > 0)
return username;
throw new NpgsqlException("No username could be found, please specify one explicitly");
}
async Task RawOpen(SslMode sslMode, NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
var cert = default(X509Certificate2?);
try
{
if (async)
await ConnectAsync(timeout, cancellationToken);
else
Connect(timeout);
_baseStream = new NetworkStream(_socket, true);
_stream = _baseStream;
if (Settings.Encoding == "UTF8")
{
TextEncoding = PGUtil.UTF8Encoding;
RelaxedTextEncoding = PGUtil.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);
IsSecure = false;
if (sslMode == SslMode.Prefer || sslMode == SslMode.Require || sslMode == SslMode.VerifyCA || sslMode == SslMode.VerifyFull)
{
WriteSslRequest();
await Flush(async, cancellationToken);
await ReadBuffer.Ensure(1, async);
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':
var clientCertificates = new X509Certificate2Collection();
var certPath = Settings.SslCertificate ?? PostgresEnvironment.SslCert ?? PostgresEnvironment.SslCertDefault;
if (certPath != null)
{
var password = Settings.SslPassword;
if (Path.GetExtension(certPath).ToUpperInvariant() != ".PFX")
{
#if NET5_0_OR_GREATER
// It's PEM time
var keyPath = Settings.SslKey ?? PostgresEnvironment.SslKey ?? PostgresEnvironment.SslKeyDefault;
cert = string.IsNullOrEmpty(password)
? X509Certificate2.CreateFromPemFile(certPath, keyPath)
: X509Certificate2.CreateFromEncryptedPemFile(certPath, password, keyPath);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
// Windows crypto API has a bug with pem certs
// See #3650
using var previousCert = cert;
cert = new X509Certificate2(cert.Export(X509ContentType.Pkcs12));
}
#else
throw new NotSupportedException("PEM certificates are only supported with .NET 5 and higher");
#endif
}
if (cert is null)
cert = new X509Certificate2(certPath, password);
clientCertificates.Add(cert);
}
ProvideClientCertificatesCallback?.Invoke(clientCertificates);
var checkCertificateRevocation = Settings.CheckCertificateRevocation;
RemoteCertificateValidationCallback? certificateValidationCallback;
if (sslMode == SslMode.Prefer || sslMode == SslMode.Require)
{
certificateValidationCallback = SslTrustServerValidation;
checkCertificateRevocation = false;
}
else if ((Settings.RootCertificate ?? PostgresEnvironment.SslCertRoot ?? PostgresEnvironment.SslCertRootDefault) is { } certRootPath)
{
certificateValidationCallback = SslRootValidation(certRootPath, sslMode == SslMode.VerifyFull);
}
else if (UserCertificateValidationCallback is not null)
{
if (sslMode is SslMode.VerifyCA or SslMode.VerifyFull)
{
throw new NotSupportedException(
string.Format(NpgsqlStrings.CannotUseSslVerifyWithUserCallback, sslMode));
}
certificateValidationCallback = UserCertificateValidationCallback;
}
else if (sslMode == SslMode.VerifyCA)
{
certificateValidationCallback = SslVerifyCAValidation;
}
else
{
Debug.Assert(sslMode == SslMode.VerifyFull);
certificateValidationCallback = SslVerifyFullValidation;
}
timeout.CheckAndApply(this);
try
{
var sslStream = new SslStream(_stream, leaveInnerStreamOpen: false, certificateValidationCallback);
var sslProtocols = SslProtocols.None;
// On .NET Framework SslProtocols.None can be disabled, see #3718
#if NETSTANDARD2_0
sslProtocols = SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12;
#endif
if (async)
await sslStream.AuthenticateAsClientAsync(Host, clientCertificates,
sslProtocols, checkCertificateRevocation);
else
sslStream.AuthenticateAsClient(Host, clientCertificates,
sslProtocols, checkCertificateRevocation);
_stream = sslStream;
}
catch (Exception e)
{
throw new NpgsqlException("Exception while performing SSL handshake", e);
}
ReadBuffer.Underlying = _stream;
WriteBuffer.Underlying = _stream;
IsSecure = true;
Logger.LogTrace("SSL negotiation successful");
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.");
}
Logger.LogTrace("Socket connected to {Host}:{Port}", Host, Port);
}
catch
{
cert?.Dispose();
_stream?.Dispose();
_stream = null!;
_baseStream?.Dispose();
_baseStream = null!;
_socket?.Dispose();
_socket = null!;
throw;
}
}
void Connect(NpgsqlTimeout timeout)
{
// Note that there aren't any timeout-able or cancellable DNS methods
var endpoints = NpgsqlConnectionStringBuilder.IsUnixSocket(Host, Port, out var socketPath)
? new EndPoint[] { new UnixDomainSocketEndPoint(socketPath) }
: Dns.GetHostAddresses(Host).Select(a => new IPEndPoint(a, Port)).ToArray();
timeout.Check();
// Give each endpoint an equal share of the remaining time
var perEndpointTimeout = -1; // Default to infinity
if (timeout.IsSet)
perEndpointTimeout = (int)(timeout.CheckAndGetTimeLeft().Ticks / endpoints.Length / 10);
for (var i = 0; i < endpoints.Length; i++)
{
var endpoint = endpoints[i];
Logger.LogTrace("Attempting to connect to {Endpoint}", endpoint);
var protocolType =
endpoint.AddressFamily == AddressFamily.InterNetwork ||
endpoint.AddressFamily == AddressFamily.InterNetworkV6
? ProtocolType.Tcp
: ProtocolType.IP;
var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, protocolType)
{
Blocking = false
};
try
{
try
{
socket.Connect(endpoint);
}
catch (SocketException e)
{
if (e.SocketErrorCode != SocketError.WouldBlock)
throw;
}
var write = new List<Socket> { socket };
var error = new List<Socket> { socket };
Socket.Select(null, write, error, perEndpointTimeout);
var errorCode = (int) socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error)!;
if (errorCode != 0)
throw new SocketException(errorCode);
if (!write.Any())
throw new TimeoutException("Timeout during connection attempt");
socket.Blocking = true;
SetSocketOptions(socket);
_socket = socket;
ConnectedEndPoint = endpoint;
return;
}
catch (Exception e)
{
try { socket.Dispose(); }
catch
{
// ignored
}
Logger.LogTrace(e, "Failed to connect to {Endpoint}", endpoint);
if (i == endpoints.Length - 1)
throw new NpgsqlException($"Failed to connect to {endpoint}", e);
}
}
}
async Task ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
{
Task<IPAddress[]> GetHostAddressesAsync(CancellationToken ct) =>
#if NET6_0_OR_GREATER
Dns.GetHostAddressesAsync(Host, ct);
#else
Dns.GetHostAddressesAsync(Host);
#endif
// Whether the framework and/or the OS platform support Dns.GetHostAddressesAsync cancellation API or they do not,
// we always fake-cancel the operation with the help of TaskTimeoutAndCancellation.ExecuteAsync. It stops waiting
// and raises the exception, while the actual task may be left running.
var endpoints = NpgsqlConnectionStringBuilder.IsUnixSocket(Host, Port, out var socketPath)
? new EndPoint[] { new UnixDomainSocketEndPoint(socketPath) }
: (await TaskTimeoutAndCancellation.ExecuteAsync(GetHostAddressesAsync, timeout, cancellationToken))
.Select(a => new IPEndPoint(a, Port)).ToArray();
// Give each IP an equal share of the remaining time
var perIpTimespan = default(TimeSpan);
var perIpTimeout = timeout;
if (timeout.IsSet)
{
perIpTimespan = new TimeSpan(timeout.CheckAndGetTimeLeft().Ticks / endpoints.Length);
perIpTimeout = new NpgsqlTimeout(perIpTimespan);
}
for (var i = 0; i < endpoints.Length; i++)
{
var endpoint = endpoints[i];
Logger.LogTrace("Attempting to connect to {Endpoint}", endpoint);
var protocolType =
endpoint.AddressFamily == AddressFamily.InterNetwork ||
endpoint.AddressFamily == AddressFamily.InterNetworkV6
? ProtocolType.Tcp
: ProtocolType.IP;
var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, protocolType);
try
{
await OpenSocketConnectionAsync(socket, endpoint, perIpTimeout, cancellationToken);
SetSocketOptions(socket);
_socket = socket;