/
SNITcpHandle.cs
828 lines (750 loc) · 30.4 KB
/
SNITcpHandle.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
// 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.ComponentModel;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.Data.SqlClient.SNI
{
/// <summary>
/// TCP connection handle
/// </summary>
internal sealed class SNITCPHandle : SNIPhysicalHandle
{
private readonly string _targetServer;
private readonly object _callbackObject;
private readonly object _sendSync;
private readonly Socket _socket;
private NetworkStream _tcpStream;
private Stream _stream;
private SslStream _sslStream;
private SslOverTdsStream _sslOverTdsStream;
private SNIAsyncCallback _receiveCallback;
private SNIAsyncCallback _sendCallback;
private bool _validateCert = true;
private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE;
private uint _status = TdsEnums.SNI_UNINITIALIZED;
private Guid _connectionId = Guid.NewGuid();
private const int MaxParallelIpAddresses = 64;
/// <summary>
/// Dispose object
/// </summary>
public override void Dispose()
{
lock (this)
{
if (_sslOverTdsStream != null)
{
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
}
if (_sslStream != null)
{
_sslStream.Dispose();
_sslStream = null;
}
if (_tcpStream != null)
{
_tcpStream.Dispose();
_tcpStream = null;
}
//Release any references held by _stream.
_stream = null;
}
}
/// <summary>
/// Connection ID
/// </summary>
public override Guid ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Connection status
/// </summary>
public override uint Status
{
get
{
return _status;
}
}
public override int ProtocolVersion
{
get
{
try
{
return (int)_sslStream.SslProtocol;
}
catch
{
return base.ProtocolVersion;
}
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="serverName">Server name</param>
/// <param name="port">TCP port number</param>
/// <param name="timerExpire">Connection timer expiration</param>
/// <param name="callbackObject">Callback object</param>
/// <param name="parallel">Parallel executions</param>
/// <param name="cachedFQDN">Key for DNS Cache</param>
/// <param name="pendingDNSInfo">Used for DNS Cache</param>
public SNITCPHandle(string serverName, int port, long timerExpire, object callbackObject, bool parallel, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo)
{
_callbackObject = callbackObject;
_targetServer = serverName;
_sendSync = new object();
SQLDNSInfo cachedDNSInfo;
bool hasCachedDNSInfo = SQLFallbackDNSCache.Instance.GetDNSInfo(cachedFQDN, out cachedDNSInfo);
try
{
TimeSpan ts = default(TimeSpan);
// In case the Timeout is Infinite, we will receive the max value of Int64 as the tick count
// The infinite Timeout is a function of ConnectionString Timeout=0
bool isInfiniteTimeOut = long.MaxValue == timerExpire;
if (!isInfiniteTimeOut)
{
ts = DateTime.FromFileTime(timerExpire) - DateTime.Now;
ts = ts.Ticks < 0 ? TimeSpan.FromTicks(0) : ts;
}
bool reportError = true;
// We will always first try to connect with serverName as before and let the DNS server to resolve the serverName.
// If the DSN resolution fails, we will try with IPs in the DNS cache if existed. We try with IPv4 first and followed by IPv6 if
// IPv4 fails. The exceptions will be throw to upper level and be handled as before.
try
{
if (parallel)
{
_socket = TryConnectParallel(serverName, port, ts, isInfiniteTimeOut, ref reportError, cachedFQDN, ref pendingDNSInfo);
}
else
{
_socket = Connect(serverName, port, ts, isInfiniteTimeOut, cachedFQDN, ref pendingDNSInfo);
}
}
catch (Exception ex)
{
// Retry with cached IP address
if (ex is SocketException || ex is ArgumentException || ex is AggregateException)
{
if (hasCachedDNSInfo == false)
{
throw;
}
else
{
int portRetry = String.IsNullOrEmpty(cachedDNSInfo.Port) ? port : Int32.Parse(cachedDNSInfo.Port);
try
{
if (parallel)
{
_socket = TryConnectParallel(cachedDNSInfo.AddrIPv4, portRetry, ts, isInfiniteTimeOut, ref reportError, cachedFQDN, ref pendingDNSInfo);
}
else
{
_socket = Connect(cachedDNSInfo.AddrIPv4, portRetry, ts, isInfiniteTimeOut, cachedFQDN, ref pendingDNSInfo);
}
}
catch (Exception exRetry)
{
if (exRetry is SocketException || exRetry is ArgumentNullException
|| exRetry is ArgumentException || exRetry is ArgumentOutOfRangeException || exRetry is AggregateException)
{
if (parallel)
{
_socket = TryConnectParallel(cachedDNSInfo.AddrIPv6, portRetry, ts, isInfiniteTimeOut, ref reportError, cachedFQDN, ref pendingDNSInfo);
}
else
{
_socket = Connect(cachedDNSInfo.AddrIPv6, portRetry, ts, isInfiniteTimeOut, cachedFQDN, ref pendingDNSInfo);
}
}
else
{
throw;
}
}
}
}
else
{
throw;
}
}
if (_socket == null || !_socket.Connected)
{
if (_socket != null)
{
_socket.Dispose();
_socket = null;
}
if (reportError)
{
ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
}
return;
}
_socket.NoDelay = true;
_tcpStream = new NetworkStream(_socket, true);
_sslOverTdsStream = new SslOverTdsStream(_tcpStream);
_sslStream = new SNISslStream(_sslOverTdsStream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate));
}
catch (SocketException se)
{
ReportTcpSNIError(se);
return;
}
catch (Exception e)
{
ReportTcpSNIError(e);
return;
}
_stream = _tcpStream;
_status = TdsEnums.SNI_SUCCESS;
}
// Connect to server with hostName and port in parellel mode.
// The IP information will be collected temporarily as the pendingDNSInfo but is not stored in the DNS cache at this point.
// Only write to the DNS cache when we receive IsSupported flag as true in the Feature Ext Ack from server.
private Socket TryConnectParallel(string hostName, int port, TimeSpan ts, bool isInfiniteTimeOut, ref bool callerReportError, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo)
{
Socket availableSocket = null;
Task<Socket> connectTask;
Task<IPAddress[]> serverAddrTask = Dns.GetHostAddressesAsync(hostName);
serverAddrTask.Wait(ts);
IPAddress[] serverAddresses = serverAddrTask.Result;
if (serverAddresses.Length > MaxParallelIpAddresses)
{
// Fail if above 64 to match legacy behavior
callerReportError = false;
ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, string.Empty);
return availableSocket;
}
string IPv4String = null;
string IPv6String = null;
foreach (IPAddress ipAddress in serverAddresses)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
IPv4String = ipAddress.ToString();
}
else if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
IPv6String = ipAddress.ToString();
}
}
if (IPv4String != null || IPv6String != null)
{
pendingDNSInfo = new SQLDNSInfo(cachedFQDN, IPv4String, IPv6String, port.ToString());
}
connectTask = ParallelConnectAsync(serverAddresses, port);
if (!(isInfiniteTimeOut ? connectTask.Wait(-1) : connectTask.Wait(ts)))
{
callerReportError = false;
ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, string.Empty);
return availableSocket;
}
availableSocket = connectTask.Result;
return availableSocket;
}
// Connect to server with hostName and port.
// The IP information will be collected temporarily as the pendingDNSInfo but is not stored in the DNS cache at this point.
// Only write to the DNS cache when we receive IsSupported flag as true in the Feature Ext Ack from server.
private static Socket Connect(string serverName, int port, TimeSpan timeout, bool isInfiniteTimeout, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo)
{
IPAddress[] ipAddresses = Dns.GetHostAddresses(serverName);
string IPv4String = null;
string IPv6String = null;
IPAddress serverIPv4 = null;
IPAddress serverIPv6 = null;
foreach (IPAddress ipAddress in ipAddresses)
{
if (ipAddress.AddressFamily == AddressFamily.InterNetwork)
{
serverIPv4 = ipAddress;
IPv4String = ipAddress.ToString();
}
else if (ipAddress.AddressFamily == AddressFamily.InterNetworkV6)
{
serverIPv6 = ipAddress;
IPv6String = ipAddress.ToString();
}
}
ipAddresses = new IPAddress[] { serverIPv4, serverIPv6 };
Socket[] sockets = new Socket[2];
if (IPv4String != null || IPv6String != null)
{
pendingDNSInfo = new SQLDNSInfo(cachedFQDN, IPv4String, IPv6String, port.ToString());
}
CancellationTokenSource cts = null;
void Cancel()
{
for (int i = 0; i < sockets.Length; ++i)
{
try
{
if (sockets[i] != null && !sockets[i].Connected)
{
sockets[i].Dispose();
sockets[i] = null;
}
}
catch { }
}
}
if (!isInfiniteTimeout)
{
cts = new CancellationTokenSource(timeout);
cts.Token.Register(Cancel);
}
Socket availableSocket = null;
try
{
for (int i = 0; i < sockets.Length; ++i)
{
try
{
if (ipAddresses[i] != null)
{
sockets[i] = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets[i].Connect(ipAddresses[i], port);
if (sockets[i] != null) // sockets[i] can be null if cancel callback is executed during connect()
{
if (sockets[i].Connected)
{
availableSocket = sockets[i];
break;
}
else
{
sockets[i].Dispose();
sockets[i] = null;
}
}
}
}
catch { }
}
}
finally
{
cts?.Dispose();
}
return availableSocket;
}
private static Task<Socket> ParallelConnectAsync(IPAddress[] serverAddresses, int port)
{
if (serverAddresses == null)
{
throw new ArgumentNullException(nameof(serverAddresses));
}
if (serverAddresses.Length == 0)
{
throw new ArgumentOutOfRangeException(nameof(serverAddresses));
}
var sockets = new List<Socket>(serverAddresses.Length);
var connectTasks = new List<Task>(serverAddresses.Length);
var tcs = new TaskCompletionSource<Socket>();
var lastError = new StrongBox<Exception>();
var pendingCompleteCount = new StrongBox<int>(serverAddresses.Length);
foreach (IPAddress address in serverAddresses)
{
var socket = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
sockets.Add(socket);
// Start all connection tasks now, to prevent possible race conditions with
// calling ConnectAsync on disposed sockets.
try
{
connectTasks.Add(socket.ConnectAsync(address, port));
}
catch (Exception e)
{
connectTasks.Add(Task.FromException(e));
}
}
for (int i = 0; i < sockets.Count; i++)
{
ParallelConnectHelper(sockets[i], connectTasks[i], tcs, pendingCompleteCount, lastError, sockets);
}
return tcs.Task;
}
private static async void ParallelConnectHelper(
Socket socket,
Task connectTask,
TaskCompletionSource<Socket> tcs,
StrongBox<int> pendingCompleteCount,
StrongBox<Exception> lastError,
List<Socket> sockets)
{
bool success = false;
try
{
// Try to connect. If we're successful, store this task into the result task.
await connectTask.ConfigureAwait(false);
success = tcs.TrySetResult(socket);
if (success)
{
// Whichever connection completes the return task is responsible for disposing
// all of the sockets (except for whichever one is stored into the result task).
// This ensures that only one thread will attempt to dispose of a socket.
// This is also the closest thing we have to canceling connect attempts.
foreach (Socket otherSocket in sockets)
{
if (otherSocket != socket)
{
otherSocket.Dispose();
}
}
}
}
catch (Exception e)
{
// Store an exception to be published if no connection succeeds
Interlocked.Exchange(ref lastError.Value, e);
}
finally
{
// If we didn't successfully transition the result task to completed,
// then someone else did and they would have cleaned up, so there's nothing
// more to do. Otherwise, no one completed it yet or we failed; either way,
// see if we're the last outstanding connection, and if we are, try to complete
// the task, and if we're successful, it's our responsibility to dispose all of the sockets.
if (!success && Interlocked.Decrement(ref pendingCompleteCount.Value) == 0)
{
if (lastError.Value != null)
{
tcs.TrySetException(lastError.Value);
}
else
{
tcs.TrySetCanceled();
}
foreach (Socket s in sockets)
{
s.Dispose();
}
}
}
}
/// <summary>
/// Enable SSL
/// </summary>
public override uint EnableSsl(uint options)
{
_validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0;
try
{
_sslStream.AuthenticateAsClient(_targetServer);
_sslOverTdsStream.FinishHandshake();
}
catch (AuthenticationException aue)
{
return ReportTcpSNIError(aue);
}
catch (InvalidOperationException ioe)
{
return ReportTcpSNIError(ioe);
}
_stream = _sslStream;
return TdsEnums.SNI_SUCCESS;
}
/// <summary>
/// Disable SSL
/// </summary>
public override void DisableSsl()
{
_sslStream.Dispose();
_sslStream = null;
_sslOverTdsStream.Dispose();
_sslOverTdsStream = null;
_stream = _tcpStream;
}
/// <summary>
/// Validate server certificate callback
/// </summary>
/// <param name="sender">Sender object</param>
/// <param name="cert">X.509 certificate</param>
/// <param name="chain">X.509 chain</param>
/// <param name="policyErrors">Policy errors</param>
/// <returns>True if certificate is valid</returns>
private bool ValidateServerCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
{
if (!_validateCert)
{
return true;
}
return SNICommon.ValidateSslServerCertificate(_targetServer, sender, cert, chain, policyErrors);
}
/// <summary>
/// Set buffer size
/// </summary>
/// <param name="bufferSize">Buffer size</param>
public override void SetBufferSize(int bufferSize)
{
_bufferSize = bufferSize;
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint Send(SNIPacket packet)
{
bool releaseLock = false;
try
{
// is the packet is marked out out-of-band (attention packets only) it must be
// sent immediately even if a send of recieve operation is already in progress
// because out of band packets are used to cancel ongoing operations
// so try to take the lock if possible but continue even if it can't be taken
if (packet.IsOutOfBand)
{
Monitor.TryEnter(this, ref releaseLock);
}
else
{
Monitor.Enter(this);
releaseLock = true;
}
// this lock ensures that two packets are not being written to the transport at the same time
// so that sending a standard and an out-of-band packet are both written atomically no data is
// interleaved
lock (_sendSync)
{
try
{
packet.WriteToStream(_stream);
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
return ReportTcpSNIError(ode);
}
catch (SocketException se)
{
return ReportTcpSNIError(se);
}
catch (IOException ioe)
{
return ReportTcpSNIError(ioe);
}
}
}
finally
{
if (releaseLock)
{
Monitor.Exit(this);
}
}
}
/// <summary>
/// Receive a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="timeoutInMilliseconds">Timeout in Milliseconds</param>
/// <returns>SNI error code</returns>
public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds)
{
SNIPacket errorPacket;
packet = null;
try
{
if (timeoutInMilliseconds > 0)
{
_socket.ReceiveTimeout = timeoutInMilliseconds;
}
else if (timeoutInMilliseconds == -1)
{
// SqlClient internally represents infinite timeout by -1, and for TcpClient this is translated to a timeout of 0
_socket.ReceiveTimeout = 0;
}
else
{
// otherwise it is timeout for 0 or less than -1
ReportTcpSNIError(0, SNICommon.ConnTimeoutError, string.Empty);
return TdsEnums.SNI_WAIT_TIMEOUT;
}
packet = RentPacket(headerSize: 0, dataSize: _bufferSize);
packet.ReadFromStream(_stream);
if (packet.Length == 0)
{
errorPacket = packet;
packet = null;
var e = new Win32Exception();
return ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message);
}
return TdsEnums.SNI_SUCCESS;
}
catch (ObjectDisposedException ode)
{
errorPacket = packet;
packet = null;
return ReportErrorAndReleasePacket(errorPacket, ode);
}
catch (SocketException se)
{
errorPacket = packet;
packet = null;
return ReportErrorAndReleasePacket(errorPacket, se);
}
catch (IOException ioe)
{
errorPacket = packet;
packet = null;
uint errorCode = ReportErrorAndReleasePacket(errorPacket, ioe);
if (ioe.InnerException is SocketException socketException && socketException.SocketErrorCode == SocketError.TimedOut)
{
errorCode = TdsEnums.SNI_WAIT_TIMEOUT;
}
return errorCode;
}
finally
{
_socket.ReceiveTimeout = 0;
}
}
/// <summary>
/// Set async callbacks
/// </summary>
/// <param name="receiveCallback">Receive callback</param>
/// <param name="sendCallback">Send callback</param>
public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback)
{
_receiveCallback = receiveCallback;
_sendCallback = sendCallback;
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
public override uint SendAsync(SNIPacket packet, SNIAsyncCallback callback = null)
{
long scopeID = SqlClientEventSource.Log.TrySNIScopeEnterEvent("<sc.SNI.SNIMarsHandle.SendAsync |SNI|INFO|SCOPE>");
try
{
SNIAsyncCallback cb = callback ?? _sendCallback;
packet.WriteToStreamAsync(_stream, cb, SNIProviders.TCP_PROV);
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
finally
{
SqlClientEventSource.Log.TrySNIScopeLeaveEvent(scopeID);
}
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public override uint ReceiveAsync(ref SNIPacket packet)
{
SNIPacket errorPacket;
packet = RentPacket(headerSize: 0, dataSize: _bufferSize);
try
{
packet.ReadFromStreamAsync(_stream, _receiveCallback);
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
catch (Exception e) when (e is ObjectDisposedException || e is SocketException || e is IOException)
{
errorPacket = packet;
packet = null;
return ReportErrorAndReleasePacket(errorPacket, e);
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <returns>SNI error status</returns>
public override uint CheckConnection()
{
try
{
// _socket.Poll method with argument SelectMode.SelectRead returns
// True : if Listen has been called and a connection is pending, or
// True : if data is available for reading, or
// True : if the connection has been closed, reset, or terminated, i.e no active connection.
// False : otherwise.
// _socket.Available property returns the number of bytes of data available to read.
//
// Since _socket.Connected alone doesn't guarantee if the connection is still active, we use it in
// combination with _socket.Poll method and _socket.Available == 0 check. When both of them
// return true we can safely determine that the connection is no longer active.
if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0))
{
return TdsEnums.SNI_ERROR;
}
}
catch (SocketException se)
{
return ReportTcpSNIError(se);
}
catch (ObjectDisposedException ode)
{
return ReportTcpSNIError(ode);
}
return TdsEnums.SNI_SUCCESS;
}
private uint ReportTcpSNIError(Exception sniException)
{
_status = TdsEnums.SNI_ERROR;
return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException);
}
private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage)
{
_status = TdsEnums.SNI_ERROR;
return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException)
{
if (packet != null)
{
ReturnPacket(packet);
}
return ReportTcpSNIError(sniException);
}
private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage)
{
if (packet != null)
{
ReturnPacket(packet);
}
return ReportTcpSNIError(nativeError, sniError, errorMessage);
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public override void KillConnection()
{
_socket.Shutdown(SocketShutdown.Both);
}
#endif
internal static void SetKeepAliveValues(ref Socket socket)
{
#if NETCOREAPP31_AND_ABOVE
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, 1);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, 30);
#endif
}
}
}