forked from dotnet/SqlClient
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlInternalConnectionTds.cs
2889 lines (2550 loc) · 139 KB
/
SqlInternalConnectionTds.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net.Http.Headers;
using System.Runtime.CompilerServices;
using System.Security;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Transactions;
using Microsoft.Data.Common;
using Microsoft.Data.ProviderBase;
using Microsoft.Identity.Client;
namespace Microsoft.Data.SqlClient
{
internal sealed class SessionStateRecord
{
internal bool _recoverable;
internal uint _version;
internal int _dataLength;
internal byte[] _data;
}
internal sealed class SessionData
{
internal const int _maxNumberOfSessionStates = 256;
internal uint _tdsVersion;
internal bool _encrypted;
internal string _database;
internal SqlCollation _collation;
internal string _language;
internal string _initialDatabase;
internal SqlCollation _initialCollation;
internal string _initialLanguage;
internal byte _unrecoverableStatesCount = 0;
internal Dictionary<string, Tuple<string, string>> _resolvedAliases;
#if DEBUG
internal bool _debugReconnectDataApplied;
#endif
internal SessionStateRecord[] _delta = new SessionStateRecord[_maxNumberOfSessionStates];
internal bool _deltaDirty = false;
internal byte[][] _initialState = new byte[_maxNumberOfSessionStates][];
public SessionData(SessionData recoveryData)
{
_initialDatabase = recoveryData._initialDatabase;
_initialCollation = recoveryData._initialCollation;
_initialLanguage = recoveryData._initialLanguage;
_resolvedAliases = recoveryData._resolvedAliases;
for (int i = 0; i < _maxNumberOfSessionStates; i++)
{
if (recoveryData._initialState[i] != null)
{
_initialState[i] = (byte[])recoveryData._initialState[i].Clone();
}
}
}
public SessionData()
{
_resolvedAliases = new Dictionary<string, Tuple<string, string>>(2);
}
public void Reset()
{
_database = null;
_collation = null;
_language = null;
if (_deltaDirty)
{
Array.Clear(_delta, 0, _delta.Length);
_deltaDirty = false;
}
_unrecoverableStatesCount = 0;
}
[Conditional("DEBUG")]
public void AssertUnrecoverableStateCountIsCorrect()
{
byte unrecoverableCount = 0;
foreach (var state in _delta)
{
if (state != null && !state._recoverable)
unrecoverableCount++;
}
Debug.Assert(unrecoverableCount == _unrecoverableStatesCount, "Unrecoverable count does not match");
}
}
internal sealed class SqlInternalConnectionTds : SqlInternalConnection, IDisposable
{
// https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/retry-after#simple-retry-for-errors-with-http-error-codes-500-600
internal const int MsalHttpRetryStatusCode = 429;
// CONNECTION AND STATE VARIABLES
private readonly SqlConnectionPoolGroupProviderInfo _poolGroupProviderInfo; // will only be null when called for ChangePassword, or creating SSE User Instance
private TdsParser _parser;
private SqlLoginAck _loginAck;
private SqlCredential _credential;
private FederatedAuthenticationFeatureExtensionData _fedAuthFeatureExtensionData;
// Connection Resiliency
private bool _sessionRecoveryRequested;
internal bool _sessionRecoveryAcknowledged;
internal SessionData _currentSessionData; // internal for use from TdsParser only, other should use CurrentSessionData property that will fix database and language
private SessionData _recoverySessionData;
// Federated Authentication
// Response obtained from the server for FEDAUTHREQUIRED prelogin option.
internal bool _fedAuthRequired;
internal bool _federatedAuthenticationRequested;
internal bool _federatedAuthenticationAcknowledged;
internal bool _federatedAuthenticationInfoRequested; // Keep this distinct from _federatedAuthenticationRequested, since some fedauth library types may not need more info
internal bool _federatedAuthenticationInfoReceived;
// The Federated Authentication returned by TryGetFedAuthTokenLocked or GetFedAuthToken.
SqlFedAuthToken _fedAuthToken = null;
internal byte[] _accessTokenInBytes;
private readonly ActiveDirectoryAuthenticationTimeoutRetryHelper _activeDirectoryAuthTimeoutRetryHelper;
private readonly SqlAuthenticationProviderManager _sqlAuthenticationProviderManager;
internal bool _cleanSQLDNSCaching = false;
private bool _serverSupportsDNSCaching = false;
/// <summary>
/// Returns buffer time allowed before access token expiry to continue using the access token.
/// </summary>
private int accessTokenExpirationBufferTime
{
get
{
return (ConnectionOptions.ConnectTimeout == ADP.InfiniteConnectionTimeout || ConnectionOptions.ConnectTimeout >= ADP.MaxBufferAccessTokenExpiry)
? ADP.MaxBufferAccessTokenExpiry : ConnectionOptions.ConnectTimeout;
}
}
/// <summary>
/// Get or set if SQLDNSCaching is supported by the server.
/// </summary>
internal bool IsSQLDNSCachingSupported
{
get
{
return _serverSupportsDNSCaching;
}
set
{
_serverSupportsDNSCaching = value;
}
}
private bool _SQLDNSRetryEnabled = false;
/// <summary>
/// Get or set if we need retrying with IP received from FeatureExtAck.
/// </summary>
internal bool IsSQLDNSRetryEnabled
{
get
{
return _SQLDNSRetryEnabled;
}
set
{
_SQLDNSRetryEnabled = value;
}
}
private bool _DNSCachingBeforeRedirect = false;
/// <summary>
/// Get or set if the control ring send redirect token and feature ext ack with true for DNSCaching
/// </summary>
internal bool IsDNSCachingBeforeRedirectSupported
{
get
{
return _DNSCachingBeforeRedirect;
}
set
{
_DNSCachingBeforeRedirect = value;
}
}
internal SQLDNSInfo pendingSQLDNSObject = null;
// TCE flags
internal byte _tceVersionSupported;
// The pool that this connection is associated with, if at all it is.
private DbConnectionPool _dbConnectionPool;
// This is used to preserve the authentication context object if we decide to cache it for subsequent connections in the same pool.
// This will finally end up in _dbConnectionPool.AuthenticationContexts, but only after 1 successful login to SQL Server using this context.
// This variable is to persist the context after we have generated it, but before we have successfully completed the login with this new context.
// If this connection attempt ended up re-using the existing context and not create a new one, this will be null (since the context is not new).
private DbConnectionPoolAuthenticationContext _newDbConnectionPoolAuthenticationContext;
// The key of the authentication context, built from information found in the FedAuthInfoToken.
private DbConnectionPoolAuthenticationContextKey _dbConnectionPoolAuthenticationContextKey;
#if DEBUG
// This is a test hook to enable testing of the retry paths for MSAL get access token.
// Sample code to enable:
//
// Type type = typeof(SqlConnection).Assembly.GetType("Microsoft.Data.SqlClient.SQLInternalConnectionTds");
// System.Reflection.FieldInfo field = type.GetField("_forceMsalRetry", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
// if (field != null) {
// field.SetValue(null, true);
// }
//
internal static bool _forceMsalRetry = false;
// This is a test hook to simulate a token expiring within the next 45 minutes.
private static bool _forceExpiryLocked = false;
// This is a test hook to simulate a token expiring within the next 10 minutes.
private static bool _forceExpiryUnLocked = false;
#endif //DEBUG
// The timespan defining the amount of time the authentication context needs to be valid for at-least, to re-use the cached context,
// without making an attempt to refresh it. IF the context is expiring within the next 45 mins, then try to take a lock and refresh
// the context, if the lock is acquired.
private static readonly TimeSpan _dbAuthenticationContextLockedRefreshTimeSpan = new TimeSpan(hours: 0, minutes: 45, seconds: 00);
// The timespan defining the minimum amount of time the authentication context needs to be valid for re-using the cached context.
// If the context is expiring within the next 10 mins, then create a new context, irrespective of if another thread is trying to do the same.
private static readonly TimeSpan _dbAuthenticationContextUnLockedRefreshTimeSpan = new TimeSpan(hours: 0, minutes: 10, seconds: 00);
// The errors in the transient error set are contained in
// https://azure.microsoft.com/en-us/documentation/articles/sql-database-develop-error-messages/#transient-faults-connection-loss-and-other-temporary-errors
private static readonly HashSet<int> s_transientErrors = new HashSet<int>
{
// SQL Error Code: 4060
// Cannot open database "%.*ls" requested by the login. The login failed.
4060,
// SQL Error Code: 10928
// Resource ID: %d. The %s limit for the database is %d and has been reached.
10928,
// SQL Error Code: 10929
// Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d.
// However, the server is currently too busy to support requests greater than %d for this database.
10929,
// SQL Error Code: 40197
// You will receive this error, when the service is down due to software or hardware upgrades, hardware failures,
// or any other failover problems. The error code (%d) embedded within the message of error 40197 provides
// additional information about the kind of failure or failover that occurred. Some examples of the error codes are
// embedded within the message of error 40197 are 40020, 40143, 40166, and 40540.
40197,
// The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d.
40501,
// Database '%.*ls' on server '%.*ls' is not currently available. Please retry the connection later.
// If the problem persists, contact customer support, and provide them the session tracing ID of '%.*ls'.
40613,
// Can not connect to the SQL pool since it is paused. Please resume the SQL pool and try again.
42108,
// The SQL pool is warming up. Please try again.
42109
};
internal SessionData CurrentSessionData
{
get
{
if (_currentSessionData != null)
{
_currentSessionData._database = CurrentDatabase;
_currentSessionData._language = _currentLanguage;
}
return _currentSessionData;
}
}
// FOR POOLING
private bool _fConnectionOpen = false;
// FOR CONNECTION RESET MANAGEMENT
private bool _fResetConnection;
private string _originalDatabase;
private string _currentFailoverPartner; // only set by ENV change from server
private string _originalLanguage;
private string _currentLanguage;
private int _currentPacketSize;
private int _asyncCommandCount; // number of async Begins minus number of async Ends.
// FOR SSE
private string _instanceName = string.Empty;
// FOR NOTIFICATIONS
private DbConnectionPoolIdentity _identity; // Used to lookup info for notification matching Start().
// FOR SYNCHRONIZATION IN TdsParser
// How to use these locks:
// 1. Whenever writing to the connection (with the exception of Cancellation) the _parserLock MUST be taken
// 2. _parserLock will also be taken during close (to prevent closing in the middle of a write)
// 3. Whenever you have the _parserLock and are calling a method that would cause the connection to close if it failed (with the exception of any writing method), you MUST set ThreadHasParserLockForClose to true
// * This is to prevent the connection deadlocking with itself (since you already have the _parserLock, and Closing the connection will attempt to re-take that lock)
// * It is safe to set ThreadHasParserLockForClose to true when writing as well, but it is unnecessary
// * If you have a method that takes _parserLock, it is a good idea check ThreadHasParserLockForClose first (if you don't expect _parserLock to be taken by something higher on the stack, then you should at least assert that it is false)
// 4. ThreadHasParserLockForClose is thread-specific - this means that you must set it to false before returning a Task, and set it back to true in the continuation
// 5. ThreadHasParserLockForClose should only be modified if you currently own the _parserLock
// 6. Reading ThreadHasParserLockForClose is thread-safe
internal class SyncAsyncLock
{
private SemaphoreSlim _semaphore = new SemaphoreSlim(1);
internal void Wait(bool canReleaseFromAnyThread)
{
Monitor.Enter(_semaphore); // semaphore is used as lock object, no relation to SemaphoreSlim.Wait/Release methods
if (canReleaseFromAnyThread || _semaphore.CurrentCount == 0)
{
_semaphore.Wait();
if (canReleaseFromAnyThread)
{
Monitor.Exit(_semaphore);
}
else
{
_semaphore.Release();
}
}
}
internal void Wait(bool canReleaseFromAnyThread, int timeout, ref bool lockTaken)
{
lockTaken = false;
bool hasMonitor = false;
try
{
Monitor.TryEnter(_semaphore, timeout, ref hasMonitor); // semaphore is used as lock object, no relation to SemaphoreSlim.Wait/Release methods
if (hasMonitor)
{
if ((canReleaseFromAnyThread) || (_semaphore.CurrentCount == 0))
{
if (_semaphore.Wait(timeout))
{
if (canReleaseFromAnyThread)
{
Monitor.Exit(_semaphore);
hasMonitor = false;
}
else
{
_semaphore.Release();
}
lockTaken = true;
}
}
else
{
lockTaken = true;
}
}
}
finally
{
if ((!lockTaken) && (hasMonitor))
{
Monitor.Exit(_semaphore);
}
}
}
internal void Release()
{
if (_semaphore.CurrentCount == 0)
{ // semaphore methods were used for locking
_semaphore.Release();
}
else
{
Monitor.Exit(_semaphore);
}
}
internal bool CanBeReleasedFromAnyThread
{
get
{
return _semaphore.CurrentCount == 0;
}
}
// Necessary but not sufficient condition for thread to have lock (since semaphore may be obtained by any thread)
internal bool ThreadMayHaveLock()
{
return Monitor.IsEntered(_semaphore) || _semaphore.CurrentCount == 0;
}
}
internal SyncAsyncLock _parserLock = new SyncAsyncLock();
private int _threadIdOwningParserLock = -1;
private SqlConnectionTimeoutErrorInternal _timeoutErrorInternal;
internal SqlConnectionTimeoutErrorInternal TimeoutErrorInternal
{
get { return _timeoutErrorInternal; }
}
// OTHER STATE VARIABLES AND REFERENCES
internal Guid _clientConnectionId = Guid.Empty;
private Guid _originalClientConnectionId = Guid.Empty;
private string _routingDestination = null;
private readonly TimeoutTimer _timeout;
// although the new password is generally not used it must be passed to the ctor
// the new Login7 packet will always write out the new password (or a length of zero and no bytes if not present)
//
internal SqlInternalConnectionTds(
DbConnectionPoolIdentity identity,
SqlConnectionString connectionOptions,
SqlCredential credential,
object providerInfo,
string newPassword,
SecureString newSecurePassword,
bool redirectedUserInstance,
SqlConnectionString userConnectionOptions = null, // NOTE: userConnectionOptions may be different to connectionOptions if the connection string has been expanded (see SqlConnectionString.Expand)
SessionData reconnectSessionData = null,
bool applyTransientFaultHandling = false,
string accessToken = null,
DbConnectionPool pool = null
) : base(connectionOptions)
{
#if DEBUG
if (reconnectSessionData != null)
{
reconnectSessionData._debugReconnectDataApplied = true;
}
#endif
Debug.Assert(reconnectSessionData == null || connectionOptions.ConnectRetryCount > 0, "Reconnect data supplied with CR turned off");
_dbConnectionPool = pool;
if (connectionOptions.ConnectRetryCount > 0)
{
_recoverySessionData = reconnectSessionData;
if (reconnectSessionData == null)
{
_currentSessionData = new SessionData();
}
else
{
_currentSessionData = new SessionData(_recoverySessionData);
_originalDatabase = _recoverySessionData._initialDatabase;
_originalLanguage = _recoverySessionData._initialLanguage;
}
}
if (accessToken != null)
{
_accessTokenInBytes = System.Text.Encoding.Unicode.GetBytes(accessToken);
}
_activeDirectoryAuthTimeoutRetryHelper = new ActiveDirectoryAuthenticationTimeoutRetryHelper();
_sqlAuthenticationProviderManager = SqlAuthenticationProviderManager.Instance;
_identity = identity;
Debug.Assert(newSecurePassword != null || newPassword != null, "cannot have both new secure change password and string based change password to be null");
Debug.Assert(credential == null || (string.IsNullOrEmpty(connectionOptions.UserID) && string.IsNullOrEmpty(connectionOptions.Password)), "cannot mix the new secure password system and the connection string based password");
Debug.Assert(credential == null || !connectionOptions.IntegratedSecurity, "Cannot use SqlCredential and Integrated Security");
_poolGroupProviderInfo = (SqlConnectionPoolGroupProviderInfo)providerInfo;
_fResetConnection = connectionOptions.ConnectionReset;
if (_fResetConnection && _recoverySessionData == null)
{
_originalDatabase = connectionOptions.InitialCatalog;
_originalLanguage = connectionOptions.CurrentLanguage;
}
_timeoutErrorInternal = new SqlConnectionTimeoutErrorInternal();
_credential = credential;
_parserLock.Wait(canReleaseFromAnyThread: false);
ThreadHasParserLockForClose = true; // In case of error, let ourselves know that we already own the parser lock
try
{
_timeout = TimeoutTimer.StartSecondsTimeout(connectionOptions.ConnectTimeout);
// If transient fault handling is enabled then we can retry the login up to the ConnectRetryCount.
int connectionEstablishCount = applyTransientFaultHandling ? connectionOptions.ConnectRetryCount + 1 : 1;
int transientRetryIntervalInMilliSeconds = connectionOptions.ConnectRetryInterval * 1000; // Max value of transientRetryInterval is 60*1000 ms. The max value allowed for ConnectRetryInterval is 60
for (int i = 0; i < connectionEstablishCount; i++)
{
try
{
OpenLoginEnlist(_timeout, connectionOptions, credential, newPassword, newSecurePassword, redirectedUserInstance);
break;
}
catch (SqlException sqlex)
{
if (i + 1 == connectionEstablishCount
|| !applyTransientFaultHandling
|| _timeout.IsExpired
|| _timeout.MillisecondsRemaining < transientRetryIntervalInMilliSeconds
|| !IsTransientError(sqlex))
{
throw;
}
else
{
Thread.Sleep(transientRetryIntervalInMilliSeconds);
}
}
}
}
finally
{
ThreadHasParserLockForClose = false;
_parserLock.Release();
}
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlInternalConnectionTds.ctor|ADV> {0}, constructed new TDS internal connection", ObjectID);
}
// Returns true if the Sql error is a transient.
private bool IsTransientError(SqlException exc)
{
if (exc == null)
{
return false;
}
foreach (SqlError error in exc.Errors)
{
if (s_transientErrors.Contains(error.Number))
{
// When server timeouts, connection is doomed. Reset here to allow reconnect.
UnDoomThisConnection();
return true;
}
}
return false;
}
internal Guid ClientConnectionId
{
get
{
return _clientConnectionId;
}
}
internal Guid OriginalClientConnectionId
{
get
{
return _originalClientConnectionId;
}
}
internal string RoutingDestination
{
get
{
return _routingDestination;
}
}
internal RoutingInfo RoutingInfo { get; private set; } = null;
internal override SqlInternalTransaction CurrentTransaction
{
get
{
return _parser.CurrentTransaction;
}
}
internal override SqlInternalTransaction AvailableInternalTransaction
{
get
{
return _parser._fResetConnection ? null : CurrentTransaction;
}
}
internal override SqlInternalTransaction PendingTransaction
{
get
{
return _parser.PendingTransaction;
}
}
internal DbConnectionPoolIdentity Identity
{
get
{
return _identity;
}
}
internal string InstanceName
{
get
{
return _instanceName;
}
}
internal override bool IsLockedForBulkCopy
{
get
{
return (!Parser.MARSOn && Parser._physicalStateObj.BcpLock);
}
}
internal protected override bool IsNonPoolableTransactionRoot
{
get
{
return IsTransactionRoot && (!Is2008OrNewer || null == Pool);
}
}
internal override bool Is2008OrNewer
{
get
{
return _parser.Is2008OrNewer;
}
}
internal int PacketSize
{
get
{
return _currentPacketSize;
}
}
internal TdsParser Parser
{
get
{
return _parser;
}
}
internal string ServerProvidedFailOverPartner
{
get
{
return _currentFailoverPartner;
}
}
internal SqlConnectionPoolGroupProviderInfo PoolGroupProviderInfo
{
get
{
return _poolGroupProviderInfo;
}
}
protected override bool ReadyToPrepareTransaction
{
get
{
bool result = (null == FindLiveReader(null)); // can't prepare with a live data reader...
return result;
}
}
public override string ServerVersion
{
get
{
return (string.Format("{0:00}.{1:00}.{2:0000}", _loginAck.majorVersion,
(short)_loginAck.minorVersion, _loginAck.buildNum));
}
}
public int ServerProcessId
{
get
{
return Parser._physicalStateObj._spid;
}
}
protected override bool UnbindOnTransactionCompletion
{
get
{
return false;
}
}
/// <summary>
/// Validates if federated authentication is used, Access Token used by this connection is active for the value of 'accessTokenExpirationBufferTime'.
/// </summary>
internal override bool IsAccessTokenExpired => _federatedAuthenticationInfoRequested && DateTime.FromFileTimeUtc(_fedAuthToken.expirationFileTime) < DateTime.UtcNow.AddSeconds(accessTokenExpirationBufferTime);
////////////////////////////////////////////////////////////////////////////////////////
// GENERAL METHODS
////////////////////////////////////////////////////////////////////////////////////////
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs
protected override void ChangeDatabaseInternal(string database)
{
// Add brackets around database
database = SqlConnection.FixupDatabaseTransactionName(database);
Task executeTask = _parser.TdsExecuteSQLBatch("use " + database, ConnectionOptions.ConnectTimeout, null, _parser._physicalStateObj, sync: true);
Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes");
_parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj);
}
public override void Dispose()
{
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.SqlInternalConnectionTds.Dispose|ADV> {0} disposing", ObjectID);
try
{
TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this.
Debug.Assert(parser != null && _fConnectionOpen || parser == null && !_fConnectionOpen, "Unexpected state on dispose");
if (null != parser)
{
parser.Disconnect();
}
}
finally
{
// close will always close, even if exception is thrown
// remember to null out any object references
_loginAck = null;
_fConnectionOpen = false; // mark internal connection as closed
}
base.Dispose();
}
internal override void ValidateConnectionForExecute(SqlCommand command)
{
TdsParser parser = _parser;
if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed))
{
throw ADP.ClosedConnectionError();
}
else
{
SqlDataReader reader = null;
if (parser.MARSOn)
{
if (null != command)
{ // command can't have datareader already associated with it
reader = FindLiveReader(command);
}
}
else
{ // single execution/datareader per connection
if (_asyncCommandCount > 0)
{
throw SQL.MARSUnsupportedOnConnection();
}
reader = FindLiveReader(null);
}
if (null != reader)
{
// if MARS is on, then a datareader associated with the command exists
// or if MARS is off, then a datareader exists
throw ADP.OpenReaderExists(parser.MARSOn);
}
else if (!parser.MARSOn && parser._physicalStateObj.HasPendingData)
{
parser.DrainData(parser._physicalStateObj);
}
Debug.Assert(!parser._physicalStateObj.HasPendingData, "Should not have a busy physicalStateObject at this point!");
parser.RollbackOrphanedAPITransactions();
}
}
/// <summary>
/// Validate the enlisted transaction state, taking into consideration the ambient transaction and transaction unbinding mode.
/// If there is no enlisted transaction, this method is a nop.
/// </summary>
/// <remarks>
/// <para>
/// This method must be called while holding a lock on the SqlInternalConnection instance,
/// to ensure we don't accidentally execute after the transaction has completed on a different thread,
/// causing us to unwittingly execute in auto-commit mode.
/// </para>
///
/// <para>
/// When using Explicit transaction unbinding,
/// verify that the enlisted transaction is active and equal to the current ambient transaction.
/// </para>
///
/// <para>
/// When using Implicit transaction unbinding,
/// verify that the enlisted transaction is active.
/// If it is not active, and the transaction object has been disposed, unbind from the transaction.
/// If it is not active and not disposed, throw an exception.
/// </para>
/// </remarks>
internal void CheckEnlistedTransactionBinding()
{
// If we are enlisted in a transaction, check that transaction is active.
// When using explicit transaction unbinding, also verify that the enlisted transaction is the current transaction.
Transaction enlistedTransaction = EnlistedTransaction;
if (enlistedTransaction != null)
{
bool requireExplicitTransactionUnbind = ConnectionOptions.TransactionBinding == SqlConnectionString.TransactionBindingEnum.ExplicitUnbind;
if (requireExplicitTransactionUnbind)
{
Transaction currentTransaction = Transaction.Current;
if (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status || !enlistedTransaction.Equals(currentTransaction))
{
throw ADP.TransactionConnectionMismatch();
}
}
else // implicit transaction unbind
{
if (TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status)
{
if (EnlistedTransactionDisposed)
{
DetachTransaction(enlistedTransaction, true);
}
else
{
throw ADP.TransactionCompletedButNotDisposed();
}
}
}
}
}
internal override bool IsConnectionAlive(bool throwOnException)
{
bool isAlive = false;
isAlive = _parser._physicalStateObj.IsConnectionAlive(throwOnException);
return isAlive;
}
////////////////////////////////////////////////////////////////////////////////////////
// POOLING METHODS
////////////////////////////////////////////////////////////////////////////////////////
protected override void Activate(Transaction transaction)
{
// When we're required to automatically enlist in transactions and
// there is one we enlist in it. On the other hand, if there isn't a
// transaction and we are currently enlisted in one, then we
// unenlist from it.
//
// Regardless of whether we're required to automatically enlist,
// when there is not a current transaction, we cannot leave the
// connection enlisted in a transaction.
if (null != transaction)
{
if (ConnectionOptions.Enlist)
{
Enlist(transaction);
}
}
else
{
Enlist(null);
}
}
protected override void InternalDeactivate()
{
// When we're deactivated, the user must have called End on all
// the async commands, or we don't know that we're in a state that
// we can recover from. We doom the connection in this case, to
// prevent odd cases when we go to the wire.
if (0 != _asyncCommandCount)
{
DoomThisConnection();
}
// If we're deactivating with a delegated transaction, we
// should not be cleaning up the parser just yet, that will
// cause our transaction to be rolled back and the connection
// to be reset. We'll get called again once the delegated
// transaction is completed and we can do it all then.
if (!IsNonPoolableTransactionRoot)
{
Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?");
if (_parser != null)
{
_parser.Deactivate(IsConnectionDoomed);
if (!IsConnectionDoomed)
{
ResetConnection();
}
}
}
}
[SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs
private void ResetConnection()
{
// For implicit pooled connections, if connection reset behavior is specified,
// reset the database and language properties back to default. It is important
// to do this on activate so that the dictionary is correct before SqlConnection
// obtains a clone.
Debug.Assert(!HasLocalTransactionFromAPI, "Upon ResetConnection SqlInternalConnectionTds has a currently ongoing local transaction.");
Debug.Assert(!_parser._physicalStateObj.HasPendingData, "Upon ResetConnection SqlInternalConnectionTds has pending data.");
if (_fResetConnection)
{
// Ensure we are either going against 2000, or we are not enlisted in a
// distributed transaction - otherwise don't reset!
// Prepare the parser for the connection reset - the next time a trip
// to the server is made.
_parser.PrepareResetConnection(IsTransactionRoot && !IsNonPoolableTransactionRoot);
// Reset dictionary values, since calling reset will not send us env_changes.
CurrentDatabase = _originalDatabase;
_currentLanguage = _originalLanguage;
}
}
internal void DecrementAsyncCount()
{
Debug.Assert(_asyncCommandCount > 0);
Interlocked.Decrement(ref _asyncCommandCount);
}
internal void IncrementAsyncCount()
{
Interlocked.Increment(ref _asyncCommandCount);
}
////////////////////////////////////////////////////////////////////////////////////////
// LOCAL TRANSACTION METHODS
////////////////////////////////////////////////////////////////////////////////////////
internal override void DisconnectTransaction(SqlInternalTransaction internalTransaction)
{
TdsParser parser = Parser;
if (null != parser)
{
parser.DisconnectTransaction(internalTransaction);
}
}
internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, System.Data.IsolationLevel iso)
{
ExecuteTransaction(transactionRequest, name, iso, null, false);
}
internal override void ExecuteTransaction(TransactionRequest transactionRequest, string name, System.Data.IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest)
{
if (IsConnectionDoomed)
{ // doomed means we can't do anything else...
if (transactionRequest == TransactionRequest.Rollback
|| transactionRequest == TransactionRequest.IfRollback)
{
return;
}
throw SQL.ConnectionDoomed();
}
if (transactionRequest == TransactionRequest.Commit
|| transactionRequest == TransactionRequest.Rollback
|| transactionRequest == TransactionRequest.IfRollback)
{
if (!Parser.MARSOn && Parser._physicalStateObj.BcpLock)
{