/
TdsParser.cs
12833 lines (11155 loc) · 540 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
// 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.Buffers;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Security.Authentication;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Data.Common;
using Microsoft.Data.Sql;
using Microsoft.Data.SqlClient.DataClassification;
using Microsoft.Data.SqlClient.Server;
using Microsoft.Data.SqlTypes;
namespace Microsoft.Data.SqlClient
{
internal struct SNIErrorDetails
{
public string errorMessage;
public uint nativeError;
public uint sniErrorNumber;
public int provider;
public uint lineNumber;
public string function;
public Exception exception;
}
// The TdsParser Object controls reading/writing to the netlib, parsing the tds,
// and surfacing objects to the user.
internal sealed partial class TdsParser
{
private static int _objectTypeCount; // EventSource counter
private readonly SqlClientLogger _logger = new SqlClientLogger();
private readonly string _typeName;
internal readonly int _objectID = Interlocked.Increment(ref _objectTypeCount);
internal int ObjectID => _objectID;
// 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
private const int constBinBufferSize = 4096; // Size of the buffer used to read input parameter of type Stream
private const int constTextBufferSize = 4096; // Size of the buffer (in chars) user to read input parameter of type TextReader
private const string enableTruncateSwitch = "Switch.Microsoft.Data.SqlClient.TruncateScaledDecimal"; // for applications that need to maintain backwards compatibility with the previous behavior
// 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 s_sniSupportedEncryptionOption = TdsParserStateObjectFactory.Singleton.EncryptionOptions;
private EncryptionOptions _encryptionOption = s_sniSupportedEncryptionOption;
private SqlInternalTransaction _currentTransaction;
private SqlInternalTransaction _pendingTransaction; // pending transaction for Yukon and beyond.
// 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 _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 volatile static uint s_maxSSPILength = 0; // variable to hold max SSPI data size, keep for token from server
// 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();
// XML metadata substitute 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;
/// <summary>
/// Get or set if column encryption is supported by the server.
/// </summary>
internal bool IsColumnEncryptionSupported { get; set; } = false;
/// <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 bool isTcpProtocol { get; set; }
internal string FQDNforDNSCahce { get; set; }
/// <summary>
/// Get if data classification is enabled by the server.
/// </summary>
internal bool IsDataClassificationEnabled =>
(DataClassificationVersion != TdsEnums.DATA_CLASSIFICATION_NOT_ENABLED);
/// <summary>
/// Get or set data classification version. A value of 0 means that sensitivity classification is not enabled.
/// </summary>
internal int DataClassificationVersion { get; set; }
internal TdsParser(bool MARS, bool fAsynchronous)
{
_fMARS = MARS; // may change during Connect to pre Yukon servers
_physicalStateObj = TdsParserStateObjectFactory.Singleton.CreateTdsParserStateObject(this);
DataClassificationVersion = TdsEnums.DATA_CLASSIFICATION_NOT_ENABLED;
_typeName = GetType().Name;
}
internal SqlInternalConnectionTds Connection
{
get
{
return _connHandler;
}
}
private static bool EnableTruncateSwitch
{
get
{
bool value;
value = AppContext.TryGetSwitch(enableTruncateSwitch, out value) ? value : false;
return value;
}
}
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 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 && SqlClientEventSource.Log.IsEnabled());
}
}
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,
SqlAuthenticationMethod authType)
{
if (_state != TdsParserState.Closed)
{
Debug.Fail("TdsParser.Connect called on non-closed connection!");
return;
}
_connHandler = connHandler;
_loginWithFailover = withFailover;
// Clean up IsSQLDNSCachingSupported flag from previous status
_connHandler.IsSQLDNSCachingSupported = false;
uint sniStatus = TdsParserStateObjectFactory.Singleton.SNIStatus;
if (sniStatus != TdsEnums.SNI_SUCCESS)
{
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
_physicalStateObj.Dispose();
ThrowExceptionAndWarning(_physicalStateObj);
Debug.Fail("SNI returned status != success, but no error thrown?");
}
else
{
_sniSpnBuffer = null;
switch (authType)
{
case SqlAuthenticationMethod.ActiveDirectoryPassword:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory Password authentication");
break;
case SqlAuthenticationMethod.ActiveDirectoryIntegrated:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory Integrated authentication");
break;
case SqlAuthenticationMethod.ActiveDirectoryInteractive:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory Interactive authentication");
break;
case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory Service Principal authentication");
break;
case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory Device Code Flow authentication");
break;
case SqlAuthenticationMethod.ActiveDirectoryManagedIdentity:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory Managed Identity authentication");
break;
case SqlAuthenticationMethod.ActiveDirectoryMSI:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Active Directory MSI authentication");
break;
case SqlAuthenticationMethod.SqlPassword:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> SQL Password authentication");
break;
default:
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> SQL authentication");
break;
}
}
_sniSpnBuffer = null;
// AD Integrated behaves like Windows integrated when connecting to a non-fedAuth server
if (integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated)
{
LoadSSPILibrary();
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> SSPI or Active Directory Authentication Library for SQL Server based integrated authentication");
}
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;
FQDNforDNSCahce = serverInfo.ResolvedServerName;
int commaPos = FQDNforDNSCahce.IndexOf(",");
if (commaPos != -1)
{
FQDNforDNSCahce = FQDNforDNSCahce.Substring(0, commaPos);
}
_connHandler.pendingSQLDNSObject = null;
// AD Integrated behaves like Windows integrated when connecting to a non-fedAuth server
_physicalStateObj.CreatePhysicalSNIHandle(serverInfo.ExtendedServerName, ignoreSniOpenTimeout, timerExpire,
out instanceName, ref _sniSpnBuffer, false, true, fParallel, FQDNforDNSCahce, ref _connHandler.pendingSQLDNSObject, integratedSecurity || authType == SqlAuthenticationMethod.ActiveDirectoryIntegrated);
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();
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|ERR|SEC> Login failure");
ThrowExceptionAndWarning(_physicalStateObj);
Debug.Fail("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_PreLoginBeforeSuccessfulWrite;
_physicalStateObj.TimeoutTime = timerExpire;
bool marsCapable = false;
_connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.InitializeConnection);
_connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
uint result = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId);
Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
if (null == _connHandler.pendingSQLDNSObject)
{
// for DNS Caching phase 1
_physicalStateObj.AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce, ref _connHandler.pendingSQLDNSObject);
}
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Sending prelogin handshake");
SendPreLoginHandshake(instanceName, encrypt);
_connHandler.TimeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.SendPreLoginHandshake);
_connHandler.TimeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake);
_physicalStateObj.SniContext = SniContext.Snix_PreLogin;
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Consuming prelogin handshake");
PreLoginHandshakeStatus status = ConsumePreLoginHandshake(encrypt, trustServerCert, integratedSecurity, out marsCapable, out _connHandler._fedAuthRequired);
if (status == PreLoginHandshakeStatus.InstanceFailure)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Prelogin handshake unsuccessful. Reattempting prelogin handshake");
_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, ref _sniSpnBuffer, true, true, fParallel, FQDNforDNSCahce, ref _connHandler.pendingSQLDNSObject, integratedSecurity);
if (TdsEnums.SNI_SUCCESS != _physicalStateObj.Status)
{
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|ERR|SEC> Login failure");
ThrowExceptionAndWarning(_physicalStateObj);
}
uint retCode = _physicalStateObj.SniGetConnectionId(ref _connHandler._clientConnectionId);
Debug.Assert(retCode == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionId");
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|SEC> Sending prelogin handshake");
if (null == _connHandler.pendingSQLDNSObject)
{
// for DNS Caching phase 1
_physicalStateObj.AssignPendingDNSInfo(serverInfo.UserProtocol, FQDNforDNSCahce, ref _connHandler.pendingSQLDNSObject);
}
SendPreLoginHandshake(instanceName, encrypt);
status = ConsumePreLoginHandshake(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)
{
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.Connect|ERR|SEC> Prelogin handshake unsuccessful. Login failure");
throw SQL.InstanceFailure();
}
}
if (_fMARS && marsCapable)
{
// if user explicitly disables mars or mars not supported, don't create the session pool
_sessionPool = new TdsParserSessionPool(this);
}
else
{
_fMARS = false;
}
return;
}
internal void RemoveEncryption()
{
Debug.Assert(_encryptionOption == EncryptionOptions.LOGIN, "Invalid encryption option state");
uint error = _physicalStateObj.DisableSsl();
if (error != TdsEnums.SNI_SUCCESS)
{
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
ThrowExceptionAndWarning(_physicalStateObj);
}
// create a new packet encryption changes the internal packet size
_physicalStateObj.ClearAllWritePackets();
}
internal void EnableMars()
{
if (_fMARS)
{
// Cache physical stateObj and connection.
_pMarsPhysicalConObj = _physicalStateObj;
if (TdsParserStateObjectFactory.UseManagedSNI)
_pMarsPhysicalConObj.IncrementPendingCallbacks();
uint info = 0;
uint error = _pMarsPhysicalConObj.EnableMars(ref info);
if (error != TdsEnums.SNI_SUCCESS)
{
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
ThrowExceptionAndWarning(_physicalStateObj);
}
PostReadAsyncForMars();
_physicalStateObj = CreateSession(); // Create and open default MARS stateObj and connection.
}
}
internal TdsParserStateObject CreateSession()
{
TdsParserStateObject session = TdsParserStateObjectFactory.Singleton.CreateSessionObject(this, _pMarsPhysicalConObj, true);
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.TdsParser.CreateSession|ADV> {0} created session {1}", ObjectID, session.ObjectID);
return session;
}
internal TdsParserStateObject GetSession(object owner)
{
TdsParserStateObject session = null;
if (MARSOn)
{
session = _sessionPool.GetSession(owner);
Debug.Assert(!session.HasPendingData, "pending data on a pooled MARS session");
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.TdsParser.GetSession|ADV> {0} getting session {1} from pool", ObjectID, session.ObjectID);
}
else
{
session = _physicalStateObj;
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.TdsParser.GetSession|ADV> {0} getting physical session {1}", 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;
}
}
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:
int 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:
FillGuidBytes(_connHandler._clientConnectionId, payload.AsSpan(payloadLength, GUID_SIZE));
payloadLength += GUID_SIZE;
offset += GUID_SIZE;
optionDataSize = GUID_SIZE;
ActivityCorrelator.ActivityId actId = ActivityCorrelator.Next();
FillGuidBytes(actId.Id, payload.AsSpan(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(uint);
offset += actIdSize;
optionDataSize += actIdSize;
SqlClientEventSource.Log.TryTraceEvent("<sc.TdsParser.SendPreLoginHandshake|INFO> ClientConnectionID {0}, ActivityID {1}", _connHandler?._clientConnectionId, actId);
break;
case (int)PreLoginOptions.FEDAUTHREQUIRED:
payload[payloadLength++] = 0x01;
offset += 1;
optionDataSize += 1;
break;
default:
Debug.Fail("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(bool encrypt, bool trustServerCert, bool integratedSecurity, out bool marsCapable, out bool fedAuthRequired)
{
marsCapable = _fMARS; // Assign default value
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();
}
byte[] payload = new byte[_physicalStateObj._inBytesPacket];
Debug.Assert(_physicalStateObj._syncOverAsync, "Should not attempt pends in a synchronous call");
result = _physicalStateObj.TryReadByteArray(payload, 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.
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.Fail("Invalid client encryption option detected");
break;
}
if (_encryptionOption == EncryptionOptions.ON ||
_encryptionOption == EncryptionOptions.LOGIN)
{
uint error = 0;
// Validate Certificate if Trust Server Certificate=false and Encryption forced (EncryptionOptions.ON) from Server.
bool shouldValidateServerCert = (_encryptionOption == EncryptionOptions.ON && !trustServerCert) || (_connHandler._accessTokenInBytes != null && !trustServerCert);
uint 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.
// This applies to Native SNI
info |= TdsEnums.SNI_SSL_IGNORE_CHANNEL_BINDINGS;
}
error = _physicalStateObj.EnableSsl(ref info);
if (error != TdsEnums.SNI_SUCCESS)
{
_physicalStateObj.AddError(ProcessSNIError(_physicalStateObj));
ThrowExceptionAndWarning(_physicalStateObj);
}
int protocolVersion = 0;
WaitForSSLHandShakeToComplete(ref error, ref protocolVersion);
SslProtocols protocol = (SslProtocols)protocolVersion;
string warningMessage = protocol.GetProtocolWarning();
if (!string.IsNullOrEmpty(warningMessage))
{
// This logs console warning of insecure protocol in use.
_logger.LogWarning(_typeName, MethodBase.GetCurrentMethod().Name, warningMessage);
}
// create a new packet encryption changes the internal packet size
_physicalStateObj.ClearAllWritePackets();
}
break;
case (int)PreLoginOptions.INSTANCE:
payloadOffset = payload[offset++] << 8 | payload[offset++];
payloadLength = payload[offset++] << 8 | payload[offset++];
byte ERROR_INST = 0x1;
byte instanceResult = payload[payloadOffset];
if (instanceResult == ERROR_INST)
{
// Check if server says ERROR_INST. That either means the cached info
// we used to connect is not valid or we connected to a named instance
// listening on default params.
return PreLoginHandshakeStatus.InstanceFailure;
}
break;
case (int)PreLoginOptions.THREADID:
// DO NOTHING FOR THREADID
offset += 4;
break;
case (int)PreLoginOptions.MARS:
payloadOffset = payload[offset++] << 8 | payload[offset++];
payloadLength = payload[offset++] << 8 | payload[offset++];
marsCapable = (payload[payloadOffset] == 0 ? false : true);
Debug.Assert(payload[payloadOffset] == 0 || payload[payloadOffset] == 1, "Value for Mars PreLoginHandshake option not equal to 1 or 0!");
break;