diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj index ac8f2d2200..0e16bd61e8 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft.Data.SqlClient.csproj @@ -275,6 +275,69 @@ Microsoft\Data\SqlClient\LocalAppContextSwitches.cs + + Microsoft\Data\SqlClient\ManagedSni\ConcurrentQueueSemaphore.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniAsyncCallback.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniError.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniCommon.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniHandle.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniLoadHandle.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniMarsConnection.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniMarsHandle.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniNetworkStream.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniNpHandle.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniPacket.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniPhysicalHandle.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniProviders.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniProxy.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniSmuxFlags.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniSmuxHeader.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniSslStream.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SniTcpHandle.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SslOverTdsStream.netcore.cs + + + Microsoft\Data\SqlClient\ManagedSni\SslOverTdsStream.NetCoreApp.cs + + + Microsoft\Data\SqlClient\ManagedSni\SsrpClient.netcore.cs + Microsoft\Data\SqlClient\NoneAttestationEnclaveProvider.cs @@ -731,25 +794,8 @@ System\Diagnostics\CodeAnalysis.cs - + - - - - - - - - - - - - - - - - - @@ -882,6 +928,9 @@ Microsoft\Data\SqlClient\LocalDb\LocalDbApi.Windows.cs + + Microsoft\Data\SqlClient\ManagedSni\LocalDB.netcore.Windows.cs + Microsoft\Data\SqlClient\PacketHandle.Windows.cs @@ -910,7 +959,6 @@ Microsoft\Data\SqlTypes\SqlFileStream.Windows.cs - @@ -929,6 +977,9 @@ Microsoft\Data\SqlClient\LocalDb\LocalDbApi.Unix.cs + + Microsoft\Data\SqlClient\ManagedSni\LocalDB.netcore.Unix.cs + Microsoft\Data\SqlClient\PacketHandle.netcore.Unix.cs @@ -951,7 +1002,6 @@ Microsoft\Data\SqlTypes\SqlFileStream.netcore.Unix.cs - diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIStreams.ValueTask.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIStreams.ValueTask.cs deleted file mode 100644 index f5f38f0efe..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIStreams.ValueTask.cs +++ /dev/null @@ -1,109 +0,0 @@ -// 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.Threading; -using System.Threading.Tasks; -using System; - -namespace Microsoft.Data.SqlClient.SNI -{ - internal sealed partial class SNISslStream - { - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); - } - - public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - await _readAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - return await base.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); - } - catch (Exception e) - { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNISslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); - throw; - } - finally - { - _readAsyncSemaphore.Release(); - } - } - - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return WriteAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); - } - - public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - { - await _writeAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - await base.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); - } - catch (Exception e) - { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNISslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); - throw; - } - finally - { - _writeAsyncSemaphore.Release(); - } - } - } - - internal sealed partial class SNINetworkStream - { - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); - } - - public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) - { - await _readAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - return await base.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); - } - catch (Exception e) - { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNISslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); - throw; - } - finally - { - _readAsyncSemaphore.Release(); - } - } - - // Prevent the WriteAsync collisions by running the task in a Semaphore Slim - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - { - return WriteAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); - } - - public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) - { - await _writeAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); - try - { - await base.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); - } - catch (Exception e) - { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNISslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); - throw; - } - finally - { - _writeAsyncSemaphore.Release(); - } - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIStreams.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIStreams.cs deleted file mode 100644 index 389f25eeae..0000000000 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIStreams.cs +++ /dev/null @@ -1,41 +0,0 @@ -// 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.Net.Security; -using System.IO; -using System.Net.Sockets; - -namespace Microsoft.Data.SqlClient.SNI -{ - /// - /// This class extends SslStream to customize stream behavior for Managed SNI implementation. - /// - internal sealed partial class SNISslStream : SslStream - { - private readonly ConcurrentQueueSemaphore _writeAsyncSemaphore; - private readonly ConcurrentQueueSemaphore _readAsyncSemaphore; - - public SNISslStream(Stream innerStream, bool leaveInnerStreamOpen, RemoteCertificateValidationCallback userCertificateValidationCallback) - : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback) - { - _writeAsyncSemaphore = new ConcurrentQueueSemaphore(1); - _readAsyncSemaphore = new ConcurrentQueueSemaphore(1); - } - } - - /// - /// This class extends NetworkStream to customize stream behavior for Managed SNI implementation. - /// - internal sealed partial class SNINetworkStream : NetworkStream - { - private readonly ConcurrentQueueSemaphore _writeAsyncSemaphore; - private readonly ConcurrentQueueSemaphore _readAsyncSemaphore; - - public SNINetworkStream(Socket socket, bool ownsSocket) : base(socket, ownsSocket) - { - _writeAsyncSemaphore = new ConcurrentQueueSemaphore(1); - _readAsyncSemaphore = new ConcurrentQueueSemaphore(1); - } - } -} diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs index 2f242a083f..d71332a25a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Unix.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.Data.SqlClient.SNI; +using Microsoft.Data.SqlClient.ManagedSni; namespace Microsoft.Data.SqlClient { @@ -26,7 +26,7 @@ private void WaitForSSLHandShakeToComplete(ref uint error, ref int protocolVersi private SNIErrorDetails GetSniErrorDetails() { SNIErrorDetails details; - SNIError sniError = SNIProxy.Instance.GetLastError(); + SniError sniError = SniProxy.Instance.GetLastError(); details.sniErrorNumber = sniError.sniError; details.errorMessage = sniError.errorMessage; details.nativeError = sniError.nativeError; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs index de4bcb1338..25bc6f87c5 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParser.Windows.cs @@ -5,7 +5,8 @@ using System; using System.Diagnostics; using Interop.Windows.Sni; -using Microsoft.Data.SqlClient.SNI; +using Microsoft.Data.SqlClient.ManagedSni; +using SniError = Microsoft.Data.SqlClient.ManagedSni.SniError; namespace Microsoft.Data.SqlClient { @@ -68,7 +69,7 @@ private SNIErrorDetails GetSniErrorDetails() if (TdsParserStateObjectFactory.UseManagedSNI) { - SNIError sniError = SNIProxy.Instance.GetLastError(); + SniError sniError = SniProxy.Instance.GetLastError(); details.sniErrorNumber = sniError.sniError; details.errorMessage = sniError.errorMessage; details.nativeError = sniError.nativeError; @@ -79,7 +80,7 @@ private SNIErrorDetails GetSniErrorDetails() } else { - SniNativeWrapper.SniGetLastError(out SniError sniError); + SniNativeWrapper.SniGetLastError(out Interop.Windows.Sni.SniError sniError); details.sniErrorNumber = sniError.sniError; details.errorMessage = sniError.errorMessage; details.nativeError = sniError.nativeError; diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs index e6dddc79f9..a403f8b556 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectManaged.cs @@ -7,20 +7,19 @@ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Net.Security; using System.Runtime.CompilerServices; -using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; -namespace Microsoft.Data.SqlClient.SNI +// @TODO: If this is in the manages SNI namespace, it should be in the managed SNI folder +namespace Microsoft.Data.SqlClient.ManagedSni { internal sealed class TdsParserStateObjectManaged : TdsParserStateObject { - private SNIMarsConnection? _marsConnection; - private SNIHandle? _sessionHandle; + private SniMarsConnection? _marsConnection; + private SniHandle? _sessionHandle; public TdsParserStateObjectManaged(TdsParser parser) : base(parser) { } @@ -34,7 +33,7 @@ internal TdsParserStateObjectManaged(TdsParser parser, TdsParserStateObject phys protected override bool CheckPacket(PacketHandle packet, TaskCompletionSource source) { - SNIPacket p = packet.ManagedPacket; + SniPacket p = packet.ManagedPacket; return p.IsInvalid || source != null; } @@ -52,7 +51,7 @@ protected override void CreateSessionHandle(TdsParserStateObject physicalConnect } } - internal SNIMarsHandle CreateMarsSession(object callbackObject, bool async) + internal SniMarsHandle CreateMarsSession(object callbackObject, bool async) { SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.CreateMarsSession | Info | State Object Id {0}, Session Id {1}, Async = {2}", _objectID, _sessionHandle?.ConnectionId, async); if (_marsConnection is null) @@ -94,7 +93,7 @@ internal override void CreatePhysicalSNIHandle( string hostNameInCertificate, string serverCertificateFilename) { - SNIHandle? sessionHandle = SNIProxy.CreateConnectionHandle(serverName, timeout, out instanceName, ref spns, serverSPN, + SniHandle? sessionHandle = SniProxy.CreateConnectionHandle(serverName, timeout, out instanceName, ref spns, serverSPN, flushCache, async, parallel, isIntegratedSecurity, iPAddressPreference, cachedFQDN, ref pendingDNSInfo, tlsFirst, hostNameInCertificate, serverCertificateFilename); @@ -120,9 +119,9 @@ internal override void AssignPendingDNSInfo(string userProtocol, string DNSCache // No-op } - internal void ReadAsyncCallback(SNIPacket packet, uint error) + internal void ReadAsyncCallback(SniPacket packet, uint error) { - SNIHandle? sessionHandle = _sessionHandle; + SniHandle? sessionHandle = _sessionHandle; if (sessionHandle is not null) { ReadAsyncCallback(IntPtr.Zero, PacketHandle.FromManagedPacket(packet), error); @@ -140,9 +139,9 @@ internal void ReadAsyncCallback(SNIPacket packet, uint error) } } - internal void WriteAsyncCallback(SNIPacket packet, uint sniError) + internal void WriteAsyncCallback(SniPacket packet, uint sniError) { - SNIHandle? sessionHandle = _sessionHandle; + SniHandle? sessionHandle = _sessionHandle; if (sessionHandle is not null) { WriteAsyncCallback(IntPtr.Zero, PacketHandle.FromManagedPacket(packet), sniError); @@ -167,7 +166,7 @@ protected override void RemovePacketFromPendingList(PacketHandle packet) internal override void Dispose() { - SNIHandle? sessionHandle = Interlocked.Exchange(ref _sessionHandle, null); + SniHandle? sessionHandle = Interlocked.Exchange(ref _sessionHandle, null); if (sessionHandle is not null) { SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.Dispose | Info | State Object Id {0}, Session Id {1}, Disposing session Handle and counters.", _objectID, sessionHandle.ConnectionId); @@ -204,7 +203,7 @@ protected override void FreeGcHandle(int remaining, bool release) internal override bool IsFailedHandle() { - SNIHandle? sessionHandle = _sessionHandle; + SniHandle? sessionHandle = _sessionHandle; if (sessionHandle is not null) { return sessionHandle.Status != TdsEnums.SNI_SUCCESS; @@ -215,9 +214,9 @@ internal override bool IsFailedHandle() internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error) { - SNIHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); + SniHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); - error = sessionHandle.Receive(out SNIPacket packet, timeoutRemaining); + error = sessionHandle.Receive(out SniPacket packet, timeoutRemaining); SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.ReadSyncOverAsync | Info | State Object Id {0}, Session Id {1}", _objectID, sessionHandle.ConnectionId); #if DEBUG @@ -234,14 +233,14 @@ internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint internal override void ReleasePacket(PacketHandle syncReadPacket) { - SNIPacket packet = syncReadPacket.ManagedPacket; + SniPacket packet = syncReadPacket.ManagedPacket; SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.ReleasePacket | Info | State Object Id {0}, Session Id {1}, Packet DataLeft {2}", _objectID, _sessionHandle?.ConnectionId, packet?.DataLeft); #if DEBUG SqlClientEventSource.Log.TryAdvancedTraceEvent("TdsParserStateObjectManaged.ReleasePacket | TRC | State Object Id {0}, Session Id {1}, Packet {2} will be released, Packet Owner Id {3}, Packet dataLeft {4}", _objectID, _sessionHandle?.ConnectionId, packet?._id, packet?._owner.ConnectionId, packet?.DataLeft); #endif if (packet is not null) { - SNIHandle? sessionHandle = _sessionHandle; + SniHandle? sessionHandle = _sessionHandle; if (sessionHandle is not null) { sessionHandle.ReturnPacket(packet); @@ -257,13 +256,13 @@ internal override void ReleasePacket(PacketHandle syncReadPacket) internal override uint CheckConnection() { - SNIHandle? handle = GetSessionSNIHandleHandleOrThrow(); + SniHandle? handle = GetSessionSNIHandleHandleOrThrow(); return handle is null ? TdsEnums.SNI_SUCCESS : handle.CheckConnection(); } internal override PacketHandle ReadAsync(SessionHandle handle, out uint error) { - SNIPacket? packet = null; + SniPacket? packet = null; error = handle.ManagedHandle.ReceiveAsync(ref packet); SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.ReadAsync | Info | State Object Id {0}, Session Id {1}, Packet DataLeft {2}", _objectID, _sessionHandle?.ConnectionId, packet?.DataLeft); @@ -286,8 +285,8 @@ internal override PacketHandle CreateAndSetAttentionPacket() internal override uint WritePacket(PacketHandle packetHandle, bool sync) { uint result = TdsEnums.SNI_UNINITIALIZED; - SNIHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); - SNIPacket? packet = packetHandle.ManagedPacket; + SniHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); + SniPacket? packet = packetHandle.ManagedPacket; if (sync) { @@ -318,8 +317,8 @@ internal override bool IsValidPacket(PacketHandle packet) internal override PacketHandle GetResetWritePacket(int dataSize) { - SNIHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); - SNIPacket packet = sessionHandle.RentPacket(headerSize: sessionHandle.ReserveHeaderSize, dataSize: dataSize); + SniHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); + SniPacket packet = sessionHandle.RentPacket(headerSize: sessionHandle.ReserveHeaderSize, dataSize: dataSize); #if DEBUG Debug.Assert(packet.IsActive, "packet is not active, a serious pooling error may have occurred"); #endif @@ -346,7 +345,7 @@ internal override uint SniGetConnectionId(ref Guid clientConnectionId) internal override uint DisableSsl() { - SNIHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); + SniHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.DisableSsl | Info | Session Id {0}", sessionHandle.ConnectionId); sessionHandle.DisableSsl(); return TdsEnums.SNI_SUCCESS; @@ -354,8 +353,8 @@ internal override uint DisableSsl() internal override uint EnableMars(ref uint info) { - SNIHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); - _marsConnection = new SNIMarsConnection(sessionHandle); + SniHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); + _marsConnection = new SniMarsConnection(sessionHandle); SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.EnableMars | Info | State Object Id {0}, Session Id {1}", _objectID, sessionHandle.ConnectionId); if (_marsConnection.StartReceive() == TdsEnums.SNI_SUCCESS_IO_PENDING) @@ -368,7 +367,7 @@ internal override uint EnableMars(ref uint info) internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCertificateFilename) { - SNIHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); + SniHandle sessionHandle = GetSessionSNIHandleHandleOrThrow(); try { SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.EnableSsl | Info | Session Id {0}", sessionHandle.ConnectionId); @@ -377,7 +376,7 @@ internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCert catch (Exception e) { SqlClientEventSource.Log.TryTraceEvent("TdsParserStateObjectManaged.EnableSsl | Err | Session Id {0}, SNI Handshake failed with exception: {1}", sessionHandle.ConnectionId, e.Message); - return SNICommon.ReportSNIError(SNIProviders.SSL_PROV, SNICommon.HandshakeFailureError, e); + return SniCommon.ReportSNIError(SniProviders.SSL_PROV, SniCommon.HandshakeFailureError, e); } } @@ -393,9 +392,9 @@ internal override uint WaitForSSLHandShakeToComplete(out int protocolVersion) return 0; } - private SNIHandle GetSessionSNIHandleHandleOrThrow() + private SniHandle GetSessionSNIHandleHandleOrThrow() { - SNIHandle? sessionHandle = _sessionHandle; + SniHandle? sessionHandle = _sessionHandle; if (sessionHandle is null) { ThrowClosedConnection(); diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/ConcurrentQueueSemaphore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/ConcurrentQueueSemaphore.netcore.cs similarity index 97% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/ConcurrentQueueSemaphore.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/ConcurrentQueueSemaphore.netcore.cs index 46d3b70a25..fff46abea6 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/ConcurrentQueueSemaphore.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/ConcurrentQueueSemaphore.netcore.cs @@ -2,12 +2,13 @@ // 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; +#if NET + using System.Collections.Concurrent; using System.Threading; using System.Threading.Tasks; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// This class implements a FIFO Queue with SemaphoreSlim for ordered execution of parallel tasks. @@ -56,5 +57,6 @@ public void Release() _semaphore.Release(); } } - } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/LocalDB.netcore.Unix.cs similarity index 89% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/LocalDB.netcore.Unix.cs index a9b235d47c..8ab05865a2 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Unix.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/LocalDB.netcore.Unix.cs @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { internal class LocalDB { @@ -14,3 +16,5 @@ internal static string GetLocalDBConnectionString(string localDbInstance) } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/LocalDB.netcore.Windows.cs similarity index 91% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/LocalDB.netcore.Windows.cs index 6f8e855542..bcea4a8404 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/LocalDB.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/LocalDB.netcore.Windows.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Runtime.InteropServices; using System.Text; @@ -9,8 +11,7 @@ using Interop.Windows.Kernel32; using Microsoft.Win32; - -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { internal sealed class LocalDB { @@ -55,7 +56,7 @@ private string GetConnectionString(string localDbInstance) int result = localDBStartInstanceFunc(localDbInstance, 0, localDBConnectionString, ref sizeOfbuffer); if (result != TdsEnums.SNI_SUCCESS) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBErrorCode, Strings.SNI_ERROR_50); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.LocalDBErrorCode, Strings.SNI_ERROR_50); SqlClientEventSource.Log.TrySNITraceEvent(nameof(LocalDB), EventType.ERR, "Unsuccessful 'LocalDBStartInstance' method call with {0} result to start '{1}' localDb instance", args0: result, args1: localDbInstance); localDBConnectionString = null; } @@ -72,17 +73,17 @@ internal static uint MapLocalDBErrorStateToCode(LocalDBErrorState errorState) switch (errorState) { case LocalDBErrorState.NO_INSTALLATION: - return SNICommon.LocalDBNoInstallation; + return SniCommon.LocalDBNoInstallation; case LocalDBErrorState.INVALID_CONFIG: - return SNICommon.LocalDBInvalidConfig; + return SniCommon.LocalDBInvalidConfig; case LocalDBErrorState.NO_SQLUSERINSTANCEDLL_PATH: - return SNICommon.LocalDBNoSqlUserInstanceDllPath; + return SniCommon.LocalDBNoSqlUserInstanceDllPath; case LocalDBErrorState.INVALID_SQLUSERINSTANCEDLL_PATH: - return SNICommon.LocalDBInvalidSqlUserInstanceDllPath; + return SniCommon.LocalDBInvalidSqlUserInstanceDllPath; case LocalDBErrorState.NONE: return 0; default: - return SNICommon.LocalDBInvalidConfig; + return SniCommon.LocalDBInvalidConfig; } } @@ -133,7 +134,7 @@ private bool LoadUserInstanceDll() // If there was no DLL path found, then there is an error. if (dllPath == null) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, MapLocalDBErrorStateToCode(registryQueryErrorState), MapLocalDBErrorStateToErrorMessage(registryQueryErrorState)); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, MapLocalDBErrorStateToCode(registryQueryErrorState), MapLocalDBErrorStateToErrorMessage(registryQueryErrorState)); SqlClientEventSource.Log.TrySNITraceEvent(nameof(LocalDB), EventType.ERR, "User instance DLL path is null."); return false; } @@ -141,7 +142,7 @@ private bool LoadUserInstanceDll() // In case the registry had an empty path for dll if (string.IsNullOrWhiteSpace(dllPath)) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBInvalidSqlUserInstanceDllPath, Strings.SNI_ERROR_55); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.LocalDBInvalidSqlUserInstanceDllPath, Strings.SNI_ERROR_55); SqlClientEventSource.Log.TrySNITraceEvent(nameof(LocalDB), EventType.ERR, "User instance DLL path is invalid. DLL path = {0}", dllPath); return false; } @@ -151,7 +152,7 @@ private bool LoadUserInstanceDll() if (libraryHandle.IsInvalid) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBFailedToLoadDll, Strings.SNI_ERROR_56); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.LocalDBFailedToLoadDll, Strings.SNI_ERROR_56); SqlClientEventSource.Log.TrySNITraceEvent(nameof(LocalDB), EventType.ERR, "Library Handle is invalid. Could not load the dll."); libraryHandle.Dispose(); return false; @@ -162,7 +163,7 @@ private bool LoadUserInstanceDll() if (_startInstanceHandle == IntPtr.Zero) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, Strings.SNI_ERROR_57); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.LocalDBBadRuntime, Strings.SNI_ERROR_57); SqlClientEventSource.Log.TrySNITraceEvent(nameof(LocalDB), EventType.ERR, "Was not able to load the PROC from DLL. Bad Runtime."); libraryHandle.Dispose(); return false; @@ -173,7 +174,7 @@ private bool LoadUserInstanceDll() if (localDBStartInstanceFunc == null) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBBadRuntime, Strings.SNI_ERROR_57); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.LocalDBBadRuntime, Strings.SNI_ERROR_57); libraryHandle.Dispose(); _startInstanceHandle = IntPtr.Zero; return false; @@ -266,3 +267,5 @@ private string GetUserInstanceDllPath(out LocalDBErrorState errorState) } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniAsyncCallback.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniAsyncCallback.netcore.cs new file mode 100644 index 0000000000..832d8bc1ce --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniAsyncCallback.netcore.cs @@ -0,0 +1,17 @@ +// 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. + +#if NET + +namespace Microsoft.Data.SqlClient.ManagedSni +{ + /// + /// SNI Asynchronous callback + /// + /// SNI packet + /// SNI error code + internal delegate void SniAsyncCallback(SniPacket packet, uint sniErrorCode); +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs similarity index 69% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs index 0f98b34673..6aaf23f877 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNICommon.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniCommon.netcore.cs @@ -2,115 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; -using System.Buffers.Binary; using System.Diagnostics; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Data.Common; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Data.ProviderBase; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { - /// - /// SNI Asynchronous callback - /// - /// SNI packet - /// SNI error code - internal delegate void SNIAsyncCallback(SNIPacket packet, uint sniErrorCode); - - /// - /// SNI provider identifiers - /// - internal enum SNIProviders - { - HTTP_PROV = 0, // HTTP Provider - NP_PROV = 1, // Named Pipes Provider - SESSION_PROV = 2, // Session Provider - SIGN_PROV = 3, // Sign Provider - SM_PROV = 4, // Shared Memory Provider - SMUX_PROV = 5, // SMUX Provider - SSL_PROV = 6, // SSL Provider - TCP_PROV = 7, // TCP Provider - VIA_PROV = 8, // Virtual Interface Architecture Provider - CTAIP_PROV = 9, - MAX_PROVS = 10, // Number of providers - INVALID_PROV = 11 // SQL Network Interfaces - } - - /// - /// SMUX packet header - /// - internal sealed class SNISMUXHeader - { - public const int HEADER_LENGTH = 16; - - public byte SMID; - public byte flags; - public ushort sessionId; - public uint length; - public uint sequenceNumber; - public uint highwater; - - public void Read(byte[] bytes) - { - SMID = bytes[0]; - flags = bytes[1]; - Span span = bytes.AsSpan(); - sessionId = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(2)); - length = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(4)) - SNISMUXHeader.HEADER_LENGTH; - sequenceNumber = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(8)); - highwater = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(12)); - } - - public void Write(Span bytes) - { - uint value = highwater; - // access the highest element first to cause the largest range check in the jit, then fill in the rest of the value and carry on as normal - bytes[15] = (byte)((value >> 24) & 0xff); - bytes[12] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12); - bytes[13] = (byte)((value >> 8) & 0xff); - bytes[14] = (byte)((value >> 16) & 0xff); - - bytes[0] = SMID; // BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0); - bytes[1] = flags; // BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1); - - value = sessionId; - bytes[2] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2); - bytes[3] = (byte)((value >> 8) & 0xff); - - value = length; - bytes[4] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4); - bytes[5] = (byte)((value >> 8) & 0xff); - bytes[6] = (byte)((value >> 16) & 0xff); - bytes[7] = (byte)((value >> 24) & 0xff); - - value = sequenceNumber; - bytes[8] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8); - bytes[9] = (byte)((value >> 8) & 0xff); - bytes[10] = (byte)((value >> 16) & 0xff); - bytes[11] = (byte)((value >> 24) & 0xff); - - } - } - - /// - /// SMUX packet flags - /// - [Flags] - internal enum SNISMUXFlags - { - SMUX_SYN = 1, // Begin SMUX connection - SMUX_ACK = 2, // Acknowledge SMUX packets - SMUX_FIN = 4, // End SMUX connection - SMUX_DATA = 8 // SMUX data packet - } - - internal class SNICommon + internal class SniCommon { // Each error number maps to SNI_ERROR_* in String.resx internal const int ConnTerminatedError = 2; @@ -151,11 +56,11 @@ internal class SNICommon /// True if certificate is valid internal static bool ValidateSslServerCertificate(Guid connectionId, string targetServerName, string hostNameInCertificate, X509Certificate serverCert, string validationCertFileName, SslPolicyErrors policyErrors) { - using (TrySNIEventScope.Create(nameof(SNICommon))) + using (TrySNIEventScope.Create(nameof(SniCommon))) { if (policyErrors == SslPolicyErrors.None) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to None.", args0: connectionId, args1: targetServerName); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to None.", args0: connectionId, args1: targetServerName); return true; } @@ -183,7 +88,7 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ catch (Exception e) { // if this fails, then fall back to the HostNameInCertificate or TargetServer validation. - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Exception occurred loading specified ServerCertificate: {1}, treating it as if ServerCertificate has not been specified.", args0: connectionId, args1: e.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Exception occurred loading specified ServerCertificate: {1}, treating it as if ServerCertificate has not been specified.", args0: connectionId, args1: e.Message); } } @@ -191,12 +96,12 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ { if (serverCert.GetRawCertData().AsSpan().SequenceEqual(validationCertificate.GetRawCertData().AsSpan())) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, "Connection Id {0}, ServerCertificate matches the certificate provided by the server. Certificate validation passed.", args0: connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, ServerCertificate matches the certificate provided by the server. Certificate validation passed.", args0: connectionId); return true; } else { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, "Connection Id {0}, ServerCertificate doesn't match the certificate provided by the server. Certificate validation failed.", args0: connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, ServerCertificate doesn't match the certificate provided by the server. Certificate validation failed.", args0: connectionId); throw ADP.SSLCertificateAuthenticationException(Strings.SQL_RemoteCertificateDoesNotMatchServerCertificate); } } @@ -206,13 +111,13 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ StringBuilder messageBuilder = new(); if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateNotAvailable)) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to RemoteCertificateNotAvailable.", args0: connectionId, args1: targetServerName); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SSL Server certificate not validated as PolicyErrors set to RemoteCertificateNotAvailable.", args0: connectionId, args1: targetServerName); messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNotAvailable); } if (policyErrors.HasFlag(SslPolicyErrors.RemoteCertificateChainErrors)) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.ERR, "Connection Id {0}, targetServerName {0}, SslPolicyError {1}, SSL Policy certificate chain has errors.", args0: connectionId, args1: targetServerName, args2: policyErrors); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {0}, SslPolicyError {1}, SSL Policy certificate chain has errors.", args0: connectionId, args1: targetServerName, args2: policyErrors); // get the chain status from the certificate X509Certificate2 cert2 = serverCert as X509Certificate2; @@ -229,7 +134,7 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ chainStatusInformation.AppendLine(); } } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SslPolicyError {2}, SSL Policy certificate chain has errors. ChainStatus {3}", args0: connectionId, args1: targetServerName, args2: policyErrors, args3: chainStatusInformation); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, targetServerName {1}, SslPolicyError {2}, SSL Policy certificate chain has errors. ChainStatus {3}", args0: connectionId, args1: targetServerName, args2: policyErrors, args3: chainStatusInformation); messageBuilder.AppendFormat(Strings.SQL_RemoteCertificateChainErrors, chainStatusInformation); messageBuilder.AppendLine(); } @@ -239,7 +144,7 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ X509Certificate2 cert2 = serverCert as X509Certificate2; if (!cert2.MatchesHostname(serverNameToValidate)) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.ERR, "Connection Id {0}, serverNameToValidate {1}, Target Server name or HNIC does not match the Subject/SAN in Certificate.", args0: connectionId, args1: serverNameToValidate); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Connection Id {0}, serverNameToValidate {1}, Target Server name or HNIC does not match the Subject/SAN in Certificate.", args0: connectionId, args1: serverNameToValidate); messageBuilder.AppendLine(Strings.SQL_RemoteCertificateNameMismatch); } } @@ -250,7 +155,7 @@ internal static bool ValidateSslServerCertificate(Guid connectionId, string targ } } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, "Connection Id {0}, certificate with subject: {1}, validated successfully.", args0: connectionId, args1: serverCert.Subject); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Connection Id {0}, certificate with subject: {1}, validated successfully.", args0: connectionId, args1: serverCert.Subject); return true; } } @@ -269,9 +174,9 @@ internal static IPAddress[] GetDnsIpAddresses(string serverName, TimeoutTimer ti internal static IPAddress[] GetDnsIpAddresses(string serverName) { - using (TrySNIEventScope.Create(nameof(SNICommon))) + using (TrySNIEventScope.Create(nameof(SniCommon))) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.INFO, "Getting DNS host entries for serverName {0}.", args0: serverName); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.INFO, "Getting DNS host entries for serverName {0}.", args0: serverName); return Dns.GetHostAddresses(serverName); } } @@ -284,10 +189,10 @@ internal static IPAddress[] GetDnsIpAddresses(string serverName) /// SNI error code /// Error message /// - internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uint sniError, string errorMessage) + internal static uint ReportSNIError(SniProviders provider, uint nativeError, uint sniError, string errorMessage) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.ERR, "Provider = {0}, native Error = {1}, SNI Error = {2}, Error Message = {3}", args0: provider, args1: nativeError, args2: sniError, args3: errorMessage); - return ReportSNIError(new SNIError(provider, nativeError, sniError, errorMessage)); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Provider = {0}, native Error = {1}, SNI Error = {2}, Error Message = {3}", args0: provider, args1: nativeError, args2: sniError, args3: errorMessage); + return ReportSNIError(new SniError(provider, nativeError, sniError, errorMessage)); } /// @@ -298,10 +203,10 @@ internal static uint ReportSNIError(SNIProviders provider, uint nativeError, uin /// SNI Exception /// Native SNI error code /// - internal static uint ReportSNIError(SNIProviders provider, uint sniError, Exception sniException, uint nativeErrorCode = 0) + internal static uint ReportSNIError(SniProviders provider, uint sniError, Exception sniException, uint nativeErrorCode = 0) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNICommon), EventType.ERR, "Provider = {0}, SNI Error = {1}, Exception = {2}", args0: provider, args1: sniError, args2: sniException?.Message); - return ReportSNIError(new SNIError(provider, sniError, sniException, nativeErrorCode)); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniCommon), EventType.ERR, "Provider = {0}, SNI Error = {1}, Exception = {2}", args0: provider, args1: sniError, args2: sniException?.Message); + return ReportSNIError(new SniError(provider, sniError, sniException, nativeErrorCode)); } /// @@ -309,10 +214,12 @@ internal static uint ReportSNIError(SNIProviders provider, uint sniError, Except /// /// SNI error /// - internal static uint ReportSNIError(SNIError error) + internal static uint ReportSNIError(SniError error) { - SNILoadHandle.SingletonInstance.LastError = error; + SniLoadHandle.SingletonInstance.LastError = error; return TdsEnums.SNI_ERROR; } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIError.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniError.netcore.cs similarity index 83% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIError.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniError.netcore.cs index 080e274f94..1a33de1d96 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIError.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniError.netcore.cs @@ -2,19 +2,21 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// SNI error /// - internal class SNIError + internal class SniError { // Error numbers from native SNI implementation internal const uint CertificateValidationErrorCode = 2148074277; - public readonly SNIProviders provider; + public readonly SniProviders provider; public readonly string errorMessage; public readonly uint nativeError; public readonly uint sniError; @@ -22,7 +24,7 @@ internal class SNIError public readonly uint lineNumber; public readonly Exception exception; - public SNIError(SNIProviders provider, uint nativeError, uint sniErrorCode, string errorMessage) + public SniError(SniProviders provider, uint nativeError, uint sniErrorCode, string errorMessage) { lineNumber = 0; function = string.Empty; @@ -33,7 +35,7 @@ public SNIError(SNIProviders provider, uint nativeError, uint sniErrorCode, stri exception = null; } - public SNIError(SNIProviders provider, uint sniErrorCode, Exception sniException, uint nativeErrorCode = 0) + public SniError(SniProviders provider, uint sniErrorCode, Exception sniException, uint nativeErrorCode = 0) { lineNumber = 0; function = string.Empty; @@ -45,3 +47,5 @@ public SNIError(SNIProviders provider, uint sniErrorCode, Exception sniException } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIHandle.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs similarity index 86% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIHandle.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs index 515686f6a3..1f3ee01ab8 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIHandle.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniHandle.netcore.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Collections.Generic; using System.Net.Security; @@ -10,12 +12,12 @@ using System.Threading; using System.Threading.Tasks; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// SNI connection handle /// - internal abstract class SNIHandle + internal abstract class SniHandle { protected static readonly SslProtocols s_supportedProtocols = SslProtocols.None; @@ -47,7 +49,7 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam /// /// Receive callback /// Send callback - public abstract void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback); + public abstract void SetAsyncCallbacks(SniAsyncCallback receiveCallback, SniAsyncCallback sendCallback); /// /// Set buffer size @@ -60,14 +62,14 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam /// /// SNI packet /// SNI error code - public abstract uint Send(SNIPacket packet); + public abstract uint Send(SniPacket packet); /// /// Send a packet asynchronously /// /// SNI packet /// SNI error code - public abstract uint SendAsync(SNIPacket packet); + public abstract uint SendAsync(SniPacket packet); /// /// Receive a packet synchronously @@ -75,14 +77,14 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam /// SNI packet /// Timeout in Milliseconds /// SNI error code - public abstract uint Receive(out SNIPacket packet, int timeoutInMilliseconds); + public abstract uint Receive(out SniPacket packet, int timeoutInMilliseconds); /// /// Receive a packet asynchronously /// /// SNI packet /// SNI error code - public abstract uint ReceiveAsync(ref SNIPacket packet); + public abstract uint ReceiveAsync(ref SniPacket packet); /// /// Enable SSL @@ -112,19 +114,22 @@ protected static void AuthenticateAsClient(SslStream sslStream, string serverNam public virtual int ReserveHeaderSize => 0; - public abstract SNIPacket RentPacket(int headerSize, int dataSize); + public abstract SniPacket RentPacket(int headerSize, int dataSize); - public abstract void ReturnPacket(SNIPacket packet); + public abstract void ReturnPacket(SniPacket packet); /// /// Gets a value that indicates the security protocol used to authenticate this connection. /// public virtual int ProtocolVersion { get; } = 0; -#if DEBUG + + #if DEBUG /// /// Test handle for killing underlying connection /// public abstract void KillConnection(); -#endif + #endif } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniLoadHandle.netcore.cs similarity index 80% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniLoadHandle.netcore.cs index c1a5e1a573..5c0d85ba67 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNILoadHandle.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniLoadHandle.netcore.cs @@ -2,26 +2,28 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System.Threading; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// Global SNI settings and status /// - internal class SNILoadHandle + internal class SniLoadHandle { - public static readonly SNILoadHandle SingletonInstance = new SNILoadHandle(); + public static readonly SniLoadHandle SingletonInstance = new SniLoadHandle(); public readonly EncryptionOptions _encryptionOption = EncryptionOptions.OFF; - public ThreadLocal _lastError = new ThreadLocal(static () => new SNIError(SNIProviders.INVALID_PROV, 0, TdsEnums.SNI_SUCCESS, string.Empty)); + public ThreadLocal _lastError = new ThreadLocal(static () => new SniError(SniProviders.INVALID_PROV, 0, TdsEnums.SNI_SUCCESS, string.Empty)); private readonly uint _status = TdsEnums.SNI_SUCCESS; /// /// Last SNI error /// - public SNIError LastError + public SniError LastError { get { @@ -63,3 +65,5 @@ public EncryptionOptions Options public bool ClientOSEncryptionSupport => true; } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs similarity index 76% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs index f929a1ba32..030dfb7452 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsConnection.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsConnection.netcore.cs @@ -2,28 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// SNI MARS connection. Multiple MARS streams will be overlaid on this connection. /// - internal class SNIMarsConnection + internal class SniMarsConnection { private readonly Guid _connectionId; - private readonly Dictionary _sessions; + private readonly Dictionary _sessions; private readonly byte[] _headerBytes; - private readonly SNISMUXHeader _currentHeader; + private readonly SniSmuxHeader _currentHeader; private readonly object _sync; - private SNIHandle _lowerHandle; + private SniHandle _lowerHandle; private ushort _nextSessionId; private int _currentHeaderByteCount; private int _dataBytesLeft; - private SNIPacket _currentPacket; + private SniPacket _currentPacket; /// /// Connection ID @@ -38,29 +40,29 @@ internal class SNIMarsConnection /// Constructor /// /// Lower handle - public SNIMarsConnection(SNIHandle lowerHandle) + public SniMarsConnection(SniHandle lowerHandle) { _sync = new object(); _connectionId = Guid.NewGuid(); - _sessions = new Dictionary(); - _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH]; - _currentHeader = new SNISMUXHeader(); + _sessions = new Dictionary(); + _headerBytes = new byte[SniSmuxHeader.HEADER_LENGTH]; + _currentHeader = new SniSmuxHeader(); _nextSessionId = 0; _currentHeaderByteCount = 0; _dataBytesLeft = 0; _lowerHandle = lowerHandle; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "Created MARS Session Id {0}", args0: ConnectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "Created MARS Session Id {0}", args0: ConnectionId); _lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete); } - public SNIMarsHandle CreateMarsSession(object callbackObject, bool async) + public SniMarsHandle CreateMarsSession(object callbackObject, bool async) { lock (DemuxerSync) { ushort sessionId = _nextSessionId++; - SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, async); + SniMarsHandle handle = new SniMarsHandle(this, sessionId, callbackObject, async); _sessions.Add(sessionId, handle); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, SNI MARS Handle Id {1}, created new MARS Session {2}", args0: ConnectionId, args1: handle?.ConnectionId, args2: sessionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, SNI MARS Handle Id {1}, created new MARS Session {2}", args0: ConnectionId, args1: handle?.ConnectionId, args2: sessionId); return handle; } } @@ -71,17 +73,17 @@ public SNIMarsHandle CreateMarsSession(object callbackObject, bool async) /// public uint StartReceive() { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { - SNIPacket packet = null; + SniPacket packet = null; if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, Success IO pending.", args0: ConnectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, Success IO pending.", args0: ConnectionId); return TdsEnums.SNI_SUCCESS_IO_PENDING; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, Connection not usable.", args0: ConnectionId); - return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, Strings.SNI_ERROR_19); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, Connection not usable.", args0: ConnectionId); + return SniCommon.ReportSNIError(SniProviders.SMUX_PROV, 0, SniCommon.ConnNotUsableError, Strings.SNI_ERROR_19); } } @@ -90,9 +92,9 @@ public uint StartReceive() /// /// SNI packet /// SNI error code - public uint Send(SNIPacket packet) + public uint Send(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { lock (DemuxerSync) { @@ -106,9 +108,9 @@ public uint Send(SNIPacket packet) /// /// SNI packet /// SNI error code - public uint SendAsync(SNIPacket packet) + public uint SendAsync(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { lock (DemuxerSync) { @@ -122,15 +124,15 @@ public uint SendAsync(SNIPacket packet) /// /// SNI packet /// SNI error code - public uint ReceiveAsync(ref SNIPacket packet) + public uint ReceiveAsync(ref SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { if (packet != null) { ReturnPacket(packet); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, Packet {1} returned", args0: ConnectionId, args1: packet?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, Packet {1} returned", args0: ConnectionId, args1: packet?._id); #endif packet = null; } @@ -139,7 +141,7 @@ public uint ReceiveAsync(ref SNIPacket packet) { var response = _lowerHandle.ReceiveAsync(ref packet); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, Received new packet {1}", args0: ConnectionId, args1: packet?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, Received new packet {1}", args0: ConnectionId, args1: packet?._id); #endif return response; } @@ -152,7 +154,7 @@ public uint ReceiveAsync(ref SNIPacket packet) /// SNI error status public uint CheckConnection() { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { lock (DemuxerSync) { @@ -164,20 +166,20 @@ public uint CheckConnection() /// /// Process a receive error /// - public void HandleReceiveError(SNIPacket packet) + public void HandleReceiveError(SniPacket packet) { Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked."); - foreach (SNIMarsHandle handle in _sessions.Values) + foreach (SniMarsHandle handle in _sessions.Values) { if (packet.HasAsyncIOCompletionCallback) { handle.HandleReceiveError(packet); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, Packet {1} has Completion Callback", args0: ConnectionId, args1: packet?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, Packet {1} has Completion Callback", args0: ConnectionId, args1: packet?._id); } else { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, Packet {1} does not have Completion Callback, error not handled.", args0: ConnectionId, args1: packet?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, Packet {1} does not have Completion Callback, error not handled.", args0: ConnectionId, args1: packet?._id); #endif } } @@ -190,7 +192,7 @@ public void HandleReceiveError(SNIPacket packet) /// /// SNI packet /// SNI error code - public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) + public void HandleSendComplete(SniPacket packet, uint sniErrorCode) { packet.InvokeAsyncIOCompletionCallback(sniErrorCode); } @@ -200,20 +202,20 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) /// /// SNI packet /// SNI error code - public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) + public void HandleReceiveComplete(SniPacket packet, uint sniErrorCode) { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { - SNISMUXHeader currentHeader = null; - SNIPacket currentPacket = null; - SNIMarsHandle currentSession = null; + SniSmuxHeader currentHeader = null; + SniPacket currentPacket = null; + SniMarsHandle currentSession = null; if (sniErrorCode != TdsEnums.SNI_SUCCESS) { lock (DemuxerSync) { HandleReceiveError(packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, Handled receive error code: {1}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, Handled receive error code: {1}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); return; } } @@ -222,21 +224,21 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) { lock (DemuxerSync) { - if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH) + if (_currentHeaderByteCount != SniSmuxHeader.HEADER_LENGTH) { currentHeader = null; currentPacket = null; currentSession = null; - while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH) + while (_currentHeaderByteCount != SniSmuxHeader.HEADER_LENGTH) { - int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount); + int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SniSmuxHeader.HEADER_LENGTH - _currentHeaderByteCount); _currentHeaderByteCount += bytesTaken; if (bytesTaken == 0) { sniErrorCode = ReceiveAsync(ref packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, Non-SMUX Header SNI Packet received with code {1}", args0: ConnectionId, args1: sniErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, Non-SMUX Header SNI Packet received with code {1}", args0: ConnectionId, args1: sniErrorCode); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { @@ -244,7 +246,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) } HandleReceiveError(packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, Handled receive error code: {1}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, Handled receive error code: {1}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); return; } } @@ -253,14 +255,14 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) _dataBytesLeft = (int)_currentHeader.length; _currentPacket = _lowerHandle.RentPacket(headerSize: 0, dataSize: (int)_currentHeader.length); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, _dataBytesLeft {1}, _currentPacket {2}, Reading data of length: _currentHeader.length {3}", args0: _lowerHandle?.ConnectionId, args1: _dataBytesLeft, args2: currentPacket?._id, args3: _currentHeader?.length); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, _dataBytesLeft {1}, _currentPacket {2}, Reading data of length: _currentHeader.length {3}", args0: _lowerHandle?.ConnectionId, args1: _dataBytesLeft, args2: currentPacket?._id, args3: _currentHeader?.length); #endif } currentHeader = _currentHeader; currentPacket = _currentPacket; - if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA) + if (_currentHeader.flags == (byte)SniSmuxFlags.SMUX_DATA) { if (_dataBytesLeft > 0) { @@ -270,7 +272,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) if (_dataBytesLeft > 0) { sniErrorCode = ReceiveAsync(ref packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, SMUX DATA Header SNI Packet received with code {1}, _dataBytesLeft {2}", args0: ConnectionId, args1: sniErrorCode, args2: _dataBytesLeft); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, SMUX DATA Header SNI Packet received with code {1}, _dataBytesLeft {2}", args0: ConnectionId, args1: sniErrorCode, args2: _dataBytesLeft); if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING) { @@ -278,7 +280,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) } HandleReceiveError(packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, Handled receive error code: {1}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, Handled receive error code: {1}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); return; } } @@ -288,47 +290,47 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) if (!_sessions.ContainsKey(_currentHeader.sessionId)) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.InvalidParameterError, Strings.SNI_ERROR_5); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.SMUX_PROV, 0, SniCommon.InvalidParameterError, Strings.SNI_ERROR_5); HandleReceiveError(packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "Current Header Session Id {0} not found, MARS Session Id {1} will be destroyed, New SNI error created: {2}", args0: _currentHeader?.sessionId, args1: _lowerHandle?.ConnectionId, args2: sniErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "Current Header Session Id {0} not found, MARS Session Id {1} will be destroyed, New SNI error created: {2}", args0: _currentHeader?.sessionId, args1: _lowerHandle?.ConnectionId, args2: sniErrorCode); _lowerHandle.Dispose(); _lowerHandle = null; return; } - if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN) + if (_currentHeader.flags == (byte)SniSmuxFlags.SMUX_FIN) { _sessions.Remove(_currentHeader.sessionId); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "SMUX_FIN | MARS Session Id {0}, SMUX_FIN flag received, Current Header Session Id {1} removed", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "SMUX_FIN | MARS Session Id {0}, SMUX_FIN flag received, Current Header Session Id {1} removed", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); } else { currentSession = _sessions[_currentHeader.sessionId]; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "MARS Session Id {0}, Current Session assigned to Session Id {1}", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "MARS Session Id {0}, Current Session assigned to Session Id {1}", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); } } - if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA) + if (currentHeader.flags == (byte)SniSmuxFlags.SMUX_DATA) { currentSession.HandleReceiveComplete(currentPacket, currentHeader); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "SMUX_DATA | MARS Session Id {0}, Current Session {1} completed receiving Data", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "SMUX_DATA | MARS Session Id {0}, Current Session {1} completed receiving Data", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); } - if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK) + if (_currentHeader.flags == (byte)SniSmuxFlags.SMUX_ACK) { try { currentSession.HandleAck(currentHeader.highwater); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "SMUX_ACK | MARS Session Id {0}, Current Session {1} handled ack", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "SMUX_ACK | MARS Session Id {0}, Current Session {1} handled ack", args0: _lowerHandle?.ConnectionId, args1: _currentHeader?.sessionId); } catch (Exception e) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "SMUX_ACK | MARS Session Id {0}, Exception occurred: {2}", args0: _currentHeader?.sessionId, args1: e?.Message); - SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "SMUX_ACK | MARS Session Id {0}, Exception occurred: {2}", args0: _currentHeader?.sessionId, args1: e?.Message); + SniCommon.ReportSNIError(SniProviders.SMUX_PROV, SniCommon.InternalExceptionError, e); } #if DEBUG Debug.Assert(_currentPacket == currentPacket, "current and _current are not the same"); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.INFO, "SMUX_ACK | MARS Session Id {0}, Current Packet {1} returned", args0: _lowerHandle?.ConnectionId, args1: currentPacket?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.INFO, "SMUX_ACK | MARS Session Id {0}, Current Packet {1} returned", args0: _lowerHandle?.ConnectionId, args1: currentPacket?._id); #endif ReturnPacket(currentPacket); currentPacket = null; @@ -347,7 +349,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) } HandleReceiveError(packet); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsConnection), EventType.ERR, "MARS Session Id {0}, packet.DataLeft 0, SNI error {2}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsConnection), EventType.ERR, "MARS Session Id {0}, packet.DataLeft 0, SNI error {2}", args0: _lowerHandle?.ConnectionId, args1: sniErrorCode); return; } } @@ -360,7 +362,7 @@ public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode) /// public uint EnableSsl(uint options) { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { return _lowerHandle.EnableSsl(options); } @@ -371,33 +373,35 @@ public uint EnableSsl(uint options) /// public void DisableSsl() { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { _lowerHandle.DisableSsl(); } } - public SNIPacket RentPacket(int headerSize, int dataSize) + public SniPacket RentPacket(int headerSize, int dataSize) { return _lowerHandle.RentPacket(headerSize, dataSize); } - public void ReturnPacket(SNIPacket packet) + public void ReturnPacket(SniPacket packet) { _lowerHandle.ReturnPacket(packet); } -#if DEBUG + #if DEBUG /// /// Test handle for killing underlying connection /// public void KillConnection() { - using (TrySNIEventScope.Create(nameof(SNIMarsConnection))) + using (TrySNIEventScope.Create(nameof(SniMarsConnection))) { _lowerHandle.KillConnection(); } } -#endif + #endif } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs similarity index 78% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs index b7f682f6d5..ed69c242bf 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIMarsHandle.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniMarsHandle.netcore.cs @@ -2,38 +2,40 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// MARS handle /// - internal sealed class SNIMarsHandle : SNIHandle + internal sealed class SniMarsHandle : SniHandle { private const uint ACK_THRESHOLD = 2; - private readonly SNIMarsConnection _connection; + private readonly SniMarsConnection _connection; private readonly uint _status = TdsEnums.SNI_UNINITIALIZED; - private readonly Queue _receivedPacketQueue = new Queue(); - private readonly Queue _sendPacketQueue = new Queue(); + private readonly Queue _receivedPacketQueue = new Queue(); + private readonly Queue _sendPacketQueue = new Queue(); private readonly object _callbackObject; private readonly Guid _connectionId; private readonly ushort _sessionId; private readonly ManualResetEventSlim _packetEvent = new ManualResetEventSlim(false); private readonly ManualResetEventSlim _ackEvent = new ManualResetEventSlim(false); - private readonly SNISMUXHeader _currentHeader = new SNISMUXHeader(); - private readonly SNIAsyncCallback _handleSendCompleteCallback; + private readonly SniSmuxHeader _currentHeader = new SniSmuxHeader(); + private readonly SniAsyncCallback _handleSendCompleteCallback; private uint _sendHighwater = 4; private int _asyncReceives = 0; private uint _receiveHighwater = 4; private uint _receiveHighwaterLastAck = 4; private uint _sequenceNumber; - private SNIError _connectionError; + private SniError _connectionError; /// /// Connection ID @@ -45,7 +47,7 @@ internal sealed class SNIMarsHandle : SNIHandle /// public override uint Status => _status; - public override int ReserveHeaderSize => SNISMUXHeader.HEADER_LENGTH; + public override int ReserveHeaderSize => SniSmuxHeader.HEADER_LENGTH; public override int ProtocolVersion => _connection.ProtocolVersion; @@ -54,17 +56,17 @@ internal sealed class SNIMarsHandle : SNIHandle /// public override void Dispose() { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { try { - SendControlPacket(SNISMUXFlags.SMUX_FIN); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Sent SMUX_FIN packet to terminate session.", args0: ConnectionId); + SendControlPacket(SniSmuxFlags.SMUX_FIN); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Sent SMUX_FIN packet to terminate session.", args0: ConnectionId); } catch (Exception e) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.ERR, "MARS Session Id {0}, Internal exception error = {1}, Member Name={2}", args0: ConnectionId, args1: e?.Message, args2: e?.GetType()?.Name); - SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.ERR, "MARS Session Id {0}, Internal exception error = {1}, Member Name={2}", args0: ConnectionId, args1: e?.Message, args2: e?.GetType()?.Name); + SniCommon.ReportSNIError(SniProviders.SMUX_PROV, SniCommon.InternalExceptionError, e); } } } @@ -76,15 +78,15 @@ public override void Dispose() /// MARS session ID /// Callback object /// true if connection is asynchronous - public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object callbackObject, bool async) + public SniMarsHandle(SniMarsConnection connection, ushort sessionId, object callbackObject, bool async) { _sessionId = sessionId; _connection = connection; _connectionId = connection.ConnectionId; _callbackObject = callbackObject; _handleSendCompleteCallback = HandleSendComplete; - SendControlPacket(SNISMUXFlags.SMUX_SYN); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Sent SMUX_SYN packet to start a new session, session Id {1}", args0: ConnectionId, args1: _sessionId); + SendControlPacket(SniSmuxFlags.SMUX_SYN); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Sent SMUX_SYN packet to start a new session, session Id {1}", args0: ConnectionId, args1: _sessionId); _status = TdsEnums.SNI_SUCCESS; } @@ -92,39 +94,39 @@ public SNIMarsHandle(SNIMarsConnection connection, ushort sessionId, object call /// Send control packet /// /// SMUX header flags - private void SendControlPacket(SNISMUXFlags flags) + private void SendControlPacket(SniSmuxFlags flags) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { - SNIPacket packet = RentPacket(headerSize: SNISMUXHeader.HEADER_LENGTH, dataSize: 0); + SniPacket packet = RentPacket(headerSize: SniSmuxHeader.HEADER_LENGTH, dataSize: 0); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Packet rented {1}, packet dataLeft {2}", args0: ConnectionId, args1: packet?._id, args2: packet?.DataLeft); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Packet rented {1}, packet dataLeft {2}", args0: ConnectionId, args1: packet?._id, args2: packet?.DataLeft); #endif lock (this) { SetupSMUXHeader(0, flags); - _currentHeader.Write(packet.GetHeaderBuffer(SNISMUXHeader.HEADER_LENGTH)); + _currentHeader.Write(packet.GetHeaderBuffer(SniSmuxHeader.HEADER_LENGTH)); packet.SetHeaderActive(); } _connection.Send(packet); ReturnPacket(packet); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Packet returned {1}, packet dataLeft {2}", args0: ConnectionId, args1: packet?._id, args2: packet?.DataLeft); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Packet returned {1}, packet dataLeft {2}", args0: ConnectionId, args1: packet?._id, args2: packet?.DataLeft); ; #endif } } - private void SetupSMUXHeader(int length, SNISMUXFlags flags) + private void SetupSMUXHeader(int length, SniSmuxFlags flags) { Debug.Assert(Monitor.IsEntered(this), "must take lock on self before updating smux header"); _currentHeader.SMID = 83; _currentHeader.flags = (byte)flags; _currentHeader.sessionId = _sessionId; - _currentHeader.length = (uint)SNISMUXHeader.HEADER_LENGTH + (uint)length; - _currentHeader.sequenceNumber = ((flags == SNISMUXFlags.SMUX_FIN) || (flags == SNISMUXFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++; + _currentHeader.length = (uint)SniSmuxHeader.HEADER_LENGTH + (uint)length; + _currentHeader.sequenceNumber = ((flags == SniSmuxFlags.SMUX_FIN) || (flags == SniSmuxFlags.SMUX_ACK)) ? _sequenceNumber - 1 : _sequenceNumber++; _currentHeader.highwater = _receiveHighwater; _receiveHighwaterLastAck = _currentHeader.highwater; } @@ -134,15 +136,15 @@ private void SetupSMUXHeader(int length, SNISMUXFlags flags) /// /// SNI packet /// The packet with the SMUx header set. - private SNIPacket SetPacketSMUXHeader(SNIPacket packet) + private SniPacket SetPacketSMUXHeader(SniPacket packet) { - Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to smux packet without smux reservation"); + Debug.Assert(packet.ReservedHeaderSize == SniSmuxHeader.HEADER_LENGTH, "mars handle attempting to smux packet without smux reservation"); - SetupSMUXHeader(packet.Length, SNISMUXFlags.SMUX_DATA); - _currentHeader.Write(packet.GetHeaderBuffer(SNISMUXHeader.HEADER_LENGTH)); + SetupSMUXHeader(packet.Length, SniSmuxFlags.SMUX_DATA); + _currentHeader.Write(packet.GetHeaderBuffer(SniSmuxHeader.HEADER_LENGTH)); packet.SetHeaderActive(); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Setting SMUX_DATA header in current header for packet {1}", args0: ConnectionId, args1: packet?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Setting SMUX_DATA header in current header for packet {1}", args0: ConnectionId, args1: packet?._id); #endif return packet; } @@ -152,10 +154,10 @@ private SNIPacket SetPacketSMUXHeader(SNIPacket packet) /// /// SNI packet /// SNI error code - public override uint Send(SNIPacket packet) + public override uint Send(SniPacket packet) { - Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without smux reservation in Send"); - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + Debug.Assert(packet.ReservedHeaderSize == SniSmuxHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without smux reservation in Send"); + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { while (true) { @@ -167,22 +169,22 @@ public override uint Send(SNIPacket packet) } } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, Waiting for Acknowledgment event.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, Waiting for Acknowledgment event.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); _ackEvent.Wait(); lock (this) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue count found {1}, Acknowledgment event Reset", args0: ConnectionId, args1: _sendPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue count found {1}, Acknowledgment event Reset", args0: ConnectionId, args1: _sendPacketQueue?.Count); _ackEvent.Reset(); } } - SNIPacket muxedPacket = null; + SniPacket muxedPacket = null; lock (this) { muxedPacket = SetPacketSMUXHeader(packet); } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, SMUX Packet is going to be sent.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, SMUX Packet is going to be sent.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); return _connection.Send(muxedPacket); } } @@ -192,22 +194,22 @@ public override uint Send(SNIPacket packet) /// /// SNI packet /// SNI error code - private uint InternalSendAsync(SNIPacket packet) + private uint InternalSendAsync(SniPacket packet) { - Debug.Assert(packet.ReservedHeaderSize == SNISMUXHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without smux reservation in InternalSendAsync"); - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + Debug.Assert(packet.ReservedHeaderSize == SniSmuxHeader.HEADER_LENGTH, "mars handle attempting to send muxed packet without smux reservation in InternalSendAsync"); + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { lock (this) { if (_sequenceNumber >= _sendHighwater) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, SNI Queue is full", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, SNI Queue is full", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); return TdsEnums.SNI_QUEUE_FULL; } - SNIPacket muxedPacket = SetPacketSMUXHeader(packet); + SniPacket muxedPacket = SetPacketSMUXHeader(packet); muxedPacket.SetAsyncIOCompletionCallback(_handleSendCompleteCallback); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, Sending packet", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, Sending packet", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); return _connection.SendAsync(muxedPacket); } } @@ -219,9 +221,9 @@ private uint InternalSendAsync(SNIPacket packet) /// SNI error code private uint SendPendingPackets() { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { - SNIPacket packet = null; + SniPacket packet = null; while (true) { @@ -236,18 +238,18 @@ private uint SendPendingPackets() if (result != TdsEnums.SNI_SUCCESS && result != TdsEnums.SNI_SUCCESS_IO_PENDING) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.ERR, "MARS Session Id {0}, InternalSendAsync result is not SNI_SUCCESS and is not SNI_SUCCESS_IO_PENDING", args0: ConnectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.ERR, "MARS Session Id {0}, InternalSendAsync result is not SNI_SUCCESS and is not SNI_SUCCESS_IO_PENDING", args0: ConnectionId); return result; } _sendPacketQueue.Dequeue(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue dequeued, count {1}", args0: ConnectionId, args1: _sendPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue dequeued, count {1}", args0: ConnectionId, args1: _sendPacketQueue?.Count); continue; } else { _ackEvent.Set(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue count found {1}, acknowledgment set", args0: ConnectionId, args1: _sendPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue count found {1}, acknowledgment set", args0: ConnectionId, args1: _sendPacketQueue?.Count); } } @@ -264,9 +266,9 @@ private uint SendPendingPackets() /// /// SNI packet /// SNI error code - public override uint SendAsync(SNIPacket packet) + public override uint SendAsync(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { packet.SetAsyncIOCompletionCallback(_handleSendCompleteCallback); lock (this) @@ -275,7 +277,7 @@ public override uint SendAsync(SNIPacket packet) } SendPendingPackets(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue enqueued, count {1}", args0: ConnectionId, args1: _sendPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sendPacketQueue enqueued, count {1}", args0: ConnectionId, args1: _sendPacketQueue?.Count); return TdsEnums.SNI_SUCCESS_IO_PENDING; } @@ -286,9 +288,9 @@ public override uint SendAsync(SNIPacket packet) /// /// SNI packet /// SNI error code - public override uint ReceiveAsync(ref SNIPacket packet) + public override uint ReceiveAsync(ref SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { lock (_receivedPacketQueue) { @@ -296,14 +298,14 @@ public override uint ReceiveAsync(ref SNIPacket packet) if (_connectionError != null) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.ERR, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}, _connectionError {5}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck, args5: _connectionError); - return SNICommon.ReportSNIError(_connectionError); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.ERR, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}, _connectionError {5}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck, args5: _connectionError); + return SniCommon.ReportSNIError(_connectionError); } if (queueCount == 0) { _asyncReceives++; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, queueCount 0, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, queueCount 0, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck); return TdsEnums.SNI_SUCCESS_IO_PENDING; } @@ -313,7 +315,7 @@ public override uint ReceiveAsync(ref SNIPacket packet) if (queueCount == 1) { #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, packet dequeued {1}, packet Owner {2}, packet refCount {3}, received Packet Queue count {4}", args0: ConnectionId, args1: packet?._id, args2: packet?._owner, args3: packet?._refCount, args4: _receivedPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, packet dequeued {1}, packet Owner {2}, packet refCount {3}, received Packet Queue count {4}", args0: ConnectionId, args1: packet?._id, args2: packet?._owner, args3: packet?._refCount, args4: _receivedPacketQueue?.Count); #endif _packetEvent.Reset(); } @@ -324,7 +326,7 @@ public override uint ReceiveAsync(ref SNIPacket packet) _receiveHighwater++; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}, queueCount {5}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck, args5: _receivedPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}, queueCount {5}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck, args5: _receivedPacketQueue?.Count); SendAckIfNecessary(); return TdsEnums.SNI_SUCCESS; } @@ -333,9 +335,9 @@ public override uint ReceiveAsync(ref SNIPacket packet) /// /// Handle receive error /// - public void HandleReceiveError(SNIPacket packet) + public void HandleReceiveError(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { // SNIMarsHandle should only receive calls to this function from the SNIMarsConnection aggregator class // which should handle ownership of the packet because the individual mars handles are not aware of @@ -343,8 +345,8 @@ public void HandleReceiveError(SNIPacket packet) lock (_receivedPacketQueue) { - _connectionError = SNILoadHandle.SingletonInstance.LastError; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.ERR, "MARS Session Id {0}, _connectionError to be handled: {1}", args0: ConnectionId, args1: _connectionError); + _connectionError = SniLoadHandle.SingletonInstance.LastError; + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.ERR, "MARS Session Id {0}, _connectionError to be handled: {1}", args0: ConnectionId, args1: _connectionError); _packetEvent.Set(); } @@ -357,9 +359,9 @@ public void HandleReceiveError(SNIPacket packet) /// /// SNI packet /// SNI error code - public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) + public void HandleSendComplete(SniPacket packet, uint sniErrorCode) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { lock (this) { @@ -369,7 +371,7 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) } _connection.ReturnPacket(packet); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Returned Packet: {1}", args0: ConnectionId, args1: packet?._id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Returned Packet: {1}", args0: ConnectionId, args1: packet?._id); #endif } } @@ -380,13 +382,13 @@ public void HandleSendComplete(SNIPacket packet, uint sniErrorCode) /// Send highwater mark public void HandleAck(uint highwater) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { lock (this) { if (_sendHighwater != highwater) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, Setting _sendHighwater {1} to highwater {2} and send pending packets.", args0: ConnectionId, args1: _sendHighwater, args2: highwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, Setting _sendHighwater {1} to highwater {2} and send pending packets.", args0: ConnectionId, args1: _sendHighwater, args2: highwater); _sendHighwater = highwater; SendPendingPackets(); } @@ -399,15 +401,15 @@ public void HandleAck(uint highwater) /// /// SNI packet /// SMUX header - public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) + public void HandleReceiveComplete(SniPacket packet, SniSmuxHeader header) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { lock (this) { if (_sendHighwater != header.highwater) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, header.highwater {1}, _sendHighwater {2}, Handle Ack with header.highwater", args0: ConnectionId, args1: header?.highwater, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, header.highwater {1}, _sendHighwater {2}, Handle Ack with header.highwater", args0: ConnectionId, args1: header?.highwater, args2: _sendHighwater); HandleAck(header.highwater); } @@ -417,13 +419,13 @@ public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { _receivedPacketQueue.Enqueue(packet); _packetEvent.Set(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _receivedPacketQueue count {3}, packet event set", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: _receivedPacketQueue?.Count); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _receivedPacketQueue count {3}, packet event set", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: _receivedPacketQueue?.Count); return; } _asyncReceives--; Debug.Assert(_callbackObject != null); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _asyncReceives {3}", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: _asyncReceives); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _asyncReceives {3}", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: _asyncReceives); ((TdsParserStateObject)_callbackObject).ReadAsyncCallback(PacketHandle.FromManagedPacket(packet), 0); } @@ -435,7 +437,7 @@ public void HandleReceiveComplete(SNIPacket packet, SNISMUXHeader header) { _receiveHighwater++; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck); SendAckIfNecessary(); } } @@ -456,8 +458,8 @@ private void SendAckIfNecessary() if (receiveHighwater - receiveHighwaterLastAck > ACK_THRESHOLD) { - SendControlPacket(SNISMUXFlags.SMUX_ACK); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4} Sending acknowledgment ACK_THRESHOLD {5}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck, args5: ACK_THRESHOLD); + SendControlPacket(SniSmuxFlags.SMUX_ACK); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _asyncReceives {1}, _receiveHighwater {2}, _sendHighwater {3}, _receiveHighwaterLastAck {4} Sending acknowledgment ACK_THRESHOLD {5}", args0: ConnectionId, args1: _asyncReceives, args2: _receiveHighwater, args3: _sendHighwater, args4: _receiveHighwaterLastAck, args5: ACK_THRESHOLD); } } @@ -467,9 +469,9 @@ private void SendAckIfNecessary() /// SNI packet /// Timeout in Milliseconds /// SNI error code - public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) + public override uint Receive(out SniPacket packet, int timeoutInMilliseconds) { - using (TrySNIEventScope.Create(nameof(SNIMarsHandle))) + using (TrySNIEventScope.Create(nameof(SniMarsHandle))) { packet = null; int queueCount; @@ -481,12 +483,12 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) { if (_connectionError != null) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.ERR, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _connectionError found: {3}.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: _connectionError); - return SNICommon.ReportSNIError(_connectionError); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.ERR, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _connectionError found: {3}.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: _connectionError); + return SniCommon.ReportSNIError(_connectionError); } queueCount = _receivedPacketQueue.Count; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, W_receivedPacketQueue count {3}.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: queueCount); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, W_receivedPacketQueue count {3}.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: queueCount); if (queueCount > 0) { @@ -495,7 +497,7 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) if (queueCount == 1) { _packetEvent.Reset(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, packet event reset, _receivedPacketQueue count 1.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, packet event reset, _receivedPacketQueue count 1.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); } result = TdsEnums.SNI_SUCCESS; @@ -510,15 +512,15 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) } SendAckIfNecessary(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, returning with result {3}.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: result); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, returning with result {3}.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater, args3: result); return result; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, Waiting for packet event.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, Waiting for packet event.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); if (!_packetEvent.Wait(timeoutInMilliseconds)) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnTimeoutError, Strings.SNI_ERROR_11); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _packetEvent wait timed out.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.SMUX_PROV, 0, SniCommon.ConnTimeoutError, Strings.SNI_ERROR_11); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniMarsHandle), EventType.INFO, "MARS Session Id {0}, _sequenceNumber {1}, _sendHighwater {2}, _packetEvent wait timed out.", args0: ConnectionId, args1: _sequenceNumber, args2: _sendHighwater); return TdsEnums.SNI_WAIT_TIMEOUT; } } @@ -539,7 +541,7 @@ public override uint CheckConnection() /// /// Receive callback /// Send callback - public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) + public override void SetAsyncCallbacks(SniAsyncCallback receiveCallback, SniAsyncCallback sendCallback) { } @@ -555,12 +557,12 @@ public override void SetBufferSize(int bufferSize) public override void DisableSsl() => _connection.DisableSsl(); - public override SNIPacket RentPacket(int headerSize, int dataSize) => _connection.RentPacket(headerSize, dataSize); + public override SniPacket RentPacket(int headerSize, int dataSize) => _connection.RentPacket(headerSize, dataSize); - public override void ReturnPacket(SNIPacket packet) => _connection.ReturnPacket(packet); + public override void ReturnPacket(SniPacket packet) => _connection.ReturnPacket(packet); -#if DEBUG + #if DEBUG /// /// Test handle for killing underlying connection /// @@ -568,6 +570,8 @@ public override void KillConnection() { _connection.KillConnection(); } -#endif + #endif } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNetworkStream.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNetworkStream.netcore.cs new file mode 100644 index 0000000000..f939ba4b7e --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNetworkStream.netcore.cs @@ -0,0 +1,77 @@ +// 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. + +#if NET + +using System; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Data.SqlClient.ManagedSni +{ + /// + /// This class extends NetworkStream to customize stream behavior for Managed SNI implementation. + /// + internal sealed class SniNetworkStream : NetworkStream + { + private readonly ConcurrentQueueSemaphore _writeAsyncSemaphore; + private readonly ConcurrentQueueSemaphore _readAsyncSemaphore; + + public SniNetworkStream(Socket socket, bool ownsSocket) : base(socket, ownsSocket) + { + _writeAsyncSemaphore = new ConcurrentQueueSemaphore(1); + _readAsyncSemaphore = new ConcurrentQueueSemaphore(1); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await _readAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await base.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniSslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); + throw; + } + finally + { + _readAsyncSemaphore.Release(); + } + } + + // Prevent the WriteAsync collisions by running the task in a Semaphore Slim + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return WriteAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); + } + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await _writeAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await base.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniSslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); + throw; + } + finally + { + _writeAsyncSemaphore.Release(); + } + } + } +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs similarity index 81% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs index 8f8af57f58..e244209f23 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNINpHandle.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniNpHandle.netcore.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.ComponentModel; using System.IO; @@ -12,12 +14,12 @@ using System.Threading; using Microsoft.Data.ProviderBase; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// Named Pipe connection handle /// - internal sealed class SNINpHandle : SNIPhysicalHandle + internal sealed class SniNpHandle : SniPhysicalHandle { internal const string DefaultPipePath = @"sql\query"; // e.g. \\HOSTNAME\pipe\sql\query // private const int MAX_PIPE_INSTANCES = 255; // TODO: Investigate pipe instance limit. @@ -32,19 +34,19 @@ internal sealed class SNINpHandle : SNIPhysicalHandle private SslOverTdsStream _sslOverTdsStream; private SslStream _sslStream; - private SNIAsyncCallback _receiveCallback; - private SNIAsyncCallback _sendCallback; + private SniAsyncCallback _receiveCallback; + private SniAsyncCallback _sendCallback; private bool _validateCert = true; private readonly uint _status = TdsEnums.SNI_UNINITIALIZED; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; private readonly Guid _connectionId = Guid.NewGuid(); - public SNINpHandle(string serverName, string pipeName, TimeoutTimer timeout, bool tlsFirst, string hostNameInCertificate, string serverCertificateFilename) + public SniNpHandle(string serverName, string pipeName, TimeoutTimer timeout, bool tlsFirst, string hostNameInCertificate, string serverCertificateFilename) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Setting server name = {1}, pipe name = {2}", args0: _connectionId, args1: serverName, args2: pipeName); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Setting server name = {1}, pipe name = {2}", args0: _connectionId, args1: serverName, args2: pipeName); _sendSync = new object(); _targetServer = serverName; @@ -61,7 +63,7 @@ public SNINpHandle(string serverName, string pipeName, TimeoutTimer timeout, boo if (timeout.IsInfinite) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Setting server name = {1}, pipe name = {2}. Connecting with infinite timeout.", args0: _connectionId, args1: serverName, @@ -71,7 +73,7 @@ public SNINpHandle(string serverName, string pipeName, TimeoutTimer timeout, boo else { int timeoutMilliseconds = timeout.MillisecondsRemainingInt; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Setting server name = {1}, pipe name = {2}. Connecting within the {3} specified milliseconds.", args0: _connectionId, args1: serverName, @@ -82,24 +84,24 @@ public SNINpHandle(string serverName, string pipeName, TimeoutTimer timeout, boo } catch (TimeoutException te) { - SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, te); + SniCommon.ReportSNIError(SniProviders.NP_PROV, SniCommon.ConnOpenFailedError, te); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, Connection Timed out. Error Code 1 Exception = {1}", args0: _connectionId, args1: te?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, Connection Timed out. Error Code 1 Exception = {1}", args0: _connectionId, args1: te?.Message); return; } catch (IOException ioe) { - SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.ConnOpenFailedError, ioe); + SniCommon.ReportSNIError(SniProviders.NP_PROV, SniCommon.ConnOpenFailedError, ioe); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, IO Exception occurred. Error Code 1 Exception = {1}", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, IO Exception occurred. Error Code 1 Exception = {1}", args0: _connectionId, args1: ioe?.Message); return; } if (!_pipeStream.IsConnected || !_pipeStream.CanWrite || !_pipeStream.CanRead) { - SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.ConnOpenFailedError, Strings.SNI_ERROR_40); + SniCommon.ReportSNIError(SniProviders.NP_PROV, 0, SniCommon.ConnOpenFailedError, Strings.SNI_ERROR_40); _status = TdsEnums.SNI_ERROR; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, Pipe Stream not operational. Error Code 1 Exception = {1}", args0: _connectionId, args1: Strings.SNI_ERROR_1); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, Pipe Stream not operational. Error Code 1 Exception = {1}", args0: _connectionId, args1: Strings.SNI_ERROR_1); return; } @@ -110,7 +112,7 @@ public SNINpHandle(string serverName, string pipeName, TimeoutTimer timeout, boo _sslOverTdsStream = new SslOverTdsStream(_pipeStream, _connectionId); stream = _sslOverTdsStream; } - _sslStream = new SNISslStream(stream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); + _sslStream = new SniSslStream(stream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); _stream = _pipeStream; _status = TdsEnums.SNI_SUCCESS; @@ -138,16 +140,16 @@ public override int ProtocolVersion public override uint CheckConnection() { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { if (!_stream.CanWrite || !_stream.CanRead) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, Cannot write or read to/from the stream", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, Cannot write or read to/from the stream", args0: _connectionId); return TdsEnums.SNI_ERROR; } else { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Can read and write to/from stream.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Can read and write to/from stream.", args0: _connectionId); return TdsEnums.SNI_SUCCESS; } } @@ -177,15 +179,15 @@ public override void Dispose() //Release any references held by _stream. _stream = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, All streams disposed and references cleared.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, All streams disposed and references cleared.", args0: _connectionId); } } - public override uint Receive(out SNIPacket packet, int timeout) + public override uint Receive(out SniPacket packet, int timeout) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { - SNIPacket errorPacket; + SniPacket errorPacket; lock (this) { packet = null; @@ -193,14 +195,14 @@ public override uint Receive(out SNIPacket packet, int timeout) { packet = RentPacket(headerSize: 0, dataSize: _bufferSize); packet.ReadFromStream(_stream); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Rented and read packet, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Rented and read packet, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); if (packet.Length == 0) { errorPacket = packet; packet = null; var e = new Win32Exception(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, Packet length found 0, Win32 exception raised: {1}", args0: _connectionId, args1: e?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, Packet length found 0, Win32 exception raised: {1}", args0: _connectionId, args1: e?.Message); return ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message); } } @@ -208,14 +210,14 @@ public override uint Receive(out SNIPacket packet, int timeout) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}.", args0: _connectionId, args1: ode?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}.", args0: _connectionId, args1: ode?.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (IOException ioe) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}.", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}.", args0: _connectionId, args1: ioe?.Message); return ReportErrorAndReleasePacket(errorPacket, ioe); } return TdsEnums.SNI_SUCCESS; @@ -223,39 +225,39 @@ public override uint Receive(out SNIPacket packet, int timeout) } } - public override uint ReceiveAsync(ref SNIPacket packet) + public override uint ReceiveAsync(ref SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { - SNIPacket errorPacket; + SniPacket errorPacket; packet = RentPacket(headerSize: 0, dataSize: _bufferSize); packet.SetAsyncIOCompletionCallback(_receiveCallback); try { packet.ReadFromStreamAsync(_stream); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Rented and read packet asynchronously, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Rented and read packet asynchronously, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); return TdsEnums.SNI_SUCCESS_IO_PENDING; } catch (ObjectDisposedException ode) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}.", args0: _connectionId, args1: ode?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}.", args0: _connectionId, args1: ode?.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (IOException ioe) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}.", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}.", args0: _connectionId, args1: ioe?.Message); return ReportErrorAndReleasePacket(errorPacket, ioe); } } } - public override uint Send(SNIPacket packet) + public override uint Send(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { bool releaseLock = false; try @@ -281,18 +283,18 @@ public override uint Send(SNIPacket packet) { try { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Packet writing to stream, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Packet writing to stream, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); packet.WriteToStream(_stream); return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}.", args0: _connectionId, args1: ode?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}.", args0: _connectionId, args1: ode?.Message); return ReportErrorAndReleasePacket(packet, ode); } catch (IOException ioe) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}.", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}.", args0: _connectionId, args1: ioe?.Message); return ReportErrorAndReleasePacket(packet, ioe); } } @@ -307,17 +309,17 @@ public override uint Send(SNIPacket packet) } } - public override uint SendAsync(SNIPacket packet) + public override uint SendAsync(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Packet writing to stream, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); - packet.WriteToStreamAsync(_stream, _sendCallback, SNIProviders.NP_PROV); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Packet writing to stream, dataLeft {1}", args0: _connectionId, args1: packet?.DataLeft); + packet.WriteToStreamAsync(_stream, _sendCallback, SniProviders.NP_PROV); return TdsEnums.SNI_SUCCESS_IO_PENDING; } } - public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) + public override void SetAsyncCallbacks(SniAsyncCallback receiveCallback, SniAsyncCallback sendCallback) { _receiveCallback = receiveCallback; _sendCallback = sendCallback; @@ -325,7 +327,7 @@ public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyn public override uint EnableSsl(uint options) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; try @@ -346,13 +348,13 @@ public override uint EnableSsl(uint options) } catch (AuthenticationException aue) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, AuthenticationException message = {1}.", args0: ConnectionId, args1: aue?.Message); - return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, aue); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, AuthenticationException message = {1}.", args0: ConnectionId, args1: aue?.Message); + return SniCommon.ReportSNIError(SniProviders.NP_PROV, SniCommon.InternalExceptionError, aue); } catch (InvalidOperationException ioe) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.ERR, "Connection Id {0}, InvalidOperationException message = {1}.", args0: ConnectionId, args1: ioe?.Message); - return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, ioe); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.ERR, "Connection Id {0}, InvalidOperationException message = {1}.", args0: ConnectionId, args1: ioe?.Message); + return SniCommon.ReportSNIError(SniProviders.NP_PROV, SniCommon.InternalExceptionError, ioe); } _stream = _sslStream; return TdsEnums.SNI_SUCCESS; @@ -379,16 +381,16 @@ public override void DisableSsl() /// true if valid private bool ValidateServerCertificate(object sender, X509Certificate serverCertificate, X509Chain chain, SslPolicyErrors policyErrors) { - using (TrySNIEventScope.Create(nameof(SNINpHandle))) + using (TrySNIEventScope.Create(nameof(SniNpHandle))) { if (!_validateCert) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Certificate validation not requested.", args0: ConnectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Certificate validation not requested.", args0: ConnectionId); return true; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Proceeding to SSL certificate validation.", args0: ConnectionId); - return SNICommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Proceeding to SSL certificate validation.", args0: ConnectionId); + return SniCommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors); } } @@ -401,27 +403,27 @@ public override void SetBufferSize(int bufferSize) _bufferSize = bufferSize; } - private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException) + private uint ReportErrorAndReleasePacket(SniPacket packet, Exception sniException) { if (packet != null) { ReturnPacket(packet); } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Packet returned, error occurred: {1}", args0: ConnectionId, args1: sniException?.Message); - return SNICommon.ReportSNIError(SNIProviders.NP_PROV, SNICommon.InternalExceptionError, sniException); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Packet returned, error occurred: {1}", args0: ConnectionId, args1: sniException?.Message); + return SniCommon.ReportSNIError(SniProviders.NP_PROV, SniCommon.InternalExceptionError, sniException); } - private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage) + private uint ReportErrorAndReleasePacket(SniPacket packet, uint nativeError, uint sniError, string errorMessage) { if (packet != null) { ReturnPacket(packet); } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNINpHandle), EventType.INFO, "Connection Id {0}, Packet returned, error occurred: {1}", args0: ConnectionId, args1: errorMessage); - return SNICommon.ReportSNIError(SNIProviders.NP_PROV, nativeError, sniError, errorMessage); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniNpHandle), EventType.INFO, "Connection Id {0}, Packet returned, error occurred: {1}", args0: ConnectionId, args1: errorMessage); + return SniCommon.ReportSNIError(SniProviders.NP_PROV, nativeError, sniError, errorMessage); } -#if DEBUG + #if DEBUG /// /// Test handle for killing underlying connection /// @@ -430,6 +432,8 @@ public override void KillConnection() _pipeStream.Dispose(); _pipeStream = null; } -#endif + #endif } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIPacket.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniPacket.netcore.cs similarity index 87% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIPacket.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniPacket.netcore.cs index fd542e542f..5270513c05 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIPacket.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniPacket.netcore.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET // #define TRACE_HISTORY // this is used for advanced debugging when you need to trace the entire lifetime of a single packet, be very careful with it using System; @@ -11,12 +12,12 @@ using System.Threading; using System.Threading.Tasks; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// SNI Packet /// - internal sealed class SNIPacket + internal sealed class SniPacket { private static readonly Action, object> s_readCallback = ReadFromStreamAsyncContinuation; private int _dataLength; // the length of the data in the data segment, advanced by Append-ing data, does not include smux header length @@ -25,14 +26,14 @@ internal sealed class SNIPacket private int _headerLength; // the amount of space at the start of the array reserved for the smux header, this is zeroed in SetHeader // _headerOffset is not needed because it is always 0 private byte[] _data; - private SNIAsyncCallback _asyncIOCompletionCallback; + private SniAsyncCallback _asyncIOCompletionCallback; #if DEBUG internal readonly int _id; // in debug mode every packet is assigned a unique id so that the entire lifetime can be tracked when debugging /// refcount = 0 means that a packet should only exist in the pool /// refcount = 1 means that a packet is active /// refcount > 1 means that a packet has been reused in some way and is a serious error internal int _refCount; - internal readonly SNIHandle _owner; // used in debug builds to check that packets are being returned to the correct pool + internal readonly SniHandle _owner; // used in debug builds to check that packets are being returned to the correct pool internal string _traceTag; // used in debug builds to assist tracing what steps the packet has been through #if TRACE_HISTORY @@ -59,7 +60,7 @@ public enum Direction /// public bool IsActive => _refCount == 1; - public SNIPacket(SNIHandle owner, int id) + public SniPacket(SniHandle owner, int id) : this() { #if TRACE_HISTORY @@ -67,22 +68,22 @@ public SNIPacket(SNIHandle owner, int id) #endif _id = id; _owner = owner; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} instantiated,", args0: _owner?.ConnectionId, args1: _id); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} instantiated,", args0: _owner?.ConnectionId, args1: _id); } // the finalizer is only included in debug builds and is used to ensure that all packets are correctly recycled // it is not an error if a packet is dropped but it is undesirable so all efforts should be made to make sure we // do not drop them for the GC to pick up - ~SNIPacket() + ~SniPacket() { if (_data != null) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.ERR, "Finalizer called for unreleased SNIPacket, Connection Id {0}, Packet Id {1}, _refCount {2}, DataLeft {3}, tag {4}", args0: _owner?.ConnectionId, args1: _id, args2: _refCount, args3: DataLeft, args4: _traceTag); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.ERR, "Finalizer called for unreleased SNIPacket, Connection Id {0}, Packet Id {1}, _refCount {2}, DataLeft {3}, tag {4}", args0: _owner?.ConnectionId, args1: _id, args2: _refCount, args3: DataLeft, args4: _traceTag); } } #endif - public SNIPacket() + public SniPacket() { } @@ -114,7 +115,7 @@ public SNIPacket() /// Set async receive callback /// /// Completion callback - public void SetAsyncIOCompletionCallback(SNIAsyncCallback asyncIOCompletionCallback) => _asyncIOCompletionCallback = asyncIOCompletionCallback; + public void SetAsyncIOCompletionCallback(SniAsyncCallback asyncIOCompletionCallback) => _asyncIOCompletionCallback = asyncIOCompletionCallback; /// /// Invoke the receive callback @@ -135,7 +136,7 @@ public void Allocate(int headerLength, int dataLength) _dataOffset = 0; _headerLength = headerLength; #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} allocated with _headerLength {2}, _dataCapacity {3}", args0: _owner?.ConnectionId, args1: _id, args2: _headerLength, args3: _dataCapacity); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} allocated with _headerLength {2}, _dataCapacity {3}", args0: _owner?.ConnectionId, args1: _id, args2: _headerLength, args3: _dataCapacity); #endif } @@ -156,12 +157,12 @@ public void GetData(byte[] buffer, ref int dataSize) /// Packet /// Data to take /// Amount of data taken - public int TakeData(SNIPacket packet, int size) + public int TakeData(SniPacket packet, int size) { int dataSize = TakeData(packet._data, packet._headerLength + packet._dataLength, size); packet._dataLength += dataSize; #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} took data from Packet Id {2} dataSize {3}, _dataLength {4}", args0: _owner?.ConnectionId, args1: _id, args2: packet?._id, args3: dataSize, args4: packet._dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} took data from Packet Id {2} dataSize {3}, _dataLength {4}", args0: _owner?.ConnectionId, args1: _id, args2: packet?._id, args3: dataSize, args4: packet._dataLength); #endif return dataSize; } @@ -176,7 +177,7 @@ public void AppendData(byte[] data, int size) Buffer.BlockCopy(data, 0, _data, _headerLength + _dataLength, size); _dataLength += size; #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} was appended with size {2}, _dataLength {3}", args0: _owner?.ConnectionId, args1: _id, args2: size, args3: _dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} was appended with size {2}, _dataLength {3}", args0: _owner?.ConnectionId, args1: _id, args2: size, args3: _dataLength); #endif } @@ -202,7 +203,7 @@ public int TakeData(byte[] buffer, int dataOffset, int size) Buffer.BlockCopy(_data, _headerLength + _dataOffset, buffer, dataOffset, size); _dataOffset += size; #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} took data size {2}, _dataLength {3}, _dataOffset {4}", args0: _owner?.ConnectionId, args1: _id, args2: size, args3: _dataLength, args4: _dataOffset); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} took data size {2}, _dataLength {3}, _dataOffset {4}", args0: _owner?.ConnectionId, args1: _id, args2: size, args3: _dataLength, args4: _dataOffset); #endif return size; } @@ -222,7 +223,7 @@ public void SetHeaderActive() _dataLength += _headerLength; _headerLength = 0; #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} header set to active.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} header set to active.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); #endif } @@ -240,7 +241,7 @@ public void Release() _dataCapacity = 0; } #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _headerLength {2} and _dataLength {3} released.", args0: _owner?.ConnectionId, args1: _id, args2: _headerLength, args3: _dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _headerLength {2} and _dataLength {3} released.", args0: _owner?.ConnectionId, args1: _id, args2: _headerLength, args3: _dataLength); #endif _dataLength = 0; _dataOffset = 0; @@ -257,7 +258,7 @@ public void ReadFromStream(Stream stream) { _dataLength = stream.Read(_data, _headerLength, _dataCapacity); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} read from stream.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} read from stream.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); #endif } @@ -279,14 +280,14 @@ public void ReadFromStreamAsync(Stream stream) private static void ReadFromStreamAsyncContinuation(Task task, object state) { - SNIPacket packet = (SNIPacket)state; + SniPacket packet = (SniPacket)state; bool error = false; Exception e = task.Exception?.InnerException; if (e != null) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, e); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.TCP_PROV, SniCommon.InternalExceptionError, e); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.ERR, "Connection Id {0}, Internal Exception occurred while reading data: {1}", args0: packet._owner?.ConnectionId, args1: e?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.ERR, "Connection Id {0}, Internal Exception occurred while reading data: {1}", args0: packet._owner?.ConnectionId, args1: e?.Message); #endif error = true; } @@ -294,13 +295,13 @@ private static void ReadFromStreamAsyncContinuation(Task task, object state { packet._dataLength = task.Result; #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} read from stream.", args0: packet._owner?.ConnectionId, args1: packet._id, args2: packet._dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} read from stream.", args0: packet._owner?.ConnectionId, args1: packet._id, args2: packet._dataLength); #endif if (packet._dataLength == 0) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.ConnTerminatedError, Strings.SNI_ERROR_2); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.TCP_PROV, 0, SniCommon.ConnTerminatedError, Strings.SNI_ERROR_2); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.ERR, "Connection Id {0}, No data read from stream, connection was terminated.", args0: packet._owner?.ConnectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.ERR, "Connection Id {0}, No data read from stream, connection was terminated.", args0: packet._owner?.ConnectionId); #endif error = true; } @@ -317,7 +318,7 @@ public void WriteToStream(Stream stream) { stream.Write(_data, _headerLength, _dataLength); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} written to stream.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} written to stream.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); #endif } @@ -327,21 +328,21 @@ public void WriteToStream(Stream stream) /// Stream to write to /// SNI Asynchronous Callback /// SNI provider identifier - public async void WriteToStreamAsync(Stream stream, SNIAsyncCallback callback, SNIProviders provider) + public async void WriteToStreamAsync(Stream stream, SniAsyncCallback callback, SniProviders provider) { uint status = TdsEnums.SNI_SUCCESS; try { await stream.WriteAsync(_data, 0, _dataLength, CancellationToken.None).ConfigureAwait(false); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} written to stream.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.INFO, "Connection Id {0}, Packet Id {1} _dataLength {2} written to stream.", args0: _owner?.ConnectionId, args1: _id, args2: _dataLength); #endif } catch (Exception e) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, SNICommon.InternalExceptionError, e); + SniLoadHandle.SingletonInstance.LastError = new SniError(provider, SniCommon.InternalExceptionError, e); #if DEBUG - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIPacket), EventType.ERR, "Connection Id {0}, Internal Exception occurred while writing data: {1}", args0: _owner?.ConnectionId, args1: e?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniPacket), EventType.ERR, "Connection Id {0}, Internal Exception occurred while writing data: {1}", args0: _owner?.ConnectionId, args1: e?.Message); #endif status = TdsEnums.SNI_ERROR; } @@ -349,3 +350,5 @@ public async void WriteToStreamAsync(Stream stream, SNIAsyncCallback callback, S } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIPhysicalHandle.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniPhysicalHandle.netcore.cs similarity index 85% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIPhysicalHandle.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniPhysicalHandle.netcore.cs index 1acc6a14c8..3ee2111e78 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIPhysicalHandle.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniPhysicalHandle.netcore.cs @@ -2,38 +2,40 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using Microsoft.Data.SqlClient.Utilities; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { - internal abstract class SNIPhysicalHandle : SNIHandle + internal abstract class SniPhysicalHandle : SniHandle { protected const int DefaultPoolSize = 4; #if DEBUG private static int s_packetId; #endif - private ObjectPool _pool; + private ObjectPool _pool; - protected SNIPhysicalHandle(int poolSize = DefaultPoolSize) + protected SniPhysicalHandle(int poolSize = DefaultPoolSize) { - _pool = new ObjectPool(poolSize); + _pool = new ObjectPool(poolSize); } - public override SNIPacket RentPacket(int headerSize, int dataSize) + public override SniPacket RentPacket(int headerSize, int dataSize) { - SNIPacket packet; + SniPacket packet; if (!_pool.TryGet(out packet)) { #if DEBUG int id = Interlocked.Increment(ref s_packetId); - packet = new SNIPacket(this, id); + packet = new SniPacket(this, id); #else - packet = new SNIPacket(); + packet = new SniPacket(); #endif } #if DEBUG @@ -57,7 +59,7 @@ public override SNIPacket RentPacket(int headerSize, int dataSize) return packet; } - public override void ReturnPacket(SNIPacket packet) + public override void ReturnPacket(SniPacket packet) { #if DEBUG Debug.Assert(packet != null, "releasing null SNIPacket"); @@ -98,3 +100,5 @@ private string GetStackParts() #endif } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniProviders.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniProviders.netcore.cs new file mode 100644 index 0000000000..2c040a11cf --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniProviders.netcore.cs @@ -0,0 +1,30 @@ +// 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. + +#if NET + +namespace Microsoft.Data.SqlClient.ManagedSni +{ + /// + /// SNI provider identifiers + /// + internal enum SniProviders + { + // @TODO: Rename to follow enum naming conventions, remove PROV suffix - we get it, it's in the Providers enum. + HTTP_PROV = 0, // HTTP Provider + NP_PROV = 1, // Named Pipes Provider + SESSION_PROV = 2, // Session Provider + SIGN_PROV = 3, // Sign Provider + SM_PROV = 4, // Shared Memory Provider + SMUX_PROV = 5, // SMUX Provider + SSL_PROV = 6, // SSL Provider + TCP_PROV = 7, // TCP Provider + VIA_PROV = 8, // Virtual Interface Architecture Provider + CTAIP_PROV = 9, + MAX_PROVS = 10, // Number of providers + INVALID_PROV = 11 // SQL Network Interfaces + } +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniProxy.netcore.cs similarity index 89% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniProxy.netcore.cs index 265f80246c..c09e5a7b27 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNIProxy.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniProxy.netcore.cs @@ -2,31 +2,30 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; -using System.Buffers; -using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Net; -using System.Net.Security; using System.Net.Sockets; using System.Text; using Microsoft.Data.ProviderBase; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// Managed SNI proxy implementation. Contains many SNI entry points used by SqlClient. /// - internal class SNIProxy + internal class SniProxy { private const int DefaultSqlServerPort = 1433; private const int DefaultSqlServerDacPort = 1434; private const string SqlServerSpnHeader = "MSSQLSvc"; - private static readonly SNIProxy s_singleton = new SNIProxy(); + private static readonly SniProxy s_singleton = new SniProxy(); - internal static SNIProxy Instance => s_singleton; + internal static SniProxy Instance => s_singleton; /// /// Create a SNI connection handle @@ -47,7 +46,7 @@ internal class SNIProxy /// Used for the HostName in certificate /// Used for the path to the Server Certificate /// SNI handle - internal static SNIHandle CreateConnectionHandle( + internal static SniHandle CreateConnectionHandle( string fullServerName, TimeoutTimer timeout, out byte[] instanceName, @@ -82,7 +81,7 @@ internal static SNIHandle CreateConnectionHandle( return null; } - SNIHandle sniHandle = null; + SniHandle sniHandle = null; switch (details.ResolvedProtocol) { case DataSource.Protocol.Admin: @@ -107,7 +106,7 @@ internal static SNIHandle CreateConnectionHandle( } catch (Exception e) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, SNICommon.ErrorSpnLookup, e); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, SniCommon.ErrorSpnLookup, e); } } @@ -190,7 +189,7 @@ private static string[] GetSqlServerSPNs(string hostNameOrAddress, string portOr /// Host name in certificate /// Used for the path to the Server Certificate /// SNITCPHandle - private static SNITCPHandle CreateTcpHandle( + private static SniTcpHandle CreateTcpHandle( DataSource details, TimeoutTimer timeout, bool parallel, @@ -208,7 +207,7 @@ private static SNITCPHandle CreateTcpHandle( string hostName = details.ServerName; if (string.IsNullOrWhiteSpace(hostName)) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, 0, SNICommon.InvalidConnStringError, Strings.SNI_ERROR_25); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.TCP_PROV, 0, SniCommon.InvalidConnStringError, Strings.SNI_ERROR_25); return null; } @@ -219,12 +218,12 @@ private static SNITCPHandle CreateTcpHandle( try { details.ResolvedPort = port = isAdminConnection ? - SSRP.GetDacPortByInstanceName(hostName, details.InstanceName, timeout, parallel, ipPreference) : - SSRP.GetPortByInstanceName(hostName, details.InstanceName, timeout, parallel, ipPreference); + SsrpClient.GetDacPortByInstanceName(hostName, details.InstanceName, timeout, parallel, ipPreference) : + SsrpClient.GetPortByInstanceName(hostName, details.InstanceName, timeout, parallel, ipPreference); } catch (SocketException se) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.TCP_PROV, SNICommon.ErrorLocatingServerInstance, se); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.TCP_PROV, SniCommon.ErrorLocatingServerInstance, se); return null; } } @@ -237,7 +236,7 @@ private static SNITCPHandle CreateTcpHandle( port = isAdminConnection ? DefaultSqlServerDacPort : DefaultSqlServerPort; } - return new SNITCPHandle(hostName, port, timeout, parallel, ipPreference, cachedFQDN, ref pendingDNSInfo, + return new SniTcpHandle(hostName, port, timeout, parallel, ipPreference, cachedFQDN, ref pendingDNSInfo, tlsFirst, hostNameInCertificate, serverCertificateFilename); } @@ -251,24 +250,24 @@ private static SNITCPHandle CreateTcpHandle( /// Host name in certificate /// Used for the path to the Server Certificate /// SNINpHandle - private static SNINpHandle CreateNpHandle(DataSource details, TimeoutTimer timeout, bool parallel, bool tlsFirst, string hostNameInCertificate, string serverCertificateFilename) + private static SniNpHandle CreateNpHandle(DataSource details, TimeoutTimer timeout, bool parallel, bool tlsFirst, string hostNameInCertificate, string serverCertificateFilename) { if (parallel) { // Connecting to a SQL Server instance using the MultiSubnetFailover connection option is only supported when using the TCP protocol - SNICommon.ReportSNIError(SNIProviders.NP_PROV, 0, SNICommon.MultiSubnetFailoverWithNonTcpProtocol, Strings.SNI_ERROR_49); + SniCommon.ReportSNIError(SniProviders.NP_PROV, 0, SniCommon.MultiSubnetFailoverWithNonTcpProtocol, Strings.SNI_ERROR_49); return null; } - return new SNINpHandle(details.PipeHostName, details.PipeName, timeout, tlsFirst, hostNameInCertificate, serverCertificateFilename); + return new SniNpHandle(details.PipeHostName, details.PipeName, timeout, tlsFirst, hostNameInCertificate, serverCertificateFilename); } /// /// Get last SNI error on this thread /// /// - internal SNIError GetLastError() + internal SniError GetLastError() { - return SNILoadHandle.SingletonInstance.LastError; + return SniLoadHandle.SingletonInstance.LastError; } /// @@ -385,11 +384,11 @@ private DataSource(string dataSource) if (_dataSourceAfterTrimmingProtocol.Contains(Slash)) // Pipe paths only allow back slashes { if (ResolvedProtocol == Protocol.None) - ReportSNIError(SNIProviders.INVALID_PROV); + ReportSNIError(SniProviders.INVALID_PROV); else if (ResolvedProtocol == Protocol.NP) - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); else if (ResolvedProtocol == Protocol.TCP) - ReportSNIError(SNIProviders.TCP_PROV); + ReportSNIError(SniProviders.TCP_PROV); } } @@ -442,8 +441,8 @@ internal static string GetLocalDBInstance(string dataSource, out bool error) } else if (index > 0) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.ErrorLocatingServerInstance, Strings.SNI_ERROR_26); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNIProxy), EventType.ERR, "Incompatible use of prefix with LocalDb: '{0}'", dataSource); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.ErrorLocatingServerInstance, Strings.SNI_ERROR_26); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniProxy), EventType.ERR, "Incompatible use of prefix with LocalDb: '{0}'", dataSource); error = true; } else if (index == 0) @@ -461,7 +460,7 @@ internal static string GetLocalDBInstance(string dataSource, out bool error) } else { - SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.INVALID_PROV, 0, SNICommon.LocalDBNoInstanceName, Strings.SNI_ERROR_51); + SniLoadHandle.SingletonInstance.LastError = new SniError(SniProviders.INVALID_PROV, 0, SniCommon.LocalDBNoInstanceName, Strings.SNI_ERROR_51); error = true; } } @@ -528,7 +527,7 @@ private bool InferConnectionDetails() // Bad Data Source like "server, " if (string.IsNullOrEmpty(parameter)) { - ReportSNIError(SNIProviders.INVALID_PROV); + ReportSNIError(SniProviders.INVALID_PROV); return false; } @@ -540,21 +539,21 @@ private bool InferConnectionDetails() else if (ResolvedProtocol != Protocol.TCP) { // Parameter has been specified for non-TCP protocol. This is not allowed. - ReportSNIError(SNIProviders.INVALID_PROV); + ReportSNIError(SniProviders.INVALID_PROV); return false; } int port; if (!int.TryParse(parameter, out port)) { - ReportSNIError(SNIProviders.TCP_PROV); + ReportSNIError(SniProviders.TCP_PROV); return false; } // If the user explicitly specified a invalid port in the connection string. if (port < 1) { - ReportSNIError(SNIProviders.TCP_PROV); + ReportSNIError(SniProviders.TCP_PROV); return false; } @@ -568,13 +567,13 @@ private bool InferConnectionDetails() if (string.IsNullOrWhiteSpace(InstanceName)) { - ReportSNIError(SNIProviders.INVALID_PROV); + ReportSNIError(SniProviders.INVALID_PROV); return false; } if (DefaultSqlServerInstanceName.Equals(InstanceName)) { - ReportSNIError(SNIProviders.INVALID_PROV); + ReportSNIError(SniProviders.INVALID_PROV); return false; } @@ -586,9 +585,9 @@ private bool InferConnectionDetails() return true; } - private void ReportSNIError(SNIProviders provider) + private void ReportSNIError(SniProviders provider) { - SNILoadHandle.SingletonInstance.LastError = new SNIError(provider, 0, SNICommon.InvalidConnStringError, Strings.SNI_ERROR_25); + SniLoadHandle.SingletonInstance.LastError = new SniError(provider, 0, SniCommon.InvalidConnStringError, Strings.SNI_ERROR_25); IsBadDataSource = true; } @@ -615,14 +614,14 @@ private bool InferNamedPipesInformation() } else { - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); return false; } } else { PipeHostName = ServerName = _dataSourceAfterTrimmingProtocol; - PipeName = SNINpHandle.DefaultPipePath; + PipeName = SniNpHandle.DefaultPipePath; } InferLocalServerName(); @@ -638,7 +637,7 @@ private bool InferNamedPipesInformation() // Another valid Sql named pipe for an named instance is \\.\pipe\MSSQL$MYINSTANCE\sql\query if (tokensByBackSlash.Length < 6) { - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); return false; } @@ -646,14 +645,14 @@ private bool InferNamedPipesInformation() if (string.IsNullOrEmpty(host)) { - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); return false; } //Check if the "pipe" keyword is the first part of path if (!PipeToken.Equals(tokensByBackSlash[3])) { - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); return false; } @@ -685,7 +684,7 @@ private bool InferNamedPipesInformation() } catch (UriFormatException) { - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); return false; } @@ -697,7 +696,7 @@ private bool InferNamedPipesInformation() else if (ResolvedProtocol != Protocol.NP) { // In case the path began with a "\\" and protocol was not Named Pipes - ReportSNIError(SNIProviders.NP_PROV); + ReportSNIError(SniProviders.NP_PROV); return false; } return true; @@ -705,7 +704,9 @@ private bool InferNamedPipesInformation() return false; } - private static bool IsLocalHost(string serverName) - => ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName); + private static bool IsLocalHost(string serverName) => + ".".Equals(serverName) || "(local)".Equals(serverName) || "localhost".Equals(serverName); } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSmuxFlags.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSmuxFlags.netcore.cs new file mode 100644 index 0000000000..feffee9113 --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSmuxFlags.netcore.cs @@ -0,0 +1,40 @@ +// 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. + +#if NET + +using System; + +namespace Microsoft.Data.SqlClient.ManagedSni +{ + /// + /// SMUX packet flags + /// + [Flags] + internal enum SniSmuxFlags + { + // @TODO: Should probably drop the SMUX prefix - it's pretty obvious since it's in the SmuxFlags enum. + /// + /// Begin SMUX connection. + /// + SMUX_SYN = 1, + + /// + /// Acknowledge SMUX packets. + /// + SMUX_ACK = 2, + + /// + /// End SMUX connection. + /// + SMUX_FIN = 4, + + /// + /// SMUX data packet. + /// + SMUX_DATA = 8 + } +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSmuxHeader.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSmuxHeader.netcore.cs new file mode 100644 index 0000000000..10bde29f7f --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSmuxHeader.netcore.cs @@ -0,0 +1,69 @@ +// 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. + +#if NET + +using System; +using System.Buffers.Binary; + +namespace Microsoft.Data.SqlClient.ManagedSni +{ + /// + /// SMUX packet header + /// + internal sealed class SniSmuxHeader + { + public const int HEADER_LENGTH = 16; + + public byte SMID; + public byte flags; + public ushort sessionId; + public uint length; + public uint sequenceNumber; + public uint highwater; + + public void Read(byte[] bytes) + { + SMID = bytes[0]; + flags = bytes[1]; + Span span = bytes.AsSpan(); + sessionId = BinaryPrimitives.ReadUInt16LittleEndian(span.Slice(2)); + length = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(4)) - SniSmuxHeader.HEADER_LENGTH; + sequenceNumber = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(8)); + highwater = BinaryPrimitives.ReadUInt32LittleEndian(span.Slice(12)); + } + + public void Write(Span bytes) + { + uint value = highwater; + // access the highest element first to cause the largest range check in the jit, then fill in the rest of the value and carry on as normal + bytes[15] = (byte)((value >> 24) & 0xff); + bytes[12] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.highwater).CopyTo(headerBytes, 12); + bytes[13] = (byte)((value >> 8) & 0xff); + bytes[14] = (byte)((value >> 16) & 0xff); + + bytes[0] = SMID; // BitConverter.GetBytes(_currentHeader.SMID).CopyTo(headerBytes, 0); + bytes[1] = flags; // BitConverter.GetBytes(_currentHeader.flags).CopyTo(headerBytes, 1); + + value = sessionId; + bytes[2] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sessionId).CopyTo(headerBytes, 2); + bytes[3] = (byte)((value >> 8) & 0xff); + + value = length; + bytes[4] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.length).CopyTo(headerBytes, 4); + bytes[5] = (byte)((value >> 8) & 0xff); + bytes[6] = (byte)((value >> 16) & 0xff); + bytes[7] = (byte)((value >> 24) & 0xff); + + value = sequenceNumber; + bytes[8] = (byte)(value & 0xff); // BitConverter.GetBytes(_currentHeader.sequenceNumber).CopyTo(headerBytes, 8); + bytes[9] = (byte)((value >> 8) & 0xff); + bytes[10] = (byte)((value >> 16) & 0xff); + bytes[11] = (byte)((value >> 24) & 0xff); + + } + } +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSslStream.netcore.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSslStream.netcore.cs new file mode 100644 index 0000000000..a7fc289d7f --- /dev/null +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniSslStream.netcore.cs @@ -0,0 +1,81 @@ +// 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. + +#if NET + +using System; +using System.IO; +using System.Net.Security; +using System.Threading; +using System.Threading.Tasks; + +namespace Microsoft.Data.SqlClient.ManagedSni +{ + /// + /// This class extends SslStream to customize stream behavior for Managed SNI implementation. + /// + internal sealed class SniSslStream : SslStream + { + private readonly ConcurrentQueueSemaphore _writeAsyncSemaphore; + private readonly ConcurrentQueueSemaphore _readAsyncSemaphore; + + public SniSslStream( + Stream innerStream, + bool leaveInnerStreamOpen, + RemoteCertificateValidationCallback userCertificateValidationCallback) + : base(innerStream, leaveInnerStreamOpen, userCertificateValidationCallback) + { + _writeAsyncSemaphore = new ConcurrentQueueSemaphore(1); + _readAsyncSemaphore = new ConcurrentQueueSemaphore(1); + } + + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); + } + + public override async ValueTask ReadAsync(Memory buffer, CancellationToken cancellationToken = default) + { + await _readAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + return await base.ReadAsync(buffer, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniSslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); + throw; + } + finally + { + _readAsyncSemaphore.Release(); + } + } + + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) + { + return WriteAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); + } + + public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken cancellationToken = default) + { + await _writeAsyncSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); + try + { + await base.WriteAsync(buffer, cancellationToken).ConfigureAwait(false); + } + catch (Exception e) + { + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniSslStream), EventType.ERR, "Internal Exception occurred while reading data: {0}", args0: e?.Message); + throw; + } + finally + { + _writeAsyncSemaphore.Release(); + } + } + } +} + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs similarity index 89% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs index b3ecfb156a..656060beeb 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SNITcpHandle.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SniTcpHandle.netcore.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Collections.Generic; using System.ComponentModel; @@ -15,12 +17,12 @@ using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// TCP connection handle /// - internal sealed class SNITCPHandle : SNIPhysicalHandle + internal sealed class SniTcpHandle : SniPhysicalHandle { private readonly string _targetServer; private readonly object _sendSync; @@ -33,8 +35,8 @@ internal sealed class SNITCPHandle : SNIPhysicalHandle private Stream _stream; private SslStream _sslStream; private SslOverTdsStream _sslOverTdsStream; - private SNIAsyncCallback _receiveCallback; - private SNIAsyncCallback _sendCallback; + private SniAsyncCallback _receiveCallback; + private SniAsyncCallback _sendCallback; private bool _validateCert = true; private int _bufferSize = TdsEnums.DEFAULT_LOGIN_PACKET_SIZE; @@ -70,7 +72,7 @@ public override void Dispose() //Release any references held by _stream. _stream = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, All streams disposed.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, All streams disposed.", args0: _connectionId); } } @@ -124,7 +126,7 @@ public override int ProtocolVersion /// Support TDS8.0 /// Host Name in Certificate /// Used for the path to the Server Certificate - public SNITCPHandle( + public SniTcpHandle( string serverName, int port, TimeoutTimer timeout, @@ -136,9 +138,9 @@ public SNITCPHandle( string hostNameInCertificate, string serverCertificateFilename) { - using (TrySNIEventScope.Create(nameof(SNITCPHandle))) + using (TrySNIEventScope.Create(nameof(SniTcpHandle))) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Setting server name = {1}", args0: _connectionId, args1: serverName); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Setting server name = {1}", args0: _connectionId, args1: serverName); _targetServer = serverName; _tlsFirst = tlsFirst; @@ -153,7 +155,7 @@ public SNITCPHandle( { bool reportError = true; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Connecting to serverName {1} and port {2}", args0: _connectionId, args1: serverName, args2: port); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Connecting to serverName {1} and port {2}", args0: _connectionId, args1: serverName, args2: port); // We will always first try to connect with serverName as before and let DNS resolve the serverName. // If DNS resolution fails, we will try with IPs in the DNS cache if they exist. We try with cached IPs based on IPAddressPreference. // Exceptions will be thrown to the caller and be handled as before. @@ -179,13 +181,13 @@ public SNITCPHandle( { if (hasCachedDNSInfo == false) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Cached DNS Info not found, exception occurred thrown: {1}", args0: _connectionId, args1: ex?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Cached DNS Info not found, exception occurred thrown: {1}", args0: _connectionId, args1: ex?.Message); throw; } else { int portRetry = string.IsNullOrEmpty(cachedDNSInfo.Port) ? port : int.Parse(cachedDNSInfo.Port); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Retrying with cached DNS IP Address {1} and port {2}", args0: _connectionId, args1: cachedDNSInfo.AddrIPv4, args2: cachedDNSInfo.Port); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Retrying with cached DNS IP Address {1} and port {2}", args0: _connectionId, args1: cachedDNSInfo.AddrIPv4, args2: cachedDNSInfo.Port); string firstCachedIP; string secondCachedIP; @@ -221,7 +223,7 @@ public SNITCPHandle( if (exRetry is SocketException || exRetry is ArgumentNullException || exRetry is ArgumentException || exRetry is ArgumentOutOfRangeException || exRetry is AggregateException) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Retrying exception {1}", args0: _connectionId, args1: exRetry?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Retrying exception {1}", args0: _connectionId, args1: exRetry?.Message); if (parallel) { _socket = TryConnectParallel(secondCachedIP, portRetry, timeout, ref reportError, cachedFQDN, ref pendingDNSInfo); @@ -233,7 +235,7 @@ public SNITCPHandle( } else { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Retry failed, exception occurred: {1}", args0: _connectionId, args1: exRetry?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Retry failed, exception occurred: {1}", args0: _connectionId, args1: exRetry?.Message); throw; } } @@ -255,15 +257,15 @@ public SNITCPHandle( if (reportError) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0} could not be opened, exception occurred: {1}", args0: _connectionId, args1: Strings.SNI_ERROR_40); - ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, Strings.SNI_ERROR_40); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0} could not be opened, exception occurred: {1}", args0: _connectionId, args1: Strings.SNI_ERROR_40); + ReportTcpSNIError(0, SniCommon.ConnOpenFailedError, Strings.SNI_ERROR_40); } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0} Socket could not be opened.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0} Socket could not be opened.", args0: _connectionId); return; } _socket.NoDelay = true; - _tcpStream = new SNINetworkStream(_socket, true); + _tcpStream = new SniNetworkStream(_socket, true); Stream stream = _tcpStream; if (!_tlsFirst) @@ -271,24 +273,24 @@ public SNITCPHandle( _sslOverTdsStream = new SslOverTdsStream(_tcpStream, _connectionId); stream = _sslOverTdsStream; } - _sslStream = new SNISslStream(stream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); + _sslStream = new SniSslStream(stream, true, new RemoteCertificateValidationCallback(ValidateServerCertificate)); } catch (SocketException se) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0} Socket exception occurred: Error Code {1}, Message {2}", args0: _connectionId, args1: se?.SocketErrorCode, args2: se?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0} Socket exception occurred: Error Code {1}, Message {2}", args0: _connectionId, args1: se?.SocketErrorCode, args2: se?.Message); ReportTcpSNIError(se); return; } catch (Exception e) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0} Exception occurred: {1}", args0: _connectionId, args1: e?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0} Exception occurred: {1}", args0: _connectionId, args1: e?.Message); ReportTcpSNIError(e); return; } _stream = _tcpStream; _status = TdsEnums.SNI_SUCCESS; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0} Socket opened successfully, TCP stream ready.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0} Socket opened successfully, TCP stream ready.", args0: _connectionId); } } @@ -297,21 +299,21 @@ public SNITCPHandle( // 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, TimeoutTimer timeout, ref bool callerReportError, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo) { - using (TrySNIEventScope.Create(nameof(SNITCPHandle))) + using (TrySNIEventScope.Create(nameof(SniTcpHandle))) { Socket availableSocket = null; bool isInfiniteTimeOut = timeout.IsInfinite; IPAddress[] serverAddresses = isInfiniteTimeOut - ? SNICommon.GetDnsIpAddresses(hostName) - : SNICommon.GetDnsIpAddresses(hostName, timeout); + ? SniCommon.GetDnsIpAddresses(hostName) + : SniCommon.GetDnsIpAddresses(hostName, timeout); if (serverAddresses.Length > MaxParallelIpAddresses) { // Fail if above 64 to match legacy behavior callerReportError = false; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0} serverAddresses.Length {1} Exception: {2}", args0: _connectionId, args1: serverAddresses.Length, args2: Strings.SNI_ERROR_47); - ReportTcpSNIError(0, SNICommon.MultiSubnetFailoverWithMoreThan64IPs, Strings.SNI_ERROR_47); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0} serverAddresses.Length {1} Exception: {2}", args0: _connectionId, args1: serverAddresses.Length, args2: Strings.SNI_ERROR_47); + ReportTcpSNIError(0, SniCommon.MultiSubnetFailoverWithMoreThan64IPs, Strings.SNI_ERROR_47); return availableSocket; } @@ -366,9 +368,9 @@ private static IEnumerable GetHostAddressesSortedByPreference(string // 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, TimeoutTimer timeout, SqlConnectionIPAddressPreference ipPreference, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo) { - using (TrySNIEventScope.Create(nameof(SNITCPHandle))) + using (TrySNIEventScope.Create(nameof(SniTcpHandle))) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "IP preference : {0}", Enum.GetName(typeof(SqlConnectionIPAddressPreference), ipPreference)); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "IP preference : {0}", Enum.GetName(typeof(SqlConnectionIPAddressPreference), ipPreference)); bool isInfiniteTimeout = timeout.IsInfinite; IEnumerable ipAddresses = GetHostAddressesSortedByPreference(serverName, ipPreference); @@ -388,7 +390,7 @@ private static Socket Connect(string serverName, int port, TimeoutTimer timeout, // enable keep-alive on socket SetKeepAliveValues(ref socket); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connecting to IP address {0} and port {1} using {2} address family. Is infinite timeout: {3}", ipAddress, port, @@ -434,7 +436,7 @@ private static Socket Connect(string serverName, int port, TimeoutTimer timeout, checkWriteLst = new List(1) { socket }; checkErrorLst = new List(1) { socket }; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Determining the status of the socket during the remaining timeout of {0} microseconds.", socketSelectTimeout); @@ -468,7 +470,7 @@ private static Socket Connect(string serverName, int port, TimeoutTimer timeout, { SqlClientEventSource.Log.TryAdvancedTraceEvent( "{0}.{1}{2}THIS EXCEPTION IS BEING SWALLOWED: {3}", - nameof(SNITCPHandle), nameof(Connect), EventType.ERR, e); + nameof(SniTcpHandle), nameof(Connect), EventType.ERR, e); } finally { @@ -483,7 +485,7 @@ private static Socket Connect(string serverName, int port, TimeoutTimer timeout, private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, TimeoutTimer timeout, string cachedFQDN, ref SQLDNSInfo pendingDNSInfo) { - using (TrySNIEventScope.Create(nameof(SNITCPHandle))) + using (TrySNIEventScope.Create(nameof(SniTcpHandle))) { if (serverAddresses == null) { @@ -508,7 +510,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim // enable keep-alive on socket SetKeepAliveValues(ref socket); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connecting to IP address {0} and port {1} using {2} address family. Is infinite timeout: {3}", address, port, @@ -564,7 +566,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim checkErrorLst.Clear(); checkErrorLst.AddRange(socketsInFlight); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Watching pending sockets during the remaining timeout of {0} microseconds.", socketSelectTimeout); @@ -578,14 +580,14 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim // Socket.Select can throw if one of the sockets has issues. That socket will be in checkErrorLst. // Log the error and let that socket be removed from socketsInFlight below. SqlClientEventSource.Log.TryAdvancedTraceEvent( - "{0}.{1}{2}THIS EXCEPTION IS BEING SWALLOWED: {3}", nameof(SNITCPHandle), nameof(ParallelConnect), EventType.ERR, e); + "{0}.{1}{2}THIS EXCEPTION IS BEING SWALLOWED: {3}", nameof(SniTcpHandle), nameof(ParallelConnect), EventType.ERR, e); lastError = e; } if (timeout.IsExpired) { SqlClientEventSource.Log.TryAdvancedTraceEvent( - "{0}.{1}{2}ParallelConnect timeout expired.", nameof(SNITCPHandle), nameof(ParallelConnect), EventType.INFO); + "{0}.{1}{2}ParallelConnect timeout expired.", nameof(SniTcpHandle), nameof(ParallelConnect), EventType.INFO); break; } @@ -596,7 +598,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim if (!checkErrorLst.Contains(s) && s.Connected) { connectedSocket = s; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connected to endpoint: {0}", connectedSocket.RemoteEndPoint); connectedSocket.Blocking = true; string iPv4String = null; @@ -622,7 +624,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim foreach (Socket socket in checkErrorLst) { SqlClientEventSource.Log.TryAdvancedTraceEvent( - "{0}.{1}{2}Failed to connect to endpoint: {3}. Error: {4}", nameof(SNITCPHandle), + "{0}.{1}{2}Failed to connect to endpoint: {3}. Error: {4}", nameof(SniTcpHandle), nameof(ParallelConnect), EventType.INFO, sockets[socket], lastError); socketsInFlight.Remove(socket); } @@ -631,7 +633,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim foreach (Socket socket in checkWriteLst) { SqlClientEventSource.Log.TryAdvancedTraceEvent( - "{0}.{1}{2}Failed to connect to endpoint: {3}. Error: {4}", nameof(SNITCPHandle), + "{0}.{1}{2}Failed to connect to endpoint: {3}. Error: {4}", nameof(SniTcpHandle), nameof(ParallelConnect), EventType.INFO, sockets[socket], lastError); socketsInFlight.Remove(socket); } @@ -644,7 +646,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim if (socket != connectedSocket) { SqlClientEventSource.Log.TryAdvancedTraceEvent( - "{0}.{1}{2}Disposing non-selected socket for endpoint: {3}", nameof(SNITCPHandle), + "{0}.{1}{2}Disposing non-selected socket for endpoint: {3}", nameof(SniTcpHandle), nameof(ParallelConnect), EventType.INFO, sockets[socket]); socket?.Dispose(); } @@ -654,7 +656,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim { SqlClientEventSource.Log.TryAdvancedTraceEvent( "{0}.{1}{2}No socket connections succeeded. Last error: {3}", - nameof(SNITCPHandle), nameof(ParallelConnect), EventType.ERR, lastError); + nameof(SniTcpHandle), nameof(ParallelConnect), EventType.ERR, lastError); } return connectedSocket; @@ -666,7 +668,7 @@ private static Socket ParallelConnect(IPAddress[] serverAddresses, int port, Tim /// public override uint EnableSsl(uint options) { - using (TrySNIEventScope.Create(nameof(SNIHandle))) + using (TrySNIEventScope.Create(nameof(SniHandle))) { _validateCert = (options & TdsEnums.SNI_SSL_VALIDATE_CERTIFICATE) != 0; @@ -687,17 +689,17 @@ public override uint EnableSsl(uint options) } catch (AuthenticationException aue) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Authentication exception occurred: {1}", args0: _connectionId, args1: aue?.Message); - return ReportTcpSNIError(aue, SNIError.CertificateValidationErrorCode); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Authentication exception occurred: {1}", args0: _connectionId, args1: aue?.Message); + return ReportTcpSNIError(aue, SniError.CertificateValidationErrorCode); } catch (InvalidOperationException ioe) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Invalid Operation Exception occurred: {1}", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Invalid Operation Exception occurred: {1}", args0: _connectionId, args1: ioe?.Message); return ReportTcpSNIError(ioe); } _stream = _sslStream; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, SSL enabled successfully.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, SSL enabled successfully.", args0: _connectionId); return TdsEnums.SNI_SUCCESS; } } @@ -707,14 +709,14 @@ public override uint EnableSsl(uint options) /// public override void DisableSsl() { - using (TrySNIEventScope.Create(nameof(SNITCPHandle))) + using (TrySNIEventScope.Create(nameof(SniTcpHandle))) { _sslStream.Dispose(); _sslStream = null; _sslOverTdsStream?.Dispose(); _sslOverTdsStream = null; _stream = _tcpStream; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, SSL Disabled. Communication will continue on TCP Stream.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, SSL Disabled. Communication will continue on TCP Stream.", args0: _connectionId); } } @@ -730,12 +732,12 @@ private bool ValidateServerCertificate(object sender, X509Certificate serverCert { if (!_validateCert) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Certificate will not be validated.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Certificate will not be validated.", args0: _connectionId); return true; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Certificate will be validated for Target Server name", args0: _connectionId); - return SNICommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Certificate will be validated for Target Server name", args0: _connectionId); + return SniCommon.ValidateSslServerCertificate(_connectionId, _targetServer, _hostNameInCertificate, serverCertificate, _serverCertificateFilename, policyErrors); } /// @@ -752,7 +754,7 @@ public override void SetBufferSize(int bufferSize) /// /// SNI packet /// SNI error code - public override uint Send(SNIPacket packet) + public override uint Send(SniPacket packet) { bool releaseLock = false; try @@ -779,22 +781,22 @@ public override uint Send(SNIPacket packet) try { packet.WriteToStream(_stream); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Data sent to stream synchronously", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Data sent to stream synchronously", args0: _connectionId); return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); return ReportTcpSNIError(ode); } catch (SocketException se) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, SocketException occurred: {1}", args0: _connectionId, args1: se?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, SocketException occurred: {1}", args0: _connectionId, args1: se?.Message); return ReportTcpSNIError(se); } catch (IOException ioe) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, IOException occurred: {1}", args0: _connectionId, args1: ioe?.Message); return ReportTcpSNIError(ioe); } } @@ -819,17 +821,17 @@ public override uint Send(SNIPacket packet) /// - If less than -1 or equal to 0, results in a timeout error. /// /// SNI error code indicating the result of the operation. - public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) + public override uint Receive(out SniPacket packet, int timeoutInMilliseconds) { - SNIPacket errorPacket; + SniPacket errorPacket; lock (this) { packet = null; if (_socket == null) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Socket is null.", args0: _connectionId); - return ReportTcpSNIError(0, SNICommon.ConnOpenFailedError, Strings.SNI_ERROR_10); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Socket is null.", args0: _connectionId); + return ReportTcpSNIError(0, SniCommon.ConnOpenFailedError, Strings.SNI_ERROR_10); } try @@ -845,8 +847,8 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) else { // otherwise it is timeout for 0 or less than -1 - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Error 258, Timeout error occurred.", args0: _connectionId); - ReportTcpSNIError(0, SNICommon.ConnTimeoutError, Strings.SNI_ERROR_11); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Error 258, Timeout error occurred.", args0: _connectionId); + ReportTcpSNIError(0, SniCommon.ConnTimeoutError, Strings.SNI_ERROR_11); return TdsEnums.SNI_WAIT_TIMEOUT; } @@ -858,25 +860,25 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) errorPacket = packet; packet = null; var e = new Win32Exception(); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Win32 exception occurred: {1}", args0: _connectionId, args1: e?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Win32 exception occurred: {1}", args0: _connectionId, args1: e?.Message); return ReportErrorAndReleasePacket(errorPacket, (uint)e.NativeErrorCode, 0, e.Message); } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Data read from stream synchronously", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Data read from stream synchronously", args0: _connectionId); return TdsEnums.SNI_SUCCESS; } catch (ObjectDisposedException ode) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); return ReportErrorAndReleasePacket(errorPacket, ode); } catch (SocketException se) { errorPacket = packet; packet = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, Socket exception occurred: {1}", args0: _connectionId, args1: se?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, Socket exception occurred: {1}", args0: _connectionId, args1: se?.Message); return ReportErrorAndReleasePacket(errorPacket, se); } catch (IOException ioe) @@ -886,11 +888,11 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) uint errorCode = ReportErrorAndReleasePacket(errorPacket, ioe); if (ioe.InnerException is SocketException socketException && socketException.SocketErrorCode == SocketError.TimedOut) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, IO exception occurred with Wait Timeout (error 258): {1}", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, IO exception occurred with Wait Timeout (error 258): {1}", args0: _connectionId, args1: ioe?.Message); errorCode = TdsEnums.SNI_WAIT_TIMEOUT; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.ERR, "Connection Id {0}, IO exception occurred: {1}", args0: _connectionId, args1: ioe?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.ERR, "Connection Id {0}, IO exception occurred: {1}", args0: _connectionId, args1: ioe?.Message); return errorCode; } finally @@ -907,7 +909,7 @@ public override uint Receive(out SNIPacket packet, int timeoutInMilliseconds) /// /// Receive callback /// Send callback - public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyncCallback sendCallback) + public override void SetAsyncCallbacks(SniAsyncCallback receiveCallback, SniAsyncCallback sendCallback) { _receiveCallback = receiveCallback; _sendCallback = sendCallback; @@ -918,12 +920,12 @@ public override void SetAsyncCallbacks(SNIAsyncCallback receiveCallback, SNIAsyn /// /// SNI packet /// SNI error code - public override uint SendAsync(SNIPacket packet) + public override uint SendAsync(SniPacket packet) { - using (TrySNIEventScope.Create(nameof(SNITCPHandle))) + using (TrySNIEventScope.Create(nameof(SniTcpHandle))) { - packet.WriteToStreamAsync(_stream, _sendCallback, SNIProviders.TCP_PROV); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Data sent to stream asynchronously", args0: _connectionId); + packet.WriteToStreamAsync(_stream, _sendCallback, SniProviders.TCP_PROV); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Data sent to stream asynchronously", args0: _connectionId); return TdsEnums.SNI_SUCCESS_IO_PENDING; } } @@ -933,15 +935,15 @@ public override uint SendAsync(SNIPacket packet) /// /// SNI packet /// SNI error code - public override uint ReceiveAsync(ref SNIPacket packet) + public override uint ReceiveAsync(ref SniPacket packet) { - SNIPacket errorPacket; + SniPacket errorPacket; packet = RentPacket(headerSize: 0, dataSize: _bufferSize); packet.SetAsyncIOCompletionCallback(_receiveCallback); try { packet.ReadFromStreamAsync(_stream); - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Data received from stream asynchronously", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Data received from stream asynchronously", args0: _connectionId); return TdsEnums.SNI_SUCCESS_IO_PENDING; } catch (Exception e) when (e is ObjectDisposedException || e is SocketException || e is IOException) @@ -972,18 +974,18 @@ public override uint CheckConnection() // return true we can safely determine that the connection is no longer active. if (!_socket.Connected || (_socket.Poll(100, SelectMode.SelectRead) && _socket.Available == 0)) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Socket not usable.", args0: _connectionId); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Socket not usable.", args0: _connectionId); return TdsEnums.SNI_ERROR; } } catch (SocketException se) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, Socket Exception occurred: {1}", args0: _connectionId, args1: se?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, Socket Exception occurred: {1}", args0: _connectionId, args1: se?.Message); return ReportTcpSNIError(se); } catch (ObjectDisposedException ode) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SNITCPHandle), EventType.INFO, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SniTcpHandle), EventType.INFO, "Connection Id {0}, ObjectDisposedException occurred: {1}", args0: _connectionId, args1: ode?.Message); return ReportTcpSNIError(ode); } @@ -993,16 +995,16 @@ public override uint CheckConnection() private uint ReportTcpSNIError(Exception sniException, uint nativeErrorCode = 0) { _status = TdsEnums.SNI_ERROR; - return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, SNICommon.InternalExceptionError, sniException, nativeErrorCode); + return SniCommon.ReportSNIError(SniProviders.TCP_PROV, SniCommon.InternalExceptionError, sniException, nativeErrorCode); } private uint ReportTcpSNIError(uint nativeError, uint sniError, string errorMessage) { _status = TdsEnums.SNI_ERROR; - return SNICommon.ReportSNIError(SNIProviders.TCP_PROV, nativeError, sniError, errorMessage); + return SniCommon.ReportSNIError(SniProviders.TCP_PROV, nativeError, sniError, errorMessage); } - private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniException) + private uint ReportErrorAndReleasePacket(SniPacket packet, Exception sniException) { if (packet != null) { @@ -1011,7 +1013,7 @@ private uint ReportErrorAndReleasePacket(SNIPacket packet, Exception sniExceptio return ReportTcpSNIError(sniException); } - private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uint sniError, string errorMessage) + private uint ReportErrorAndReleasePacket(SniPacket packet, uint nativeError, uint sniError, string errorMessage) { if (packet != null) { @@ -1020,7 +1022,7 @@ private uint ReportErrorAndReleasePacket(SNIPacket packet, uint nativeError, uin return ReportTcpSNIError(nativeError, sniError, errorMessage); } -#if DEBUG + #if DEBUG /// /// Test handle for killing underlying connection /// @@ -1028,7 +1030,7 @@ public override void KillConnection() { _socket.Shutdown(SocketShutdown.Both); } -#endif + #endif internal static void SetKeepAliveValues(ref Socket socket) { @@ -1038,3 +1040,5 @@ internal static void SetKeepAliveValues(ref Socket socket) } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SslOverTdsStream.NetCoreApp.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SslOverTdsStream.NetCoreApp.cs similarity index 96% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SslOverTdsStream.NetCoreApp.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SslOverTdsStream.NetCoreApp.cs index be8d1a0160..ff3358c50a 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SslOverTdsStream.NetCoreApp.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SslOverTdsStream.NetCoreApp.cs @@ -2,26 +2,28 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Buffers; using System.Threading; using System.Threading.Tasks; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { internal sealed partial class SslOverTdsStream { - public override int Read(byte[] buffer, int offset, int count) - => Read(buffer.AsSpan(offset, count)); + public override int Read(byte[] buffer, int offset, int count) => + Read(buffer.AsSpan(offset, count)); - public override void Write(byte[] buffer, int offset, int count) - => Write(buffer.AsSpan(offset, count)); + public override void Write(byte[] buffer, int offset, int count) => + Write(buffer.AsSpan(offset, count)); - public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - => ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); + public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + ReadAsync(new Memory(buffer, offset, count), cancellationToken).AsTask(); - public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) - => WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken).AsTask(); + public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => + WriteAsync(new ReadOnlyMemory(buffer, offset, count), cancellationToken).AsTask(); public override int Read(Span buffer) { @@ -293,3 +295,5 @@ public override async ValueTask WriteAsync(ReadOnlyMemory buffer, Cancella } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SslOverTdsStream.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SslOverTdsStream.netcore.cs similarity index 98% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SslOverTdsStream.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SslOverTdsStream.netcore.cs index e0f48a28d3..ae3dae0c06 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SslOverTdsStream.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SslOverTdsStream.netcore.cs @@ -2,11 +2,13 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.IO; using System.IO.Pipes; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { /// /// SSL encapsulated over TDS transport. During SSL handshake, SSL packets are @@ -123,3 +125,5 @@ private static void SetupPreLoginPacketHeader(byte[] buffer, int dataLength, int } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SsrpClient.netcore.cs similarity index 95% rename from src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs rename to src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SsrpClient.netcore.cs index 085551c16e..1aebffefbe 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/SNI/SSRP.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/ManagedSni/SsrpClient.netcore.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#if NET + using System; using System.Collections.Generic; using System.Diagnostics; @@ -12,9 +14,9 @@ using System.Threading.Tasks; using Microsoft.Data.ProviderBase; -namespace Microsoft.Data.SqlClient.SNI +namespace Microsoft.Data.SqlClient.ManagedSni { - internal sealed class SSRP + internal sealed class SsrpClient { private const char SemicolonSeparator = ';'; private const int SqlServerBrowserPort = 1434; //port SQL Server Browser @@ -38,7 +40,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc { Debug.Assert(!string.IsNullOrWhiteSpace(browserHostName), "browserHostName should not be null, empty, or whitespace"); Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace"); - using (TrySNIEventScope.Create(nameof(SSRP))) + using (TrySNIEventScope.Create(nameof(SsrpClient))) { byte[] instanceInfoRequest = CreateInstanceInfoRequest(instanceName); byte[] responsePacket = null; @@ -54,7 +56,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc // the same error as if the response was empty. The higher error suits all scenarios. // But log it, just in case there is a different, underlying issue that support needs // to troubleshoot. - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.ERR, "SocketException Message = {0}", args0: se?.Message); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.ERR, "SocketException Message = {0}", args0: se?.Message); throw; } @@ -86,7 +88,7 @@ internal static int GetPortByInstanceName(string browserHostName, string instanc private static byte[] CreateInstanceInfoRequest(string instanceName) { Debug.Assert(!string.IsNullOrWhiteSpace(instanceName), "instanceName should not be null, empty, or whitespace"); - using (TrySNIEventScope.Create(nameof(SSRP))) + using (TrySNIEventScope.Create(nameof(SsrpClient))) { const byte ClntUcastInst = 0x04; instanceName += char.MinValue; @@ -170,7 +172,7 @@ private class SsrpResult /// response packet from UDP server private static byte[] SendUDPRequest(string browserHostname, int port, byte[] requestPacket, TimeoutTimer timeout, bool allIPsInParallel, SqlConnectionIPAddressPreference ipPreference) { - using (TrySNIEventScope.Create(nameof(SSRP))) + using (TrySNIEventScope.Create(nameof(SsrpClient))) { Debug.Assert(!string.IsNullOrWhiteSpace(browserHostname), "browserhostname should not be null, empty, or whitespace"); Debug.Assert(port >= 0 && port <= 65535, "Invalid port"); @@ -188,8 +190,8 @@ private static byte[] SendUDPRequest(string browserHostname, int port, byte[] re } IPAddress[] ipAddresses = timeout.IsInfinite - ? SNICommon.GetDnsIpAddresses(browserHostname) - : SNICommon.GetDnsIpAddresses(browserHostname, timeout); + ? SniCommon.GetDnsIpAddresses(browserHostname) + : SniCommon.GetDnsIpAddresses(browserHostname, timeout); Debug.Assert(ipAddresses.Length > 0, "DNS should throw if zero addresses resolve"); IPAddress[] ipv4Addresses = null; @@ -338,10 +340,10 @@ private static SsrpResult SendUDPRequest(IPEndPoint endPoint, byte[] requestPack Task sendTask = client.SendAsync(requestPacket, requestPacket.Length, endPoint); Task receiveTask = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, "Waiting for UDP Client to fetch Port info."); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "Waiting for UDP Client to fetch Port info."); if (sendTask.Wait(sendTimeOutMs) && (receiveTask = client.ReceiveAsync()).Wait(receiveTimeOutMs)) { - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, "Received Port info from UDP Client."); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "Received Port info from UDP Client."); result.ResponsePacket = receiveTask.Result.Buffer; } } @@ -358,7 +360,7 @@ private static SsrpResult SendUDPRequest(IPEndPoint endPoint, byte[] requestPack { result.Error = e; } - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "SendUDPRequest ({0}) resulted in exception: {1}", args0: endPoint.ToString(), args1: e.Message); } @@ -368,14 +370,14 @@ private static SsrpResult SendUDPRequest(IPEndPoint endPoint, byte[] requestPack else { result.Error = ae; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "SendUDPRequest ({0}) resulted in exception: {1}", args0: endPoint.ToString(), args1: ae.Message); } } catch (Exception e) { result.Error = e; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "SendUDPRequest ({0}) resulted in exception: {1}", args0: endPoint.ToString(), args1: e.Message); } @@ -396,13 +398,13 @@ internal static string SendBroadcastUDPRequest() // https://docs.microsoft.com/en-us/openspecs/windows_protocols/mc-sqlr/f2640a2d-3beb-464b-a443-f635842ebc3e#Appendix_A_3 int currentTimeOut = FirstTimeoutForCLNT_BCAST_EX; - using (TrySNIEventScope.Create(nameof(SSRP))) + using (TrySNIEventScope.Create(nameof(SsrpClient))) { using (UdpClient clientListener = new UdpClient()) { Task sendTask = clientListener.SendAsync(CLNT_BCAST_EX_Request, CLNT_BCAST_EX_Request.Length, new IPEndPoint(IPAddress.Broadcast, SqlServerBrowserPort)); Task receiveTask = null; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, "Waiting for UDP Client to fetch list of instances."); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "Waiting for UDP Client to fetch list of instances."); Stopwatch sw = new Stopwatch(); //for waiting until 15 sec elapsed sw.Start(); try @@ -410,7 +412,7 @@ internal static string SendBroadcastUDPRequest() while ((receiveTask = clientListener.ReceiveAsync()).Wait(currentTimeOut) && sw.ElapsedMilliseconds <= ReceiveMAXTimeoutsForCLNT_BCAST_EX && receiveTask != null) { currentTimeOut = ReceiveTimeoutsForCLNT_BCAST_EX; - SqlClientEventSource.Log.TrySNITraceEvent(nameof(SSRP), EventType.INFO, "Received instnace info from UDP Client."); + SqlClientEventSource.Log.TrySNITraceEvent(nameof(SsrpClient), EventType.INFO, "Received instnace info from UDP Client."); if (receiveTask.Result.Buffer.Length < ValidResponseSizeForCLNT_BCAST_EX) //discard invalid response { response.Append(Encoding.ASCII.GetString(receiveTask.Result.Buffer, ServerResponseHeaderSizeForCLNT_BCAST_EX, receiveTask.Result.Buffer.Length - ServerResponseHeaderSizeForCLNT_BCAST_EX)); //RESP_DATA(VARIABLE) - 3 (RESP_SIZE + SVR_RESP) @@ -462,3 +464,5 @@ private static void SplitIPv4AndIPv6(IPAddress[] input, out IPAddress[] ipv4Addr } } } + +#endif diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.Windows.cs index 9e8c3f6fc7..b73f063a9c 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.Windows.cs @@ -30,38 +30,40 @@ internal readonly ref struct PacketHandle /// which is due to be passed to the native SNI layer. /// public const int NativePacketType = 2; -#if NET + + #if NET /// /// PacketHandle is transporting a managed packet. The ManagedPacket field is valid. /// A PacketHandle used by the managed SNI layer will always have this type. /// public const int ManagedPacketType = 3; - public readonly SNI.SNIPacket ManagedPacket; -#endif + public readonly ManagedSni.SniPacket ManagedPacket; + #endif + public readonly SNIPacket NativePacket; public readonly IntPtr NativePointer; public readonly int Type; -#if NET - private PacketHandle(IntPtr nativePointer, SNIPacket nativePacket, SNI.SNIPacket managedPacket, int type) + #if NET + private PacketHandle(IntPtr nativePointer, SNIPacket nativePacket, ManagedSni.SniPacket managedPacket, int type) { Type = type; ManagedPacket = managedPacket; NativePointer = nativePointer; NativePacket = nativePacket; } -#else + #else private PacketHandle(IntPtr nativePointer, SNIPacket nativePacket, int type) { Type = type; NativePointer = nativePointer; NativePacket = nativePacket; } -#endif + #endif -#if NET - public static PacketHandle FromManagedPacket(SNI.SNIPacket managedPacket) => + #if NET + public static PacketHandle FromManagedPacket(ManagedSni.SniPacket managedPacket) => new PacketHandle(default, default, managedPacket, ManagedPacketType); public static PacketHandle FromNativePointer(IntPtr nativePointer) => @@ -69,12 +71,12 @@ public static PacketHandle FromNativePointer(IntPtr nativePointer) => public static PacketHandle FromNativePacket(SNIPacket nativePacket) => new PacketHandle(default, nativePacket, default, NativePacketType); -#else + #else public static PacketHandle FromNativePointer(IntPtr nativePointer) => new PacketHandle(nativePointer, default, NativePointerType); public static PacketHandle FromNativePacket(SNIPacket nativePacket) => new PacketHandle(default, nativePacket, NativePacketType); -#endif + #endif } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.netcore.Unix.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.netcore.Unix.cs index 7a560a1896..42bf62c5f5 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.netcore.Unix.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/PacketHandle.netcore.Unix.cs @@ -36,16 +36,16 @@ internal readonly ref struct PacketHandle /// public const int ManagedPacketType = 3; - public readonly SNI.SNIPacket ManagedPacket; + public readonly ManagedSni.SniPacket ManagedPacket; public readonly int Type; - private PacketHandle(SNI.SNIPacket managedPacket, int type) + private PacketHandle(ManagedSni.SniPacket managedPacket, int type) { Type = type; ManagedPacket = managedPacket; } - public static PacketHandle FromManagedPacket(SNI.SNIPacket managedPacket) => + public static PacketHandle FromManagedPacket(ManagedSni.SniPacket managedPacket) => new PacketHandle(managedPacket, ManagedPacketType); } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.Windows.cs index 516c4bc37d..b5b2068961 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.Windows.cs @@ -18,13 +18,14 @@ internal readonly ref struct SessionHandle public const int NativeHandleType = 1; public const int ManagedHandleType = 2; + public readonly ManagedSni.SniHandle ManagedHandle; public readonly int Type; - public readonly SNI.SNIHandle ManagedHandle; #endif + public readonly SNIHandle NativeHandle; #if NET - public SessionHandle(SNI.SNIHandle managedHandle, SNIHandle nativeHandle, int type) + public SessionHandle(ManagedSni.SniHandle managedHandle, SNIHandle nativeHandle, int type) { Type = type; ManagedHandle = managedHandle; @@ -33,9 +34,11 @@ public SessionHandle(SNI.SNIHandle managedHandle, SNIHandle nativeHandle, int ty public bool IsNull => (Type == NativeHandleType) ? NativeHandle is null : ManagedHandle is null; - public static SessionHandle FromManagedSession(SNI.SNIHandle managedSessionHandle) => new SessionHandle(managedSessionHandle, default, ManagedHandleType); + public static SessionHandle FromManagedSession(ManagedSni.SniHandle managedSessionHandle) => + new SessionHandle(managedSessionHandle, default, ManagedHandleType); - public static SessionHandle FromNativeHandle(SNIHandle nativeSessionHandle) => new SessionHandle(default, nativeSessionHandle, NativeHandleType); + public static SessionHandle FromNativeHandle(SNIHandle nativeSessionHandle) => + new SessionHandle(default, nativeSessionHandle, NativeHandleType); #else public SessionHandle(SNIHandle nativeHandle) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.netcore.Unix.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.netcore.Unix.cs index 0ea1d30a83..8465da3684 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.netcore.Unix.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SessionHandle.netcore.Unix.cs @@ -19,10 +19,10 @@ internal readonly ref struct SessionHandle public const int NativeHandleType = 1; public const int ManagedHandleType = 2; + public readonly ManagedSni.SniHandle ManagedHandle; public readonly int Type; - public readonly SNI.SNIHandle ManagedHandle; - public SessionHandle(SNI.SNIHandle managedHandle, int type) + public SessionHandle(ManagedSni.SniHandle managedHandle, int type) { Type = type; ManagedHandle = managedHandle; @@ -30,7 +30,8 @@ public SessionHandle(SNI.SNIHandle managedHandle, int type) public bool IsNull => ManagedHandle is null; - public static SessionHandle FromManagedSession(SNI.SNIHandle managedSessionHandle) => new SessionHandle(managedSessionHandle, ManagedHandleType); + public static SessionHandle FromManagedSession(ManagedSni.SniHandle managedSessionHandle) => + new SessionHandle(managedSessionHandle, ManagedHandleType); } } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Unix.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Unix.cs index 86bc3013a9..f7cb55d451 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Unix.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Unix.cs @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. -using Microsoft.Data.SqlClient.SNI; +using Microsoft.Data.SqlClient.ManagedSni; namespace Microsoft.Data.SqlClient { @@ -13,14 +13,14 @@ internal sealed class TdsParserStateObjectFactory public static readonly TdsParserStateObjectFactory Singleton = new TdsParserStateObjectFactory(); - public EncryptionOptions EncryptionOptions => SNI.SNILoadHandle.SingletonInstance.Options; + public EncryptionOptions EncryptionOptions => ManagedSni.SniLoadHandle.SingletonInstance.Options; - public uint SNIStatus => SNI.SNILoadHandle.SingletonInstance.Status; + public uint SNIStatus => ManagedSni.SniLoadHandle.SingletonInstance.Status; /// /// Verify client encryption possibility. /// - public bool ClientOSEncryptionSupport => SNI.SNILoadHandle.SingletonInstance.ClientOSEncryptionSupport; + public bool ClientOSEncryptionSupport => ManagedSni.SniLoadHandle.SingletonInstance.ClientOSEncryptionSupport; public TdsParserStateObject CreateTdsParserStateObject(TdsParser parser) { diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs index 3e849231ab..8b8fe9186b 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserStateObjectFactory.Windows.cs @@ -2,9 +2,9 @@ // 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; #if NET -using Microsoft.Data.SqlClient.SNI; +using System; +using Microsoft.Data.SqlClient.ManagedSni; #endif namespace Microsoft.Data.SqlClient @@ -27,14 +27,14 @@ internal sealed class TdsParserStateObjectFactory public EncryptionOptions EncryptionOptions => #if NET - UseManagedSNI ? SNI.SNILoadHandle.SingletonInstance.Options : SNILoadHandle.SingletonInstance.Options; + UseManagedSNI ? ManagedSni.SniLoadHandle.SingletonInstance.Options : SNILoadHandle.SingletonInstance.Options; #else SNILoadHandle.SingletonInstance.Options; #endif public uint SNIStatus => #if NET - UseManagedSNI ? SNI.SNILoadHandle.SingletonInstance.Status : SNILoadHandle.SingletonInstance.Status; + UseManagedSNI ? ManagedSni.SniLoadHandle.SingletonInstance.Status : SNILoadHandle.SingletonInstance.Status; #else SNILoadHandle.SingletonInstance.Status; #endif @@ -44,7 +44,7 @@ internal sealed class TdsParserStateObjectFactory /// public bool ClientOSEncryptionSupport => #if NET - UseManagedSNI ? SNI.SNILoadHandle.SingletonInstance.ClientOSEncryptionSupport : SNILoadHandle.SingletonInstance.ClientOSEncryptionSupport; + UseManagedSNI ? ManagedSni.SniLoadHandle.SingletonInstance.ClientOSEncryptionSupport : SNILoadHandle.SingletonInstance.ClientOSEncryptionSupport; #else SNILoadHandle.SingletonInstance.ClientOSEncryptionSupport; #endif diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs index c9f054a882..4086c73265 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/InternalConnectionWrapper.cs @@ -128,7 +128,7 @@ public void KillConnection() object stateObject = TdsParserHelper.GetStateObject(tdsParser); Assembly assembly = Assembly.Load(new AssemblyName(typeof(SqlConnection).GetTypeInfo().Assembly.FullName)); - Type sniHandleType = assembly.GetType("Microsoft.Data.SqlClient.SNI.SNIHandle"); + Type sniHandleType = assembly.GetType("Microsoft.Data.SqlClient.ManagedSni.SniHandle"); MethodInfo killConn = null; if (sniHandleType is not null) diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs index 625f0e9d9b..dadbb5c58c 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/Common/SystemDataInternals/TdsParserStateObjectHelper.cs @@ -45,7 +45,7 @@ static TdsParserStateObjectHelper() // These managed SNI handles are allowed to be null, since they // won't exist in .NET Framework builds. s_tdsParserStateObjectManaged = - assembly.GetType("Microsoft.Data.SqlClient.SNI.TdsParserStateObjectManaged"); + assembly.GetType("Microsoft.Data.SqlClient.ManagedSni.TdsParserStateObjectManaged"); s_tdsParserStateObjectManagedSessionHandle = null; if (s_tdsParserStateObjectManaged is not null) { @@ -101,7 +101,7 @@ internal static object GetSessionHandle(object stateObject) { throw new ArgumentException("Library being tested does not implement TdsParserStateObjectManaged", nameof(stateObject)); } - if (! s_tdsParserStateObjectManaged.IsInstanceOfType(stateObject)) + if (!s_tdsParserStateObjectManaged.IsInstanceOfType(stateObject)) { throw new ArgumentException("Object provided was not a TdsParserStateObjectManaged", nameof(stateObject)); } diff --git a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs index 9f6673332c..24e5a277af 100644 --- a/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs +++ b/src/Microsoft.Data.SqlClient/tests/ManualTests/SQL/InstanceNameTest/InstanceNameTest.cs @@ -160,9 +160,9 @@ private static string GetSPNInfo(string dataSource, string inInstanceName) { Assembly sqlConnectionAssembly = Assembly.GetAssembly(typeof(SqlConnection)); - Type sniProxyType = sqlConnectionAssembly.GetType("Microsoft.Data.SqlClient.SNI.SNIProxy"); - Type ssrpType = sqlConnectionAssembly.GetType("Microsoft.Data.SqlClient.SNI.SSRP"); - Type dataSourceType = sqlConnectionAssembly.GetType("Microsoft.Data.SqlClient.SNI.DataSource"); + Type sniProxyType = sqlConnectionAssembly.GetType("Microsoft.Data.SqlClient.ManagedSni.SniProxy"); + Type ssrpType = sqlConnectionAssembly.GetType("Microsoft.Data.SqlClient.ManagedSni.SsrpClient"); + Type dataSourceType = sqlConnectionAssembly.GetType("Microsoft.Data.SqlClient.ManagedSni.DataSource"); Type timeoutTimerType = sqlConnectionAssembly.GetType("Microsoft.Data.ProviderBase.TimeoutTimer"); Type[] dataSourceConstructorTypesArray = new Type[] { typeof(string) };