-
Notifications
You must be signed in to change notification settings - Fork 263
/
TdsParserStateObject.netfx.cs
1918 lines (1677 loc) · 80.3 KB
/
TdsParserStateObject.netfx.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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Data.Common;
using Microsoft.Data.ProviderBase;
namespace Microsoft.Data.SqlClient
{
using PacketHandle = IntPtr;
internal readonly ref struct SessionHandle
{
public readonly SNIHandle NativeHandle;
public SessionHandle(SNIHandle nativeHandle) => NativeHandle = nativeHandle;
public bool IsNull => NativeHandle is null;
}
internal partial class TdsParserStateObject
{
private static class TdsParserStateObjectFactory
{
/// <summary>
/// Always false in case of netfx. Only needed for merging with netcore codebase.
/// </summary>
internal const bool UseManagedSNI = false;
}
private SNIHandle _sessionHandle = null; // the SNI handle we're to work on
// SNI variables // multiple resultsets in one batch.
private SNIPacket _sniPacket = null; // Will have to re-vamp this for MARS
internal SNIPacket _sniAsyncAttnPacket = null; // Packet to use to send Attn
private readonly WritePacketCache _writePacketCache = new WritePacketCache(); // Store write packets that are ready to be re-used
private readonly Dictionary<IntPtr, SNIPacket> _pendingWritePackets = new Dictionary<IntPtr, SNIPacket>(); // Stores write packets that have been sent to SNI, but have not yet finished writing (i.e. we are waiting for SNI's callback)
// Async variables
private GCHandle _gcHandle; // keeps this object alive until we're closed.
// This variable is used to prevent sending an attention by another thread that is not the
// current owner of the stateObj. I currently do not know how this can happen. Mark added
// the code but does not remember either. At some point, we need to research killing this
// logic.
private volatile int _allowObjectID;
// Used for blanking out password in trace.
internal int _tracePasswordOffset = 0;
internal int _tracePasswordLength = 0;
internal int _traceChangePasswordOffset = 0;
internal int _traceChangePasswordLength = 0;
//////////////////
// Constructors //
//////////////////
internal TdsParserStateObject(TdsParser parser, SNIHandle physicalConnection, bool async)
{
// Construct a MARS session
Debug.Assert(null != parser, "no parser?");
_parser = parser;
_onTimeoutAsync = OnTimeoutAsync;
SniContext = SniContext.Snix_GetMarsSession;
Debug.Assert(null != _parser._physicalStateObj, "no physical session?");
Debug.Assert(null != _parser._physicalStateObj._inBuff, "no in buffer?");
Debug.Assert(null != _parser._physicalStateObj._outBuff, "no out buffer?");
Debug.Assert(_parser._physicalStateObj._outBuff.Length ==
_parser._physicalStateObj._inBuff.Length, "Unexpected unequal buffers.");
// Determine packet size based on physical connection buffer lengths.
SetPacketSize(_parser._physicalStateObj._outBuff.Length);
SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async);
SQLDNSInfo cachedDNSInfo;
SQLFallbackDNSCache.Instance.GetDNSInfo(_parser.FQDNforDNSCache, out cachedDNSInfo);
_sessionHandle = new SNIHandle(myInfo, physicalConnection, _parser.Connection.ConnectionOptions.IPAddressPreference, cachedDNSInfo);
if (_sessionHandle.Status != TdsEnums.SNI_SUCCESS)
{
AddError(parser.ProcessSNIError(this));
ThrowExceptionAndWarning();
}
// we post a callback that represents the call to dispose; once the
// object is disposed, the next callback will cause the GC Handle to
// be released.
IncrementPendingCallbacks();
_lastSuccessfulIOTimer = parser._physicalStateObj._lastSuccessfulIOTimer;
}
internal SSPIContextProvider CreateSSPIContextProvider() => new NativeSSPIContextProvider();
////////////////
// Properties //
////////////////
internal SNIHandle Handle
{
get
{
return _sessionHandle;
}
}
internal uint Status
{
get
{
if (_sessionHandle != null)
{
return _sessionHandle.Status;
}
else
{ // SQL BU DT 395431.
return TdsEnums.SNI_UNINITIALIZED;
}
}
}
internal SessionHandle SessionHandle => new SessionHandle(Handle);
/////////////////////
// General methods //
/////////////////////
// This method is only called by the command or datareader as a result of a user initiated
// cancel request.
internal void Cancel(int objectID)
{
bool hasLock = false;
try
{
// Keep looping until we either grabbed the lock (and therefore sent attention) or the connection closes\breaks
while ((!hasLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
{
Monitor.TryEnter(this, WaitForCancellationLockPollTimeout, ref hasLock);
if (hasLock)
{ // Lock for the time being - since we need to synchronize the attention send.
// This lock is also protecting against concurrent close and async continuations
// don't allow objectID -1 since it is reserved for 'not associated with a command'
// yes, the 2^32-1 comand won't cancel - but it also won't cancel when we don't want it
if ((!_cancelled) && (objectID == _allowObjectID) && (objectID != -1))
{
_cancelled = true;
if (HasPendingData && !_attentionSent)
{
bool hasParserLock = false;
// Keep looping until we have the parser lock (and so are allowed to write), or the connection closes\breaks
while ((!hasParserLock) && (_parser.State != TdsParserState.Closed) && (_parser.State != TdsParserState.Broken))
{
try
{
_parser.Connection._parserLock.Wait(canReleaseFromAnyThread: false, timeout: WaitForCancellationLockPollTimeout, lockTaken: ref hasParserLock);
if (hasParserLock)
{
_parser.Connection.ThreadHasParserLockForClose = true;
SendAttention();
}
}
finally
{
if (hasParserLock)
{
if (_parser.Connection.ThreadHasParserLockForClose)
{
_parser.Connection.ThreadHasParserLockForClose = false;
}
_parser.Connection._parserLock.Release();
}
}
}
}
}
}
}
}
finally
{
if (hasLock)
{
Monitor.Exit(this);
}
}
}
private void ResetCancelAndProcessAttention()
{
// This method is shared by CloseSession initiated by DataReader.Close or completed
// command execution, as well as the session reclamation code for cases where the
// DataReader is opened and then GC'ed.
lock (this)
{
// Reset cancel state.
_cancelled = false;
_allowObjectID = -1;
if (_attentionSent)
{
// Make sure we're cleaning up the AttentionAck if Cancel happened before taking the lock.
// We serialize Cancel/CloseSession to prevent a race condition between these two states.
// The problem is that both sending and receiving attentions are time taking
// operations.
#if DEBUG
TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection();
RuntimeHelpers.PrepareConstrainedRegions();
try
{
tdsReliabilitySection.Start();
#endif //DEBUG
Parser.ProcessPendingAck(this);
#if DEBUG
}
finally
{
tdsReliabilitySection.Stop();
}
#endif //DEBUG
}
SetTimeoutStateStopped();
}
}
private SNINativeMethodWrapper.ConsumerInfo CreateConsumerInfo(bool async)
{
SNINativeMethodWrapper.ConsumerInfo myInfo = new SNINativeMethodWrapper.ConsumerInfo();
Debug.Assert(_outBuff.Length == _inBuff.Length, "Unexpected unequal buffers.");
myInfo.defaultBufferSize = _outBuff.Length; // Obtain packet size from outBuff size.
if (async)
{
myInfo.readDelegate = SNILoadHandle.SingletonInstance.ReadAsyncCallbackDispatcher;
myInfo.writeDelegate = SNILoadHandle.SingletonInstance.WriteAsyncCallbackDispatcher;
_gcHandle = GCHandle.Alloc(this, GCHandleType.Normal);
myInfo.key = (IntPtr)_gcHandle;
}
return myInfo;
}
internal void CreatePhysicalSNIHandle(
string serverName,
TimeoutTimer timeout,
out byte[] instanceName,
byte[] spnBuffer,
bool flushCache,
bool async,
bool fParallel,
TransparentNetworkResolutionState transparentNetworkResolutionState,
int totalTimeout,
SqlConnectionIPAddressPreference ipPreference,
string cachedFQDN,
string hostNameInCertificate = "")
{
SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async);
// serverName : serverInfo.ExtendedServerName
// may not use this serverName as key
_ = SQLFallbackDNSCache.Instance.GetDNSInfo(cachedFQDN, out SQLDNSInfo cachedDNSInfo);
_sessionHandle = new SNIHandle(myInfo, serverName, spnBuffer, timeout.MillisecondsRemainingInt,
out instanceName, flushCache, !async, fParallel, transparentNetworkResolutionState, totalTimeout,
ipPreference, cachedDNSInfo, hostNameInCertificate);
}
internal bool IsPacketEmpty(PacketHandle readPacket) => readPacket == default;
internal PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error)
{
SNIHandle handle = Handle ?? throw ADP.ClosedConnectionError();
PacketHandle readPacket = default;
error = SNINativeMethodWrapper.SNIReadSyncOverAsync(handle, ref readPacket, timeoutRemaining);
return readPacket;
}
internal PacketHandle ReadAsync(SessionHandle handle, out uint error)
{
PacketHandle readPacket = default;
error = SNINativeMethodWrapper.SNIReadAsync(handle.NativeHandle, ref readPacket);
return readPacket;
}
internal uint CheckConnection() => SNINativeMethodWrapper.SNICheckConnection(Handle);
internal void ReleasePacket(PacketHandle syncReadPacket) => SNINativeMethodWrapper.SNIPacketRelease(syncReadPacket);
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal int DecrementPendingCallbacks(bool release)
{
int remaining = Interlocked.Decrement(ref _pendingCallbacks);
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.TdsParserStateObject.DecrementPendingCallbacks|ADV> {0}, after decrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks);
if ((0 == remaining || release) && _gcHandle.IsAllocated)
{
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.TdsParserStateObject.DecrementPendingCallbacks|ADV> {0}, FREEING HANDLE!", ObjectID);
_gcHandle.Free();
}
// NOTE: TdsParserSessionPool may call DecrementPendingCallbacks on a TdsParserStateObject which is already disposed
// This is not dangerous (since the stateObj is no longer in use), but we need to add a workaround in the assert for it
Debug.Assert((remaining == -1 && _sessionHandle == null) || (0 <= remaining && remaining < 3), $"_pendingCallbacks values is invalid after decrementing: {remaining}");
return remaining;
}
internal void Dispose()
{
SafeHandle packetHandle = _sniPacket;
SafeHandle sessionHandle = _sessionHandle;
SafeHandle asyncAttnPacket = _sniAsyncAttnPacket;
_sniPacket = null;
_sessionHandle = null;
_sniAsyncAttnPacket = null;
DisposeCounters();
if (null != sessionHandle || null != packetHandle)
{
// Comment CloseMARSSession
// UNDONE - if there are pending reads or writes on logical connections, we need to block
// here for the callbacks!!! This only applies to async. Should be fixed by async fixes for
// AD unload/exit.
// TODO: Make this a BID trace point!
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
finally
{
if (packetHandle != null)
{
packetHandle.Dispose();
}
if (asyncAttnPacket != null)
{
asyncAttnPacket.Dispose();
}
if (sessionHandle != null)
{
sessionHandle.Dispose();
DecrementPendingCallbacks(true); // Will dispose of GC handle.
}
}
}
if (_writePacketCache != null)
{
lock (_writePacketLockObject)
{
RuntimeHelpers.PrepareConstrainedRegions();
try
{ }
finally
{
_writePacketCache.Dispose();
// Do not set _writePacketCache to null, just in case a WriteAsyncCallback completes after this point
}
}
}
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal int IncrementPendingCallbacks()
{
int remaining = Interlocked.Increment(ref _pendingCallbacks);
SqlClientEventSource.Log.TryAdvancedTraceEvent("<sc.TdsParserStateObject.IncrementPendingCallbacks|ADV> {0}, after incrementing _pendingCallbacks: {1}", ObjectID, _pendingCallbacks);
Debug.Assert(0 < remaining && remaining <= 3, $"_pendingCallbacks values is invalid after incrementing: {remaining}");
return remaining;
}
internal void StartSession(int objectID)
{
_allowObjectID = objectID;
}
/// <summary>
/// Checks to see if the underlying connection is still valid (used by idle connection resiliency - for active connections)
/// NOTE: This is not safe to do on a connection that is currently in use
/// NOTE: This will mark the connection as broken if it is found to be dead
/// </summary>
/// <returns>True if the connection is still alive, otherwise false</returns>
internal bool ValidateSNIConnection()
{
if ((_parser == null) || ((_parser.State == TdsParserState.Broken) || (_parser.State == TdsParserState.Closed)))
{
return false;
}
if (DateTime.UtcNow.Ticks - _lastSuccessfulIOTimer._value <= CheckConnectionWindow)
{
return true;
}
uint error = TdsEnums.SNI_SUCCESS;
SniContext = SniContext.Snix_Connect;
try
{
Interlocked.Increment(ref _readingCount);
SNIHandle handle = Handle;
if (handle != null)
{
error = SNINativeMethodWrapper.SNICheckConnection(handle);
}
}
finally
{
Interlocked.Decrement(ref _readingCount);
}
return (error == TdsEnums.SNI_SUCCESS) || (error == TdsEnums.SNI_WAIT_TIMEOUT);
}
// This method should only be called by ReadSni! If not - it may have problems with timeouts!
private void ReadSniError(TdsParserStateObject stateObj, uint error)
{
TdsParser.ReliabilitySection.Assert("unreliable call to ReadSniSyncError"); // you need to setup for a thread abort somewhere before you call this method
if (TdsEnums.SNI_WAIT_TIMEOUT == error)
{
Debug.Assert(_syncOverAsync, "Should never reach here with async on!");
bool fail = false;
if (IsTimeoutStateExpired)
{ // This is now our second timeout - time to give up.
fail = true;
}
else
{
stateObj.SetTimeoutStateStopped();
Debug.Assert(_parser.Connection != null, "SqlConnectionInternalTds handler can not be null at this point.");
AddError(new SqlError(TdsEnums.TIMEOUT_EXPIRED, 0x00, TdsEnums.MIN_ERROR_CLASS, _parser.Server, _parser.Connection.TimeoutErrorInternal.GetErrorMessage(), "", 0, TdsEnums.SNI_WAIT_TIMEOUT));
if (!stateObj._attentionSent)
{
if (stateObj.Parser.State == TdsParserState.OpenLoggedIn)
{
stateObj.SendAttention(mustTakeWriteLock: true);
PacketHandle syncReadPacket = default;
RuntimeHelpers.PrepareConstrainedRegions();
bool shouldDecrement = false;
try
{
Interlocked.Increment(ref _readingCount);
shouldDecrement = true;
syncReadPacket = ReadSyncOverAsync(stateObj.GetTimeoutRemaining(), out error);
Interlocked.Decrement(ref _readingCount);
shouldDecrement = false;
if (TdsEnums.SNI_SUCCESS == error)
{
// We will end up letting the run method deal with the expected done:done_attn token stream.
stateObj.ProcessSniPacket(syncReadPacket, 0);
return;
}
else
{
Debug.Assert(!IsValidPacket(syncReadPacket), "unexpected syncReadPacket without corresponding SNIPacketRelease");
fail = true; // Subsequent read failed, time to give up.
}
}
finally
{
if (shouldDecrement)
{
Interlocked.Decrement(ref _readingCount);
}
if (!IsPacketEmpty(syncReadPacket))
{
// Be sure to release packet, otherwise it will be leaked by native.
ReleasePacket(syncReadPacket);
}
}
}
else
{
if (_parser._loginWithFailover)
{
// For DbMirroring Failover during login, never break the connection, just close the TdsParser
_parser.Disconnect();
}
else if ((_parser.State == TdsParserState.OpenNotLoggedIn) && (_parser.Connection.ConnectionOptions.MultiSubnetFailover || _parser.Connection.ConnectionOptions.TransparentNetworkIPResolution))
{
// For MultiSubnet Failover during login, never break the connection, just close the TdsParser
_parser.Disconnect();
}
else
fail = true; // We aren't yet logged in - just fail.
}
}
}
if (fail)
{
_parser.State = TdsParserState.Broken; // We failed subsequent read, we have to quit!
_parser.Connection.BreakConnection();
}
}
else
{
// Caution: ProcessSNIError always returns a fatal error!
AddError(_parser.ProcessSNIError(stateObj));
}
ThrowExceptionAndWarning();
AssertValidState();
}
public void ProcessSniPacket(PacketHandle packet, uint error)
{
if (error != 0)
{
if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
{
// Do nothing with callback if closed or broken and error not 0 - callback can occur
// after connection has been closed. PROBLEM IN NETLIB - DESIGN FLAW.
return;
}
AddError(_parser.ProcessSNIError(this));
AssertValidState();
}
else
{
uint dataSize = 0;
uint getDataError = SNINativeMethodWrapper.SNIPacketGetData(packet, _inBuff, ref dataSize);
if (getDataError == TdsEnums.SNI_SUCCESS)
{
if (_inBuff.Length < dataSize)
{
Debug.Assert(true, "Unexpected dataSize on Read");
throw SQL.InvalidInternalPacketSize(StringsHelper.GetString(Strings.SqlMisc_InvalidArraySizeMessage));
}
_lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
_inBytesRead = (int)dataSize;
_inBytesUsed = 0;
if (_snapshot != null)
{
_snapshot.AppendPacketData(_inBuff, _inBytesRead);
if (_snapshotReplay)
{
_snapshot.MoveNext();
#if DEBUG
_snapshot.AssertCurrent();
#endif
}
}
SniReadStatisticsAndTracing();
SqlClientEventSource.Log.TryAdvancedTraceBinEvent("TdsParser.ReadNetworkPacketAsyncCallback | INFO | ADV | State Object Id {0}, Packet read. In Buffer {1}, In Bytes Read: {2}", ObjectID, _inBuff, (ushort)_inBytesRead);
AssertValidState();
}
else
{
throw SQL.ParsingError(ParsingErrorState.ProcessSniPacketFailed);
}
}
}
private void ChangeNetworkPacketTimeout(int dueTime, int period)
{
Timer networkPacketTimeout = _networkPacketTimeout;
if (networkPacketTimeout != null)
{
try
{
networkPacketTimeout.Change(dueTime, period);
}
catch (ObjectDisposedException)
{
// _networkPacketTimeout is set to null before Disposing, but there is still a slight chance
// that object was disposed after we took a copy
}
}
}
public void ReadAsyncCallback(IntPtr key, PacketHandle packet, uint error)
{
// Key never used.
// Note - it's possible that when native calls managed that an asynchronous exception
// could occur in the native->managed transition, which would
// have two impacts:
// 1) user event not called
// 2) DecrementPendingCallbacks not called, which would mean this object would be leaked due
// to the outstanding GCRoot until AppDomain.Unload.
// We live with the above for the time being due to the constraints of the current
// reliability infrastructure provided by the CLR.
TaskCompletionSource<object> source = _networkPacketTaskSource;
#if DEBUG
if ((s_forcePendingReadsToWaitForUser) && (_realNetworkPacketTaskSource != null))
{
source = _realNetworkPacketTaskSource;
}
#endif
// The mars physical connection can get a callback
// with a packet but no result after the connection is closed.
if (source == null && _parser._pMarsPhysicalConObj == this)
{
return;
}
RuntimeHelpers.PrepareConstrainedRegions();
bool processFinallyBlock = true;
try
{
Debug.Assert(IntPtr.Zero == packet || IntPtr.Zero != packet && source != null, "AsyncResult null on callback");
if (_parser.MARSOn)
{
// Only take reset lock on MARS and Async.
CheckSetResetConnectionState(error, CallbackType.Read);
}
ChangeNetworkPacketTimeout(Timeout.Infinite, Timeout.Infinite);
// The timer thread may be unreliable under high contention scenarios. It cannot be
// assumed that the timeout has happened on the timer thread callback. Check the timeout
// synchrnously and then call OnTimeoutSync to force an atomic change of state.
if (TimeoutHasExpired)
{
OnTimeoutSync(asyncClose: true);
}
// try to change to the stopped state but only do so if currently in the running state
// and use cmpexch so that all changes out of the running state are atomic
int previousState = Interlocked.CompareExchange(ref _timeoutState, TimeoutState.Stopped, TimeoutState.Running);
// if the state is anything other than running then this query has reached an end so
// set the correlation _timeoutIdentityValue to 0 to prevent late callbacks executing
if (_timeoutState != TimeoutState.Running)
{
_timeoutIdentityValue = 0;
}
ProcessSniPacket(packet, error);
}
catch (Exception e)
{
processFinallyBlock = ADP.IsCatchableExceptionType(e);
throw;
}
finally
{
// pendingCallbacks may be 2 after decrementing, this indicates that a fatal timeout is occurring, and therefore we shouldn't complete the task
int pendingCallbacks = DecrementPendingCallbacks(false); // may dispose of GC handle.
if ((processFinallyBlock) && (source != null) && (pendingCallbacks < 2))
{
if (error == 0)
{
if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, (state) => source.TrySetResult(null), null);
}
else
{
source.TrySetResult(null);
}
}
else
{
if (_executionContext != null)
{
ExecutionContext.Run(_executionContext, (state) => ReadAsyncCallbackCaptureException(source), null);
}
else
{
ReadAsyncCallbackCaptureException(source);
}
}
}
AssertValidState();
}
}
private void ReadAsyncCallbackCaptureException(TaskCompletionSource<object> source)
{
bool captureSuccess = false;
try
{
if (_hasErrorOrWarning)
{
// Do the close on another thread, since we don't want to block the callback thread
ThrowExceptionAndWarning(asyncClose: true);
}
else if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
{
// Connection was closed by another thread before we parsed the packet, so no error was added to the collection
throw ADP.ClosedConnectionError();
}
}
catch (Exception ex)
{
if (source.TrySetException(ex))
{
// There was an exception, and it was successfully stored in the task
captureSuccess = true;
}
}
if (!captureSuccess)
{
// Either there was no exception, or the task was already completed
// This is unusual, but possible if a fatal timeout occurred on another thread (which should mean that the connection is now broken)
Debug.Assert(_parser.State == TdsParserState.Broken || _parser.State == TdsParserState.Closed || _parser.Connection.IsConnectionDoomed, "Failed to capture exception while the connection was still healthy");
// The safest thing to do is to ensure that the connection is broken and attempt to cancel the task
// This must be done from another thread to not block the callback thread
Task.Factory.StartNew(() =>
{
_parser.State = TdsParserState.Broken;
_parser.Connection.BreakConnection();
source.TrySetCanceled();
});
}
}
#pragma warning disable 420 // a reference to a volatile field will not be treated as volatile
public void WriteAsyncCallback(IntPtr key, PacketHandle packet, uint sniError)
{ // Key never used.
RemovePacketFromPendingList(packet);
try
{
if (sniError != TdsEnums.SNI_SUCCESS)
{
SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObject.WriteAsyncCallback | Info | State Object Id {0}, Write async returned error code {1}", _objectID, (int)sniError);
try
{
AddError(_parser.ProcessSNIError(this));
ThrowExceptionAndWarning(asyncClose: true);
}
catch (Exception e)
{
TaskCompletionSource<object> writeCompletionSource = _writeCompletionSource;
if (writeCompletionSource != null)
{
writeCompletionSource.TrySetException(e);
}
else
{
_delayedWriteAsyncCallbackException = e;
// Ensure that _delayedWriteAsyncCallbackException is set before checking _writeCompletionSource
Interlocked.MemoryBarrier();
// Double check that _writeCompletionSource hasn't been created in the meantime
writeCompletionSource = _writeCompletionSource;
if (writeCompletionSource != null)
{
Exception delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
writeCompletionSource.TrySetException(delayedException);
}
}
}
return;
}
}
else
{
_lastSuccessfulIOTimer._value = DateTime.UtcNow.Ticks;
}
}
finally
{
#if DEBUG
if (SqlCommand.DebugForceAsyncWriteDelay > 0)
{
new Timer(obj =>
{
Interlocked.Decrement(ref _asyncWriteCount);
TaskCompletionSource<object> writeCompletionSource = _writeCompletionSource;
if (_asyncWriteCount == 0 && writeCompletionSource != null)
{
writeCompletionSource.TrySetResult(null);
}
}, null, SqlCommand.DebugForceAsyncWriteDelay, Timeout.Infinite);
}
else
{
#else
{
#endif
Interlocked.Decrement(ref _asyncWriteCount);
}
}
#if DEBUG
if (SqlCommand.DebugForceAsyncWriteDelay > 0)
{
return;
}
#endif
TaskCompletionSource<object> completionSource = _writeCompletionSource;
if (_asyncWriteCount == 0 && completionSource != null)
{
completionSource.TrySetResult(null);
}
}
#pragma warning restore 420
/////////////////////////////////////////
// Network/Packet Writing & Processing //
/////////////////////////////////////////
//
// Takes a secure string and offsets and saves them for a write latter when the information is written out to SNI Packet
// This method is provided to better handle the life cycle of the clear text of the secure string
// This method also ensures that the clear text is not held in the unpined managed buffer so that it avoids getting moved around by CLR garbage collector
// TdsParserStaticMethods.EncryptPassword operation is also done in the unmanaged buffer for the clear text later
//
internal void WriteSecureString(SecureString secureString)
{
TdsParser.ReliabilitySection.Assert("unreliable call to WriteSecureString"); // you need to setup for a thread abort somewhere before you call this method
Debug.Assert(_securePasswords[0] == null || _securePasswords[1] == null, "There are more than two secure passwords");
int index = _securePasswords[0] != null ? 1 : 0;
_securePasswords[index] = secureString;
_securePasswordOffsetsInBuffer[index] = _outBytesUsed;
// loop through and write the entire array
int lengthInBytes = secureString.Length * 2;
// It is guaranteed both secure password and secure change password should fit into the first packet
// Given current TDS format and implementation it is not possible that one of secure string is the last item and exactly fill up the output buffer
// if this ever happens and it is correct situation, the packet needs to be written out after _outBytesUsed is update
Debug.Assert((_outBytesUsed + lengthInBytes) < _outBuff.Length, "Passwords cannot be split into two different packet or the last item which fully fill up _outBuff!!!");
_outBytesUsed += lengthInBytes;
}
internal void ResetSecurePasswordsInformation()
{
for (int i = 0; i < _securePasswords.Length; ++i)
{
_securePasswords[i] = null;
_securePasswordOffsetsInBuffer[i] = 0;
}
}
internal Task WaitForAccumulatedWrites()
{
// Checked for stored exceptions
#pragma warning disable 420 // A reference to a volatile field will not be treated as volatile - Disabling since the Interlocked APIs are volatile aware
Exception delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
throw delayedException;
}
#pragma warning restore 420
if (_asyncWriteCount == 0)
{
return null;
}
_writeCompletionSource = new TaskCompletionSource<object>();
Task task = _writeCompletionSource.Task;
// Ensure that _writeCompletionSource is set before checking state
Interlocked.MemoryBarrier();
// Now that we have set _writeCompletionSource, check if parser is closed or broken
if ((_parser.State == TdsParserState.Closed) || (_parser.State == TdsParserState.Broken))
{
throw ADP.ClosedConnectionError();
}
// Check for stored exceptions
#pragma warning disable 420 // A reference to a volatile field will not be treated as volatile - Disabling since the Interlocked APIs are volatile aware
delayedException = Interlocked.Exchange(ref _delayedWriteAsyncCallbackException, null);
if (delayedException != null)
{
throw delayedException;
}
#pragma warning restore 420
// If there are no outstanding writes, see if we can shortcut and return null
if ((_asyncWriteCount == 0) && ((!task.IsCompleted) || (task.Exception == null)))
{
task = null;
}
return task;
}
// Takes in a single byte and writes it to the buffer. If the buffer is full, it is flushed
// and then the buffer is re-initialized in flush() and then the byte is put in the buffer.
internal void WriteByte(byte b)
{
TdsParser.ReliabilitySection.Assert("unreliable call to WriteByte"); // you need to setup for a thread abort somewhere before you call this method
Debug.Assert(_outBytesUsed <= _outBuff.Length, "ERROR - TDSParser: _outBytesUsed > _outBuff.Length");
// check to make sure we haven't used the full amount of space available in the buffer, if so, flush it
if (_outBytesUsed == _outBuff.Length)
{
WritePacket(TdsEnums.SOFTFLUSH, canAccumulate: true);
}
// set byte in buffer and increment the counter for number of bytes used in the out buffer
_outBuff[_outBytesUsed++] = b;
}
internal Task WriteByteSpan(ReadOnlySpan<byte> span, bool canAccumulate = true, TaskCompletionSource<object> completion = null)
{
return WriteBytes(span, span.Length, 0, canAccumulate, completion);
}
internal Task WriteByteArray(byte[] b, int len, int offsetBuffer, bool canAccumulate = true, TaskCompletionSource<object> completion = null)
{
return WriteBytes(ReadOnlySpan<byte>.Empty, len, offsetBuffer, canAccumulate, completion, b);
}
//
// Takes a span or a byte array and writes it to the buffer
// If you pass in a span and a null array then the span wil be used.
// If you pass in a non-null array then the array will be used and the span is ignored.
// if the span cannot be written into the current packet then the remaining contents of the span are copied to a
// new heap allocated array that will used to callback into the method to continue the write operation.
private Task WriteBytes(ReadOnlySpan<byte> b, int len, int offsetBuffer, bool canAccumulate = true, TaskCompletionSource<object> completion = null, byte[] array = null)
{
if (array != null)
{
b = new ReadOnlySpan<byte>(array, offsetBuffer, len);
}
try
{
TdsParser.ReliabilitySection.Assert("unreliable call to WriteByteArray"); // you need to setup for a thread abort somewhere before you call this method
bool async = _parser._asyncWrite; // NOTE: We are capturing this now for the assert after the Task is returned, since WritePacket will turn off async if there is an exception
Debug.Assert(async || _asyncWriteCount == 0);
// Do we have to send out in packet size chunks, or can we rely on netlib layer to break it up?
// would prefer to do something like:
//
// if (len > what we have room for || len > out buf)
// flush buffer
// UnsafeNativeMethods.Write(b)
//
int offset = offsetBuffer;
Debug.Assert(b.Length >= len, "Invalid length sent to WriteBytes()!");
// loop through and write the entire array
do
{
if ((_outBytesUsed + len) > _outBuff.Length)
{
// If the remainder of the data won't fit into the buffer, then we have to put
// whatever we can into the buffer, and flush that so we can then put more into
// the buffer on the next loop of the while.
int remainder = _outBuff.Length - _outBytesUsed;
// write the remainder
Span<byte> copyTo = _outBuff.AsSpan(_outBytesUsed, remainder);
ReadOnlySpan<byte> copyFrom = b.Slice(0, remainder);
Debug.Assert(copyTo.Length == copyFrom.Length, $"copyTo.Length:{copyTo.Length} and copyFrom.Length{copyFrom.Length:D} should be the same");
copyFrom.CopyTo(copyTo);
offset += remainder;
_outBytesUsed += remainder;
len -= remainder;
b = b.Slice(remainder, len);
Task packetTask = WritePacket(TdsEnums.SOFTFLUSH, canAccumulate);
if (packetTask != null)