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
1912 lines (1682 loc) · 71.8 KB
/
NpgsqlConnector.cs
File metadata and controls
1912 lines (1682 loc) · 71.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
// Copyright (C) 2002 The Npgsql Development Team
// npgsql-general@gborg.postgresql.org
// http://gborg.postgresql.org/project/npgsql/projdisplay.php
//
// 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.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using Common.Logging;
using Mono.Security.Protocol.Tls;
using Npgsql.Localization;
using Npgsql.BackendMessages;
using Npgsql.TypeHandlers;
using NpgsqlTypes;
using System.Text;
using System.Text.RegularExpressions;
using Npgsql.FrontendMessages;
using SecurityProtocolType = Mono.Security.Protocol.Tls.SecurityProtocolType;
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
{
readonly NpgsqlConnectionStringBuilder _settings;
/// <summary>
/// The physical connection socket to the backend.
/// </summary>
internal Socket Socket { get; set; }
/// <summary>
/// The physical connection stream to the backend.
/// </summary>
internal NpgsqlNetworkStream BaseStream { get; set; }
// The top level stream to the backend.
// This is a BufferedStream.
// With SSL, this stream sits on top of the SSL stream, which sits on top of _baseStream.
// Otherwise, this stream sits directly on top of _baseStream.
internal Stream Stream { get; set; }
/// <summary>
/// Buffer used for reading data.
/// </summary>
internal NpgsqlBuffer Buffer { get; private set; }
/// <summary>
/// The connection mediator.
/// </summary>
internal NpgsqlMediator Mediator { get; private set; }
/// <summary>
/// Version of backend server this connector is connected to.
/// </summary>
internal Version ServerVersion { get; set; }
/// <summary>
/// The secret key of the backend for this connector, used for query cancellation.
/// </summary>
internal int BackendSecretKey { get; set; }
/// <summary>
/// The process ID of the backend for this connector.
/// </summary>
internal int BackendProcessId { get; set; }
internal bool Pooled { get; private set; }
internal TypeHandlerRegistry TypeHandlerRegistry { get; set; }
TransactionStatus _txStatus;
NpgsqlTransaction _tx;
/// <summary>
/// The number of messages that were prepended to the current message chain.
/// </summary>
byte _prependedMessages;
/// <summary>
/// A chain of messages to be sent to the backend.
/// </summary>
List<FrontendMessage> _messagesToSend;
internal NpgsqlDataReader CurrentReader;
/// <summary>
/// Holds all run-time parameters received from the backend (via ParameterStatus messages)
/// </summary>
internal Dictionary<string, string> BackendParams;
/// <summary>
/// Commands to be executed when the reader is done.
/// Current usage is for when a prepared command is disposed while its reader is still open; the
/// actual DEALLOCATE message must be deferred.
/// </summary>
List<string> _deferredCommands;
/// <summary>
/// Whether the backend is an AWS Redshift instance
/// </summary>
bool? _isRedshift;
// For IsValid test
readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
string _initQueries;
internal SSPIHandler SSPI { get; set; }
static readonly ILog _log = LogManager.GetCurrentClassLogger();
SemaphoreSlim _notificationSemaphore;
byte[] _emptyBuffer = new byte[0];
int _notificationBlockRecursionDepth;
#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();
#endregion
public NpgsqlConnector(NpgsqlConnection connection)
: this(connection.CopyConnectionStringBuilder(), connection.Pooling)
{}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="connectionString">Connection string.</param>
/// <param name="pooled">Pooled</param>
public NpgsqlConnector(NpgsqlConnectionStringBuilder connectionString, bool pooled)
{
State = ConnectorState.Closed;
_txStatus = TransactionStatus.Idle;
_settings = connectionString;
Pooled = pooled;
BackendParams = new Dictionary<string, string>();
Mediator = new NpgsqlMediator();
_messagesToSend = new List<FrontendMessage>();
_preparedStatementIndex = 0;
_portalIndex = 0;
_deferredCommands = new List<string>();
}
#region Configuration settings
/// <summary>
/// Return Connection String.
/// </summary>
internal static bool UseSslStream = true;
internal string ConnectionString { get { return _settings.ConnectionString; } }
internal string Host { get { return _settings.Host; } }
internal int Port { get { return _settings.Port; } }
internal string Database { get { return _settings.ContainsKey(Keywords.Database) ? _settings.Database : _settings.UserName; } }
internal string UserName { get { return _settings.UserName; } }
internal string Password { get { return _settings.Password; } }
internal bool SSL { get { return _settings.SSL; } }
internal SslMode SslMode { get { return _settings.SslMode; } }
internal int BufferSize { get { return _settings.BufferSize; } }
internal bool UseMonoSsl { get { return ValidateRemoteCertificateCallback == null; } }
internal int ConnectionTimeout { get { return _settings.Timeout; } }
internal int DefaultCommandTimeout { get { return _settings.CommandTimeout; } }
internal bool Enlist { get { return _settings.Enlist; } }
internal bool IntegratedSecurity { get { return _settings.IntegratedSecurity; } }
internal Version CompatVersion { get { return _settings.Compatible; } }
#endregion Configuration settings
#region State management
volatile 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);
switch (value)
{
case ConnectorState.Ready:
ExecuteDeferredCommands();
if (CurrentReader != null) {
CurrentReader.Command.State = CommandState.Idle;
CurrentReader = null;
}
break;
case ConnectorState.Closed:
case ConnectorState.Broken:
if (CurrentReader != null) {
CurrentReader.Command.State = CommandState.Idle;
CurrentReader = null;
}
ClearTransaction();
break;
case ConnectorState.Connecting:
case ConnectorState.Executing:
case ConnectorState.Fetching:
case ConnectorState.CopyIn:
case ConnectorState.CopyOut:
break;
default:
throw new ArgumentOutOfRangeException("value");
}
}
}
/// <summary>
/// Returns whether the connector is open, regardless of any task it is currently performing
/// </summary>
internal bool IsConnected
{
get
{
switch (State)
{
case ConnectorState.Ready:
case ConnectorState.Executing:
case ConnectorState.Fetching:
case ConnectorState.CopyIn:
case ConnectorState.CopyOut:
return true;
case ConnectorState.Closed:
case ConnectorState.Connecting:
case ConnectorState.Broken:
return false;
default:
throw new ArgumentOutOfRangeException("State", "Unknown state: " + State);
}
}
}
/// <summary>
/// Returns whether the connector is open and performing a task, i.e. not ready for a query
/// </summary>
internal bool IsBusy
{
get
{
switch (State)
{
case ConnectorState.Executing:
case ConnectorState.Fetching:
case ConnectorState.CopyIn:
case ConnectorState.CopyOut:
return true;
case ConnectorState.Ready:
case ConnectorState.Closed:
case ConnectorState.Connecting:
case ConnectorState.Broken:
return false;
default:
throw new ArgumentOutOfRangeException("State", "Unknown state: " + State);
}
}
}
internal void CheckReadyState()
{
switch (State)
{
case ConnectorState.Ready:
return;
case ConnectorState.Closed:
case ConnectorState.Broken:
case ConnectorState.Connecting:
throw new InvalidOperationException(L10N.ConnectionNotOpen);
case ConnectorState.Executing:
case ConnectorState.Fetching:
throw new InvalidOperationException("There is already an open DataReader associated with this Connection which must be closed first.");
case ConnectorState.CopyIn:
case ConnectorState.CopyOut:
throw new InvalidOperationException("A COPY operation is in progress and must complete first.");
default:
throw new ArgumentOutOfRangeException("Connector.State", "Unknown state: " + State);
}
}
#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 void Open()
{
if (State != ConnectorState.Closed) {
throw new InvalidOperationException("Can't open, state is " + State);
}
State = ConnectorState.Connecting;
ServerVersion = null;
// Keep track of time remaining; Even though there may be multiple timeout-able calls,
// this allows us to still respect the caller's timeout expectation.
var connectTimeRemaining = ConnectionTimeout * 1000;
// Get a raw connection, possibly SSL...
RawOpen(connectTimeRemaining);
try
{
var startupMessage = new StartupMessage(Database, UserName);
if (!string.IsNullOrEmpty(_settings.ApplicationName)) {
startupMessage.ApplicationName = _settings.ApplicationName;
}
if (!string.IsNullOrEmpty(_settings.SearchPath)) {
startupMessage.SearchPath = _settings.SearchPath;
}
var len = startupMessage.Length;
if (len >= Buffer.Size) { // Should really never happen, just in case
throw new Exception(String.Format("Buffer ({0} bytes) not big enough to contain Startup message ({1} bytes)", Buffer.Size, len));
}
startupMessage.Prepare();
if (startupMessage.Length > Buffer.Size) {
throw new Exception("Startup message bigger than buffer");
}
startupMessage.Write(Buffer);
// TODO: Possible optimization: send settings like ssl_renegotiation in the same packet,
// reduce one roundtrip
Buffer.Flush();
HandleAuthentication();
}
catch
{
if (Stream != null)
{
try {
Stream.Dispose();
}
catch {}
}
throw;
}
// After attachment, the stream will close the connector (this) when the stream gets disposed.
BaseStream.AttachConnector(this);
// Fall back to the old way, SELECT VERSION().
// This should not happen for protocol version 3+.
if (ServerVersion == null)
{
//NpgsqlCommand command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this);
//ServerVersion = new Version(PGUtil.ExtractServerVersion((string) command.ExecuteScalar()));
using (var command = new NpgsqlCommand("set DATESTYLE TO ISO;select version();", this))
{
ServerVersion = new Version(PGUtil.ExtractServerVersion((string)command.ExecuteScalar()));
}
}
ProcessServerVersion();
var sbInitQueries = new StringWriter();
// Some connection parameters for protocol 3 had been sent in the startup packet.
// The rest will be setted here.
if (SupportsSslRenegotiationLimit) {
sbInitQueries.WriteLine("SET ssl_renegotiation_limit=0;");
}
_initQueries = sbInitQueries.ToString();
ExecuteBlind(_initQueries);
TypeHandlerRegistry.Setup(this);
// Make a shallow copy of the type mapping that the connector will own.
// It is possible that the connector may add types to its private
// mapping that will not be valid to another connector, even
// if connected to the same backend version.
//NativeToBackendTypeConverterOptions.OidToNameMapping = NpgsqlTypesHelper.CreateAndLoadInitialTypesMapping(this).Clone();
State = ConnectorState.Ready;
if (_settings.SyncNotification)
{
AddNotificationListener();
}
}
public void RawOpen(int timeout)
{
// Keep track of time remaining; Even though there may be multiple timeout-able calls,
// this allows us to still respect the caller's timeout expectation.
var attemptStart = DateTime.Now;
var result = Dns.BeginGetHostAddresses(Host, null, null);
if (!result.AsyncWaitHandle.WaitOne(timeout, true))
{
// Timeout was used up attempting the Dns lookup
throw new TimeoutException(L10N.DnsLookupTimeout);
}
timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);
var ips = Dns.EndGetHostAddresses(result);
Socket socket = null;
Exception lastSocketException = null;
// try every ip address of the given hostname, use the first reachable one
// make sure not to exceed the caller's timeout expectation by splitting the
// time we have left between all the remaining ip's in the list.
for (var i = 0; i < ips.Length; i++)
{
_log.Trace("Attempting to connect to " + ips[i]);
var ep = new IPEndPoint(ips[i], Port);
socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
attemptStart = DateTime.Now;
try
{
result = socket.BeginConnect(ep, null, null);
if (!result.AsyncWaitHandle.WaitOne(timeout / (ips.Length - i), true))
{
throw new TimeoutException(L10N.ConnectionTimeout);
}
socket.EndConnect(result);
// connect was successful, leave the loop
break;
}
catch (Exception e)
{
_log.Warn("Failed to connect to " + ips[i]);
timeout -= Convert.ToInt32((DateTime.Now - attemptStart).TotalMilliseconds);
lastSocketException = e;
socket.Close();
socket = null;
}
}
if (socket == null)
{
throw lastSocketException;
}
var baseStream = new NpgsqlNetworkStream(socket, true);
Stream sslStream = null;
// If the PostgreSQL server has SSL connectors enabled Open SslClientStream if (response == 'S') {
if (SSL || (SslMode == SslMode.Require) || (SslMode == SslMode.Prefer))
{
baseStream
.WriteInt32(8)
.WriteInt32(80877103);
// Receive response
var response = (Char)baseStream.ReadByte();
if (response != 'S')
{
if (SslMode == SslMode.Require) {
throw new InvalidOperationException(L10N.SslRequestError);
}
}
else
{
//create empty collection
var clientCertificates = new X509CertificateCollection();
//trigger the callback to fetch some certificates
DefaultProvideClientCertificatesCallback(clientCertificates);
//if (context.UseMonoSsl)
if (!UseSslStream)
{
var sslStreamPriv = new SslClientStream(baseStream, Host, true, SecurityProtocolType.Default, clientCertificates)
{
ClientCertSelectionDelegate = DefaultCertificateSelectionCallback,
ServerCertValidationDelegate = DefaultCertificateValidationCallback,
PrivateKeyCertSelectionDelegate = DefaultPrivateKeySelectionCallback
};
sslStream = sslStreamPriv;
IsSecure = true;
}
else
{
var sslStreamPriv = new SslStream(baseStream, true, DefaultValidateRemoteCertificateCallback);
sslStreamPriv.AuthenticateAsClient(Host, clientCertificates, System.Security.Authentication.SslProtocols.Default, false);
sslStream = sslStreamPriv;
IsSecure = true;
}
}
}
Socket = socket;
BaseStream = baseStream;
//Stream = new BufferedStream(sslStream ?? baseStream, 8192);
Stream = BaseStream;
Buffer = new NpgsqlBuffer(Stream, BufferSize, PGUtil.UTF8Encoding);
_log.DebugFormat("Connected to {0}:{1 }", Host, Port);
}
void HandleAuthentication()
{
_log.Trace("Authenticating...");
while (true)
{
var msg = ReadSingleMessage();
switch (msg.Code)
{
case BackendMessageCode.ReadyForQuery:
State = ConnectorState.Ready;
return;
case BackendMessageCode.AuthenticationRequest:
ProcessAuthenticationMessage((AuthenticationRequestMessage)msg);
continue;
default:
throw new Exception("Unexpected message received while authenticating: " + msg.Code);
}
}
}
void ProcessAuthenticationMessage(AuthenticationRequestMessage msg)
{
PasswordMessage passwordMessage;
switch (msg.AuthRequestType)
{
case AuthenticationRequestType.AuthenticationOk:
return;
case AuthenticationRequestType.AuthenticationCleartextPassword:
passwordMessage = PasswordMessage.CreateClearText(Password);
break;
case AuthenticationRequestType.AuthenticationMD5Password:
passwordMessage = PasswordMessage.CreateMD5(Password, UserName, ((AuthenticationMD5PasswordMessage)msg).Salt);
break;
case AuthenticationRequestType.AuthenticationGSS:
if (!IntegratedSecurity) {
throw new Exception("GSS authentication but IntegratedSecurity not enabled");
}
// For GSSAPI we have to use the supplied hostname
SSPI = new SSPIHandler(Host, "POSTGRES", true);
passwordMessage = new PasswordMessage(SSPI.Continue(null));
break;
case AuthenticationRequestType.AuthenticationSSPI:
if (!IntegratedSecurity) {
throw new Exception("SSPI authentication but IntegratedSecurity not enabled");
}
// For SSPI we have to get the IP-Address (hostname doesn't work)
var ipAddressString = ((IPEndPoint)Socket.RemoteEndPoint).Address.ToString();
SSPI = new SSPIHandler(ipAddressString, "POSTGRES", false);
passwordMessage = new PasswordMessage(SSPI.Continue(null));
break;
case AuthenticationRequestType.AuthenticationGSSContinue:
var passwdRead = SSPI.Continue(((AuthenticationGSSContinueMessage)msg).AuthenticationData);
if (passwdRead.Length != 0)
{
passwordMessage = new PasswordMessage(passwdRead);
break;
}
return;
default:
throw new NotSupportedException(String.Format(L10N.AuthenticationMethodNotSupported, msg.AuthRequestType));
}
passwordMessage.Prepare();
passwordMessage.Write(Buffer);
Buffer.Flush();
}
#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 PrependMessage(FrontendMessage msg)
{
_prependedMessages++;
_messagesToSend.Add(msg);
}
[GenerateAsync]
internal void SendAllMessages()
{
try
{
foreach (var msg in _messagesToSend)
{
SendMessage(msg);
}
Buffer.Flush();
}
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>
void SendSingleMessage(FrontendMessage msg)
{
AddMessage(msg);
SendAllMessages();
}
[GenerateAsync]
void SendMessage(FrontendMessage msg)
{
try
{
_log.DebugFormat("Sending: {0}", msg);
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, 0, directBuf.Size == 0 ? directBuf.Buffer.Length : directBuf.Size);
directBuf.Buffer = null;
directBuf.Size = 0;
}
}
return;
}
throw PGUtil.ThrowIfReached();
}
catch
{
State = ConnectorState.Broken;
throw;
}
}
#endregion
#region Backend message processing
[GenerateAsync]
internal BackendMessage ReadSingleMessage(DataRowLoadingMode dataRowLoadingMode = DataRowLoadingMode.NonSequential, bool ignoreNotifications = true)
{
try
{
return DoReadSingleMessage(dataRowLoadingMode, ignoreNotifications);
}
catch (NpgsqlException)
{
throw;
}
catch
{
State = ConnectorState.Broken;
throw;
}
}
[GenerateAsync]
BackendMessage DoReadSingleMessage(DataRowLoadingMode dataRowLoadingMode = DataRowLoadingMode.NonSequential, bool ignoreNotifications = true)
{
NpgsqlError error = null;
while (true)
{
var buf = Buffer;
Buffer.Ensure(5);
var messageCode = (BackendMessageCode) Buffer.ReadByte();
Contract.Assume(Enum.IsDefined(typeof(BackendMessageCode), messageCode), "Unknown message code: " + messageCode);
var len = Buffer.ReadInt32() - 4; // Transmitted length includes itself
if (messageCode == BackendMessageCode.DataRow && dataRowLoadingMode != DataRowLoadingMode.NonSequential)
{
if (dataRowLoadingMode == DataRowLoadingMode.Skip)
{
Buffer.Skip(len);
continue;
}
}
else if (len > Buffer.ReadBytesLeft)
{
buf = buf.EnsureOrAllocateTemp(len);
}
var msg = ParseServerMessage(buf, messageCode, len, dataRowLoadingMode);
if (msg != null || !ignoreNotifications && (messageCode == BackendMessageCode.NoticeResponse || messageCode == BackendMessageCode.NotificationResponse))
{
if (error != null)
{
Contract.Assert(messageCode == BackendMessageCode.ReadyForQuery, "Expected ReadyForQuery after ErrorResponse");
throw new NpgsqlException(error);
}
return msg;
}
else if (messageCode == BackendMessageCode.ErrorResponse)
{
// An ErrorResponse is (almost) always followed by a ReadyForQuery. Save the error
// and throw it as an exception when the ReadyForQuery is received (next)
// The exception is during the startup/authentication phase, where the server closes
// the connection after an ErrorResponse
error = new NpgsqlError(buf);
if (State == ConnectorState.Connecting) {
throw new NpgsqlException(error);
}
}
}
}
BackendMessage ParseServerMessage(NpgsqlBuffer buf, BackendMessageCode code, int len, DataRowLoadingMode dataRowLoadingMode)
{
switch (code)
{
case BackendMessageCode.RowDescription:
// TODO: Recycle
var rowDescriptionMessage = new RowDescriptionMessage();
return rowDescriptionMessage.Load(buf, TypeHandlerRegistry);
case BackendMessageCode.DataRow:
Contract.Assert(dataRowLoadingMode == DataRowLoadingMode.NonSequential || dataRowLoadingMode == DataRowLoadingMode.Sequential);
return dataRowLoadingMode == DataRowLoadingMode.Sequential
? _dataRowSequentialMessage.Load(buf)
: _dataRowNonSequentialMessage.Load(buf);
case BackendMessageCode.CompletedResponse:
return _commandCompleteMessage.Load(buf, len);
case BackendMessageCode.ReadyForQuery:
var rfq = _readyForQueryMessage.Load(buf);
TransactionStatus = rfq.TransactionStatusIndicator;
return rfq;
case BackendMessageCode.EmptyQueryResponse:
return EmptyQueryMessage.Instance;
case BackendMessageCode.ParseComplete:
return ParseCompleteMessage.Instance;
case BackendMessageCode.ParameterDescription:
return _parameterDescriptionMessage.Load(buf);
case BackendMessageCode.BindComplete:
return BindCompleteMessage.Instance;
case BackendMessageCode.NoData:
return NoDataMessage.Instance;
case BackendMessageCode.CloseComplete:
return CloseCompletedMessage.Instance;
case BackendMessageCode.ParameterStatus:
HandleParameterStatus(buf.ReadNullTerminatedString(), buf.ReadNullTerminatedString());
return null;
case BackendMessageCode.NoticeResponse:
// TODO: Recycle
FireNotice(new NpgsqlError(buf));
return null;
case BackendMessageCode.NotificationResponse:
FireNotification(new NpgsqlNotificationEventArgs(buf));
return null;
case BackendMessageCode.AuthenticationRequest:
var authType = (AuthenticationRequestType)buf.ReadInt32();
_log.Trace("Received AuthenticationRequest of type " + authType);
switch (authType)
{
case AuthenticationRequestType.AuthenticationOk:
return AuthenticationOkMessage.Instance;
case AuthenticationRequestType.AuthenticationCleartextPassword:
return AuthenticationCleartextPasswordMessage.Instance;
case AuthenticationRequestType.AuthenticationMD5Password:
return AuthenticationMD5PasswordMessage.Load(buf);
case AuthenticationRequestType.AuthenticationGSS:
return AuthenticationGSSMessage.Instance;
case AuthenticationRequestType.AuthenticationSSPI:
return AuthenticationSSPIMessage.Instance;
case AuthenticationRequestType.AuthenticationGSSContinue:
return AuthenticationGSSContinueMessage.Load(buf, len);
default:
throw new NotSupportedException(String.Format(L10N.AuthenticationMethodNotSupported, authType));
}
case BackendMessageCode.BackendKeyData:
BackendProcessId = buf.ReadInt32();
BackendSecretKey = buf.ReadInt32();
return null;
case BackendMessageCode.CopyData:
case BackendMessageCode.CopyDone:
case BackendMessageCode.CancelRequest:
case BackendMessageCode.CopyDataRows:
case BackendMessageCode.CopyInResponse:
case BackendMessageCode.CopyOutResponse:
throw new NotImplementedException();
case BackendMessageCode.PortalSuspended:
case BackendMessageCode.IO_ERROR:
Debug.Fail("Unimplemented message: " + code);
throw new NotImplementedException("Unimplemented message: " + code);
case BackendMessageCode.ErrorResponse:
return null;
case BackendMessageCode.FunctionCallResponse:
// We don't use the obsolete function call protocol
throw new Exception("Unexpected backend message: " + code);
default:
throw PGUtil.ThrowIfReached("Unknown backend message code: " + code);
}
}
/// <summary>
/// Reads backend messages and discards them, stopping only after a message of the given types has
/// been seen. Note that when this method is called, the buffer position must be properly set at
/// the start of the next message.
/// </summary>
internal BackendMessage SkipUntil(params BackendMessageCode[] stopAt)
{
Contract.Requires(!stopAt.Any(c => c == BackendMessageCode.DataRow), "Shouldn't be used for rows, doesn't know about sequential");
while (true)
{
var msg = ReadSingleMessage(DataRowLoadingMode.Skip);
Contract.Assert(!(msg is DataRowMessage));
if (stopAt.Contains(msg.Code)) {
return msg;
}
}
}
/// <summary>
/// Processes the response from any messages that were prepended to the message chain.
/// These messages are currently assumed to be simple queries with no result sets.
/// </summary>
[GenerateAsync]
internal void ReadPrependedMessageResponses()
{
for (; _prependedMessages > 0; _prependedMessages--)
{
SkipUntil(BackendMessageCode.ReadyForQuery);
}
}
#endregion Backend message processing
#region Transactions
/// <summary>
/// The current transaction status for this connector.
/// </summary>
internal TransactionStatus TransactionStatus
{
get { return _txStatus; }
private set
{
if (value == _txStatus) { return; }
switch (value) {
case TransactionStatus.Idle:
ClearTransaction();
break;
case TransactionStatus.InTransactionBlock:
case TransactionStatus.InFailedTransactionBlock:
break;
case TransactionStatus.Pending:
throw new Exception("Invalid TransactionStatus (should be frontend-only)");
default:
throw PGUtil.ThrowIfReached();
}
_txStatus = value;
}
}
/// <summary>
/// The transaction currently in progress, if any.
/// 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 backend transaction status.
/// </summary>
internal NpgsqlTransaction Transaction
{
get { return _tx; }
set
{
Contract.Requires(TransactionStatus == TransactionStatus.Idle);
_tx = value;
_txStatus = TransactionStatus.Pending;
}
}
internal void ClearTransaction()
{
if (_txStatus == TransactionStatus.Idle) { return; }
_tx.Connection = null;
_tx = null;
_txStatus = TransactionStatus.Idle;
}
#endregion
#region Copy In / Out
internal NpgsqlCopyFormat CopyFormat { get; private set; }
// TODO: Currently unused
NpgsqlCopyFormat ReadCopyHeader()
{
var copyFormat = (byte)Buffer.ReadByte();
var numCopyFields = Buffer.ReadInt16();
var copyFieldFormats = new short[numCopyFields];
for (short i = 0; i < numCopyFields; i++)
{
copyFieldFormats[i] = Buffer.ReadInt16();
}
return new NpgsqlCopyFormat(copyFormat, copyFieldFormats);
}
/// <summary>
/// Called from NpgsqlState.ProcessBackendResponses upon CopyInResponse.
/// If CopyStream is already set, it is used to read data to push to server, after which the copy is completed.
/// Otherwise CopyStream is set to a writable NpgsqlCopyInStream that calls SendCopyData each time it is written to.
/// </summary>
internal void StartCopyIn(NpgsqlCopyFormat copyFormat)
{
CopyFormat = copyFormat;
var userFeed = Mediator.CopyStream;