/
NpgsqlConnector.cs
2111 lines (1813 loc) · 83.8 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.Collections.Generic;
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.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Npgsql.BackendMessages;
using Npgsql.Logging;
using Npgsql.TypeMapping;
using Npgsql.Util;
using static Npgsql.Util.Statics;
namespace Npgsql
{
/// <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>
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!;
internal NpgsqlConnectionStringBuilder Settings { get; }
internal string ConnectionString { get; }
ProvideClientCertificatesCallback? ProvideClientCertificatesCallback { get; }
RemoteCertificateValidationCallback? UserCertificateValidationCallback { get; }
internal 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; }
/// <summary>
/// A unique ID identifying this connector, used for logging. Currently mapped to BackendProcessId
/// </summary>
internal int Id => BackendProcessId;
internal NpgsqlDatabaseInfo DatabaseInfo { get; private set; } = default!;
internal ConnectorTypeMapper TypeMapper { get; set; } = default!;
/// <summary>
/// The current transaction status for this connector.
/// </summary>
internal TransactionStatus TransactionStatus { get; set; }
/// <summary>
/// The transaction currently in progress, if any.
/// </summary>
/// <remarks>
/// <para>
/// Note that this doesn't mean a transaction request has actually been sent to the backend - for
/// efficiency we defer sending the request to the first query after BeginTransaction is called.
/// See <see cref="TransactionStatus"/> for the actual transaction status.
/// </para>
/// <para>
/// Also, the user can initiate a transaction in SQL (i.e. BEGIN), in which case there will be no
/// NpgsqlTransaction instance. As a result, never check <see cref="Transaction"/> to know whether
/// a transaction is in progress, check <see cref="TransactionStatus"/> instead.
/// </para>
/// </remarks>
internal NpgsqlTransaction? Transaction { 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>
int _pendingPrependedResponses;
internal NpgsqlDataReader? CurrentReader;
internal PreparedStatementManager PreparedStatementManager;
/// <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[], byte[])> _rawParameters = new List<(byte[] Name, byte[] Value)>();
/// <summary>
/// The timeout for reading messages that are part of the user's command
/// (i.e. which aren't internal prepended commands).
/// </summary>
internal int UserTimeout { private get; set; }
int ReceiveTimeout
{
set
{
// TODO: Socket.ReceiveTimeout doesn't work for async.
if (value != _currentTimeout)
_socket.ReceiveTimeout = _currentTimeout = value;
}
}
/// <summary>
/// Contains the current value of the socket's ReceiveTimeout, used to determine whether
/// we need to change it when commands are received.
/// </summary>
int _currentTimeout;
// This is used by NpgsqlCommand, but we place it on the connector because only one instance is needed
// at any one time (per connection).
internal SqlQueryParser SqlParser { get; }
/// <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 int _keepAlive;
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;
/// <summary>
/// If pooled, the timestamp when this connector was returned to the pool.
/// </summary>
internal DateTime ReleaseTimestamp { get; set; } = DateTime.MaxValue;
internal int ClearCounter { get; set; }
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
#endregion
#region Constants
/// <summary>
/// The minimum timeout that can be set on internal commands such as COMMIT, ROLLBACK.
/// </summary>
internal const int MinimumInternalCommandTimeout = 3;
#endregion
#region Reusable Message Objects
byte[]? _resetWithoutDeallocateMessage;
int _resetWithoutDeallocateResponseCount;
// Backend
readonly CommandCompleteMessage _commandCompleteMessage = new CommandCompleteMessage();
readonly ReadyForQueryMessage _readyForQueryMessage = new ReadyForQueryMessage();
readonly ParameterDescriptionMessage _parameterDescriptionMessage = new ParameterDescriptionMessage();
readonly DataRowMessage _dataRowMessage = new DataRowMessage();
readonly RowDescriptionMessage _rowDescriptionMessage = new RowDescriptionMessage();
// Since COPY is rarely used, allocate these lazily
CopyInResponseMessage? _copyInResponseMessage;
CopyOutResponseMessage? _copyOutResponseMessage;
CopyDataMessage? _copyDataMessage;
#endregion
internal NpgsqlDataReader DataReader { get; }
#region Constructors
internal NpgsqlConnector(NpgsqlConnection connection)
: this(connection.Settings, connection.OriginalConnectionString)
{
Connection = connection;
Connection.Connector = this;
ProvideClientCertificatesCallback = Connection.ProvideClientCertificatesCallback;
UserCertificateValidationCallback = Connection.UserCertificateValidationCallback;
}
NpgsqlConnector(NpgsqlConnector connector)
: this(connector.Settings, connector.ConnectionString)
{
ProvideClientCertificatesCallback = connector.ProvideClientCertificatesCallback;
UserCertificateValidationCallback = connector.UserCertificateValidationCallback;
}
/// <summary>
/// Creates a new connector with the given connection string.
/// </summary>
/// <param name="settings">The parsed connection string.</param>
/// <param name="connectionString">The connection string.</param>
NpgsqlConnector(NpgsqlConnectionStringBuilder settings, string connectionString)
{
State = ConnectorState.Closed;
TransactionStatus = TransactionStatus.Idle;
Settings = settings;
ConnectionString = connectionString;
PostgresParameters = new Dictionary<string, string>();
SqlParser = new SqlQueryParser(UseConformantStrings);
CancelLock = new object();
_isKeepAliveEnabled = Settings.KeepAlive > 0;
if (_isKeepAliveEnabled)
{
_keepAlive = Settings.KeepAlive * 1000;
_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);
}
#endregion
#region Configuration settings
string Host => Settings.Host!;
int Port => Settings.Port;
string KerberosServiceName => Settings.KerberosServiceName;
SslMode SslMode => Settings.SslMode;
int ConnectionTimeout => Settings.Timeout;
bool IntegratedSecurity => Settings.IntegratedSecurity;
internal bool ConvertInfinityDateTime => Settings.ConvertInfinityDateTime;
int InternalCommandTimeout
{
get
{
var internalTimeout = Settings.InternalCommandTimeout;
if (internalTimeout == -1)
return Math.Max(Settings.CommandTimeout, MinimumInternalCommandTimeout) * 1000;
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
{
get
{
switch (State)
{
case ConnectorState.Ready:
case ConnectorState.Executing:
case ConnectorState.Fetching:
case ConnectorState.Waiting:
case ConnectorState.Copy:
return true;
case ConnectorState.Closed:
case ConnectorState.Connecting:
case ConnectorState.Broken:
return false;
default:
throw new ArgumentOutOfRangeException("Unknown state: " + State);
}
}
}
internal bool IsReady => State == ConnectorState.Ready;
internal bool IsClosed => State == ConnectorState.Closed;
internal bool IsBroken => State == ConnectorState.Broken;
bool _isConnecting;
#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(Connection != null && Connection.Connector == this);
Debug.Assert(State == ConnectorState.Closed);
if (string.IsNullOrWhiteSpace(Host))
throw new ArgumentException("Host can't be null");
_isConnecting = true;
State = ConnectorState.Connecting;
try {
await RawOpen(timeout, async, cancellationToken);
var username = GetUsername();
if (Settings.Database == null)
Settings.Database = username;
WriteStartupMessage(username);
await Flush(async);
timeout.Check();
await Authenticate(username, timeout, async);
// We treat BackendKeyData as optional because some PostgreSQL-like database
// don't send it (CockroachDB, CrateDB)
var msg = await ReadMessage(async);
if (msg.Code == BackendMessageCode.BackendKeyData)
{
var keyDataMsg = (BackendKeyDataMessage)msg;
BackendProcessId = keyDataMsg.BackendProcessId;
_backendSecretKey = keyDataMsg.BackendSecretKey;
msg = await ReadMessage(async);
}
if (msg.Code != BackendMessageCode.ReadyForQuery)
throw new NpgsqlException($"Received backend message {msg.Code} while expecting ReadyForQuery. Please file a bug.");
State = ConnectorState.Ready;
await LoadDatabaseInfo(timeout, async);
if (Settings.Pooling && DatabaseInfo.SupportsDiscard)
GenerateResetMessage();
Counters.NumberOfNonPooledConnections.Increment();
Counters.HardConnectsPerSecond.Increment();
Log.Trace($"Opened connection to {Host}:{Port}");
// If an exception occurs during open, Break() below shouldn't close the connection, which would also
// update pool state. Instead we let the exception propagate and get handled by the calling pool code.
// We use an extra state flag because the connector's State varies during the type loading query
// above (Executing, Fetching...). Note also that Break() gets called from ReadMessageLong().
_isConnecting = false;
}
catch
{
Break();
throw;
}
}
internal async Task LoadDatabaseInfo(NpgsqlTimeout timeout, bool async)
{
// 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)
TypeMapper = new ConnectorTypeMapper(this);
Debug.Assert(Connection != null);
if (!NpgsqlDatabaseInfo.Cache.TryGetValue(ConnectionString, out var database))
NpgsqlDatabaseInfo.Cache[ConnectionString] = database = await NpgsqlDatabaseInfo.Load(Connection, timeout, async);
DatabaseInfo = database;
TypeMapper.Bind(DatabaseInfo);
}
void WriteStartupMessage(string username)
{
var startupParams = new Dictionary<string, string>
{
["user"] = username,
["client_encoding"] =
Settings.ClientEncoding ??
Environment.GetEnvironmentVariable("PGCLIENTENCODING") ??
"UTF8"
};
Debug.Assert(Settings.Database != null);
startupParams["database"] = Settings.Database;
if (!string.IsNullOrEmpty(Settings.ApplicationName))
startupParams["application_name"] = Settings.ApplicationName;
if (!string.IsNullOrEmpty(Settings.SearchPath))
startupParams["search_path"] = Settings.SearchPath;
// SSL renegotiation support has been dropped in recent versions of PostgreSQL
// (OpenSSL implementations were buggy etc.), but disable them for older un-patched
// versions which turns it on by default.
// Amazon Redshift doesn't recognize the ssl_renegotiation_limit parameter and bombs
// (https://forums.aws.amazon.com/thread.jspa?messageID=721898򰏪)
if (IsSecure && !IsRedshift)
startupParams["ssl_renegotiation_limit"] = "0";
var timezone = Settings.Timezone ?? Environment.GetEnvironmentVariable("PGTZ");
if (timezone != null)
startupParams["TimeZone"] = timezone;
WriteStartup(startupParams);
}
string GetUsername()
{
var username = Settings.Username;
if (!string.IsNullOrEmpty(username))
return username;
#if NET461
if (PGUtil.IsWindows && Type.GetType("Mono.Runtime") == null)
{
username = WindowsUsernameProvider.GetUsername(Settings.IncludeRealm);
if (!string.IsNullOrEmpty(username))
return username;
}
#endif
if (!PGUtil.IsWindows)
{
username = KerberosUsernameProvider.GetUsername(Settings.IncludeRealm);
if (!string.IsNullOrEmpty(username))
return username;
}
username = Environment.UserName;
if (!string.IsNullOrEmpty(username))
return username;
username = Environment.GetEnvironmentVariable("USERNAME") ?? Environment.GetEnvironmentVariable("USER");
if (!string.IsNullOrEmpty(username))
return username;
if (username == null)
throw new NpgsqlException("No username could be found, please specify one explicitly");
return username;
}
async Task RawOpen(NpgsqlTimeout timeout, bool async, CancellationToken cancellationToken)
{
try
{
if (async)
await ConnectAsync(timeout, cancellationToken);
else
Connect(timeout);
Debug.Assert(_socket != null);
_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, Settings.ReadBufferSize, TextEncoding, RelaxedTextEncoding);
WriteBuffer = new NpgsqlWriteBuffer(this, _stream, Settings.WriteBufferSize, TextEncoding);
if (SslMode == SslMode.Require || SslMode == SslMode.Prefer)
{
WriteSslRequest();
await Flush(async);
await ReadBuffer.Ensure(1, async);
var response = (char)ReadBuffer.ReadByte();
timeout.Check();
switch (response)
{
default:
throw new NpgsqlException($"Received unknown response {response} for SSLRequest (expecting S or N)");
case 'N':
if (SslMode == SslMode.Require)
{
throw new NpgsqlException("SSL connection requested. No SSL enabled connection from this host is configured.");
}
break;
case 'S':
var clientCertificates = new X509CertificateCollection();
ProvideClientCertificatesCallback?.Invoke(clientCertificates);
RemoteCertificateValidationCallback certificateValidationCallback;
if (Settings.TrustServerCertificate)
certificateValidationCallback = (sender, certificate, chain, errors) => true;
else if (UserCertificateValidationCallback != null)
certificateValidationCallback = UserCertificateValidationCallback;
else
certificateValidationCallback = DefaultUserCertificateValidationCallback;
var sslStream = new SslStream(_stream, false, certificateValidationCallback);
if (async)
await sslStream.AuthenticateAsClientAsync(Host, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Settings.CheckCertificateRevocation);
else
sslStream.AuthenticateAsClient(Host, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, Settings.CheckCertificateRevocation);
_stream = sslStream;
timeout.Check();
ReadBuffer.Clear(); // Reset to empty after reading single SSL char
ReadBuffer.Underlying = _stream;
WriteBuffer.Underlying = _stream;
IsSecure = true;
Log.Trace("SSL negotiation successful");
break;
}
}
if (!IsSecure)
{
WriteBuffer.AwaitableSocket = new AwaitableSocket(new SocketAsyncEventArgs(), _socket);
ReadBuffer.AwaitableSocket = new AwaitableSocket(new SocketAsyncEventArgs(), _socket);
}
Log.Trace($"Socket connected to {Host}:{Port}");
}
catch
{
#pragma warning disable CS8625
try { _stream?.Dispose(); } catch {
// ignored
}
_stream = null;
try { _baseStream?.Dispose(); }
catch
{
// ignored
}
_baseStream = null;
try { _socket?.Dispose(); }
catch
{
// ignored
}
_socket = null;
throw;
#pragma warning restore CS8625
}
}
void Connect(NpgsqlTimeout timeout)
{
EndPoint[] endpoints;
if (!string.IsNullOrEmpty(Host) && Host[0] == '/')
{
endpoints = new EndPoint[] { new UnixEndPoint(Path.Combine(Host, $".s.PGSQL.{Port}")) };
}
else
{
// Note that there aren't any timeout-able DNS methods, and we want to use sync-only
// methods (not to rely on any TP threads etc.)
endpoints = 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)
{
var timeoutTicks = timeout.TimeLeft.Ticks;
if (timeoutTicks <= 0)
throw new TimeoutException();
perEndpointTimeout = (int)(timeoutTicks / endpoints.Length / 10);
}
for (var i = 0; i < endpoints.Length; i++)
{
var endpoint = endpoints[i];
Log.Trace($"Attempting to connect to {endpoint}");
var protocolType = endpoint.AddressFamily == AddressFamily.InterNetwork ? 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())
{
Log.Trace($"Timeout after {new TimeSpan(perEndpointTimeout * 10).TotalSeconds} seconds when connecting to {endpoint}");
try { socket.Dispose(); }
catch
{
// ignored
}
if (i == endpoints.Length - 1)
throw new TimeoutException();
continue;
}
socket.Blocking = true;
SetSocketOptions(socket);
_socket = socket;
return;
}
catch (TimeoutException) { throw; }
catch
{
try { socket.Dispose(); }
catch
{
// ignored
}
Log.Trace("Failed to connect to {endpoint}");
if (i == endpoints.Length - 1)
throw;
}
}
}
async Task ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
{
EndPoint[] endpoints;
if (!string.IsNullOrEmpty(Host) && Host[0] == '/')
{
endpoints = new EndPoint[] { new UnixEndPoint(Path.Combine(Host, $".s.PGSQL.{Port}")) };
}
else
{
// Note that there aren't any timeoutable or cancellable DNS methods
endpoints = (await Dns.GetHostAddressesAsync(Host).WithCancellation(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)
{
var timeoutTicks = timeout.TimeLeft.Ticks;
if (timeoutTicks <= 0)
throw new TimeoutException();
perIpTimespan = new TimeSpan(timeoutTicks / endpoints.Length);
perIpTimeout = new NpgsqlTimeout(perIpTimespan);
}
for (var i = 0; i < endpoints.Length; i++)
{
var endpoint = endpoints[i];
Log.Trace($"Attempting to connect to {endpoint}");
var protocolType = endpoint.AddressFamily == AddressFamily.InterNetwork ? ProtocolType.Tcp : ProtocolType.IP;
var socket = new Socket(endpoint.AddressFamily, SocketType.Stream, protocolType);
var connectTask = Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, endpoint, null);
try
{
try
{
await connectTask.WithCancellationAndTimeout(perIpTimeout, cancellationToken);
}
catch (OperationCanceledException)
{
#pragma warning disable 4014
// ReSharper disable once MethodSupportsCancellation
// ReSharper disable once AccessToDisposedClosure
connectTask.ContinueWith(t => socket.Dispose());
#pragma warning restore 4014
if (timeout.HasExpired)
{
Log.Trace($"Timeout after {perIpTimespan.TotalSeconds} seconds when connecting to {endpoint}");
if (i == endpoints.Length - 1)
{
throw new TimeoutException();
}
continue;
}
// We're here if an actual cancellation was requested (not a timeout)
throw;
}
SetSocketOptions(socket);
_socket = socket;
return;
}
catch (TimeoutException) { throw; }
catch (OperationCanceledException) { throw; }
catch
{
try { socket.Dispose(); }
catch
{
// ignored
}
Log.Trace($"Failed to connect to {endpoint}");
if (i == endpoints.Length - 1)
{
throw;
}
}
}
}
void SetSocketOptions(Socket socket)
{
if (socket.AddressFamily == AddressFamily.InterNetwork)
socket.NoDelay = true;
if (Settings.SocketReceiveBufferSize > 0)
socket.ReceiveBufferSize = Settings.SocketReceiveBufferSize;
if (Settings.SocketSendBufferSize > 0)
socket.SendBufferSize = Settings.SocketSendBufferSize;
if (Settings.TcpKeepAlive)
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
if (Settings.TcpKeepAliveInterval > 0 && Settings.TcpKeepAliveTime == 0)
throw new ArgumentException("If TcpKeepAliveInterval is defined, TcpKeepAliveTime must be defined as well");
if (Settings.TcpKeepAliveTime > 0)
{
if (!PGUtil.IsWindows)
throw new PlatformNotSupportedException(
"Npgsql management of TCP keepalive is supported only on Windows. " +
"TCP keepalives can still be used on other systems but are enabled via the TcpKeepAlive option or configured globally for the machine, see the relevant docs.");
var time = Settings.TcpKeepAliveTime;
var interval = Settings.TcpKeepAliveInterval > 0
? Settings.TcpKeepAliveInterval
: Settings.TcpKeepAliveTime;
// For the following see https://msdn.microsoft.com/en-us/library/dd877220.aspx
var uintSize = Marshal.SizeOf(typeof(uint));
var inOptionValues = new byte[uintSize * 3];
BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)time).CopyTo(inOptionValues, uintSize);
BitConverter.GetBytes((uint)interval).CopyTo(inOptionValues, uintSize * 2);
var result = socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);
if (result != 0)
throw new NpgsqlException($"Got non-zero value when trying to set TCP keepalive: {result}");
}
}
#endregion
#region Frontend message processing
/// <summary>
/// Prepends a message to be sent at the beginning of the next message chain.
/// </summary>
internal void PrependInternalMessage(byte[] rawMessage, int responseMessageCount)
{
_pendingPrependedResponses += responseMessageCount;
var t = WritePregenerated(rawMessage, false);
Debug.Assert(t.IsCompleted, $"Could not fully write pregenerated message into the buffer");
}
#endregion
#region Backend message processing
internal IBackendMessage ReadMessage(DataRowLoadingMode dataRowLoadingMode=DataRowLoadingMode.NonSequential)
=> ReadMessage(false, dataRowLoadingMode).GetAwaiter().GetResult()!;
internal ValueTask<IBackendMessage> ReadMessage(bool async, DataRowLoadingMode dataRowLoadingMode = DataRowLoadingMode.NonSequential)
=> DoReadMessage(async, dataRowLoadingMode)!;
internal ValueTask<IBackendMessage?> ReadMessageWithNotifications(bool async)
=> DoReadMessage(async, DataRowLoadingMode.NonSequential, true);
ValueTask<IBackendMessage?> DoReadMessage(
bool async,
DataRowLoadingMode dataRowLoadingMode = DataRowLoadingMode.NonSequential,
bool readingNotifications = false)
{
if (_pendingPrependedResponses > 0 ||
dataRowLoadingMode != DataRowLoadingMode.NonSequential ||
readingNotifications ||
ReadBuffer.ReadBytesLeft < 5)
{
return ReadMessageLong(dataRowLoadingMode, readingNotifications);
}
var messageCode = (BackendMessageCode)ReadBuffer.ReadByte();
switch (messageCode)
{
case BackendMessageCode.NoticeResponse:
case BackendMessageCode.NotificationResponse:
case BackendMessageCode.ParameterStatus:
case BackendMessageCode.ErrorResponse:
ReadBuffer.ReadPosition--;
return ReadMessageLong(dataRowLoadingMode, readingNotifications);
}
PGUtil.ValidateBackendMessageCode(messageCode);
var len = ReadBuffer.ReadInt32() - 4; // Transmitted length includes itself
if (len > ReadBuffer.ReadBytesLeft)
{
ReadBuffer.ReadPosition -= 5;
return ReadMessageLong(dataRowLoadingMode, readingNotifications);
}
return new ValueTask<IBackendMessage?>(ParseServerMessage(ReadBuffer, messageCode, len, false));
async ValueTask<IBackendMessage?> ReadMessageLong(
DataRowLoadingMode dataRowLoadingMode2,
bool readingNotifications2,
bool isReadingPrependedMessage = false)
{
// First read the responses of any prepended messages.
if (_pendingPrependedResponses > 0 && !isReadingPrependedMessage)
{
try
{
// TODO: There could be room for optimization here, rather than the async call(s)
ReceiveTimeout = InternalCommandTimeout;
for (; _pendingPrependedResponses > 0; _pendingPrependedResponses--)
await ReadMessageLong(DataRowLoadingMode.Skip, false, true);
}
catch (PostgresException)
{
Break();
throw;
}
}
try
{
ReceiveTimeout = UserTimeout;
PostgresException? error = null;
while (true)
{
await ReadBuffer.Ensure(5, async, readingNotifications2);
messageCode = (BackendMessageCode)ReadBuffer.ReadByte();
PGUtil.ValidateBackendMessageCode(messageCode);
len = ReadBuffer.ReadInt32() - 4; // Transmitted length includes itself
if ((messageCode == BackendMessageCode.DataRow &&
dataRowLoadingMode2 != DataRowLoadingMode.NonSequential) ||
messageCode == BackendMessageCode.CopyData)
{
if (dataRowLoadingMode2 == DataRowLoadingMode.Skip)
{
await ReadBuffer.Skip(len, async);
continue;
}
}
else if (len > ReadBuffer.ReadBytesLeft)
{
if (len > ReadBuffer.Size)
{
if (_origReadBuffer == null)
_origReadBuffer = ReadBuffer;
ReadBuffer = ReadBuffer.AllocateOversize(len);
}
await ReadBuffer.Ensure(len, async);
}
var msg = ParseServerMessage(ReadBuffer, messageCode, len, isReadingPrependedMessage);
switch (messageCode)
{
case BackendMessageCode.ErrorResponse:
Debug.Assert(msg == null);
// An ErrorResponse is (almost) always followed by a ReadyForQuery. Save the error
// and throw it as an exception when the ReadyForQuery is received (next).
error = PostgresException.Load(ReadBuffer);
if (State == ConnectorState.Connecting)
{
// During the startup/authentication phase, an ErrorResponse isn't followed by
// an RFQ. Instead, the server closes the connection immediately
throw error;
}
continue;
case BackendMessageCode.ReadyForQuery:
if (error != null)
throw error;
break;
// Asynchronous messages which can come anytime, they have already been handled
// in ParseServerMessage. Read the next message.
case BackendMessageCode.NoticeResponse:
case BackendMessageCode.NotificationResponse:
case BackendMessageCode.ParameterStatus:
Debug.Assert(msg == null);
if (!readingNotifications2)
continue;
return null;
}
Debug.Assert(msg != null, "Message is null for code: " + messageCode);
return msg;
}
}
catch (PostgresException)
{
if (CurrentReader != null)
{
// The reader cleanup will call EndUserAction
await CurrentReader.Cleanup(async);
}
else
{
EndUserAction();
}
throw;