From abfae6575cb4fa3347260ad607368c55bb1357e2 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Wed, 13 Nov 2024 17:38:11 -0600 Subject: [PATCH 1/9] Cleanup member variables of SniNativeWrapper --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 91 ++++++++++--------- 1 file changed, 47 insertions(+), 44 deletions(-) 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..1ad4ca39ab 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -17,8 +17,13 @@ namespace Microsoft.Data.SqlClient { internal static class SniNativeWrapper { + #region Member Variables + + private const int SniIpv6AddrStringBufferLength = 48; + private const int SniOpenTimeOut = -1; + #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,15 +31,13 @@ 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 @@ -90,81 +93,81 @@ internal unsafe static void SetData(Byte[] data) #region DLL Imports internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref uint pInfo) => - NativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); + s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => - NativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); + s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); internal static uint SNICheckConnection([In] SNIHandle pConn) => - NativeMethods.SniCheckConnection(pConn); + s_nativeMethods.SniCheckConnection(pConn); internal static uint SNIClose(IntPtr pConn) => - NativeMethods.SniClose(pConn); + s_nativeMethods.SniClose(pConn); internal static void SNIGetLastError(out SniError pErrorStruct) => - NativeMethods.SniGetLastError(out pErrorStruct); + s_nativeMethods.SniGetLastError(out pErrorStruct); internal static void SNIPacketRelease(IntPtr pPacket) => - NativeMethods.SniPacketRelease(pPacket); + s_nativeMethods.SniPacketRelease(pPacket); internal static void SNIPacketReset([In] SNIHandle pConn, IoType IOType, SNIPacket pPacket, ConsumerNumber ConsNum) => - NativeMethods.SniPacketReset(pConn, IOType, pPacket, ConsNum); + s_nativeMethods.SniPacketReset(pConn, IOType, pPacket, ConsNum); internal static uint SNIQueryInfo(QueryType QType, ref uint pbQInfo) => - NativeMethods.SniQueryInfo(QType, ref pbQInfo); + s_nativeMethods.SniQueryInfo(QType, ref pbQInfo); internal static uint SNIQueryInfo(QueryType QType, ref IntPtr pbQInfo) => - NativeMethods.SniQueryInfo(QType, ref pbQInfo); + s_nativeMethods.SniQueryInfo(QType, ref pbQInfo); internal static uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket) => - NativeMethods.SniReadAsync(pConn, ref ppNewPacket); + s_nativeMethods.SniReadAsync(pConn, ref ppNewPacket); internal static uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout) => - NativeMethods.SniReadSyncOverAsync(pConn, ref ppNewPacket, timeout); + s_nativeMethods.SniReadSyncOverAsync(pConn, ref ppNewPacket, timeout); internal static uint SNIRemoveProvider(SNIHandle pConn, Provider ProvNum) => - NativeMethods.SniRemoveProvider(pConn, ProvNum); + s_nativeMethods.SniRemoveProvider(pConn, ProvNum); internal static uint SNISecInitPackage(ref uint pcbMaxToken) => - NativeMethods.SniSecInitPackage(ref pcbMaxToken); + s_nativeMethods.SniSecInitPackage(ref pcbMaxToken); internal static uint SNISetInfo(SNIHandle pConn, QueryType QType, [In] ref uint pbQInfo) => - NativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); + s_nativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); internal static uint SNITerminate() => - NativeMethods.SniTerminate(); + s_nativeMethods.SniTerminate(); internal static uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => - NativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); + s_nativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => - NativeMethods.SniIsTokenRestricted(token, out isRestricted); + s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); private static uint GetSniMaxComposedSpnLength() => - NativeMethods.SniGetMaxComposedSpnLength(); + s_nativeMethods.SniGetMaxComposedSpnLength(); private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Guid pbQInfo) => - NativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); + s_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); + s_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); + s_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); + s_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); + s_nativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); private static uint SNIInitialize([In] IntPtr pmo) => - NativeMethods.SniInitialize(pmo); + s_nativeMethods.SniInitialize(pmo); private static uint SNIOpenSyncExWrapper(ref SniClientConsumerInfo pClientConsumerInfo, out IntPtr ppConn) => - NativeMethods.SniOpenSyncExWrapper(ref pClientConsumerInfo, out ppConn); + s_nativeMethods.SniOpenSyncExWrapper(ref pClientConsumerInfo, out ppConn); private static uint SNIOpenWrapper( [In] ref SniConsumerInfo pConsumerInfo, @@ -174,7 +177,7 @@ private static uint SNIOpenWrapper( [MarshalAs(UnmanagedType.Bool)] bool fSync, SqlConnectionIPAddressPreference ipPreference, [In] ref SniDnsCacheInfo pDNSCachedInfo) => - NativeMethods.SniOpenWrapper( + s_nativeMethods.SniOpenWrapper( ref pConsumerInfo, szConnect, pConn, @@ -184,13 +187,13 @@ private static uint SNIOpenWrapper( ref pDNSCachedInfo); private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IoType IOType) => - NativeMethods.SniPacketAllocateWrapper(pConn, IOType); + s_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); + s_nativeMethods.SniPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize); private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf) => - NativeMethods.SniPacketSetData(pPacket, pbBuf, cbBuf); + s_nativeMethods.SniPacketSetData(pPacket, pbBuf, cbBuf); private static unsafe uint SNISecGenClientContextWrapper( [In] SNIHandle pConn, @@ -208,7 +211,7 @@ private static unsafe uint SNISecGenClientContextWrapper( { fixed (byte* pInPtr = pIn) { - return NativeMethods.SniSecGenClientContextWrapper( + return s_nativeMethods.SniSecGenClientContextWrapper( pConn, pInPtr, (uint)pIn.Length, @@ -223,23 +226,23 @@ private static unsafe uint SNISecGenClientContextWrapper( } private static uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket) => - NativeMethods.SniWriteAsyncWrapper(pConn, pPacket); + s_nativeMethods.SniWriteAsyncWrapper(pConn, pPacket); private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket) => - NativeMethods.SniWriteSyncOverAsync(pConn, pPacket); + s_nativeMethods.SniWriteSyncOverAsync(pConn, pPacket); internal static IntPtr SNIServerEnumOpen() => - NativeMethods.SniServerEnumOpen(); + s_nativeMethods.SniServerEnumOpen(); internal static void SNIServerEnumClose([In] IntPtr packet) => - NativeMethods.SniServerEnumClose(packet); + s_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); + s_nativeMethods.SniServerEnumRead(packet, readBuffer, bufferLength, out more); #endregion @@ -263,7 +266,7 @@ internal static uint SniGetConnectionIPString(SNIHandle pConn, ref string connIP UInt32 ret; uint connIPLen = 0; - int bufferSize = SniIP6AddrStringBufferLength; + int bufferSize = SniIpv6AddrStringBufferLength; StringBuilder addrBuffer = new StringBuilder(bufferSize); ret = SNIGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out connIPLen); From 5361d6c9c99e3bc4877dcef58fefa1204c39da8b Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Wed, 13 Nov 2024 17:54:09 -0600 Subject: [PATCH 2/9] Sort public methods (as per target names) --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 452 +++++++++--------- 1 file changed, 227 insertions(+), 225 deletions(-) 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 1ad4ca39ab..84ef7a277c 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -50,217 +50,50 @@ internal static int SniMaxComposedSpnLength } } + #region Public Methods + + internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => + s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); + #if NETFRAMEWORK - static AppDomain GetDefaultAppDomainInternal() + [ResourceExposure(ResourceScope.None)] + [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] + internal static uint SNIAddProvider(SNIHandle pConn, + Provider providerEnum, + AuthProviderInfo authInfo) { - return AppDomain.CurrentDomain; - } + UInt32 ret; + uint ERROR_SUCCESS = 0; - internal static _AppDomain GetDefaultAppDomain() - { - return GetDefaultAppDomainInternal(); - } + Debug.Assert(authInfo.clientCertificateCallback == null, "CTAIP support has been removed"); - [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() - { - int size; - IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size)); - byte[] result = null; + ret = SNIAddProvider(pConn, providerEnum, ref authInfo); - if (ptr != IntPtr.Zero) + if (ret == ERROR_SUCCESS) { - result = new byte[size]; - Marshal.Copy(ptr, result, 0, size); + // 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"); } - 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) => s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); - - internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => - s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); - + internal static uint SNICheckConnection([In] SNIHandle pConn) => s_nativeMethods.SniCheckConnection(pConn); - + internal static uint SNIClose(IntPtr pConn) => s_nativeMethods.SniClose(pConn); - - internal static void SNIGetLastError(out SniError pErrorStruct) => - s_nativeMethods.SniGetLastError(out pErrorStruct); - - internal static void SNIPacketRelease(IntPtr pPacket) => - s_nativeMethods.SniPacketRelease(pPacket); - - internal static void SNIPacketReset([In] 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 uint SNISecInitPackage(ref uint pcbMaxToken) => - s_nativeMethods.SniSecInitPackage(ref pcbMaxToken); - - internal static uint SNISetInfo(SNIHandle pConn, QueryType QType, [In] ref uint pbQInfo) => - s_nativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); - - internal static uint SNITerminate() => - s_nativeMethods.SniTerminate(); - - internal static uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => - s_nativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); - - internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => - s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); - - private static uint GetSniMaxComposedSpnLength() => - s_nativeMethods.SniGetMaxComposedSpnLength(); - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Guid pbQInfo) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - - #if NETFRAMEWORK - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, [MarshalAs(UnmanagedType.Bool)] out bool pbQInfo) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - #endif - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out ushort portNum) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out portNum); - - private static uint SNIGetPeerAddrStrWrapper([In] SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLen) => - s_nativeMethods.SniGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out addrLen); - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Provider provNum) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); - - private static uint SNIInitialize([In] IntPtr pmo) => - s_nativeMethods.SniInitialize(pmo); - - private static uint SNIOpenSyncExWrapper(ref SniClientConsumerInfo pClientConsumerInfo, out IntPtr ppConn) => - s_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) => - s_nativeMethods.SniOpenWrapper( - ref pConsumerInfo, - szConnect, - pConn, - out ppConn, - fSync, - ipPreference, - ref pDNSCachedInfo); - - private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IoType IOType) => - s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); - - private static uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize) => - s_nativeMethods.SniPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize); - - private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf) => - s_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 s_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) => - s_nativeMethods.SniWriteAsyncWrapper(pConn, pPacket); - - private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket) => - s_nativeMethods.SniWriteSyncOverAsync(pConn, pPacket); - - internal static IntPtr SNIServerEnumOpen() => - s_nativeMethods.SniServerEnumOpen(); - - internal static void SNIServerEnumClose([In] IntPtr packet) => - s_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) => - s_nativeMethods.SniServerEnumRead(packet, readBuffer, bufferLength, out more); - #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) { UInt32 ret; @@ -275,12 +108,28 @@ internal static uint SniGetConnectionIPString(SNIHandle pConn, ref string connIP return ret; } - + + internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum) + { + return 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) + { + return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); + } + internal static uint SNIInitialize() { return SNIInitialize(IntPtr.Zero); } - + + internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => + s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); + internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo) { // initialize consumer info for MARS @@ -295,7 +144,7 @@ internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHan return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ipPreference, ref native_cachedDNSInfo); } - + internal static unsafe uint SNIOpenSyncEx( ConsumerInfo consumerInfo, string constring, @@ -376,42 +225,20 @@ internal static unsafe uint SNIOpenSyncEx( } } } - - #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"); - } - - 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 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]) @@ -419,7 +246,7 @@ internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int SNIPacketSetData(packet, pin_data, (uint)length); } } - + #if NETFRAMEWORK //[ResourceExposure(ResourceScope::None)] // @@ -545,12 +372,26 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w } } #endif - - + + internal static void SNIPacketReset([In] 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 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) + //netcore fixed (byte* pInBuff = inBuff) { return SNISecGenClientContextWrapper( pConnectionObject, @@ -564,7 +405,32 @@ internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, null); } } - + + internal static uint SNISecInitPackage(ref uint pcbMaxToken) => + s_nativeMethods.SniSecInitPackage(ref pcbMaxToken); + + internal static void SNIServerEnumClose([In] IntPtr packet) => + s_nativeMethods.SniServerEnumClose(packet); + + internal static IntPtr SNIServerEnumOpen() => + s_nativeMethods.SniServerEnumOpen(); + + internal static int SNIServerEnumRead( + [In] IntPtr packet, + [In] [MarshalAs(UnmanagedType.LPArray)] char[] readBuffer, + [In] int bufferLength, + [MarshalAs(UnmanagedType.Bool)] out bool more) => + s_nativeMethods.SniServerEnumRead(packet, readBuffer, bufferLength, out more); + + internal static uint SNISetInfo(SNIHandle pConn, QueryType QType, [In] ref uint pbQInfo) => + s_nativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); + + internal static uint SNITerminate() => + s_nativeMethods.SniTerminate(); + + internal static uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => + s_nativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); + internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) { if (sync) @@ -576,6 +442,142 @@ internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync return SNIWriteAsyncWrapper(pConn, packet); } } + + #endregion + + + + #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() + { + int size; + IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size)); + byte[] result = null; + + if (ptr != IntPtr.Zero) + { + result = new byte[size]; + Marshal.Copy(ptr, result, 0, size); + } + + 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); + } + } + #endif + + #region DLL Imports + + private static uint GetSniMaxComposedSpnLength() => + s_nativeMethods.SniGetMaxComposedSpnLength(); + + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Guid pbQInfo) => + s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); + + #if NETFRAMEWORK + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, [MarshalAs(UnmanagedType.Bool)] out bool pbQInfo) => + s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); + #endif + + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out ushort portNum) => + s_nativeMethods.SniGetInfoWrapper(pConn, QType, out portNum); + + private static uint SNIGetPeerAddrStrWrapper([In] SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLen) => + s_nativeMethods.SniGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out addrLen); + + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Provider provNum) => + s_nativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); + + private static uint SNIInitialize([In] IntPtr pmo) => + s_nativeMethods.SniInitialize(pmo); + + private static uint SNIOpenSyncExWrapper(ref SniClientConsumerInfo pClientConsumerInfo, out IntPtr ppConn) => + s_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) => + s_nativeMethods.SniOpenWrapper( + ref pConsumerInfo, + szConnect, + pConn, + out ppConn, + fSync, + ipPreference, + ref pDNSCachedInfo); + + private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IoType IOType) => + s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); + + private static uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize) => + s_nativeMethods.SniPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize); + + private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf) => + s_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 s_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) => + s_nativeMethods.SniWriteAsyncWrapper(pConn, pPacket); + + private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket) => + s_nativeMethods.SniWriteSyncOverAsync(pConn, pPacket); + + #endregion private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsumerInfo native_consumerInfo) { From 5440bc0864738fea464963f9c062bbf40f2ac180 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Wed, 13 Nov 2024 17:58:15 -0600 Subject: [PATCH 3/9] Sort private methods (most of these will be removed in next commit) --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 131 +++++++++--------- 1 file changed, 65 insertions(+), 66 deletions(-) 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 84ef7a277c..a4929d9d5f 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -444,77 +444,47 @@ internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync } #endregion - - - - #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() - { - int size; - IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size)); - byte[] result = null; - - if (ptr != IntPtr.Zero) - { - result = new byte[size]; - Marshal.Copy(ptr, result, 0, size); - } - - 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); - } - } - #endif - - #region DLL Imports + #region Private Methods private static uint GetSniMaxComposedSpnLength() => s_nativeMethods.SniGetMaxComposedSpnLength(); + private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsumerInfo native_consumerInfo) + { + native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; + native_consumerInfo.fnReadComp = consumerInfo.readDelegate != null + ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) + : IntPtr.Zero; + native_consumerInfo.fnWriteComp = consumerInfo.writeDelegate != null + ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) + : IntPtr.Zero; + native_consumerInfo.ConsumerKey = consumerInfo.key; + } + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Guid pbQInfo) => s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - + #if NETFRAMEWORK private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, [MarshalAs(UnmanagedType.Bool)] out bool pbQInfo) => s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); #endif + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Provider provNum) => + s_nativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); + private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out ushort portNum) => s_nativeMethods.SniGetInfoWrapper(pConn, QType, out portNum); - + private static uint SNIGetPeerAddrStrWrapper([In] SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLen) => s_nativeMethods.SniGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out addrLen); - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Provider provNum) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); - + private static uint SNIInitialize([In] IntPtr pmo) => s_nativeMethods.SniInitialize(pmo); - + private static uint SNIOpenSyncExWrapper(ref SniClientConsumerInfo pClientConsumerInfo, out IntPtr ppConn) => s_nativeMethods.SniOpenSyncExWrapper(ref pClientConsumerInfo, out ppConn); - + private static uint SNIOpenWrapper( [In] ref SniConsumerInfo pConsumerInfo, [MarshalAs(UnmanagedType.LPWStr)] string szConnect, @@ -531,13 +501,13 @@ private static uint SNIOpenWrapper( fSync, ipPreference, ref pDNSCachedInfo); - + private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IoType IOType) => s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); - + private static uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize) => s_nativeMethods.SniPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize); - + private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf) => s_nativeMethods.SniPacketSetData(pPacket, pbBuf, cbBuf); @@ -570,26 +540,55 @@ private static unsafe uint SNISecGenClientContextWrapper( pwszPassword); } } - + private static uint SNIWriteAsyncWrapper(SNIHandle pConn, [In] SNIPacket pPacket) => s_nativeMethods.SniWriteAsyncWrapper(pConn, pPacket); - + private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket) => s_nativeMethods.SniWriteSyncOverAsync(pConn, pPacket); - + #endregion + + + #if NETFRAMEWORK + static AppDomain GetDefaultAppDomainInternal() + { + return AppDomain.CurrentDomain; + } - private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsumerInfo native_consumerInfo) + internal static _AppDomain GetDefaultAppDomain() { - native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; - native_consumerInfo.fnReadComp = consumerInfo.readDelegate != null - ? Marshal.GetFunctionPointerForDelegate(consumerInfo.readDelegate) - : IntPtr.Zero; - native_consumerInfo.fnWriteComp = consumerInfo.writeDelegate != null - ? Marshal.GetFunctionPointerForDelegate(consumerInfo.writeDelegate) - : IntPtr.Zero; - native_consumerInfo.ConsumerKey = consumerInfo.key; + 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() + { + int size; + IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size)); + byte[] result = null; + + if (ptr != IntPtr.Zero) + { + result = new byte[size]; + Marshal.Copy(ptr, result, 0, size); + } + + 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); + } } + #endif } } From 93825787eca8a5f39c660d52708a2ae07a506103 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Wed, 13 Nov 2024 18:17:56 -0600 Subject: [PATCH 4/9] Remove unneeded private methods --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 175 ++++-------------- 1 file changed, 41 insertions(+), 134 deletions(-) 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 a4929d9d5f..5d495552fb 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -44,7 +44,7 @@ internal static int SniMaxComposedSpnLength { if (s_sniMaxComposedSpnLength == -1) { - s_sniMaxComposedSpnLength = checked((int)GetSniMaxComposedSpnLength()); + s_sniMaxComposedSpnLength = checked((int)s_nativeMethods.SniGetMaxComposedSpnLength()); } return s_sniMaxComposedSpnLength; } @@ -72,7 +72,7 @@ internal static uint SNIAddProvider(SNIHandle pConn, 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 _); + ret = s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_SUPPORTS_SYNC_OVER_ASYNC, out bool _); Debug.Assert(ret == ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType"); } @@ -89,10 +89,8 @@ internal static uint SNICheckConnection([In] SNIHandle pConn) => internal static uint SNIClose(IntPtr pConn) => s_nativeMethods.SniClose(pConn); - internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) - { - return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_CONNID, out connId); - } + 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) { @@ -102,7 +100,7 @@ internal static uint SniGetConnectionIPString(SNIHandle pConn, ref string connIP int bufferSize = SniIpv6AddrStringBufferLength; StringBuilder addrBuffer = new StringBuilder(bufferSize); - ret = SNIGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out connIPLen); + ret = s_nativeMethods.SniGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out connIPLen); connIPStr = addrBuffer.ToString(0, Convert.ToInt32(connIPLen)); @@ -111,7 +109,7 @@ internal static uint SniGetConnectionIPString(SNIHandle pConn, ref string connIP internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum) { - return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PEERPORT, out portNum); + return s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PEERPORT, out portNum); } internal static void SNIGetLastError(out SniError pErrorStruct) => @@ -119,13 +117,11 @@ internal static void SNIGetLastError(out SniError pErrorStruct) => internal static uint SniGetProviderNumber(SNIHandle pConn, ref Provider provNum) { - return SNIGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); - } - - internal static uint SNIInitialize() - { - return SNIInitialize(IntPtr.Zero); + return s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); } + + internal static uint SNIInitialize() => + s_nativeMethods.SniInitialize(IntPtr.Zero); internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); @@ -142,7 +138,7 @@ internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHan native_cachedDNSInfo.wszCachedTcpIPv6 = cachedDNSInfo?.AddrIPv6; native_cachedDNSInfo.wszCachedTcpPort = cachedDNSInfo?.Port; - return SNIOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ipPreference, ref native_cachedDNSInfo); + return s_nativeMethods.SniOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ipPreference, ref native_cachedDNSInfo); } internal static unsafe uint SNIOpenSyncEx( @@ -215,26 +211,22 @@ internal static unsafe uint SNIOpenSyncEx( { clientConsumerInfo.szSPN = pin_spnBuffer; 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); + return s_nativeMethods.SniOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } } + + internal static void SNIPacketAllocate(SafeHandle pConn, IoType IOType, ref IntPtr pPacket) => + pPacket = s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); - 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 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); @@ -243,7 +235,7 @@ internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int { fixed (byte* pin_data = &data[0]) { - SNIPacketSetData(packet, pin_data, (uint)length); + s_nativeMethods.SniPacketSetData(packet, pin_data, (uint)length); } } @@ -347,10 +339,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 @@ -388,21 +377,27 @@ internal static uint SNIReadAsync(SNIHandle pConn, ref IntPtr ppNewPacket) => internal static uint SNIReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout) => s_nativeMethods.SniReadSyncOverAsync(pConn, ref ppNewPacket, timeout); - internal static unsafe uint SNISecGenClientContext(SNIHandle pConnectionObject, ReadOnlySpan inBuff, byte[] OutBuff, ref uint sendLength, byte[] serverUserName) + 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); } } @@ -435,11 +430,11 @@ internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync { if (sync) { - return SNIWriteSyncOverAsync(pConn, packet); + return s_nativeMethods.SniWriteSyncOverAsync(pConn, packet); } else { - return SNIWriteAsyncWrapper(pConn, packet); + return s_nativeMethods.SniWriteAsyncWrapper(pConn, packet); } } @@ -447,9 +442,6 @@ internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync #region Private Methods - private static uint GetSniMaxComposedSpnLength() => - s_nativeMethods.SniGetMaxComposedSpnLength(); - private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsumerInfo native_consumerInfo) { native_consumerInfo.DefaultUserDataLength = consumerInfo.defaultBufferSize; @@ -462,91 +454,6 @@ private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsum native_consumerInfo.ConsumerKey = consumerInfo.key; } - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Guid pbQInfo) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - - #if NETFRAMEWORK - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, [MarshalAs(UnmanagedType.Bool)] out bool pbQInfo) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out pbQInfo); - #endif - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out Provider provNum) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out provNum); - - private static uint SNIGetInfoWrapper([In] SNIHandle pConn, QueryType QType, out ushort portNum) => - s_nativeMethods.SniGetInfoWrapper(pConn, QType, out portNum); - - private static uint SNIGetPeerAddrStrWrapper([In] SNIHandle pConn, int bufferSize, StringBuilder addrBuffer, out uint addrLen) => - s_nativeMethods.SniGetPeerAddrStrWrapper(pConn, bufferSize, addrBuffer, out addrLen); - - private static uint SNIInitialize([In] IntPtr pmo) => - s_nativeMethods.SniInitialize(pmo); - - private static uint SNIOpenSyncExWrapper(ref SniClientConsumerInfo pClientConsumerInfo, out IntPtr ppConn) => - s_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) => - s_nativeMethods.SniOpenWrapper( - ref pConsumerInfo, - szConnect, - pConn, - out ppConn, - fSync, - ipPreference, - ref pDNSCachedInfo); - - private static IntPtr SNIPacketAllocateWrapper([In] SafeHandle pConn, IoType IOType) => - s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); - - private static uint SNIPacketGetDataWrapper([In] IntPtr packet, [In, Out] byte[] readBuffer, uint readBufferLength, out uint dataSize) => - s_nativeMethods.SniPacketGetDataWrapper(packet, readBuffer, readBufferLength, out dataSize); - - private static unsafe void SNIPacketSetData(SNIPacket pPacket, [In] byte* pbBuf, uint cbBuf) => - s_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 s_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) => - s_nativeMethods.SniWriteAsyncWrapper(pConn, pPacket); - - private static uint SNIWriteSyncOverAsync(SNIHandle pConn, [In] SNIPacket pPacket) => - s_nativeMethods.SniWriteSyncOverAsync(pConn, pPacket); - #endregion From 1b8614ece90c776d104dd54d76357013aa207967 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Wed, 13 Nov 2024 18:23:59 -0600 Subject: [PATCH 5/9] Rename methods as per naming rules --- .../Data/SqlClient/LocalDBAPI.Windows.cs | 4 +- .../Data/SqlClient/TdsParser.Windows.cs | 2 +- .../SqlClient/TdsParserStateObjectNative.cs | 28 ++++---- .../Microsoft/Data/SqlClient/LocalDBAPI.cs | 4 +- .../src/Microsoft/Data/SqlClient/TdsParser.cs | 16 ++--- .../SqlClient/TdsParserStateObject.netfx.cs | 20 +++--- .../Interop/Windows/Sni/SniNativeWrapper.cs | 67 ++++++++++--------- .../SqlDataSourceEnumeratorNativeHelper.cs | 16 ++--- .../SSPI/NativeSSPIContextProvider.cs | 4 +- .../SqlClient/TdsParserSafeHandles.Windows.cs | 20 +++--- 10 files changed, 92 insertions(+), 89 deletions(-) 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..dbbd9673cb 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 @@ -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/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 5d495552fb..e9be15ae72 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -52,13 +52,13 @@ internal static int SniMaxComposedSpnLength #region Public Methods - internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => + internal static uint SniAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); #if NETFRAMEWORK [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - internal static uint SNIAddProvider(SNIHandle pConn, + internal static uint SniAddProvider(SNIHandle pConn, Provider providerEnum, AuthProviderInfo authInfo) { @@ -67,7 +67,7 @@ internal static uint SNIAddProvider(SNIHandle pConn, Debug.Assert(authInfo.clientCertificateCallback == null, "CTAIP support has been removed"); - ret = SNIAddProvider(pConn, providerEnum, ref authInfo); + ret = SniAddProvider(pConn, providerEnum, ref authInfo); if (ret == ERROR_SUCCESS) { @@ -80,13 +80,13 @@ internal static uint SNIAddProvider(SNIHandle pConn, } #endif - internal static uint SNIAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref uint pInfo) => + internal static uint SniAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref uint pInfo) => s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); - internal static uint SNICheckConnection([In] SNIHandle pConn) => + internal static uint SniCheckConnection([In] SNIHandle pConn) => s_nativeMethods.SniCheckConnection(pConn); - internal static uint SNIClose(IntPtr pConn) => + internal static uint SniClose(IntPtr pConn) => s_nativeMethods.SniClose(pConn); internal static uint SniGetConnectionId(SNIHandle pConn, ref Guid connId) => @@ -112,7 +112,7 @@ internal static uint SniGetConnectionPort(SNIHandle pConn, ref ushort portNum) return s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PEERPORT, out portNum); } - internal static void SNIGetLastError(out SniError pErrorStruct) => + internal static void SniGetLastError(out SniError pErrorStruct) => s_nativeMethods.SniGetLastError(out pErrorStruct); internal static uint SniGetProviderNumber(SNIHandle pConn, ref Provider provNum) @@ -120,13 +120,13 @@ internal static uint SniGetProviderNumber(SNIHandle pConn, ref Provider provNum) return s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); } - internal static uint SNIInitialize() => + internal static uint SniInitialize() => s_nativeMethods.SniInitialize(IntPtr.Zero); - internal static uint UnmanagedIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => + internal static uint SniIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); - internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo) + internal static unsafe 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(); @@ -141,7 +141,7 @@ internal static unsafe uint SNIOpenMarsSession(ConsumerInfo consumerInfo, SNIHan return s_nativeMethods.SniOpenWrapper(ref native_consumerInfo, "session:", parent, out pConn, fSync, ipPreference, ref native_cachedDNSInfo); } - internal static unsafe uint SNIOpenSyncEx( + internal static unsafe uint SniOpenSyncEx( ConsumerInfo consumerInfo, string constring, ref IntPtr pConn, @@ -222,16 +222,16 @@ internal static unsafe uint SNIOpenSyncEx( } } - internal static void SNIPacketAllocate(SafeHandle pConn, IoType IOType, ref IntPtr pPacket) => + internal static void SniPacketAllocate(SafeHandle pConn, IoType IOType, ref IntPtr pPacket) => pPacket = s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); - internal static unsafe uint SNIPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize) => + internal static unsafe 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) => + internal static void SniPacketRelease(IntPtr pPacket) => s_nativeMethods.SniPacketRelease(pPacket); - internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int length) + internal static unsafe void SniPacketSetData(SNIPacket packet, byte[] data, int length) { fixed (byte* pin_data = &data[0]) { @@ -251,7 +251,7 @@ internal static unsafe void SNIPacketSetData(SNIPacket packet, byte[] data, int // 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, + 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 @@ -339,7 +339,7 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w packet.DangerousAddRef(ref mustRelease); Debug.Assert(mustRelease, "AddRef Failed!"); - SNIPacketSetData(packet, data, length); + SniPacketSetData(packet, data, length); } } finally @@ -362,22 +362,25 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w } #endif - internal static void SNIPacketReset([In] SNIHandle pConn, IoType IOType, SNIPacket pPacket, ConsumerNumber ConsNum) => + internal static void SniPacketReset([In] SNIHandle pConn, IoType IOType, SNIPacket pPacket, ConsumerNumber ConsNum) => s_nativeMethods.SniPacketReset(pConn, IOType, pPacket, ConsNum); - internal static uint SNIQueryInfo(QueryType QType, ref uint pbQInfo) => + internal static uint SniQueryInfo(QueryType QType, ref uint pbQInfo) => s_nativeMethods.SniQueryInfo(QType, ref pbQInfo); - internal static uint SNIQueryInfo(QueryType QType, ref IntPtr 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) => + 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) => + internal static uint SniReadSyncOverAsync(SNIHandle pConn, ref IntPtr ppNewPacket, int timeout) => s_nativeMethods.SniReadSyncOverAsync(pConn, ref ppNewPacket, timeout); - internal static unsafe uint SNISecGenClientContext( + internal static uint SniRemoveProvider(SNIHandle pConn, Provider ProvNum) => + s_nativeMethods.SniRemoveProvider(pConn, ProvNum); + + internal static unsafe uint SniSecGenClientContext( SNIHandle pConnectionObject, ReadOnlySpan inBuff, byte[] OutBuff, @@ -401,32 +404,32 @@ internal static unsafe uint SNISecGenClientContext( } } - internal static uint SNISecInitPackage(ref uint pcbMaxToken) => + internal static uint SniSecInitPackage(ref uint pcbMaxToken) => s_nativeMethods.SniSecInitPackage(ref pcbMaxToken); - internal static void SNIServerEnumClose([In] IntPtr packet) => + internal static void SniServerEnumClose([In] IntPtr packet) => s_nativeMethods.SniServerEnumClose(packet); - internal static IntPtr SNIServerEnumOpen() => + internal static IntPtr SniServerEnumOpen() => s_nativeMethods.SniServerEnumOpen(); - internal static int SNIServerEnumRead( + internal static int SniServerEnumRead( [In] IntPtr packet, [In] [MarshalAs(UnmanagedType.LPArray)] char[] readBuffer, [In] int bufferLength, [MarshalAs(UnmanagedType.Bool)] out bool more) => s_nativeMethods.SniServerEnumRead(packet, readBuffer, bufferLength, out more); - internal static uint SNISetInfo(SNIHandle pConn, QueryType QType, [In] ref uint pbQInfo) => + internal static uint SniSetInfo(SNIHandle pConn, QueryType QType, [In] ref uint pbQInfo) => s_nativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); - internal static uint SNITerminate() => + internal static uint SniTerminate() => s_nativeMethods.SniTerminate(); - internal static uint SNIWaitForSSLHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => + internal static uint SniWaitForSslHandshakeToComplete([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => s_nativeMethods.SniWaitForSslHandshakeToComplete(pConn, dwMilliseconds, out pProtocolVersion); - internal static uint SNIWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) + internal static uint SniWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) { if (sync) { @@ -506,7 +509,7 @@ internal static class Win32NativeMethods internal static bool IsTokenRestrictedWrapper(IntPtr token) { bool isRestricted; - uint result = SniNativeWrapper.UnmanagedIsTokenRestricted(token, out isRestricted); + uint result = SniNativeWrapper.SniIsTokenRestricted(token, out isRestricted); if (result != 0) { 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/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 { From 9ff384ac612c8632db212cfc64290b8c6eda5c63 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 14 Nov 2024 12:43:52 -0600 Subject: [PATCH 6/9] Cleanup suggestions and follow naming conventions --- .../SqlClient/TdsParserStateObjectNative.cs | 2 +- .../Data/SqlClient/TdsParser.netfx.cs | 2 +- .../Interop/Windows/Sni/SniNativeWrapper.cs | 335 +++++++++--------- .../src/Interop/Windows/SystemErrors.cs | 4 +- 4 files changed, 170 insertions(+), 173 deletions(-) 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 dbbd9673cb..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()); 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/src/Interop/Windows/Sni/SniNativeWrapper.cs b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs index e9be15ae72..1444b4c1c3 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -3,16 +3,20 @@ // 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 @@ -20,7 +24,10 @@ 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 s_nativeMethods = RuntimeInformation.ProcessArchitecture switch @@ -52,8 +59,8 @@ internal static int SniMaxComposedSpnLength #region Public Methods - internal static uint SniAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref AuthProviderInfo pInfo) => - s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); + internal static uint SniAddProvider(SNIHandle pConn, Provider provNum, ref AuthProviderInfo pInfo) => + s_nativeMethods.SniAddProvider(pConn, provNum, ref pInfo); #if NETFRAMEWORK [ResourceExposure(ResourceScope.None)] @@ -62,28 +69,24 @@ 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) + uint ret = SniAddProvider(pConn, providerEnum, ref authInfo); + if (ret == SystemErrors.ERROR_SUCCESS) { // 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 == ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType"); + Debug.Assert(ret == SystemErrors.ERROR_SUCCESS, "SNIGetInfo cannot fail with this QType"); } return ret; } #endif - internal static uint SniAddProvider(SNIHandle pConn, Provider ProvNum, [In] ref uint pInfo) => - s_nativeMethods.SniAddProvider(pConn, ProvNum, ref pInfo); + internal static uint SniAddProvider(SNIHandle pConn, Provider provNum, ref uint pInfo) => + s_nativeMethods.SniAddProvider(pConn, provNum, ref pInfo); - internal static uint SniCheckConnection([In] SNIHandle pConn) => + internal static uint SniCheckConnection(SNIHandle pConn) => s_nativeMethods.SniCheckConnection(pConn); internal static uint SniClose(IntPtr pConn) => @@ -92,58 +95,69 @@ internal static uint SniClose(IntPtr 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) + internal static uint SniGetConnectionIpString(SNIHandle pConn, ref string connIpStr) { - UInt32 ret; - uint connIPLen = 0; - - int bufferSize = SniIpv6AddrStringBufferLength; - StringBuilder addrBuffer = new StringBuilder(bufferSize); + StringBuilder addrBuffer = new StringBuilder(SniIpv6AddrStringBufferLength); - ret = s_nativeMethods.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) - { - return s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PEERPORT, out portNum); - } + 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) - { - return s_nativeMethods.SniGetInfoWrapper(pConn, QueryType.SNI_QUERY_CONN_PROVIDERNUM, out provNum); - } + 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 SniIsTokenRestricted([In] IntPtr token, [MarshalAs(UnmanagedType.Bool)] out bool isRestricted) => + internal static uint SniIsTokenRestricted(IntPtr token, out bool isRestricted) => s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); - internal static unsafe uint SniOpenMarsSession(ConsumerInfo consumerInfo, SNIHandle parent, ref IntPtr pConn, bool fSync, SqlConnectionIPAddressPreference ipPreference, SQLDNSInfo cachedDNSInfo) + 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 s_nativeMethods.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( ConsumerInfo consumerInfo, - string constring, + string connString, ref IntPtr pConn, byte[] spnBuffer, byte[] instanceName, @@ -153,25 +167,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; @@ -181,13 +195,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; }; @@ -197,35 +211,33 @@ 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 s_nativeMethods.SniOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } - else - { - // else leave szSPN null (SQL Auth) - return s_nativeMethods.SniOpenSyncExWrapper(ref clientConsumerInfo, out pConn); - } + + // Otherwise leave szSPN null (SQL Auth) + return s_nativeMethods.SniOpenSyncExWrapper(ref clientConsumerInfo, out pConn); } } - internal static void SniPacketAllocate(SafeHandle pConn, IoType IOType, ref IntPtr pPacket) => - pPacket = s_nativeMethods.SniPacketAllocateWrapper(pConn, IOType); + internal static void SniPacketAllocate(SafeHandle pConn, IoType ioType, ref IntPtr pPacket) => + pPacket = s_nativeMethods.SniPacketAllocateWrapper(pConn, ioType); - internal static unsafe uint SniPacketGetData(IntPtr packet, byte[] readBuffer, ref uint dataSize) => + 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) => @@ -233,46 +245,47 @@ internal static void SniPacketRelease(IntPtr pPacket) => internal static unsafe void SniPacketSetData(SNIPacket packet, byte[] data, int length) { - fixed (byte* pin_data = &data[0]) + fixed (byte* pData = data) { - s_nativeMethods.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 @@ -281,48 +294,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 { @@ -362,14 +367,14 @@ Int32[] passwordOffsets // Offset into data buffer where the password to be w } #endif - internal static void SniPacketReset([In] SNIHandle pConn, IoType IOType, SNIPacket pPacket, ConsumerNumber ConsNum) => - s_nativeMethods.SniPacketReset(pConn, IOType, pPacket, ConsNum); + 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 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 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); @@ -377,13 +382,13 @@ internal static uint SniReadAsync(SNIHandle pConn, ref IntPtr 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 uint SniRemoveProvider(SNIHandle pConn, Provider provNum) => + s_nativeMethods.SniRemoveProvider(pConn, provNum); internal static unsafe uint SniSecGenClientContext( SNIHandle pConnectionObject, ReadOnlySpan inBuff, - byte[] OutBuff, + byte[] outBuff, ref uint sendLength, byte[] serverUserName) { @@ -394,7 +399,7 @@ internal static unsafe uint SniSecGenClientContext( pConn: pConnectionObject, pIn: pInBuff, cbIn: (uint)inBuff.Length, - pOut: OutBuff, + pOut: outBuff, pcbOut: ref sendLength, pfDone: out _, szServerInfo: pServerUserName, @@ -407,54 +412,46 @@ internal static unsafe uint SniSecGenClientContext( internal static uint SniSecInitPackage(ref uint pcbMaxToken) => s_nativeMethods.SniSecInitPackage(ref pcbMaxToken); - internal static void SniServerEnumClose([In] IntPtr packet) => + internal static void SniServerEnumClose(IntPtr packet) => s_nativeMethods.SniServerEnumClose(packet); internal static IntPtr SniServerEnumOpen() => s_nativeMethods.SniServerEnumOpen(); - internal static int SniServerEnumRead( - [In] IntPtr packet, - [In] [MarshalAs(UnmanagedType.LPArray)] char[] readBuffer, - [In] int bufferLength, - [MarshalAs(UnmanagedType.Bool)] out bool more) => + 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, [In] ref uint pbQInfo) => - s_nativeMethods.SniSetInfo(pConn, QType, ref pbQInfo); + 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([In] SNIHandle pConn, int dwMilliseconds, out uint pProtocolVersion) => + 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) - { - if (sync) - { - return s_nativeMethods.SniWriteSyncOverAsync(pConn, packet); - } - else - { - return s_nativeMethods.SniWriteAsyncWrapper(pConn, packet); - } - } + + internal static uint SniWritePacket(SNIHandle pConn, SNIPacket packet, bool sync) => + sync + ? s_nativeMethods.SniWriteSyncOverAsync(pConn, packet) + : s_nativeMethods.SniWriteAsyncWrapper(pConn, packet); #endregion #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; + nativeConsumerInfo.ConsumerKey = consumerInfo.key; } #endregion @@ -473,10 +470,9 @@ internal static _AppDomain GetDefaultAppDomain() [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() + internal static unsafe byte[] GetData() { - int size; - IntPtr ptr = (IntPtr)(SqlDependencyProcessDispatcherStorage.NativeGetData(out size)); + IntPtr ptr = (IntPtr)SqlDependencyProcessDispatcherStorage.NativeGetData(out int size); byte[] result = null; if (ptr != IntPtr.Zero) @@ -490,12 +486,11 @@ internal unsafe static byte[] GetData() [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) + internal static unsafe void SetData(byte[] data) { - //cli::pin_ptr pin_dispatcher = &data[0]; - fixed (byte* pin_dispatcher = &data[0]) + fixed (byte* pDispatcher = data) { - SqlDependencyProcessDispatcherStorage.NativeSetData(pin_dispatcher, data.Length); + SqlDependencyProcessDispatcherStorage.NativeSetData(pDispatcher, data.Length); } } #endif 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; From 87262c577afae1d33e37ef85aa971819695c2e47 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 14 Nov 2024 13:21:44 -0600 Subject: [PATCH 7/9] Remove AppDomain method from SniNativeWrapper --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 11 ----- .../Microsoft/Data/SqlClient/SqlDependency.cs | 45 ++++++++----------- 2 files changed, 18 insertions(+), 38 deletions(-) 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 1444b4c1c3..9ac952b699 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -456,18 +456,7 @@ private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsum #endregion - #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 static unsafe byte[] GetData() 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..448fcfe665 100644 --- a/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs +++ b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs @@ -470,47 +470,38 @@ 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); + SniNativeWrapper.SetData(stream.ToArray()); // Native will be forced to synchronize and not overwrite. } } 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 From f8c0769e0088e84f95009f8306e1fdf9e250996a Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 14 Nov 2024 13:30:12 -0600 Subject: [PATCH 8/9] Remove Win32NativeMethods --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 34 ++++++------------- .../DbConnectionPoolIdentity.Windows.cs | 7 ++-- 2 files changed, 16 insertions(+), 25 deletions(-) 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 9ac952b699..86febc4c85 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -7,7 +7,6 @@ using System.Text; using Interop.Windows.Sni; using Microsoft.Data.Common; -using Microsoft.Data.SqlClient; #if NETFRAMEWORK using System.Diagnostics; @@ -121,9 +120,17 @@ internal static uint SniGetProviderNumber(SNIHandle pConn, ref Provider provNum) internal static uint SniInitialize() => s_nativeMethods.SniInitialize(IntPtr.Zero); - - internal static uint SniIsTokenRestricted(IntPtr token, out bool isRestricted) => - s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); + + internal static uint SniIsTokenRestricted(IntPtr token, out bool isRestricted) + { + uint result = s_nativeMethods.SniIsTokenRestricted(token, out isRestricted); + if (result != 0) + { + Marshal.ThrowExceptionForHR(unchecked((int)result)); + } + + return result; + } internal static uint SniOpenMarsSession( ConsumerInfo consumerInfo, @@ -485,22 +492,3 @@ internal static unsafe void SetData(byte[] data) #endif } } - -namespace Microsoft.Data -{ - internal static class Win32NativeMethods - { - internal static bool IsTokenRestrictedWrapper(IntPtr token) - { - bool isRestricted; - uint result = SniNativeWrapper.SniIsTokenRestricted(token, out isRestricted); - - if (result != 0) - { - Marshal.ThrowExceptionForHR(unchecked((int)result)); - } - - return isRestricted; - } - } -} 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; } From c0f51c8a5f4da695f74907daef5e82bc469ab556 Mon Sep 17 00:00:00 2001 From: Ben Russell Date: Thu, 14 Nov 2024 13:48:41 -0600 Subject: [PATCH 9/9] Remove sqldependency process storage methods from SniNativeWrapper --- .../Interop/Windows/Sni/SniNativeWrapper.cs | 28 -------- ...ependencyProcessDispatcherStorage.netfx.cs | 66 +++++++++++-------- .../Microsoft/Data/SqlClient/SqlDependency.cs | 7 +- 3 files changed, 44 insertions(+), 57 deletions(-) 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 86febc4c85..3f91d7d238 100644 --- a/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs +++ b/src/Microsoft.Data.SqlClient/src/Interop/Windows/Sni/SniNativeWrapper.cs @@ -462,33 +462,5 @@ private static void MarshalConsumerInfo(ConsumerInfo consumerInfo, ref SniConsum } #endregion - - #if NETFRAMEWORK - [ResourceExposure(ResourceScope.Process)] // SxS: there is no way to set scope = Instance, using Process which is wider - [ResourceConsumption(ResourceScope.Process, ResourceScope.Process)] - internal static unsafe byte[] GetData() - { - IntPtr ptr = (IntPtr)SqlDependencyProcessDispatcherStorage.NativeGetData(out int size); - byte[] result = null; - - if (ptr != IntPtr.Zero) - { - result = new byte[size]; - Marshal.Copy(ptr, result, 0, size); - } - - 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 static unsafe void SetData(byte[] data) - { - fixed (byte* pDispatcher = data) - { - SqlDependencyProcessDispatcherStorage.NativeSetData(pDispatcher, data.Length); - } - } - #endif } } 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/Microsoft/Data/SqlClient/SqlDependency.cs b/src/Microsoft.Data.SqlClient/src/Microsoft/Data/SqlClient/SqlDependency.cs index 448fcfe665..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) { @@ -489,7 +490,9 @@ private static void ObtainProcessDispatcher() 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. + + // Native will be forced to synchronize and not overwrite. + SqlDependencyProcessDispatcherStorage.NativeSetData(stream.ToArray()); } } else