-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy pathTdsParser.cs
11464 lines (9719 loc) · 522 KB
/
TdsParser.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
//------------------------------------------------------------------------------
// <copyright file="TdsParser.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">Microsoft</owner>
// <owner current="true" primary="false">Microsoft</owner>
//------------------------------------------------------------------------------
namespace System.Data.SqlClient {
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.Sql;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using MSS = Microsoft.SqlServer.Server;
// The TdsParser Object controls reading/writing to the netlib, parsing the tds,
// and surfacing objects to the user.
sealed internal class TdsParser {
private static int _objectTypeCount; // Bid counter
internal readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount);
static Task completedTask;
static Task CompletedTask {
get {
if (completedTask == null) {
completedTask = Task.FromResult<object>(null);
}
return completedTask;
}
}
internal int ObjectID {
get {
return _objectID;
}
}
// ReliabilitySection Usage:
//
// #if DEBUG
// TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
//
// RuntimeHelpers.PrepareConstrainedRegions();
// try {
// tdsReliabilitySection.Start();
// #else
// {
// #endif //DEBUG
//
// // code that requires reliability
//
// }
// #if DEBUG
// finally {
// tdsReliabilitySection.Stop();
// }
// #endif //DEBUG
internal struct ReliabilitySection {
#if DEBUG
// do not allocate TLS data in RETAIL bits
[ThreadStatic]
private static int s_reliabilityCount; // initialized to 0 by CLR
private bool m_started; // initialized to false (not started) by CLR
#endif //DEBUG
[Conditional("DEBUG")]
internal void Start() {
#if DEBUG
Debug.Assert(!m_started);
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
++s_reliabilityCount;
m_started = true;
}
#endif //DEBUG
}
[Conditional("DEBUG")]
internal void Stop() {
#if DEBUG
// cannot assert m_started - ThreadAbortException can be raised before Start is called
if (m_started) {
Debug.Assert(s_reliabilityCount > 0);
RuntimeHelpers.PrepareConstrainedRegions();
try {
}
finally {
--s_reliabilityCount;
m_started = false;
}
}
#endif //DEBUG
}
// you need to setup for a thread abort somewhere before you call this method
[Conditional("DEBUG")]
internal static void Assert(string message) {
#if DEBUG
Debug.Assert(s_reliabilityCount > 0, message);
#endif //DEBUG
}
}
// Default state object for parser
internal TdsParserStateObject _physicalStateObj = null; // Default stateObj and connection for Dbnetlib and non-MARS SNI.
// Also, default logical stateObj and connection for MARS over SNI.
internal TdsParserStateObject _pMarsPhysicalConObj = null; // With MARS enabled, cached physical stateObj and connection.
// Must keep this around - especially for callbacks on pre-MARS
// ReadAsync which will return if physical connection broken!
//
// Per Instance TDS Parser variables
//
// Constants
const int constBinBufferSize = 4096; // Size of the buffer used to read input parameter of type Stream
const int constTextBufferSize = 4096; // Size of the buffer (in chars) user to read input parameter of type TextReader
// State variables
internal TdsParserState _state = TdsParserState.Closed; // status flag for connection
private string _server = ""; // name of server that the parser connects to
internal volatile bool _fResetConnection = false; // flag to denote whether we are needing to call sp_reset
internal volatile bool _fPreserveTransaction = false; // flag to denote whether we need to preserve the transaction when reseting
private SqlCollation _defaultCollation; // default collation from the server
private int _defaultCodePage;
private int _defaultLCID;
internal Encoding _defaultEncoding = null; // for sql character data
private static EncryptionOptions _sniSupportedEncryptionOption = SNILoadHandle.SingletonInstance.Options;
private EncryptionOptions _encryptionOption = _sniSupportedEncryptionOption;
private SqlInternalTransaction _currentTransaction;
private SqlInternalTransaction _pendingTransaction; // pending transaction for Yukon and beyond.
// SQLHOT 483
// need to hold on to the transaction id if distributed transaction merely rolls back without defecting.
private long _retainedTransactionId = SqlInternalTransaction.NullTransactionId;
// This counter is used for the entire connection to track the open result count for all
// operations not under a transaction.
private int _nonTransactedOpenResultCount = 0;
// Connection reference
private SqlInternalConnectionTds _connHandler;
// Async/Mars variables
private bool _fMARS = false;
internal bool _loginWithFailover = false; // set to true while connect in failover mode so parser state object can adjust its logic
internal AutoResetEvent _resetConnectionEvent = null; // Used to serialize executes and call reset on first execute only.
internal TdsParserSessionPool _sessionPool = null; // initialized only when we're a MARS parser.
// Version variables
private bool _isShiloh = false; // set to true if we connect to a 8.0 server (SQL 2000) or later
private bool _isShilohSP1 = false; // set to true if speaking to Shiloh SP1 or later
private bool _isYukon = false; // set to true if speaking to Yukon or later
private bool _isKatmai = false;
private bool _isDenali = false;
private byte[] _sniSpnBuffer = null;
//
// SqlStatistics
private SqlStatistics _statistics = null;
private bool _statisticsIsInTransaction = false;
//
// STATIC TDS Parser variables
//
// NIC address caching
private static byte[] s_nicAddress; // cache the NIC address from the registry
// SSPI variables
private static bool s_fSSPILoaded = false; // bool to indicate whether library has been loaded
private volatile static UInt32 s_maxSSPILength = 0; // variable to hold max SSPI data size, keep for token from server
// ADAL variables
private static bool s_fADALLoaded = false; // bool to indicate whether ADAL library has been loaded
// textptr sequence
private static readonly byte[] s_longDataHeader = { 0x10, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff };
private static object s_tdsParserLock = new object();
// Various other statics
private const int ATTENTION_TIMEOUT = 5000; // internal attention timeout, in ticks
// XML metadata substitue sequence
private static readonly byte[] s_xmlMetadataSubstituteSequence = { 0xe7, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00 };
// size of Guid (e.g. _clientConnectionId, ActivityId.Id)
private const int GUID_SIZE = 16;
// NOTE: You must take the internal connection's _parserLock before modifying this
internal bool _asyncWrite = false;
// TCE supported flag, used to determine if new TDS fields are present. This is
// useful when talking to downlevel/uplevel server.
private bool _serverSupportsColumnEncryption = false;
// now data length is 1 byte
// First bit is 1 indicating client support failover partner with readonly intent
private static readonly byte[] s_FeatureExtDataAzureSQLSupportFeatureRequest = { 0x01 };
/// <summary>
/// Get or set if column encryption is supported by the server.
/// </summary>
internal bool IsColumnEncryptionSupported {
get {
return _serverSupportsColumnEncryption;
}
set {
_serverSupportsColumnEncryption = value;
}
}
/// <summary>
/// TCE version supported by the server
/// </summary>
internal byte TceVersionSupported { get; set; }
/// <summary>
/// Type of enclave being used by the server
/// </summary>
internal string EnclaveType { get; set; }
internal TdsParser(bool MARS, bool fAsynchronous) {
_fMARS = MARS; // may change during Connect to pre Yukon servers
_physicalStateObj = new TdsParserStateObject(this);
}
internal SqlInternalConnectionTds Connection {
get {
return _connHandler;
}
}
internal SqlInternalTransaction CurrentTransaction {
get {
return _currentTransaction;
}
set {
Debug.Assert(value == _currentTransaction
|| null == _currentTransaction
|| null == value
|| (null != _currentTransaction && !_currentTransaction.IsLocal), "attempting to change current transaction?");
// If there is currently a transaction active, we don't want to
// change it; this can occur when there is a delegated transaction
// and the user attempts to do an API begin transaction; in these
// cases, it's safe to ignore the set.
if ((null == _currentTransaction && null != value)
||(null != _currentTransaction && null == value)) {
_currentTransaction = value;
}
}
}
internal int DefaultLCID {
get {
return _defaultLCID;
}
}
internal EncryptionOptions EncryptionOptions {
get {
return _encryptionOption;
}
set {
_encryptionOption = value;
}
}
internal bool IsYukonOrNewer {
get {
return _isYukon;
}
}
internal bool IsKatmaiOrNewer {
get {
return _isKatmai;
}
}
internal bool MARSOn {
get {
return _fMARS;
}
}
internal SqlInternalTransaction PendingTransaction {
get {
return _pendingTransaction;
}
set {
Debug.Assert (null != value, "setting a non-null PendingTransaction?");
_pendingTransaction = value;
}
}
internal string Server {
get {
return _server;
}
}
internal TdsParserState State {
get {
return _state;
}
set {
_state = value;
}
}
internal SqlStatistics Statistics {
get {
return _statistics;
}
set {
_statistics = value;
}
}
private bool IncludeTraceHeader {
get {
return (_isDenali && Bid.TraceOn && Bid.IsOn(ActivityCorrelator.CorrelationTracePoints));
}
}
internal int IncrementNonTransactedOpenResultCount() {
// IMPORTANT - this increments the connection wide open result count for all
// operations not under a transaction! Do not call if you intend to modify the
// count for a transaction!
Debug.Assert(_nonTransactedOpenResultCount >= 0, "Unexpected result count state");
int result = Interlocked.Increment(ref _nonTransactedOpenResultCount);
return result;
}
internal void DecrementNonTransactedOpenResultCount() {
// IMPORTANT - this decrements the connection wide open result count for all
// operations not under a transaction! Do not call if you intend to modify the
// count for a transaction!
Interlocked.Decrement(ref _nonTransactedOpenResultCount);
Debug.Assert(_nonTransactedOpenResultCount >= 0, "Unexpected result count state");
}
internal void ProcessPendingAck(TdsParserStateObject stateObj) {
if (stateObj._attentionSent) {
ProcessAttention(stateObj);
}
}
internal void Connect(ServerInfo serverInfo,
SqlInternalConnectionTds connHandler,
bool ignoreSniOpenTimeout,
long timerExpire,
bool encrypt,
bool trustServerCert,
bool integratedSecurity,
bool withFailover,
bool isFirstTransparentAttempt,
SqlAuthenticationMethod authType,
bool disableTnir,
SqlAuthenticationProviderManager sqlAuthProviderManager
) {
if (_state != TdsParserState.Closed) {
Debug.Assert(false, "TdsParser.Connect called on non-closed connection!");
return;
}
_connHandler = connHandler;
_loginWithFailover = withFailover;
UInt32 sniStatus = SNILoadHandle.SingletonInstance.SNIStatus;
if (sniStatus != TdsEnums.SNI_SUCCESS) {
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
Debug.Assert(false, "SNI returned status != success, but no error thrown?");
}
//Create LocalDB instance if necessary
if (connHandler.ConnectionOptions.LocalDBInstance != null)
LocalDBAPI.CreateLocalDBInstance(connHandler.ConnectionOptions.LocalDBInstance);
if (integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated) {
LoadSSPILibrary();
// now allocate proper length of buffer
_sniSpnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength];
Bid.Trace("<sc.TdsParser.Connect|SEC> SSPI or Active Directory Authentication Library for SQL Server based integrated authentication\n");
}
else {
_sniSpnBuffer = null;
if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword) {
Bid.Trace("<sc.TdsParser.Connect|SEC> Active Directory Password authentication\n");
}
else if (authType == SqlAuthenticationMethod.SqlPassword) {
Bid.Trace("<sc.TdsParser.Connect|SEC> SQL Password authentication\n");
}
else if (authType == SqlAuthenticationMethod.ActiveDirectoryInteractive) {
Bid.Trace("<sc.TdsParser.Connect|SEC> Active Directory Interactive authentication\n");
}
else{
Bid.Trace("<sc.TdsParser.Connect|SEC> SQL authentication\n");
}
}
byte[] instanceName = null;
Debug.Assert(_connHandler != null, "SqlConnectionInternalTds handler can not be null at this point.");
_connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin);
_connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
bool fParallel = _connHandler.ConnectionOptions.MultiSubnetFailover;
TransparentNetworkResolutionState transparentNetworkResolutionState;
if (_connHandler.ConnectionOptions.TransparentNetworkIPResolution && !disableTnir)
{
if(isFirstTransparentAttempt)
transparentNetworkResolutionState = TransparentNetworkResolutionState.SequentialMode;
else
transparentNetworkResolutionState = TransparentNetworkResolutionState.ParallelMode;
}
else
transparentNetworkResolutionState = TransparentNetworkResolutionState.DisabledMode;
int totalTimeout = _connHandler.ConnectionOptions.ConnectTimeout;
_physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire,
out instanceName, _sniSpnBuffer, false, true, fParallel, transparentNetworkResolutionState, totalTimeout);
if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) {
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
// Since connect failed, free the unmanaged connection memory.
// HOWEVER - only free this after the netlib error was processed - if you
// don't, the memory for the connection object might not be accurate and thus
// a bad error could be returned (as it was when it was freed to early for me).
_physicalStateObj.Dispose();
Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Login failure\n");
ThrowExceptionAndWarning(_physicalStateObj);
Debug.Assert(false, "SNI returned status != success, but no error thrown?");
}
_server = serverInfo.ResolvedServerName;
if (null != connHandler.PoolGroupProviderInfo) {
// If we are pooling, check to see if we were processing an
// alias which has changed, which means we need to clean out
// the pool. See Webdata 104293.
// This should not apply to routing, as it is not an alias change, routed connection
// should still use VNN of AlwaysOn cluster as server for pooling purposes.
connHandler.PoolGroupProviderInfo.AliasCheck(serverInfo.PreRoutingServerName==null ?
serverInfo.ResolvedServerName: serverInfo.PreRoutingServerName);
}
_state = TdsParserState.OpenNotLoggedIn;
_physicalStateObj.SniContext = SniContext.Snix_PreLoginBeforeSuccessfullWrite; // SQL BU DT 376766
_physicalStateObj.TimeoutTime = timerExpire;
bool marsCapable = false;
_connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
_connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
UInt32 result = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId);
Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
//
Bid.Trace("<sc.TdsParser.Connect|SEC> Sending prelogin handshake\n");
SendPreLoginHandshake(instanceName, encrypt);
_connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
_connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake);
_physicalStateObj.SniContext = SniContext.Snix_PreLogin;
Bid.Trace("<sc.TdsParser.Connect|SEC> Consuming prelogin handshake\n");
PreLoginHandshakeStatus status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, out marsCapable,
out _connHandler._fedAuthRequired);
if (status == PreLoginHandshakeStatus.InstanceFailure) {
Bid.Trace("<sc.TdsParser.Connect|SEC> Prelogin handshake unsuccessful. Reattempting prelogin handshake\n");
_physicalStateObj.Dispose(); // Close previous connection
// On Instance failure re-connect and flush SNI named instance cache.
_physicalStateObj.SniContext=SniContext.Snix_Connect;
_physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire, out instanceName, _sniSpnBuffer, true, true, fParallel, transparentNetworkResolutionState, totalTimeout);
if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status) {
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Login failure\n");
ThrowExceptionAndWarning(_physicalStateObj);
}
UInt32 retCode = SNINativeMethodWrapper.SniGetConnectionId(_physicalStateObj.Handle, ref _connHandler._clientConnectionId);
Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
Bid.Trace("<sc.TdsParser.Connect|SEC> Sending prelogin handshake\n");
SendPreLoginHandshake(instanceName, encrypt);
status = ConsumePreLoginHandshake(authType, encrypt, trustServerCert, integratedSecurity, out marsCapable,
out _connHandler._fedAuthRequired);
// Don't need to check for Sphinx failure, since we've already consumed
// one pre-login packet and know we are connecting to Shiloh.
if (status == PreLoginHandshakeStatus.InstanceFailure) {
Bid.Trace("<sc.TdsParser.Connect|ERR|SEC> Prelogin handshake unsuccessful. Login failure\n");
throw SQL.InstanceFailure();
}
}
Bid.Trace("<sc.TdsParser.Connect|SEC> Prelogin handshake successful\n");
if (_fMARS && marsCapable) {
// if user explictly disables mars or mars not supported, don't create the session pool
_sessionPool = new TdsParserSessionPool(this);
}
else {
_fMARS = false;
}
if (authType == SqlAuthenticationMethod.ActiveDirectoryPassword || (authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated && _connHandler._fedAuthRequired)) {
Debug.Assert(!integratedSecurity, "The legacy Integrated Security connection string option cannot be true when using Active Directory Authentication Library for SQL Server Based workflows.");
var authProvider = sqlAuthProviderManager.GetProvider(authType);
if (authProvider != null && authProvider.GetType() == typeof(ActiveDirectoryNativeAuthenticationProvider)) {
LoadADALLibrary();
if (Bid.AdvancedOn) {
Bid.Trace("<sc.TdsParser.Connect|SEC> Active directory authentication.Loaded Active Directory Authentication Library for SQL Server\n");
}
}
}
return;
}
internal void RemoveEncryption() {
Debug.Assert(_encryptionOption == EncryptionOptions.LOGIN, "Invalid encryption option state");
UInt32 error = 0;
// Remove SSL (Encryption) SNI provider since we only wanted to encrypt login.
error = SNINativeMethodWrapper.SNIRemoveProvider(_physicalStateObj.Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV);
if (error != TdsEnums.SNI_SUCCESS) {
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
ThrowExceptionAndWarning(_physicalStateObj);
}
// create a new packet encryption changes the internal packet size Bug# 228403
try {} // EmptyTry/Finally to avoid FXCop violation
finally {
_physicalStateObj.ClearAllWritePackets();
}
}
internal void EnableMars() {
if (_fMARS) {
// Cache physical stateObj and connection.
_pMarsPhysicalConObj = _physicalStateObj;
UInt32 error = 0;
UInt32 info = 0;
// Add SMUX (MARS) SNI provider.
error = SNINativeMethodWrapper.SNIAddProvider(_pMarsPhysicalConObj.Handle, SNINativeMethodWrapper.ProviderEnum.SMUX_PROV, ref info);
if (error != TdsEnums.SNI_SUCCESS) {
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
ThrowExceptionAndWarning(_physicalStateObj);
}
// HACK HACK HACK - for Async only
// Have to post read to intialize MARS - will get callback on this when connection goes
// down or is closed.
IntPtr temp = IntPtr.Zero;
RuntimeHelpers.PrepareConstrainedRegions();
try {} finally {
_pMarsPhysicalConObj.IncrementPendingCallbacks();
error = SNINativeMethodWrapper.SNIReadAsync(_pMarsPhysicalConObj.Handle, ref temp);
if (temp != IntPtr.Zero) {
// Be sure to release packet, otherwise it will be leaked by native.
SNINativeMethodWrapper.SNIPacketRelease(temp);
}
}
Debug.Assert(IntPtr.Zero == temp, "unexpected syncReadPacket without corresponding SNIPacketRelease");
if (TdsEnums.SNI_SUCCESS_IO_PENDING != error) {
Debug.Assert(TdsEnums.SNI_SUCCESS != error, "Unexpected successfull read async on physical connection before enabling MARS!");
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
ThrowExceptionAndWarning(_physicalStateObj);
}
_physicalStateObj = CreateSession(); // Create and open default MARS stateObj and connection.
}
}
internal TdsParserStateObject CreateSession() {
TdsParserStateObject session = new TdsParserStateObject(this, (SNIHandle)_pMarsPhysicalConObj.Handle, true);
if (Bid.AdvancedOn) {
Bid.Trace("<sc.TdsParser.CreateSession|ADV> %d# created session %d\n", ObjectID, session.ObjectID);
}
return session;
}
internal TdsParserStateObject GetSession(object owner) {
TdsParserStateObject session = null;
//
if (MARSOn) {
session = _sessionPool.GetSession(owner);
Debug.Assert(!session._pendingData, "pending data on a pooled MARS session");
if (Bid.AdvancedOn) {
Bid.Trace("<sc.TdsParser.GetSession|ADV> %d# getting session %d from pool\n", ObjectID, session.ObjectID);
}
}
else {
session = _physicalStateObj;
if (Bid.AdvancedOn) {
Bid.Trace("<sc.TdsParser.GetSession|ADV> %d# getting physical session %d\n", ObjectID, session.ObjectID);
}
}
Debug.Assert(session._outputPacketNumber==1, "The packet number is expected to be 1");
return session;
}
internal void PutSession(TdsParserStateObject session) {
session.AssertStateIsClean();
if (MARSOn) {
// This will take care of disposing if the parser is closed
_sessionPool.PutSession(session);
}
else if ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken)) {
// Parser is closed\broken - dispose the stateObj
Debug.Assert(session == _physicalStateObj, "MARS is off, but session to close is not the _physicalStateObj");
_physicalStateObj.SniContext = SniContext.Snix_Close;
#if DEBUG
_physicalStateObj.InvalidateDebugOnlyCopyOfSniContext();
#endif
_physicalStateObj.Dispose();
}
else {
// Non-MARS, and session is ok - remove its owner
_physicalStateObj.Owner = null;
}
}
// This is called from a ThreadAbort - ensure that it can be run from a CER Catch
internal void BestEffortCleanup() {
_state = TdsParserState.Broken;
var stateObj = _physicalStateObj;
if (stateObj != null) {
var stateObjHandle = stateObj.Handle;
if (stateObjHandle != null) {
stateObjHandle.Dispose();
}
}
if (_fMARS) {
var sessionPool = _sessionPool;
if (sessionPool != null) {
sessionPool.BestEffortCleanup();
}
var marsStateObj = _pMarsPhysicalConObj;
if (marsStateObj != null) {
var marsStateObjHandle = marsStateObj.Handle;
if (marsStateObjHandle != null) {
marsStateObjHandle.Dispose();
}
}
}
}
private void SendPreLoginHandshake(byte[] instanceName, bool encrypt) {
// PreLoginHandshake buffer consists of:
// 1) Standard header, with type = MT_PRELOGIN
// 2) Consecutive 5 bytes for each option, (1 byte length, 2 byte offset, 2 byte payload length)
// 3) Consecutive data blocks for each option
// NOTE: packet data needs to be big endian - not the standard little endian used by
// the rest of the parser.
_physicalStateObj._outputMessageType = TdsEnums.MT_PRELOGIN;
// Initialize option offset into payload buffer
// 5 bytes for each option (1 byte length, 2 byte offset, 2 byte payload length)
int offset = (int)PreLoginOptions.NUMOPT * 5 + 1;
byte[] payload = new byte[(int)PreLoginOptions.NUMOPT * 5 + TdsEnums.MAX_PRELOGIN_PAYLOAD_LENGTH];
int payloadLength = 0;
//
for (int option = (int)PreLoginOptions.VERSION; option < (int)PreLoginOptions.NUMOPT; option++) {
int optionDataSize = 0;
// Fill in the option
_physicalStateObj.WriteByte((byte)option);
// Fill in the offset of the option data
_physicalStateObj.WriteByte((byte)((offset & 0xff00) >> 8)); // send upper order byte
_physicalStateObj.WriteByte((byte)(offset & 0x00ff)); // send lower order byte
switch (option) {
case (int)PreLoginOptions.VERSION:
Version systemDataVersion = ADP.GetAssemblyVersion();
// Major and minor
payload[payloadLength++] = (byte)(systemDataVersion.Major & 0xff);
payload[payloadLength++] = (byte)(systemDataVersion.Minor & 0xff);
// Build (Big Endian)
payload[payloadLength++] = (byte)((systemDataVersion.Build & 0xff00) >> 8);
payload[payloadLength++] = (byte)(systemDataVersion.Build & 0xff);
// Sub-build (Little Endian)
payload[payloadLength++] = (byte)(systemDataVersion.Revision & 0xff);
payload[payloadLength++] = (byte)((systemDataVersion.Revision & 0xff00) >> 8);
offset += 6;
optionDataSize = 6;
break;
case (int)PreLoginOptions.ENCRYPT:
if (_encryptionOption == EncryptionOptions.NOT_SUP) {
// If OS doesn't support encryption, inform server not supported.
payload[payloadLength] = (byte)EncryptionOptions.NOT_SUP;
}
else {
// Else, inform server of user request.
if (encrypt) {
payload[payloadLength] = (byte)EncryptionOptions.ON;
_encryptionOption = EncryptionOptions.ON;
}
else {
payload[payloadLength] = (byte)EncryptionOptions.OFF;
_encryptionOption = EncryptionOptions.OFF;
}
}
payloadLength += 1;
offset += 1;
optionDataSize = 1;
break;
case (int)PreLoginOptions.INSTANCE:
int i = 0;
while (instanceName[i] != 0) {
payload[payloadLength] = instanceName[i];
payloadLength++;
i++;
}
payload[payloadLength] = 0; // null terminate
payloadLength++;
i++;
offset += i;
optionDataSize = i;
break;
case (int)PreLoginOptions.THREADID:
Int32 threadID = TdsParserStaticMethods.GetCurrentThreadIdForTdsLoginOnly();
payload[payloadLength++] = (byte)((0xff000000 & threadID) >> 24);
payload[payloadLength++] = (byte)((0x00ff0000 & threadID) >> 16);
payload[payloadLength++] = (byte)((0x0000ff00 & threadID) >> 8);
payload[payloadLength++] = (byte)(0x000000ff & threadID);
offset += 4;
optionDataSize = 4;
break;
case (int)PreLoginOptions.MARS:
payload[payloadLength++] = (byte)(_fMARS ? 1 : 0);
offset += 1;
optionDataSize += 1;
break;
case (int)PreLoginOptions.TRACEID:
byte[] connectionIdBytes = _connHandler._clientConnectionId.ToByteArray();
Debug.Assert(GUID_SIZE == connectionIdBytes.Length);
Buffer.BlockCopy(connectionIdBytes, 0, payload, payloadLength, GUID_SIZE);
payloadLength += GUID_SIZE;
offset += GUID_SIZE;
optionDataSize = GUID_SIZE;
ActivityCorrelator.ActivityId actId = ActivityCorrelator.Next();
connectionIdBytes = actId.Id.ToByteArray();
Buffer.BlockCopy(connectionIdBytes, 0, payload, payloadLength, GUID_SIZE);
payloadLength += GUID_SIZE;
payload[payloadLength++] = (byte)(0x000000ff & actId.Sequence);
payload[payloadLength++] = (byte)((0x0000ff00 & actId.Sequence) >> 8);
payload[payloadLength++] = (byte)((0x00ff0000 & actId.Sequence) >> 16);
payload[payloadLength++] = (byte)((0xff000000 & actId.Sequence) >> 24);
int actIdSize = GUID_SIZE + sizeof(UInt32);
offset += actIdSize;
optionDataSize += actIdSize;
Bid.Trace("<sc.TdsParser.SendPreLoginHandshake|INFO> ClientConnectionID %ls, ActivityID %ls\n", _connHandler._clientConnectionId.ToString(), actId.ToString());
break;
case (int)PreLoginOptions.FEDAUTHREQUIRED:
payload[payloadLength++] = 0x01;
offset += 1;
optionDataSize += 1;
break;
default:
Debug.Assert(false, "UNKNOWN option in SendPreLoginHandshake");
break;
}
// Write data length
_physicalStateObj.WriteByte((byte)((optionDataSize & 0xff00) >> 8));
_physicalStateObj.WriteByte((byte)(optionDataSize & 0x00ff));
}
// Write out last option - to let server know the second part of packet completed
_physicalStateObj.WriteByte((byte)PreLoginOptions.LASTOPT);
// Write out payload
_physicalStateObj.WriteByteArray(payload, payloadLength, 0);
// Flush packet
_physicalStateObj.WritePacket(TdsEnums.HARDFLUSH);
}
private PreLoginHandshakeStatus ConsumePreLoginHandshake(SqlAuthenticationMethod authType, bool encrypt, bool trustServerCert, bool integratedSecurity, out bool marsCapable, out bool fedAuthRequired) {
// Assign default values
marsCapable = _fMARS;
fedAuthRequired = false;
bool isYukonOrLater = false;
Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
bool result = _physicalStateObj.TryReadNetworkPacket();
if (!result) { throw SQL.SynchronousCallMayNotPend(); }
if (_physicalStateObj._inBytesRead == 0) {
// If the server did not respond then something has gone wrong and we need to close the connection
_physicalStateObj.AddError(new SqlError(0, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.PreloginError(), "", 0));
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
}
if (!_physicalStateObj.TryProcessHeader()) { throw SQL.SynchronousCallMayNotPend(); }
if (_physicalStateObj._inBytesPacket > TdsEnums.MAX_PACKET_SIZE || _physicalStateObj._inBytesPacket <= 0) {
throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream);
}
byte[] payload = new byte[_physicalStateObj._inBytesPacket];
Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
result = _physicalStateObj.TryReadByteArray(payload, 0, payload.Length);
if (!result) { throw SQL.SynchronousCallMayNotPend(); }
if (payload[0] == 0xaa) {
// If the first byte is 0xAA, we are connecting to a 6.5 or earlier server, which
// is not supported. SQL BU DT 296425
throw SQL.InvalidSQLServerVersionUnknown();
}
int offset = 0;
int payloadOffset = 0;
int payloadLength = 0;
int option = payload[offset++];
while (option != (byte)PreLoginOptions.LASTOPT) {
switch (option) {
case (int)PreLoginOptions.VERSION:
payloadOffset = payload[offset++] << 8 | payload[offset++];
payloadLength = payload[offset++] << 8 | payload[offset++];
byte majorVersion = payload[payloadOffset];
byte minorVersion = payload[payloadOffset + 1];
int level = (payload[payloadOffset + 2] << 8) |
payload[payloadOffset + 3];
isYukonOrLater = majorVersion >= 9;
if (!isYukonOrLater) {
marsCapable = false; // If pre-Yukon, MARS not supported.
}
break;
case (int)PreLoginOptions.ENCRYPT:
payloadOffset = payload[offset++] << 8 | payload[offset++];
payloadLength = payload[offset++] << 8 | payload[offset++];
EncryptionOptions serverOption = (EncryptionOptions)payload[payloadOffset];
/* internal enum EncryptionOptions {
OFF,
ON,
NOT_SUP,
REQ,
LOGIN
} */
switch (_encryptionOption) {
case (EncryptionOptions.ON):
if (serverOption == EncryptionOptions.NOT_SUP) {
_physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByServer(), "", 0));
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
}
break;
case (EncryptionOptions.OFF):
if (serverOption == EncryptionOptions.OFF) {
// Only encrypt login.
_encryptionOption = EncryptionOptions.LOGIN;
}
else if (serverOption == EncryptionOptions.REQ) {
// Encrypt all.
_encryptionOption = EncryptionOptions.ON;
}
break;
case (EncryptionOptions.NOT_SUP):
if (serverOption == EncryptionOptions.REQ) {
_physicalStateObj.AddError(new SqlError(TdsEnums.ENCRYPTION_NOT_SUPPORTED, (byte)0x00, TdsEnums.FATAL_ERROR_CLASS, _server, SQLMessage.EncryptionNotSupportedByClient(), "", 0));
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
}
break;
default:
Debug.Assert(false, "Invalid client encryption option detected");
break;
}
if (_encryptionOption == EncryptionOptions.ON ||
_encryptionOption == EncryptionOptions.LOGIN) {
UInt32 error = 0;
// If we're using legacy server certificate validation behavior (Authentication keyword not provided and not using access token), then validate if
// Encrypt=true and Trust Sever Certificate = false.
// If using Authentication keyword or access token, validate if Trust Server Certificate=false.
bool shouldValidateServerCert = (encrypt && !trustServerCert) || ((authType != SqlAuthenticationMethod.NotSpecified || _connHandler._accessTokenInBytes != null) && !trustServerCert);
UInt32 info = (shouldValidateServerCert ? TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE : 0)
| (isYukonOrLater ? TdsEnums.SNI_SSL_USE_SCHANNEL_CACHE : 0);
if (encrypt && !integratedSecurity) {
// optimization: in case of SQL Authentication and encryption, set SNI_SSL_IGNORE_CHANNEL_BINDINGS to let SNI
// know that it does not need to allocate/retrieve the Channel Bindings from the SSL context.
info |= TdsEnums.SNI_SSL_IGNORE_CHANNEL_BINDINGS;
}
// Add SSL (Encryption) SNI provider.
error = SNINativeMethodWrapper.SNIAddProvider(_physicalStateObj.Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV, ref info);