forked from npgsql/npgsql
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNpgsqlConnector.cs
More file actions
2094 lines (1826 loc) · 77.8 KB
/
NpgsqlConnector.cs
File metadata and controls
2094 lines (1826 loc) · 77.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#region License
// The PostgreSQL License
//
// Copyright (C) 2016 The Npgsql Development Team
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose, without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph and the following two paragraphs appear in all copies.
//
// IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY
// FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES,
// INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
// DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
// THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
// ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS
// TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
#endregion
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics.Contracts;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
using AsyncRewriter;
using JetBrains.Annotations;
using Npgsql.BackendMessages;
using Npgsql.FrontendMessages;
using Npgsql.Logging;
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>
internal partial class NpgsqlConnector
{
#region Fields and Properties
/// <summary>
/// The physical connection socket to the backend.
/// </summary>
Socket _socket;
/// <summary>
/// The physical connection stream to the backend, without anything on top.
/// </summary>
NetworkStream _baseStream;
/// <summary>
/// The physical connection stream to the backend, layered with an SSL/TLS stream if in secure mode.
/// </summary>
Stream _stream;
readonly NpgsqlConnectionStringBuilder _settings;
/// <summary>
/// Contains the clear text password which was extracted from the user-provided connection string.
/// If non-cleartext authentication is requested from the server, this is set to null.
/// </summary>
readonly string _password;
/// <summary>
/// Buffer used for reading data.
/// </summary>
internal NpgsqlBuffer Buffer { get; private set; }
/// <summary>
/// Version of backend server this connector is connected to.
/// </summary>
internal Version ServerVersion { get; private set; }
/// <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 TypeHandlerRegistry TypeHandlerRegistry { get; set; }
/// <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>
byte _pendingRfqPrependedMessages;
/// <summary>
/// The number of messages that were prepended and sent to the last message chain.
/// Note that this only tracks messages which produce a ReadyForQuery message
/// </summary>
byte _sentRfqPrependedMessages;
/// <summary>
/// A chain of messages to be sent to the backend.
/// </summary>
readonly List<FrontendMessage> _messagesToSend;
internal NpgsqlDataReader CurrentReader;
/// <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> BackendParams;
#if NET45 || NET451 || DNX451
SSPIHandler _sspi;
#endif
/// <summary>
/// The frontend timeout for reading messages that are part of the user's command
/// (i.e. which aren't internal prepended commands).
/// </summary>
internal int UserCommandFrontendTimeout { private get; set; }
/// <summary>
/// Contains the current value of the statement_timeout parameter at the backend,
/// used to determine whether we need to change it when commands are sent.
/// </summary>
/// <remarks>
/// 0 means means no timeout.
/// -1 means that the current value is unknown.
/// </remarks>
int _backendTimeout;
/// <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 _frontendTimeout;
/// <summary>
/// A lock that's taken while a user action is in progress, e.g. a command being executed.
/// </summary>
SemaphoreSlim _userLock;
/// <summary>
/// A lock that's taken while a non-user-triggered async action is in progress, e.g. handling of an
/// asynchronous notification or a connection keepalive. Does <b>not</b> get taken for a user async
/// action such as <see cref="DbCommand.ExecuteReaderAsync()"/>.
/// </summary>
SemaphoreSlim _asyncLock;
/// <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>
readonly object _cancelLock;
readonly UserAction _userAction;
readonly Timer _keepAliveTimer;
static readonly byte[] EmptyBuffer = new byte[0];
static readonly NpgsqlLogger Log = NpgsqlLogManager.GetCurrentClassLogger();
#endregion
#region Constants
/// <summary>
/// Number of seconds added as a margin to the backend timeout to yield the frontend timeout.
/// We prefer the backend to timeout - it's a clean error which doesn't break the connector.
/// </summary>
const int FrontendTimeoutMargin = 3;
/// <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
// Frontend. Note that these are only used for single-query commands.
internal readonly ParseMessage ParseMessage = new ParseMessage();
internal readonly BindMessage BindMessage = new BindMessage();
internal readonly DescribeMessage DescribeMessage = new DescribeMessage();
internal readonly ExecuteMessage ExecuteMessage = new ExecuteMessage();
// Backend
readonly CommandCompleteMessage _commandCompleteMessage = new CommandCompleteMessage();
readonly ReadyForQueryMessage _readyForQueryMessage = new ReadyForQueryMessage();
readonly ParameterDescriptionMessage _parameterDescriptionMessage = new ParameterDescriptionMessage();
readonly DataRowSequentialMessage _dataRowSequentialMessage = new DataRowSequentialMessage();
readonly DataRowNonSequentialMessage _dataRowNonSequentialMessage = new DataRowNonSequentialMessage();
// Since COPY is rarely used, allocate these lazily
CopyInResponseMessage _copyInResponseMessage;
CopyOutResponseMessage _copyOutResponseMessage;
CopyDataMessage _copyDataMessage;
#endregion
#region Constructors
internal NpgsqlConnector(NpgsqlConnection connection)
: this(connection.Settings, connection.Password)
{
Connection = connection;
Connection.Connector = this;
}
/// <summary>
/// Creates a new connector with the given connection string.
/// </summary>
/// <param name="connectionString">The connection string.</param>
/// <param name="password">The clear-text password or null if not using a password.</param>
NpgsqlConnector(NpgsqlConnectionStringBuilder connectionString, string password)
{
State = ConnectorState.Closed;
TransactionStatus = TransactionStatus.Idle;
_settings = connectionString;
_password = password;
BackendParams = new Dictionary<string, string>();
_messagesToSend = new List<FrontendMessage>();
_preparedStatementIndex = 0;
_userLock = new SemaphoreSlim(1, 1);
_asyncLock = new SemaphoreSlim(1, 1);
_userAction = new UserAction(this);
_cancelLock = new object();
if (KeepAlive > 0) {
_keepAliveTimer = new Timer(PerformKeepAlive, null, Timeout.Infinite, Timeout.Infinite);
}
}
#endregion
#region Configuration settings
internal string ConnectionString => _settings.ConnectionString;
string Host => _settings.Host;
int Port => _settings.Port;
string Database => _settings.Database;
string Username => _settings.Username;
string KerberosServiceName => _settings.KerberosServiceName;
SslMode SslMode => _settings.SslMode;
bool UseSslStream => _settings.UseSslStream;
int BufferSize => _settings.BufferSize;
int ConnectionTimeout => _settings.Timeout;
bool BackendTimeouts => _settings.BackendTimeouts;
int KeepAlive => _settings.KeepAlive;
bool IntegratedSecurity => _settings.IntegratedSecurity;
bool ContinuousProcessing => _settings.ContinuousProcessing;
internal bool ConvertInfinityDateTime => _settings.ConvertInfinityDateTime;
int ActualInternalCommandTimeout
{
get
{
Contract.Ensures(Contract.Result<int>() == 0 || Contract.Result<int>() >= MinimumInternalCommandTimeout);
var internalTimeout = _settings.InternalCommandTimeout;
if (internalTimeout == -1) {
return Math.Max(_settings.CommandTimeout, MinimumInternalCommandTimeout);
}
Contract.Assert(internalTimeout == 0 || internalTimeout >= MinimumInternalCommandTimeout);
return internalTimeout;
}
}
#endregion Configuration settings
#region State management
int _state;
/// <summary>
/// Gets the current state of the connector
/// </summary>
internal ConnectorState State
{
get { return (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.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;
#endregion
#region Open
/// <summary>
/// Totally temporary until the connection pool is rewritten with timeout support
/// </summary>
internal void Open()
{
Open(new NpgsqlTimeout(TimeSpan.Zero));
}
/// <summary>
/// Opens the physical connection to the server.
/// </summary>
/// <remarks>Usually called by the RequestConnector
/// Method of the connection pool manager.</remarks>
[RewriteAsync]
internal void Open(NpgsqlTimeout timeout)
{
Contract.Requires(Connection != null && Connection.Connector == this);
Contract.Requires(State == ConnectorState.Closed);
State = ConnectorState.Connecting;
try {
RawOpen(timeout);
WriteStartupMessage();
Buffer.Flush();
timeout.Check();
HandleAuthentication(timeout);
TypeHandlerRegistry.Setup(this, timeout);
Log.Debug($"Opened connection to {Host}:{Port}", Id);
if (ContinuousProcessing) {
HandleAsyncMessages();
}
}
catch
{
BreakFromOpen();
throw;
}
}
void WriteStartupMessage()
{
var startupMessage = new StartupMessage {
["client_encoding"] = "UTF8",
["user"] = Username
};
if (!string.IsNullOrEmpty(Database))
{
startupMessage["database"] = Database;
}
if (!string.IsNullOrEmpty(_settings.ApplicationName))
{
startupMessage["application_name"] = _settings.ApplicationName;
}
if (!string.IsNullOrEmpty(_settings.SearchPath))
{
startupMessage["search_path"] = _settings.SearchPath;
}
if (_settings.BackendTimeouts && _settings.CommandTimeout != 0)
{
startupMessage["statement_timeout"] = (_settings.CommandTimeout * 1000).ToString();
_backendTimeout = _settings.CommandTimeout;
}
if (IsSecure && !IsRedshift)
{
startupMessage["ssl_renegotiation_limit"] = "0";
}
if (startupMessage.Length > Buffer.Size)
{ // Should really never happen, just in case
throw new Exception("Startup message bigger than buffer");
}
startupMessage.Write(Buffer);
}
[RewriteAsync]
void RawOpen(NpgsqlTimeout timeout)
{
try
{
Connect(timeout);
Contract.Assert(_socket != null);
_baseStream = new NetworkStream(_socket, true);
_stream = _baseStream;
Buffer = new NpgsqlBuffer(_stream, BufferSize, PGUtil.UTF8Encoding);
if (SslMode == SslMode.Require || SslMode == SslMode.Prefer)
{
Log.Trace("Attempting SSL negotiation");
SSLRequestMessage.Instance.Write(Buffer);
Buffer.Flush();
Buffer.Ensure(1);
var response = (char)Buffer.ReadByte();
timeout.Check();
switch (response)
{
default:
throw new Exception($"Received unknown response {response} for SSLRequest (expecting S or N)");
case 'N':
if (SslMode == SslMode.Require)
{
throw new InvalidOperationException("SSL connection requested. No SSL enabled connection from this host is configured.");
}
break;
case 'S':
var clientCertificates = new X509CertificateCollection();
Connection.ProvideClientCertificatesCallback?.Invoke(clientCertificates);
RemoteCertificateValidationCallback certificateValidationCallback;
if (_settings.TrustServerCertificate)
{
certificateValidationCallback = (sender, certificate, chain, errors) => true;
}
else if (Connection.UserCertificateValidationCallback != null)
{
certificateValidationCallback = Connection.UserCertificateValidationCallback;
}
else
{
certificateValidationCallback = DefaultUserCertificateValidationCallback;
}
if (!UseSslStream)
{
#if NET45 || NET451 || DNX451
var sslStream = new TlsClientStream.TlsClientStream(_stream);
sslStream.PerformInitialHandshake(Host, clientCertificates, certificateValidationCallback, false);
_stream = sslStream;
#else
throw new NotSupportedException("TLS implementation not yet supported with .NET Core, specify UseSslStream=true for now");
#endif
}
else
{
var sslStream = new SslStream(_stream, false, certificateValidationCallback);
#if DOTNET5_4
// CoreCLR removed sync methods from SslStream, see https://github.com/dotnet/corefx/pull/4868.
// Consider exactly what to do here.
sslStream.AuthenticateAsClientAsync(Host, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false).Wait();
#else
sslStream.AuthenticateAsClient(Host, clientCertificates, SslProtocols.Tls | SslProtocols.Tls11 | SslProtocols.Tls12, false);
#endif
_stream = sslStream;
}
timeout.Check();
Buffer.Underlying = _stream;
IsSecure = true;
Log.Trace("SSL negotiation successful");
break;
}
}
Log.Trace($"Socket connected to {Host}:{Port}");
}
catch
{
if (_stream != null)
{
try { _stream.Dispose(); } catch {
// ignored
}
_stream = null;
}
if (_baseStream != null)
{
try { _baseStream.Dispose(); } catch {
// ignored
}
_baseStream = null;
}
if (_socket != null)
{
try { _socket.Dispose(); } catch {
// ignored
}
_socket = null;
}
throw;
}
}
void Connect(NpgsqlTimeout timeout)
{
#if NET45 || NET451 || DNX451
// Note that there aren't any timeoutable DNS methods, and we want to use sync-only
// methods (not to rely on any TP threads etc.)
var ips = Dns.GetHostAddresses(Host);
#else
// .NET Core doesn't appear to have sync DNS methods (yet?)
var ips = Dns.GetHostAddressesAsync(Host).Result;
#endif
timeout.Check();
// Give each IP an equal share of the remaining time
var perIpTimeout = timeout.IsSet ? (int)((timeout.TimeLeft.Ticks / ips.Length) / 10) : -1;
for (var i = 0; i < ips.Length; i++)
{
Log.Trace("Attempting to connect to " + ips[i]);
var ep = new IPEndPoint(ips[i], Port);
var socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
{
Blocking = false
};
try
{
try
{
socket.Connect(ep);
}
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, perIpTimeout);
var errorCode = (int) socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error);
if (errorCode != 0) {
throw new SocketException((int)socket.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Error));
}
if (!write.Any())
{
Log.Warn(
$"Timeout after {new TimeSpan(perIpTimeout*10).TotalSeconds} seconds when connecting to {ips[i]}");
try { socket.Dispose(); }
catch
{
// ignored
}
if (i == ips.Length - 1)
{
throw new TimeoutException();
}
continue;
}
socket.Blocking = true;
_socket = socket;
return;
}
catch (TimeoutException) { throw; }
catch
{
try { socket.Dispose(); }
catch
{
// ignored
}
Log.Warn("Failed to connect to " + ips[i]);
if (i == ips.Length - 1)
{
throw;
}
}
}
}
async Task ConnectAsync(NpgsqlTimeout timeout, CancellationToken cancellationToken)
{
// Note that there aren't any timeoutable or cancellable DNS methods
var ips = await Dns.GetHostAddressesAsync(Host).WithCancellation(cancellationToken);
// Give each IP an equal share of the remaining time
var perIpTimespan = timeout.IsSet ? new TimeSpan(timeout.TimeLeft.Ticks / ips.Length) : TimeSpan.Zero;
var perIpTimeout = timeout.IsSet ? new NpgsqlTimeout(perIpTimespan) : timeout;
for (var i = 0; i < ips.Length; i++)
{
Log.Trace("Attempting to connect to " + ips[i], Id);
var ep = new IPEndPoint(ips[i], Port);
var socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
#if DOTNET5_4
var connectTask = socket.ConnectAsync(ep);
#else
var connectTask = Task.Factory.FromAsync(socket.BeginConnect, socket.EndConnect, ep, null);
#endif
try
{
try
{
await connectTask.WithCancellationAndTimeout(perIpTimeout, cancellationToken);
}
catch (OperationCanceledException)
{
#pragma warning disable 4014
// ReSharper disable once MethodSupportsCancellation
connectTask.ContinueWith(t => socket.Dispose());
#pragma warning restore 4014
if (timeout.HasExpired)
{
Log.Warn($"Timeout after {perIpTimespan.TotalSeconds} seconds when connecting to {ips[i]}");
if (i == ips.Length - 1)
{
throw new TimeoutException();
}
continue;
}
// We're here if an actual cancellation was requested (not a timeout)
throw;
}
_socket = socket;
return;
}
catch (TimeoutException) { throw; }
catch (OperationCanceledException) { throw; }
catch
{
try { socket.Dispose(); }
catch
{
// ignored
}
Log.Warn("Failed to connect to " + ips[i]);
if (i == ips.Length - 1)
{
throw;
}
}
}
}
[RewriteAsync]
void HandleAuthentication(NpgsqlTimeout timeout)
{
Log.Trace("Authenticating...", Id);
while (true)
{
var msg = ReadSingleMessage(DataRowLoadingMode.NonSequential);
timeout.Check();
switch (msg.Code)
{
case BackendMessageCode.AuthenticationRequest:
var passwordMessage = ProcessAuthenticationMessage((AuthenticationRequestMessage)msg);
if (passwordMessage != null)
{
passwordMessage.Write(Buffer);
Buffer.Flush();
timeout.Check();
}
continue;
case BackendMessageCode.BackendKeyData:
var backendKeyDataMsg = (BackendKeyDataMessage) msg;
BackendProcessId = backendKeyDataMsg.BackendProcessId;
_backendSecretKey = backendKeyDataMsg.BackendSecretKey;
continue;
case BackendMessageCode.ReadyForQuery:
State = ConnectorState.Ready;
return;
default:
throw new Exception("Unexpected message received while authenticating: " + msg.Code);
}
}
}
/// <summary>
/// Performs a step in the PostgreSQL authentication protocol
/// </summary>
/// <param name="msg">A message read from the server, instructing us on the required response</param>
/// <returns>a PasswordMessage to be sent, or null if authentication has completed successfully</returns>
[CanBeNull]
PasswordMessage ProcessAuthenticationMessage(AuthenticationRequestMessage msg)
{
switch (msg.AuthRequestType)
{
case AuthenticationRequestType.AuthenticationOk:
return null;
case AuthenticationRequestType.AuthenticationCleartextPassword:
if (_password == null) {
throw new Exception("No password has been provided but the backend requires one (in cleartext)");
}
return PasswordMessage.CreateClearText(_password);
case AuthenticationRequestType.AuthenticationMD5Password:
if (_password == null) {
throw new Exception("No password has been provided but the backend requires one (in MD5)");
}
return PasswordMessage.CreateMD5(_password, Username, ((AuthenticationMD5PasswordMessage)msg).Salt);
case AuthenticationRequestType.AuthenticationGSS:
if (!IntegratedSecurity) {
throw new Exception("GSS authentication but IntegratedSecurity not enabled");
}
#if NET45 || NET451 || DNX451
// For GSSAPI we have to use the supplied hostname
_sspi = new SSPIHandler(Host, KerberosServiceName, true);
return new PasswordMessage(_sspi.Continue(null));
#else
throw new NotSupportedException("SSPI not yet supported in .NET Core");
#endif
case AuthenticationRequestType.AuthenticationSSPI:
if (!IntegratedSecurity) {
throw new Exception("SSPI authentication but IntegratedSecurity not enabled");
}
#if NET45 || NET451 || DNX451
_sspi = new SSPIHandler(Host, KerberosServiceName, false);
return new PasswordMessage(_sspi.Continue(null));
#else
throw new NotSupportedException("SSPI not yet supported in .NET Core");
#endif
case AuthenticationRequestType.AuthenticationGSSContinue:
#if NET45 || NET451 || DNX451
var passwdRead = _sspi.Continue(((AuthenticationGSSContinueMessage)msg).AuthenticationData);
if (passwdRead.Length != 0)
{
return new PasswordMessage(passwdRead);
}
return null;
#else
throw new NotSupportedException("SSPI not yet supported in .NET Core");
#endif
default:
throw new NotSupportedException(
$"Authentication method not supported (Received: {msg.AuthRequestType})");
}
}
#endregion
#region Frontend message processing
internal void AddMessage(FrontendMessage msg)
{
_messagesToSend.Add(msg);
}
/// <summary>
/// Prepends a message to be sent at the beginning of the next message chain.
/// </summary>
internal void PrependInternalMessage(FrontendMessage msg, bool withTimeout=true)
{
// Set backend timeout if needed.
if (withTimeout) {
PrependBackendTimeoutMessage(ActualInternalCommandTimeout);
}
if (msg is QueryMessage || msg is PregeneratedMessage || msg is SyncMessage)
{
// These messages produce a ReadyForQuery response, which we will be looking for when
// processing the message chain results
checked { _pendingRfqPrependedMessages++; }
}
_messagesToSend.Add(msg);
}
internal void PrependBackendTimeoutMessage(int timeout)
{
if (_backendTimeout == timeout || !BackendTimeouts) {
return;
}
_backendTimeout = timeout;
checked { _pendingRfqPrependedMessages++; }
switch (timeout) {
case 10:
_messagesToSend.Add(PregeneratedMessage.SetStmtTimeout10Sec);
return;
case 20:
_messagesToSend.Add(PregeneratedMessage.SetStmtTimeout20Sec);
return;
case 30:
_messagesToSend.Add(PregeneratedMessage.SetStmtTimeout30Sec);
return;
case 60:
_messagesToSend.Add(PregeneratedMessage.SetStmtTimeout60Sec);
return;
case 90:
_messagesToSend.Add(PregeneratedMessage.SetStmtTimeout90Sec);
return;
case 120:
_messagesToSend.Add(PregeneratedMessage.SetStmtTimeout120Sec);
return;
default:
_messagesToSend.Add(new QueryMessage($"SET statement_timeout = {timeout*1000}"));
return;
}
}
[RewriteAsync]
internal void SendAllMessages()
{
if (!_messagesToSend.Any()) {
return;
}
// If a cancellation is in progress, wait for it to "complete" before proceeding (#615)
lock (_cancelLock) { }
_sentRfqPrependedMessages = _pendingRfqPrependedMessages;
_pendingRfqPrependedMessages = 0;
try
{
foreach (var msg in _messagesToSend)
{
SendMessage(msg);
}
Buffer.Flush();
}
catch
{
Break();
throw;
}
finally
{
_messagesToSend.Clear();
}
}
/// <summary>
/// Sends a single frontend message, used for simple messages such as rollback, etc.
/// Note that additional prepend messages may be previously enqueued, and will be sent along
/// with this message.
/// </summary>
/// <param name="msg"></param>
internal void SendSingleMessage(FrontendMessage msg)
{
AddMessage(msg);
SendAllMessages();
}
[RewriteAsync]
void SendMessage(FrontendMessage msg)
{
Log.Trace($"Sending: {msg}", Id);
var asSimple = msg as SimpleFrontendMessage;
if (asSimple != null)
{
if (asSimple.Length > Buffer.WriteSpaceLeft)
{
Buffer.Flush();
}
Contract.Assume(Buffer.WriteSpaceLeft >= asSimple.Length);
asSimple.Write(Buffer);
return;
}
var asComplex = msg as ChunkingFrontendMessage;
if (asComplex != null)
{
var directBuf = new DirectBuffer();
while (!asComplex.Write(Buffer, ref directBuf))
{
Buffer.Flush();
// The following is an optimization hack for writing large byte arrays without passing
// through our buffer
if (directBuf.Buffer != null)
{
Buffer.Underlying.Write(directBuf.Buffer, directBuf.Offset, directBuf.Size == 0 ? directBuf.Buffer.Length : directBuf.Size);
directBuf.Buffer = null;
directBuf.Size = 0;
}
}
return;
}
throw PGUtil.ThrowIfReached();
}
#endregion
#region Backend message processing
internal IBackendMessage ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode)
{
var msg = ReadSingleMessageWithPrepended(dataRowLoadingMode);
Contract.Assert(msg != null);
return msg;
}
internal Task<IBackendMessage> ReadSingleMessageAsync(DataRowLoadingMode dataRowLoadingMode, CancellationToken cancellationToken)
{
return ReadSingleMessageWithPrependedAsync(cancellationToken, dataRowLoadingMode);
}
[CanBeNull]
IBackendMessage ReadSingleMessageWithNulls(DataRowLoadingMode dataRowLoadingMode)
{
return ReadSingleMessageWithPrepended(dataRowLoadingMode, true);
}
[RewriteAsync]
[CanBeNull]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IBackendMessage ReadSingleMessageWithPrepended(DataRowLoadingMode dataRowLoadingMode = DataRowLoadingMode.NonSequential, bool returnNullForAsyncMessage = false)
{
// First read the responses of any prepended messages.
// Exceptions shouldn't happen here, we break the connector if they do
if (_sentRfqPrependedMessages > 0)
{
try
{
SetFrontendTimeout(ActualInternalCommandTimeout);
while (_sentRfqPrependedMessages > 0)
{
var msg = DoReadSingleMessage(DataRowLoadingMode.Skip, isPrependedMessage: true);
if (msg is ReadyForQueryMessage)
{
_sentRfqPrependedMessages--;