diff --git a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs index e6b9a685dc..6f045833ce 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/LocalDBAPI.Windows.cs @@ -24,14 +24,14 @@ private static IntPtr UserInstanceDLLHandle { if (s_userInstanceDLLHandle == IntPtr.Zero) { - SniNativeWrapper.SNIQueryInfo(QueryType.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); + SniNativeWrapper.SniQueryInfo(QueryType.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { SqlClientEventSource.Log.TryTraceEvent("LocalDBAPI.UserInstanceDLLHandle | LocalDB - handle obtained"); } else { - SniNativeWrapper.SNIGetLastError(out SniError sniError); + SniNativeWrapper.SniGetLastError(out SniError sniError); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_FailedGetDLLHandle"), sniError: sniError.sniError); } } 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 e2d86dc210..e0d18d5295 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 @@ -75,7 +75,7 @@ private SNIErrorDetails GetSniErrorDetails() } else { - SniNativeWrapper.SNIGetLastError(out SniError sniError); + SniNativeWrapper.SniGetLastError(out 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/TdsParserStateObjectNative.cs b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs index 3534b61740..d5c6143d8c 100644 --- a/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs +++ b/src/Microsoft.Data.SqlClient/netcore/src/Microsoft/Data/SqlClient/TdsParserStateObjectNative.cs @@ -99,7 +99,7 @@ internal override void AssignPendingDNSInfo(string userProtocol, string DNSCache result = SniNativeWrapper.SniGetConnectionPort(Handle, ref portFromSNI); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionPort"); - result = SniNativeWrapper.SniGetConnectionIPString(Handle, ref IPStringFromSNI); + result = SniNativeWrapper.SniGetConnectionIpString(Handle, ref IPStringFromSNI); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionIPString"); pendingDNSInfo = new SQLDNSInfo(DNSCacheKey, null, null, portFromSNI.ToString()); @@ -187,7 +187,7 @@ internal override void CreatePhysicalSNIHandle( protected override uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize) { Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer"); - return SniNativeWrapper.SNIPacketGetData(packet.NativePointer, _inBuff, ref dataSize); + return SniNativeWrapper.SniPacketGetData(packet.NativePointer, _inBuff, ref dataSize); } protected override bool CheckPacket(PacketHandle packet, TaskCompletionSource source) @@ -267,7 +267,7 @@ internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint throw ADP.ClosedConnectionError(); } IntPtr readPacketPtr = IntPtr.Zero; - error = SniNativeWrapper.SNIReadSyncOverAsync(handle, ref readPacketPtr, GetTimeoutRemaining()); + error = SniNativeWrapper.SniReadSyncOverAsync(handle, ref readPacketPtr, GetTimeoutRemaining()); return PacketHandle.FromNativePointer(readPacketPtr); } @@ -284,20 +284,20 @@ internal override bool IsPacketEmpty(PacketHandle readPacket) internal override void ReleasePacket(PacketHandle syncReadPacket) { Debug.Assert(syncReadPacket.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer"); - SniNativeWrapper.SNIPacketRelease(syncReadPacket.NativePointer); + SniNativeWrapper.SniPacketRelease(syncReadPacket.NativePointer); } internal override uint CheckConnection() { SNIHandle handle = Handle; - return handle == null ? TdsEnums.SNI_SUCCESS : SniNativeWrapper.SNICheckConnection(handle); + return handle == null ? TdsEnums.SNI_SUCCESS : SniNativeWrapper.SniCheckConnection(handle); } internal override PacketHandle ReadAsync(SessionHandle handle, out uint error) { Debug.Assert(handle.Type == SessionHandle.NativeHandleType, "unexpected handle type when requiring NativePointer"); IntPtr readPacketPtr = IntPtr.Zero; - error = SniNativeWrapper.SNIReadAsync(handle.NativeHandle, ref readPacketPtr); + error = SniNativeWrapper.SniReadAsync(handle.NativeHandle, ref readPacketPtr); return PacketHandle.FromNativePointer(readPacketPtr); } @@ -313,7 +313,7 @@ internal override PacketHandle CreateAndSetAttentionPacket() internal override uint WritePacket(PacketHandle packet, bool sync) { Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket"); - return SniNativeWrapper.SNIWritePacket(Handle, packet.NativePacket, sync); + return SniNativeWrapper.SniWritePacket(Handle, packet.NativePacket, sync); } internal override PacketHandle AddPacketToPendingList(PacketHandle packetToAdd) @@ -346,7 +346,7 @@ internal override PacketHandle GetResetWritePacket(int dataSize) { if (_sniPacket != null) { - SniNativeWrapper.SNIPacketReset(Handle, IoType.WRITE, _sniPacket, ConsumerNumber.SNI_Consumer_SNI); + SniNativeWrapper.SniPacketReset(Handle, IoType.WRITE, _sniPacket, ConsumerNumber.SNI_Consumer_SNI); } else { @@ -375,17 +375,17 @@ internal override void ClearAllWritePackets() internal override void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed) { Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket"); - SniNativeWrapper.SNIPacketSetData(packet.NativePacket, buffer, bytesUsed); + SniNativeWrapper.SniPacketSetData(packet.NativePacket, buffer, bytesUsed); } internal override uint SniGetConnectionId(ref Guid clientConnectionId) => SniNativeWrapper.SniGetConnectionId(Handle, ref clientConnectionId); internal override uint DisableSsl() - => SniNativeWrapper.SNIRemoveProvider(Handle, Provider.SSL_PROV); + => SniNativeWrapper.SniRemoveProvider(Handle, Provider.SSL_PROV); internal override uint EnableMars(ref uint info) - => SniNativeWrapper.SNIAddProvider(Handle, Provider.SMUX_PROV, ref info); + => SniNativeWrapper.SniAddProvider(Handle, Provider.SMUX_PROV, ref info); internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCertificateFilename) { @@ -395,15 +395,15 @@ internal override uint EnableSsl(ref uint info, bool tlsFirst, string serverCert authInfo.serverCertFileName = serverCertificateFilename; // Add SSL (Encryption) SNI provider. - return SniNativeWrapper.SNIAddProvider(Handle, Provider.SSL_PROV, ref authInfo); + return SniNativeWrapper.SniAddProvider(Handle, Provider.SSL_PROV, ref authInfo); } internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize) - => SniNativeWrapper.SNISetInfo(Handle, QueryType.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize); + => SniNativeWrapper.SniSetInfo(Handle, QueryType.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize); internal override uint WaitForSSLHandShakeToComplete(out int protocolVersion) { - uint returnValue = SniNativeWrapper.SNIWaitForSSLHandshakeToComplete(Handle, GetTimeoutRemaining(), out uint nativeProtocolVersion); + uint returnValue = SniNativeWrapper.SniWaitForSslHandshakeToComplete(Handle, GetTimeoutRemaining(), out uint nativeProtocolVersion); var nativeProtocol = (NativeProtocols)nativeProtocolVersion; #pragma warning disable CA5398 // Avoid hardcoded SslProtocols values @@ -472,7 +472,7 @@ public SNIPacket Take(SNIHandle sniHandle) { // Success - reset the packet packet = _packets.Pop(); - SniNativeWrapper.SNIPacketReset(sniHandle, IoType.WRITE, packet, ConsumerNumber.SNI_Consumer_SNI); + SniNativeWrapper.SniPacketReset(sniHandle, IoType.WRITE, packet, ConsumerNumber.SNI_Consumer_SNI); } else { diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs index 2d6192f6bf..085971fdd2 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/LocalDBAPI.cs @@ -81,7 +81,7 @@ static IntPtr UserInstanceDLLHandle Monitor.Enter(s_dllLock, ref lockTaken); if (s_userInstanceDLLHandle == IntPtr.Zero) { - SniNativeWrapper.SNIQueryInfo(QueryType.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); + SniNativeWrapper.SniQueryInfo(QueryType.SNI_QUERY_LOCALDB_HMODULE, ref s_userInstanceDLLHandle); if (s_userInstanceDLLHandle != IntPtr.Zero) { SqlClientEventSource.Log.TryTraceEvent(" LocalDB - handle obtained"); @@ -89,7 +89,7 @@ static IntPtr UserInstanceDLLHandle else { SniError sniError = new SniError(); - SniNativeWrapper.SNIGetLastError(out sniError); + SniNativeWrapper.SniGetLastError(out sniError); throw CreateLocalDBException(errorMessage: StringsHelper.GetString("LocalDB_FailedGetDLLHandle"), sniError: sniError.sniError); } } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs index e845f1bdb9..e4f6d98394 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.cs @@ -700,7 +700,7 @@ internal void RemoveEncryption() uint error = 0; // Remove SSL (Encryption) SNI provider since we only wanted to encrypt login. - error = SniNativeWrapper.SNIRemoveProvider(_physicalStateObj.Handle, Provider.SSL_PROV); + error = SniNativeWrapper.SniRemoveProvider(_physicalStateObj.Handle, Provider.SSL_PROV); if (error != TdsEnums.SNI_SUCCESS) { _physicalStateObj.AddError(ProcessSNIError(_physicalStateObj)); @@ -727,7 +727,7 @@ internal void EnableMars() uint info = 0; // Add SMUX (MARS) SNI provider. - error = SniNativeWrapper.SNIAddProvider(_pMarsPhysicalConObj.Handle, Provider.SMUX_PROV, ref info); + error = SniNativeWrapper.SniAddProvider(_pMarsPhysicalConObj.Handle, Provider.SMUX_PROV, ref info); if (error != TdsEnums.SNI_SUCCESS) { @@ -748,12 +748,12 @@ internal void EnableMars() { _pMarsPhysicalConObj.IncrementPendingCallbacks(); - error = SniNativeWrapper.SNIReadAsync(_pMarsPhysicalConObj.Handle, ref temp); + error = SniNativeWrapper.SniReadAsync(_pMarsPhysicalConObj.Handle, ref temp); if (temp != IntPtr.Zero) { // Be sure to release packet, otherwise it will be leaked by native. - SniNativeWrapper.SNIPacketRelease(temp); + SniNativeWrapper.SniPacketRelease(temp); } } Debug.Assert(IntPtr.Zero == temp, "unexpected syncReadPacket without corresponding SNIPacketRelease"); @@ -1026,7 +1026,7 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ Debug.Assert((_encryptionOption & EncryptionOptions.CLIENT_CERT) == 0, "Client certificate authentication support has been removed"); - error = SniNativeWrapper.SNIAddProvider(_physicalStateObj.Handle, Provider.SSL_PROV, authInfo); + error = SniNativeWrapper.SniAddProvider(_physicalStateObj.Handle, Provider.SSL_PROV, authInfo); if (error != TdsEnums.SNI_SUCCESS) { @@ -1038,7 +1038,7 @@ private void EnableSsl(uint info, SqlConnectionEncryptOption encrypt, bool integ // wait for SSL handshake to complete, so that the SSL context is fully negotiated before we try to use its // Channel Bindings as part of the Windows Authentication context build (SSL handshake must complete // before calling SNISecGenClientContext). - error = SniNativeWrapper.SNIWaitForSSLHandshakeToComplete(_physicalStateObj.Handle, _physicalStateObj.GetTimeoutRemaining(), out uint protocolVersion); + error = SniNativeWrapper.SniWaitForSslHandshakeToComplete(_physicalStateObj.Handle, _physicalStateObj.GetTimeoutRemaining(), out uint protocolVersion); if (error != TdsEnums.SNI_SUCCESS) { @@ -1592,7 +1592,7 @@ internal SqlError ProcessSNIError(TdsParserStateObject stateObj) Debug.Assert(SniContext.Undefined != stateObj.DebugOnlyCopyOfSniContext || ((_fMARS) && ((_state == TdsParserState.Closed) || (_state == TdsParserState.Broken))), "SniContext must not be None"); #endif SniError sniError = new SniError(); - SniNativeWrapper.SNIGetLastError(out sniError); + SniNativeWrapper.SniGetLastError(out sniError); if (sniError.sniError != 0) { @@ -2915,7 +2915,7 @@ private TdsOperationStatus TryProcessEnvChange(int tokenLength, TdsParserStateOb // Update SNI ConsumerInfo value to be resulting packet size uint unsignedPacketSize = (uint)packetSize; - uint bufferSizeResult = SniNativeWrapper.SNISetInfo(_physicalStateObj.Handle, QueryType.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize); + uint bufferSizeResult = SniNativeWrapper.SniSetInfo(_physicalStateObj.Handle, QueryType.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize); Debug.Assert(bufferSizeResult == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SNISetInfo"); } diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.netfx.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.netfx.cs index 32d9b091ce..82594a73bd 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.netfx.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParser.netfx.cs @@ -157,7 +157,7 @@ internal void AssignPendingDNSInfo(string userProtocol, string DNSCacheKey) Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionPort"); - result = SniNativeWrapper.SniGetConnectionIPString(_physicalStateObj.Handle, ref IPStringFromSNI); + result = SniNativeWrapper.SniGetConnectionIpString(_physicalStateObj.Handle, ref IPStringFromSNI); Debug.Assert(result == TdsEnums.SNI_SUCCESS, "Unexpected failure state upon calling SniGetConnectionIPString"); _connHandler.pendingSQLDNSObject = new SQLDNSInfo(DNSCacheKey, null, null, portFromSNI.ToString()); diff --git a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs index 0ce58d120a..fba8fd35e3 100644 --- a/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs +++ b/src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/TdsParserStateObject.netfx.cs @@ -285,20 +285,20 @@ internal PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error) { SNIHandle handle = Handle ?? throw ADP.ClosedConnectionError(); PacketHandle readPacket = default; - error = SniNativeWrapper.SNIReadSyncOverAsync(handle, ref readPacket, timeoutRemaining); + error = SniNativeWrapper.SniReadSyncOverAsync(handle, ref readPacket, timeoutRemaining); return readPacket; } internal PacketHandle ReadAsync(SessionHandle handle, out uint error) { PacketHandle readPacket = default; - error = SniNativeWrapper.SNIReadAsync(handle.NativeHandle, ref readPacket); + error = SniNativeWrapper.SniReadAsync(handle.NativeHandle, ref readPacket); return readPacket; } - internal uint CheckConnection() => SniNativeWrapper.SNICheckConnection(Handle); + internal uint CheckConnection() => SniNativeWrapper.SniCheckConnection(Handle); - internal void ReleasePacket(PacketHandle syncReadPacket) => SniNativeWrapper.SNIPacketRelease(syncReadPacket); + internal void ReleasePacket(PacketHandle syncReadPacket) => SniNativeWrapper.SniPacketRelease(syncReadPacket); [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal int DecrementPendingCallbacks(bool release) @@ -416,7 +416,7 @@ internal bool ValidateSNIConnection() SNIHandle handle = Handle; if (handle != null) { - error = SniNativeWrapper.SNICheckConnection(handle); + error = SniNativeWrapper.SniCheckConnection(handle); } } finally @@ -543,7 +543,7 @@ public void ProcessSniPacket(PacketHandle packet, uint error) { uint dataSize = 0; - uint getDataError = SniNativeWrapper.SNIPacketGetData(packet, _inBuff, ref dataSize); + uint getDataError = SniNativeWrapper.SniPacketGetData(packet, _inBuff, ref dataSize); if (getDataError == TdsEnums.SNI_SUCCESS) { @@ -1169,7 +1169,7 @@ private Task SNIWritePacket(SNIHandle handle, SNIPacket packet, out uint sniErro } finally { - sniError = SniNativeWrapper.SNIWritePacket(handle, packet, sync); + sniError = SniNativeWrapper.SniWritePacket(handle, packet, sync); } if (sniError == TdsEnums.SNI_SUCCESS_IO_PENDING) @@ -1281,7 +1281,7 @@ internal void SendAttention(bool mustTakeWriteLock = false, bool asyncClose = fa SNIPacket attnPacket = new SNIPacket(Handle); _sniAsyncAttnPacket = attnPacket; - SniNativeWrapper.SNIPacketSetData(attnPacket, SQL.AttentionHeader, TdsEnums.HEADER_LEN, null, null); + SniNativeWrapper.SniPacketSetData(attnPacket, SQL.AttentionHeader, TdsEnums.HEADER_LEN, null, null); RuntimeHelpers.PrepareConstrainedRegions(); try @@ -1345,7 +1345,7 @@ private Task WriteSni(bool canAccumulate) { // Prepare packet, and write to packet. SNIPacket packet = GetResetWritePacket(); - SniNativeWrapper.SNIPacketSetData(packet, _outBuff, _outBytesUsed, _securePasswords, _securePasswordOffsetsInBuffer); + SniNativeWrapper.SniPacketSetData(packet, _outBuff, _outBytesUsed, _securePasswords, _securePasswordOffsetsInBuffer); Debug.Assert(Parser.Connection._parserLock.ThreadMayHaveLock(), "Thread is writing without taking the connection lock"); Task task = SNIWritePacket(Handle, packet, out _, canAccumulate, callerHasConnectionLock: true); @@ -1400,7 +1400,7 @@ internal SNIPacket GetResetWritePacket() { if (_sniPacket != null) { - SniNativeWrapper.SNIPacketReset(Handle, IoType.WRITE, _sniPacket, ConsumerNumber.SNI_Consumer_SNI); + SniNativeWrapper.SniPacketReset(Handle, IoType.WRITE, _sniPacket, ConsumerNumber.SNI_Consumer_SNI); } else { diff --git a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs index faa34928a9..3f91d7d238 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -3,22 +3,33 @@ // See the LICENSE file in the project root for more information. using System; -using System.Diagnostics; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using System.Security; using System.Text; using Interop.Windows.Sni; using Microsoft.Data.Common; -using Microsoft.Data.SqlClient; + +#if NETFRAMEWORK +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Runtime.Versioning; +using System.Security; +using Interop.Windows; +#endif namespace Microsoft.Data.SqlClient { internal static class SniNativeWrapper { + #region Member Variables + + private const int SniIpv6AddrStringBufferLength = 48; + + #if NET + private const int SniOpenTimeOut = -1; + #endif + #if NETFRAMEWORK - private static readonly ISniNativeMethods NativeMethods = RuntimeInformation.ProcessArchitecture switch + private static readonly ISniNativeMethods s_nativeMethods = RuntimeInformation.ProcessArchitecture switch { Architecture.Arm64 => new SniNativeMethodsArm64(), Architecture.X64 => new SniNativeMethodsX64(), @@ -26,276 +37,134 @@ internal static class SniNativeWrapper _ => new SniNativeMethodsNotSupported(RuntimeInformation.ProcessArchitecture) }; #else - private static readonly ISniNativeMethods NativeMethods = new SniNativeMethods(); + private static readonly SniNativeMethods s_nativeMethods = new SniNativeMethods(); #endif - + private static int s_sniMaxComposedSpnLength = -1; - - private const int SniOpenTimeOut = -1; // infinite - - internal const int SniIP6AddrStringBufferLength = 48; // from SNI layer - + + #endregion + internal static int SniMaxComposedSpnLength { get { if (s_sniMaxComposedSpnLength == -1) { - s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength()); + s_sniMaxComposedSpnLength = checked((int)s_nativeMethods.SniGetMaxComposedSpnLength()); } return s_sniMaxComposedSpnLength; } } + #region Public Methods + + internal static uint SniAddProvider(SNIHandle pConn, Provider provNum, ref AuthProviderInfo pInfo) => + s_nativeMethods.SniAddProvider(pConn, provNum, ref pInfo); + #if NETFRAMEWORK - static AppDomain GetDefaultAppDomainInternal() - { - return AppDomain.CurrentDomain; - } - - internal static _AppDomain GetDefaultAppDomain() - { - return GetDefaultAppDomainInternal(); - } - - [ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider - [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] - internal unsafe static byte[] GetData() + [ResourceExposure(ResourceScope.None)] + [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] + internal static uint SniAddProvider(SNIHandle pConn, + Provider providerEnum, + AuthProviderInfo authInfo) { - int size; - IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size)); - byte[] result = null; + Debug.Assert(authInfo.clientCertificateCallback == null, "CTAIP support has been removed"); - if (ptr != IntPtr.Zero) + uint ret = SniAddProvider(pConn, providerEnum, ref authInfo); + if (ret == SystemErrors.ERROR_SUCCESS) { - result = new byte[size]; - Marshal.Copy(ptr, result, 0, size); + // added a provider, need to requery for sync over async support + ret = s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, out bool _); + Debug.Assert(ret == SystemErrors.ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType"); } - return result; - } - - [ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider - [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] - internal unsafe static void SetData(Byte[] data) - { - //cli::pin_ptr pin_dispatcher = &data[0]; - fixed (byte* pin_dispatcher = &data[0]) - { - SqlDependencyProcessDispatcherStorage.NativeSetData(pin_dispatcher, data.Length); - } + return ret; } #endif - - #region DLL Imports - internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref uint pInfo) => - NativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); - - internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => - NativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); - - internal static uint SNICheckConnection([In] SNIHandle pConn) => - NativeMethods.SniCheckConnection(pConn); - - internal static uint SNIClose(IntPtr pConn) => - NativeMethods.SniClose(pConn); - - internal static void SNIGetLastError(out SniError pErrorStruct) => - NativeMethods.SniGetLastError(out pErrorStruct); - - internal static void SNIPacketRelease(IntPtr pPacket) => - NativeMethods.SniPacketRelease(pPacket); - - internal static void SNIPacketReset([In] SNIHandle pConn, IoType IOType, SNIPacket pPacket, ConsumerNumber ConsNum) => - NativeMethods.SniPacketReset(pConn, IOType, pPacket, ConsNum); - - internal static uint SNIQueryInfo(QueryType QType, ref uint pbQInfo) => - NativeMethods.SniQueryInfo(QType, ref pbQInfo); - - internal static uint SNIQueryInfo(QueryType QType, ref IntPtr pbQInfo) => - NativeMethods.SniQueryInfo(QType, ref pbQInfo); - - internal static uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket) => - NativeMethods.SniReadAsync(pConn, ref ppNewPacket); - - internal static uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout) => - NativeMethods.SniReadSyncOverAsync(pConn, ref ppNewPacket, timeout); - - internal static uint SNIRemoveProvider(SNIHandle pConn, Provider ProvNum) => - NativeMethods.SniRemoveProvider(pConn, ProvNum); - - internal static uint SNISecInitPackage(ref uint pcbMaxToken) => - NativeMethods.SniSecInitPackage(ref pcbMaxToken); - - internal static uint SNISetInfo(SNIHandle pConn, QueryType QType, [In] ref uint pbQInfo) => - NativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); - - internal static uint SNITerminate() => - NativeMethods.SniTerminate(); - - internal static uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => - NativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); - - internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => - NativeMethods.SniIsTokenRestricted(token, out isRestricted); - - private static uint GetSniMaxComposedSpnLength() => - NativeMethods.SniGetMaxComposedSpnLength(); - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Guid pbQInfo) => - NativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - - #if NETFRAMEWORK - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, [MarshalAs(UnmanagedType.Bool)] out bool pbQInfo) => - NativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - #endif - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out ushort portNum) => - NativeMethods.SniGetInfoWrapper(pConn, QType, out portNum); - - private static uint SNIGetPeerAddrStrWrapper([In] SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLen) => - NativeMethods.SniGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out addrLen); - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Provider provNum) => - NativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); - - private static uint SNIInitialize([In] IntPtr pmo) => - NativeMethods.SniInitialize(pmo); - - private static uint SNIOpenSyncExWrapper(ref SniClientConsumerInfo pClientConsumerInfo, out IntPtr ppConn) => - NativeMethods.SniOpenSyncExWrapper(ref pClientConsumerInfo, out ppConn); - - private static uint SNIOpenWrapper( - [In] ref SniConsumerInfo pConsumerInfo, - [MarshalAs(UnmanagedType.LPWStr)] string szConnect, - [In] SNIHandle pConn, - out IntPtr ppConn, - [MarshalAs(UnmanagedType.Bool)] bool fSync, - SqlConnectionIPAddressPreference ipPreference, - [In] ref SniDnsCacheInfo pDNSCachedInfo) => - NativeMethods.SniOpenWrapper( - ref pConsumerInfo, - szConnect, - pConn, - out ppConn, - fSync, - ipPreference, - ref pDNSCachedInfo); - - private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IoType IOType) => - NativeMethods.SniPacketAllocateWrapper(pConn, IOType); - - private static uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize) => - NativeMethods.SniPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize); - - private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf) => - NativeMethods.SniPacketSetData(pPacket, pbBuf, cbBuf); - - private static unsafe uint SNISecGenClientContextWrapper( - [In] SNIHandle pConn, - [In, Out] ReadOnlySpan pIn, - [In, Out] byte[] pOut, - [In] ref uint pcbOut, - [MarshalAsAttribute(UnmanagedType.Bool)] - out bool pfDone, - byte* szServerInfo, - uint cbServerInfo, - [MarshalAsAttribute(UnmanagedType.LPWStr)] - string pwszUserName, - [MarshalAsAttribute(UnmanagedType.LPWStr)] - string pwszPassword) - { - fixed (byte* pInPtr = pIn) - { - return NativeMethods.SniSecGenClientContextWrapper( - pConn, - pInPtr, - (uint)pIn.Length, - pOut, - ref pcbOut, - out pfDone, - szServerInfo, - cbServerInfo, - pwszUserName, - pwszPassword); - } - } - - private static uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket) => - NativeMethods.SniWriteAsyncWrapper(pConn, pPacket); - - private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket) => - NativeMethods.SniWriteSyncOverAsync(pConn, pPacket); + internal static uint SniAddProvider(SNIHandle pConn, Provider provNum, ref uint pInfo) => + s_nativeMethods.SniAddProvider(pConn, provNum, ref pInfo); - internal static IntPtr SNIServerEnumOpen() => - NativeMethods.SniServerEnumOpen(); - - internal static void SNIServerEnumClose([In] IntPtr packet) => - NativeMethods.SniServerEnumClose(packet); - - internal static int SNIServerEnumRead( - [In] IntPtr packet, - [In] [MarshalAs(UnmanagedType.LPArray)] char[] readBuffer, - [In] int bufferLength, - [MarshalAs(UnmanagedType.Bool)] out bool more) => - NativeMethods.SniServerEnumRead(packet, readBuffer, bufferLength, out more); + internal static uint SniCheckConnection(SNIHandle pConn) => + s_nativeMethods.SniCheckConnection(pConn); - #endregion - - internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) - { - return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_CONNID, out connId); - } - - internal static uint SniGetProviderNumber(SNIHandle pConn, ref Provider provNum) - { - return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); - } - - internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum) - { - return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PEERPORT, out portNum); - } - - internal static uint SniGetConnectionIPString(SNIHandle pConn, ref string connIPStr) + internal static uint SniClose(IntPtr pConn) => + s_nativeMethods.SniClose(pConn); + + internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) => + s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_CONNID, out connId); + + internal static uint SniGetConnectionIpString(SNIHandle pConn, ref string connIpStr) { - UInt32 ret; - uint connIPLen = 0; + StringBuilder addrBuffer = new StringBuilder(SniIpv6AddrStringBufferLength); - int bufferSize = SniIP6AddrStringBufferLength; - StringBuilder addrBuffer = new StringBuilder(bufferSize); - - ret = SNIGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out connIPLen); + uint ret = s_nativeMethods.SniGetPeerAddrStrWrapper( + pConn, + SniIpv6AddrStringBufferLength, + addrBuffer, + out uint connIpLen); - connIPStr = addrBuffer.ToString(0, Convert.ToInt32(connIPLen)); + connIpStr = addrBuffer.ToString(0, Convert.ToInt32(connIpLen)); return ret; } + + internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum) => + s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PEERPORT, out portNum); + + internal static void SniGetLastError(out SniError pErrorStruct) => + s_nativeMethods.SniGetLastError(out pErrorStruct); + + internal static uint SniGetProviderNumber(SNIHandle pConn, ref Provider provNum) => + s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); + + internal static uint SniInitialize() => + s_nativeMethods.SniInitialize(IntPtr.Zero); - internal static uint SNIInitialize() + internal static uint SniIsTokenRestricted(IntPtr token, out bool isRestricted) { - return SNIInitialize(IntPtr.Zero); - } + uint result = s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); + if (result != 0) + { + Marshal.ThrowExceptionForHR(unchecked((int)result)); + } - internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo) + return result; + } + + internal static uint SniOpenMarsSession( + ConsumerInfo consumerInfo, + SNIHandle parent, + ref IntPtr pConn, + bool fSync, + SqlConnectionIPAddressPreference ipPreference, + SQLDNSInfo cachedDnsInfo) { // initialize consumer info for MARS - SniConsumerInfo native_consumerInfo = new SniConsumerInfo(); - MarshalConsumerInfo(consumerInfo, ref native_consumerInfo); + SniConsumerInfo nativeConsumerInfo = new SniConsumerInfo(); + MarshalConsumerInfo(consumerInfo, ref nativeConsumerInfo); - SniDnsCacheInfo native_cachedDNSInfo = new SniDnsCacheInfo(); - native_cachedDNSInfo.wszCachedFQDN = cachedDNSInfo?.FQDN; - native_cachedDNSInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4; - native_cachedDNSInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6; - native_cachedDNSInfo.wszCachedTcpPort = cachedDNSInfo?.Port; - - return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ipPreference, ref native_cachedDNSInfo); + SniDnsCacheInfo nativeCachedDnsInfo = new SniDnsCacheInfo() + { + wszCachedFQDN = cachedDnsInfo?.FQDN, + wszCachedTcpIPv4 = cachedDnsInfo?.AddrIPv4, + wszCachedTcpIPv6 = cachedDnsInfo?.AddrIPv6, + wszCachedTcpPort = cachedDnsInfo?.Port, + }; + + return s_nativeMethods.SniOpenWrapper( + pConsumerInfo: ref nativeConsumerInfo, + connect: "session:", + pConn: parent, + ppConn: out pConn, + fSync, + ipPreference, + pDnsCacheInfo: ref nativeCachedDnsInfo); } - - internal static unsafe uint SNIOpenSyncEx( + + internal static unsafe uint SniOpenSyncEx( ConsumerInfo consumerInfo, - string constring, + string connString, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, @@ -305,25 +174,25 @@ internal static unsafe uint SNIOpenSyncEx( bool fParallel, #if NETFRAMEWORK - Int32 transparentNetworkResolutionStateNo, - Int32 totalTimeout, + int transparentNetworkResolutionStateNo, + int totalTimeout, #endif SqlConnectionIPAddressPreference ipPreference, - SQLDNSInfo cachedDNSInfo, + SQLDNSInfo cachedDnsInfo, string hostNameInCertificate) { - fixed (byte* pin_instanceName = &instanceName[0]) + fixed (byte* pInstanceName = instanceName) { SniClientConsumerInfo clientConsumerInfo = new SniClientConsumerInfo(); // initialize client ConsumerInfo part first MarshalConsumerInfo(consumerInfo, ref clientConsumerInfo.ConsumerInfo); - clientConsumerInfo.wszConnectionString = constring; + clientConsumerInfo.wszConnectionString = connString; clientConsumerInfo.HostNameInCertificate = hostNameInCertificate; clientConsumerInfo.networkLibrary = Prefix.UNKNOWN_PREFIX; - clientConsumerInfo.szInstanceName = pin_instanceName; + clientConsumerInfo.szInstanceName = pInstanceName; clientConsumerInfo.cchInstanceName = (uint)instanceName.Length; clientConsumerInfo.fOverrideLastConnectCache = fOverrideCache; clientConsumerInfo.fSynchronousConnection = fSync; @@ -333,13 +202,13 @@ internal static unsafe uint SNIOpenSyncEx( #if NETFRAMEWORK switch (transparentNetworkResolutionStateNo) { - case (0): + case 0: clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.DisabledMode; break; - case (1): + case 1: clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.SequentialMode; break; - case (2): + case 2: clientConsumerInfo.transparentNetworkResolution = TransparentNetworkResolutionMode.ParallelMode; break; }; @@ -349,108 +218,81 @@ internal static unsafe uint SNIOpenSyncEx( clientConsumerInfo.totalTimeout = SniOpenTimeOut; #endif - clientConsumerInfo.isAzureSqlServerEndpoint = ADP.IsAzureSqlServerEndpoint(constring); + clientConsumerInfo.isAzureSqlServerEndpoint = ADP.IsAzureSqlServerEndpoint(connString); clientConsumerInfo.ipAddressPreference = ipPreference; - clientConsumerInfo.DNSCacheInfo.wszCachedFQDN = cachedDNSInfo?.FQDN; - clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv4 = cachedDNSInfo?.AddrIPv4; - clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6; - clientConsumerInfo.DNSCacheInfo.wszCachedTcpPort = cachedDNSInfo?.Port; + clientConsumerInfo.DNSCacheInfo.wszCachedFQDN = cachedDnsInfo?.FQDN; + clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv4 = cachedDnsInfo?.AddrIPv4; + clientConsumerInfo.DNSCacheInfo.wszCachedTcpIPv6 = cachedDnsInfo?.AddrIPv6; + clientConsumerInfo.DNSCacheInfo.wszCachedTcpPort = cachedDnsInfo?.Port; - if (spnBuffer != null) + if (spnBuffer is not null) { - fixed (byte* pin_spnBuffer = &spnBuffer[0]) + fixed (byte* pSpnBuffer = spnBuffer) { - clientConsumerInfo.szSPN = pin_spnBuffer; + clientConsumerInfo.szSPN = pSpnBuffer; clientConsumerInfo.cchSPN = (uint)spnBuffer.Length; - return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); + return s_nativeMethods.SniOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } - else - { - // else leave szSPN null (SQL Auth) - return SNIOpenSyncExWrapper(ref clientConsumerInfo, out pConn); - } - } - } - - #if NETFRAMEWORK - [ResourceExposure(ResourceScope.None)] - [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - internal static uint SNIAddProvider(SNIHandle pConn, - Provider providerEnum, - AuthProviderInfo authInfo) - { - UInt32 ret; - uint ERROR_SUCCESS = 0; - - Debug.Assert(authInfo.clientCertificateCallback == null, "CTAIP support has been removed"); - - ret = SNIAddProvider(pConn, providerEnum, ref authInfo); - if (ret == ERROR_SUCCESS) - { - // added a provider, need to requery for sync over async support - ret = SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, out bool _); - Debug.Assert(ret == ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType"); + // Otherwise leave szSPN null (SQL Auth) + return s_nativeMethods.SniOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } - - return ret; } - #endif - internal static void SNIPacketAllocate(SafeHandle pConn, IoType IOType, ref IntPtr pPacket) - { - pPacket = SNIPacketAllocateWrapper(pConn, IOType); - } - - internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize) - { - return SNIPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize); - } - - internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length) + internal static void SniPacketAllocate(SafeHandle pConn, IoType ioType, ref IntPtr pPacket) => + pPacket = s_nativeMethods.SniPacketAllocateWrapper(pConn, ioType); + + internal static uint SniPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize) => + s_nativeMethods.SniPacketGetDataWrapper(packet, readBuffer, (uint)readBuffer.Length, out dataSize); + + internal static void SniPacketRelease(IntPtr pPacket) => + s_nativeMethods.SniPacketRelease(pPacket); + + internal static unsafe void SniPacketSetData(SNIPacket packet, byte[] data, int length) { - fixed (byte* pin_data = &data[0]) + fixed (byte* pData = data) { - SNIPacketSetData(packet, pin_data, (uint)length); + s_nativeMethods.SniPacketSetData(packet, pData, (uint)length); } } - + #if NETFRAMEWORK - //[ResourceExposure(ResourceScope::None)] - // - // Notes on SecureString: Writing out security sensitive information to managed buffer should be avoid as these can be moved - // around by GC. There are two set of information which falls into this category: passwords and new changed password which - // are passed in as SecureString by a user. Writing out clear passwords information is delayed until this layer to ensure that - // the information is written out to buffer which is pinned in this method already. This also ensures that processing a clear password - // is done right before it is written out to SNI_Packet where gets encrypted properly. - // TdsParserStaticMethods.EncryptPassword operation is also done here to minimize the time the clear password is held in memory. Any changes - // to loose encryption algorithm is changed it should be done in both in this method as well as TdsParserStaticMethods.EncryptPassword. - // Up to current release, it is also guaranteed that both password and new change password will fit into a single login packet whose size is fixed to 4096 - // So, there is no splitting logic is needed. - internal static void SNIPacketSetData(SNIPacket packet, - Byte[] data, - Int32 length, - SecureString[] passwords, // pointer to the passwords which need to be written out to SNI Packet - Int32[] passwordOffsets // Offset into data buffer where the password to be written out to - ) + // Notes on SecureString: Writing out security sensitive information to managed buffer + // should be avoided as these can be moved around by GC. There are two set of + // information which falls into this category: passwords and new changed password which + // are passed in as SecureString by a user. Writing out clear passwords information is + // delayed until this layer to ensure that the information is written out to buffer + // which is pinned in this method already. This also ensures that processing a clear + // password is done right before it is written out to SNI_Packet where gets encrypted + // properly. TdsParserStaticMethods.EncryptPassword operation is also done here to + // minimize the time the clear password is held in memory. Any time loose encryption + // algorithms are changed it should be done in both in this method and + // TdsParserStaticMethods.EncryptPassword. + // Up to current release, it is also guaranteed that both password and new change + // password will fit into a single login packet whose size is fixed to 4096 So, no + // splitting logic is needed. + internal static void SniPacketSetData( + SNIPacket packet, + byte[] data, + int length, + SecureString[] passwords, // pointer to the passwords which need to be written out to SNI Packet + int[] passwordOffsets) // Offset into data buffer where the password to be written out to { - Debug.Assert(passwords == null || (passwordOffsets != null && passwords.Length == passwordOffsets.Length), "The number of passwords does not match the number of password offsets"); + Debug.Assert(passwords is null || (passwordOffsets is not null && passwords.Length == passwordOffsets.Length), "The number of passwords does not match the number of password offsets"); bool mustRelease = false; bool mustClearBuffer = false; IntPtr clearPassword = IntPtr.Zero; - // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions + // provides a guaranteed finally block – without this it isn’t guaranteed – non- + // interruptible by fatal exceptions RuntimeHelpers.PrepareConstrainedRegions(); try { unsafe { - - fixed (byte* pin_data = &data[0]) - { } if (passwords != null) { // Process SecureString @@ -459,48 +301,40 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w // SecureString is used if (passwords[i] != null) { - // provides a guaranteed finally block – without this it isn’t guaranteed – non interruptable by fatal exceptions + // provides a guaranteed finally block – without this it isn’t + // guaranteed – non-interruptible by fatal exceptions RuntimeHelpers.PrepareConstrainedRegions(); try { - // ========================================================================== - // Get the clear text of secure string without converting it to String type - // ========================================================================== + // ============================================================ + // Get the clear text of secure string without converting it + // to string type + // ============================================================ clearPassword = Marshal.SecureStringToCoTaskMemUnicode(passwords[i]); - // ========================================================================================================================== - // Losely encrypt the clear text - The encryption algorithm should exactly match the TdsParserStaticMethods.EncryptPassword - // ========================================================================================================================== + // ============================================================ + // Loosely encrypt the clear text - The encryption algorithm + // should exactly match the TdsParserStaticMethods.EncryptPassword + // ============================================================ + char* pwChar = (char*)clearPassword.ToPointer(); + byte* pByte = (byte*)clearPassword.ToPointer(); - unsafe + int passwordsLength = passwords[i].Length; + for (int j = 0; j < passwordsLength; ++j) { - - char* pwChar = (char*)clearPassword.ToPointer(); - byte* pByte = (byte*)(clearPassword.ToPointer()); - - - - - int s; - byte bLo; - byte bHi; - int passwordsLength = passwords[i].Length; - for (int j = 0; j < passwordsLength; ++j) - { - s = (int)*pwChar; - bLo = (byte)(s & 0xff); - bHi = (byte)((s >> 8) & 0xff); - *(pByte++) = (Byte)((((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5); - *(pByte++) = (Byte)((((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5); - ++pwChar; - } - - // =========================================================== - // Write out the losely encrypted passwords to data buffer - // =========================================================== - mustClearBuffer = true; - Marshal.Copy(clearPassword, data, passwordOffsets[i], passwordsLength * 2); + int s = *pwChar; + byte bLo = (byte)(s & 0xff); + byte bHi = (byte)((s >> 8) & 0xff); + *(pByte++) = (byte)((((bLo & 0x0f) << 4) | (bLo >> 4)) ^ 0xa5); + *(pByte++) = (byte)((((bHi & 0x0f) << 4) | (bHi >> 4)) ^ 0xa5); + ++pwChar; } + + // ============================================================ + // Write out the loosely encrypted passwords to data buffer + // ============================================================ + mustClearBuffer = true; + Marshal.Copy(clearPassword, data, passwordOffsets[i], passwordsLength * 2); } finally { @@ -517,10 +351,7 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w packet.DangerousAddRef(ref mustRelease); Debug.Assert(mustRelease, "AddRef Failed!"); - fixed (byte* pin_data = &data[0]) - { - SNIPacketSetData(packet, pin_data, (uint)length); - } + SniPacketSetData(packet, data, length); } } finally @@ -542,67 +373,94 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w } } #endif - - - internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, ReadOnlySpan inBuff, byte[] OutBuff, ref uint sendLength, byte[] serverUserName) + + internal static void SniPacketReset(SNIHandle pConn, IoType ioType, SNIPacket pPacket, ConsumerNumber consNum) => + s_nativeMethods.SniPacketReset(pConn, ioType, pPacket, consNum); + + internal static uint SniQueryInfo(QueryType qType, ref uint pbQInfo) => + s_nativeMethods.SniQueryInfo(qType, ref pbQInfo); + + internal static uint SniQueryInfo(QueryType qType, ref IntPtr pbQInfo) => + s_nativeMethods.SniQueryInfo(qType, ref pbQInfo); + + internal static uint SniReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket) => + s_nativeMethods.SniReadAsync(pConn, ref ppNewPacket); + + internal static uint SniReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout) => + s_nativeMethods.SniReadSyncOverAsync(pConn, ref ppNewPacket, timeout); + + internal static uint SniRemoveProvider(SNIHandle pConn, Provider provNum) => + s_nativeMethods.SniRemoveProvider(pConn, provNum); + + internal static unsafe uint SniSecGenClientContext( + SNIHandle pConnectionObject, + ReadOnlySpan inBuff, + byte[] outBuff, + ref uint sendLength, + byte[] serverUserName) { - fixed (byte* pin_serverUserName = &serverUserName[0]) - //netcore fixed (byte* pInBuff = inBuff) + fixed (byte* pServerUserName = serverUserName) + fixed (byte* pInBuff = inBuff) { - return SNISecGenClientContextWrapper( - pConnectionObject, - inBuff, - OutBuff, - ref sendLength, - out _, - pin_serverUserName, - (uint)serverUserName.Length, - null, - null); + return s_nativeMethods.SniSecGenClientContextWrapper( + pConn: pConnectionObject, + pIn: pInBuff, + cbIn: (uint)inBuff.Length, + pOut: outBuff, + pcbOut: ref sendLength, + pfDone: out _, + szServerInfo: pServerUserName, + cbServerInfo: (uint)serverUserName.Length, + pwszUserName: null, + pwszPassword: null); } } + + internal static uint SniSecInitPackage(ref uint pcbMaxToken) => + s_nativeMethods.SniSecInitPackage(ref pcbMaxToken); + + internal static void SniServerEnumClose(IntPtr packet) => + s_nativeMethods.SniServerEnumClose(packet); + + internal static IntPtr SniServerEnumOpen() => + s_nativeMethods.SniServerEnumOpen(); + + internal static int SniServerEnumRead(IntPtr packet, char[] readBuffer, int bufferLength, out bool more) => + s_nativeMethods.SniServerEnumRead(packet, readBuffer, bufferLength, out more); + + internal static uint SniSetInfo(SNIHandle pConn, QueryType qType, ref uint pbQInfo) => + s_nativeMethods.SniSetInfo(pConn, qType, ref pbQInfo); + + internal static uint SniTerminate() => + s_nativeMethods.SniTerminate(); + + internal static uint SniWaitForSslHandshakeToComplete( + SNIHandle pConn, + int dwMilliseconds, + out uint pProtocolVersion) => + s_nativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); + + internal static uint SniWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) => + sync + ? s_nativeMethods.SniWriteSyncOverAsync(pConn, packet) + : s_nativeMethods.SniWriteAsyncWrapper(pConn, packet); + + #endregion - internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) - { - if (sync) - { - return SNIWriteSyncOverAsync(pConn, packet); - } - else - { - return SNIWriteAsyncWrapper(pConn, packet); - } - } + #region Private Methods - private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsumerInfo native_consumerInfo) + private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsumerInfo nativeConsumerInfo) { - native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; - native_consumerInfo.fnReadComp = consumerInfo.readDelegate != null + nativeConsumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; + nativeConsumerInfo.fnReadComp = consumerInfo.readDelegate is not null ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) : IntPtr.Zero; - native_consumerInfo.fnWriteComp = consumerInfo.writeDelegate != null + nativeConsumerInfo.fnWriteComp = consumerInfo.writeDelegate is not null ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) : IntPtr.Zero; - native_consumerInfo.ConsumerKey = consumerInfo.key; - } - } -} - -namespace Microsoft.Data -{ - internal static class Win32NativeMethods - { - internal static bool IsTokenRestrictedWrapper(IntPtr token) - { - bool isRestricted; - uint result = SniNativeWrapper.UnmanagedIsTokenRestricted(token, out isRestricted); - - if (result != 0) - { - Marshal.ThrowExceptionForHR(unchecked((int)result)); - } - - return isRestricted; + nativeConsumerInfo.ConsumerKey = consumerInfo.key; } + + #endregion } } diff --git a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SqlDependencyProcessDispatcherStorage.netfx.cs b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SqlDependencyProcessDispatcherStorage.netfx.cs index c4693a32b4..bbeda47473 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SqlDependencyProcessDispatcherStorage.netfx.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SqlDependencyProcessDispatcherStorage.netfx.cs @@ -4,52 +4,64 @@ #if NETFRAMEWORK +using System; using System.Diagnostics; using System.Runtime.InteropServices; +using System.Runtime.Versioning; using System.Threading; namespace Interop.Windows.Sni { internal unsafe class SqlDependencyProcessDispatcherStorage { - static void* data; + private static void* s_data; + private static int s_size; + private static volatile int s_lock; // Int used for a spin-lock. - static int size; - static volatile int thelock; // Int used for a spin-lock. - - public static void* NativeGetData(out int passedSize) + [ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider + [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] + public static byte[] NativeGetData() { - passedSize = size; - return data; + IntPtr ptr = (IntPtr)s_data; + + byte[] result = null; + if (ptr != IntPtr.Zero) + { + result = new byte[s_size]; + Marshal.Copy(ptr, result, 0, s_size); + } + + return result; } - internal static bool NativeSetData(void* passedData, int passedSize) + [ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider + [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] + internal static void NativeSetData(byte[] data) { - bool success = false; - - while (0 != Interlocked.CompareExchange(ref thelock, 1, 0)) - { // Spin until we have the lock. - Thread.Sleep(50); // Sleep with short-timeout to prevent starvation. - } - Trace.Assert(1 == thelock); // Now that we have the lock, lock should be equal to 1. - - if (data == null) + fixed (byte* pDispatcher = data) { - data = Marshal.AllocHGlobal(passedSize).ToPointer(); + while (Interlocked.CompareExchange(ref s_lock, 1, 0) != 0) + { + // Spin until we have the lock. + Thread.Sleep(50); // Sleep with short-timeout to prevent starvation. + } + Trace.Assert(s_lock == 1); // Now that we have the lock, lock should be equal to 1. - Trace.Assert(data != null); + if (s_data == null) + { + s_data = Marshal.AllocHGlobal(data.Length).ToPointer(); - System.Buffer.MemoryCopy(passedData, data, passedSize, passedSize); + Trace.Assert(s_data != null); - Trace.Assert(0 == size); // Size should still be zero at this point. - size = passedSize; - success = true; - } + Buffer.MemoryCopy(pDispatcher, s_data, data.Length, data.Length); - int result = Interlocked.CompareExchange(ref thelock, 0, 1); - Trace.Assert(1 == result); // The release of the lock should have been successful. + Trace.Assert(0 == s_size); // Size should still be zero at this point. + s_size = data.Length; + } - return success; + int result = Interlocked.CompareExchange(ref s_lock, 0, 1); + Trace.Assert(1 == result); // The release of the lock should have been successful. + } } } } diff --git a/src/Microsoft.Data.SqlClient/src/Interop/Windows/SystemErrors.cs b/src/Microsoft.Data.SqlClient/src/Interop/Windows/SystemErrors.cs index 6a2edef310..40819ef4d9 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/SystemErrors.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/SystemErrors.cs @@ -5,8 +5,10 @@ namespace Interop.Windows { // https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx - internal partial class SystemErrors + internal class SystemErrors { + internal const int ERROR_SUCCESS = 0x00; + internal const int ERROR_FILE_NOT_FOUND = 0x2; internal const int ERROR_INVALID_HANDLE = 0x6; internal const int ERROR_SHARING_VIOLATION = 0x20; diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs index 62fbc34aed..ea622ff1cd 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/ProviderBase/DbConnectionPoolIdentity.Windows.cs @@ -43,10 +43,13 @@ private static DbConnectionPoolIdentity GetCurrentNative() string sidString = user.Value; // Win32NativeMethods.IsTokenRestricted will raise exception if the native call fails - bool isRestricted = Win32NativeMethods.IsTokenRestrictedWrapper(token); + SniNativeWrapper.SniIsTokenRestricted(token, out bool isRestricted); var lastIdentity = s_lastIdentity; - if ((lastIdentity != null) && (lastIdentity._sidString == sidString) && (lastIdentity._isRestricted == isRestricted) && (lastIdentity._isNetwork == isNetwork)) + if (lastIdentity != null && + lastIdentity._sidString == sidString && + lastIdentity._isRestricted == isRestricted && + lastIdentity._isNetwork == isNetwork) { current = lastIdentity; } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlDataSourceEnumeratorNativeHelper.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlDataSourceEnumeratorNativeHelper.cs index b99e91414a..138e671dc9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlDataSourceEnumeratorNativeHelper.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/Sql/SqlDataSourceEnumeratorNativeHelper.cs @@ -50,23 +50,23 @@ internal static DataTable GetDataSources() { } finally { - handle = SniNativeWrapper.SNIServerEnumOpen(); + handle = SniNativeWrapper.SniServerEnumOpen(); SqlClientEventSource.Log.TryTraceEvent(" {2} returned handle = {3}.", nameof(SqlDataSourceEnumeratorNativeHelper), nameof(GetDataSources), - nameof(SniNativeWrapper.SNIServerEnumOpen), handle); + nameof(SniNativeWrapper.SniServerEnumOpen), handle); } if (handle != ADP.s_ptrZero) { while (more && !TdsParserStaticMethods.TimeoutHasExpired(s_timeoutTime)) { - readLength = SniNativeWrapper.SNIServerEnumRead(handle, buffer, bufferSize, out more); + readLength = SniNativeWrapper.SniServerEnumRead(handle, buffer, bufferSize, out more); SqlClientEventSource.Log.TryTraceEvent(" {2} returned 'readlength':{3}, and 'more':{4} with 'bufferSize' of {5}", nameof(SqlDataSourceEnumeratorNativeHelper), nameof(GetDataSources), - nameof(SniNativeWrapper.SNIServerEnumRead), + nameof(SniNativeWrapper.SniServerEnumRead), readLength, more, bufferSize); if (readLength > bufferSize) { @@ -84,21 +84,21 @@ internal static DataTable GetDataSources() { if (handle != ADP.s_ptrZero) { - SniNativeWrapper.SNIServerEnumClose(handle); + SniNativeWrapper.SniServerEnumClose(handle); SqlClientEventSource.Log.TryTraceEvent(" {2} called.", nameof(SqlDataSourceEnumeratorNativeHelper), nameof(GetDataSources), - nameof(SniNativeWrapper.SNIServerEnumClose)); + nameof(SniNativeWrapper.SniServerEnumClose)); } } if (failure) { - Debug.Assert(false, $"{nameof(GetDataSources)}:{nameof(SniNativeWrapper.SNIServerEnumRead)} returned bad length"); + Debug.Assert(false, $"{nameof(GetDataSources)}:{nameof(SniNativeWrapper.SniServerEnumRead)} returned bad length"); SqlClientEventSource.Log.TryTraceEvent(" {2} returned bad length, requested buffer {3}, received {4}", nameof(SqlDataSourceEnumeratorNativeHelper), nameof(GetDataSources), - nameof(SniNativeWrapper.SNIServerEnumRead), + nameof(SniNativeWrapper.SniServerEnumRead), bufferSize, readLength); throw ADP.ArgumentOutOfRange(StringsHelper.GetString(Strings.ADP_ParameterValueOutOfRange, readLength), nameof(readLength)); diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SSPI/NativeSSPIContextProvider.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SSPI/NativeSSPIContextProvider.cs index 26145134d4..88f05d9b6d 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SSPI/NativeSSPIContextProvider.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SSPI/NativeSSPIContextProvider.cs @@ -35,7 +35,7 @@ private void LoadSSPILibrary() // use local for ref param to defer setting s_maxSSPILength until we know the call succeeded. uint maxLength = 0; - if (0 != SniNativeWrapper.SNISecInitPackage(ref maxLength)) + if (0 != SniNativeWrapper.SniSecInitPackage(ref maxLength)) SSPIError(SQLMessage.SSPIInitializeError(), TdsEnums.INIT_SSPI_PACKAGE); s_maxSSPILength = maxLength; @@ -58,7 +58,7 @@ internal override void GenerateSspiClientContext(ReadOnlyMemory receivedBu Debug.Assert(_physicalStateObj.SessionHandle.Type == SessionHandle.NativeHandleType); SNIHandle handle = _physicalStateObj.SessionHandle.NativeHandle; #endif - if (0 != SniNativeWrapper.SNISecGenClientContext(handle, receivedBuff.Span, sendBuff, ref sendLength, _sniSpnBuffer[0])) + if (0 != SniNativeWrapper.SniSecGenClientContext(handle, receivedBuff.Span, sendBuff, ref sendLength, _sniSpnBuffer[0])) { throw new InvalidOperationException(SQLMessage.SSPIGenerateError()); } diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs index 534d42f866..a72a9e4d4b 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -13,6 +13,7 @@ using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security.Permissions; +using Interop.Windows.Sni; #endif using System.Text; using System.Threading; @@ -462,7 +463,7 @@ public void AddCommandDependency(SqlCommand command) [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] private static void ObtainProcessDispatcher() { - byte[] nativeStorage = SniNativeWrapper.GetData(); + byte[] nativeStorage = SqlDependencyProcessDispatcherStorage.NativeGetData(); if (nativeStorage == null) { @@ -470,47 +471,40 @@ private static void ObtainProcessDispatcher() #if DEBUG // Possibly expensive, limit to debug. SqlClientEventSource.Log.TryNotificationTraceEvent(" AppDomain.CurrentDomain.FriendlyName: {0}", AppDomain.CurrentDomain.FriendlyName); - #endif // DEBUG - _AppDomain masterDomain = SniNativeWrapper.GetDefaultAppDomain(); - - if (masterDomain != null) + + _AppDomain masterDomain = AppDomain.CurrentDomain; + + ObjectHandle handle = CreateProcessDispatcher(masterDomain); + if (handle != null) { - ObjectHandle handle = CreateProcessDispatcher(masterDomain); + SqlDependencyProcessDispatcher dependency = (SqlDependencyProcessDispatcher)handle.Unwrap(); - if (handle != null) + if (dependency != null) { - SqlDependencyProcessDispatcher dependency = (SqlDependencyProcessDispatcher)handle.Unwrap(); - - if (dependency != null) - { - s_processDispatcher = SqlDependencyProcessDispatcher.SingletonProcessDispatcher; // Set to static instance. + s_processDispatcher = SqlDependencyProcessDispatcher.SingletonProcessDispatcher; // Set to static instance. - // Serialize and set in native. - using (MemoryStream stream = new()) - { - SqlClientObjRef objRef = new(s_processDispatcher); - DataContractSerializer serializer = new(objRef.GetType()); - GetSerializedObject(objRef, serializer, stream); - SniNativeWrapper.SetData(stream.ToArray()); // Native will be forced to synchronize and not overwrite. - } - } - else + // Serialize and set in native. + using (MemoryStream stream = new()) { - SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - ObjectHandle.Unwrap returned null!"); - throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); + SqlClientObjRef objRef = new(s_processDispatcher); + DataContractSerializer serializer = new(objRef.GetType()); + GetSerializedObject(objRef, serializer, stream); + + // Native will be forced to synchronize and not overwrite. + SqlDependencyProcessDispatcherStorage.NativeSetData(stream.ToArray()); } } else { - SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - AppDomain.CreateInstance returned null!"); - throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - ObjectHandle.Unwrap returned null!"); + throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyObtainProcessDispatcherFailureObjectHandle); } } else { - SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - unable to obtain default AppDomain!"); - throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureAppDomain); + SqlClientEventSource.Log.TryNotificationTraceEvent(" ERROR - AppDomain.CreateInstance returned null!"); + throw ADP.InternalError(ADP.InternalErrorCode.SqlDependencyProcessDispatcherFailureCreateInstance); } } else diff --git a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs index bf5871c57e..60d2cf3af9 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/TdsParserSafeHandles.Windows.cs @@ -35,7 +35,7 @@ private SNILoadHandle() : base(IntPtr.Zero, true) { } finally { - _sniStatus = SniNativeWrapper.SNIInitialize(); + _sniStatus = SniNativeWrapper.SniInitialize(); base.handle = (IntPtr)1; // Initialize to non-zero dummy variable. } } @@ -56,7 +56,7 @@ public bool ClientOSEncryptionSupport { uint value = 0; // Query OS to find out whether encryption is supported. - SniNativeWrapper.SNIQueryInfo(QueryType.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value); + SniNativeWrapper.SniQueryInfo(QueryType.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value); _clientOSEncryptionSupport = value != 0; } catch (Exception e) @@ -78,7 +78,7 @@ override protected bool ReleaseHandle() if (TdsEnums.SNI_SUCCESS == _sniStatus) { LocalDBAPI.ReleaseDLLHandles(); - SniNativeWrapper.SNITerminate(); + SniNativeWrapper.SniTerminate(); } base.handle = IntPtr.Zero; } @@ -185,7 +185,7 @@ internal SNIHandle( #if NETFRAMEWORK int transparentNetworkResolutionStateNo = (int)transparentNetworkResolutionState; - _status = SniNativeWrapper.SNIOpenSyncEx( + _status = SniNativeWrapper.SniOpenSyncEx( myInfo, serverName, ref base.handle, @@ -201,7 +201,7 @@ internal SNIHandle( cachedDNSInfo, hostNameInCertificate); #else - _status = SniNativeWrapper.SNIOpenSyncEx( + _status = SniNativeWrapper.SniOpenSyncEx( myInfo, serverName, ref base.handle, @@ -225,7 +225,7 @@ internal SNIHandle(ConsumerInfo myInfo, SNIHandle parent, SqlConnectionIPAddress { } finally { - _status = SniNativeWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync, ipPreference, cachedDNSInfo); + _status = SniNativeWrapper.SniOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync, ipPreference, cachedDNSInfo); } } @@ -244,7 +244,7 @@ override protected bool ReleaseHandle() base.handle = IntPtr.Zero; if (IntPtr.Zero != ptr) { - if (0 != SniNativeWrapper.SNIClose(ptr)) + if (0 != SniNativeWrapper.SniClose(ptr)) { return false; // SNIClose should never fail. } @@ -265,7 +265,7 @@ internal sealed class SNIPacket : SafeHandle { internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true) { - SniNativeWrapper.SNIPacketAllocate(sniHandle, IoType.WRITE, ref base.handle); + SniNativeWrapper.SniPacketAllocate(sniHandle, IoType.WRITE, ref base.handle); if (IntPtr.Zero == base.handle) { throw SQL.SNIPacketAllocationFailure(); @@ -287,7 +287,7 @@ override protected bool ReleaseHandle() base.handle = IntPtr.Zero; if (IntPtr.Zero != ptr) { - SniNativeWrapper.SNIPacketRelease(ptr); + SniNativeWrapper.SniPacketRelease(ptr); } return true; } @@ -311,7 +311,7 @@ public SNIPacket Take(SNIHandle sniHandle) { // Success - reset the packet packet = _packets.Pop(); - SniNativeWrapper.SNIPacketReset(sniHandle, IoType.WRITE, packet, ConsumerNumber.SNI_Consumer_SNI); + SniNativeWrapper.SniPacketReset(sniHandle, IoType.WRITE, packet, ConsumerNumber.SNI_Consumer_SNI); } else {