TdsParserSafeHandles.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. //------------------------------------------------------------------------------
  2. // <copyright file="TdsParserSafeHandles.cs" company="Microsoft">
  3. // Copyright (c) Microsoft Corporation. All rights reserved.
  4. // </copyright>
  5. // <owner current="true" primary="true">[....]</owner>
  6. // <owner current="true" primary="false">[....]</owner>
  7. //------------------------------------------------------------------------------
  8. namespace System.Data.SqlClient {
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Data.Common;
  12. using System.Diagnostics;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.InteropServices;
  15. using System.Security;
  16. using System.Security.Permissions;
  17. using System.Threading;
  18. using System.Runtime.ConstrainedExecution;
  19. internal sealed class SNILoadHandle : SafeHandle {
  20. internal static readonly SNILoadHandle SingletonInstance = new SNILoadHandle();
  21. internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate ReadAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(ReadDispatcher);
  22. internal readonly SNINativeMethodWrapper.SqlAsyncCallbackDelegate WriteAsyncCallbackDispatcher = new SNINativeMethodWrapper.SqlAsyncCallbackDelegate(WriteDispatcher);
  23. private readonly UInt32 _sniStatus = TdsEnums.SNI_UNINITIALIZED;
  24. private readonly EncryptionOptions _encryptionOption;
  25. private SNILoadHandle() : base(IntPtr.Zero, true) {
  26. // SQL BU DT 346588 - from security review - SafeHandle guarantees this is only called once.
  27. // The reason for the safehandle is guaranteed initialization and termination of SNI to
  28. // ensure SNI terminates and cleans up properly.
  29. RuntimeHelpers.PrepareConstrainedRegions();
  30. try {} finally {
  31. _sniStatus = SNINativeMethodWrapper.SNIInitialize();
  32. UInt32 value = 0;
  33. // VSDevDiv 479597: If initialize fails, don't call QueryInfo.
  34. if (TdsEnums.SNI_SUCCESS == _sniStatus) {
  35. // Query OS to find out whether encryption is supported.
  36. SNINativeMethodWrapper.SNIQueryInfo(SNINativeMethodWrapper.QTypes.SNI_QUERY_CLIENT_ENCRYPT_POSSIBLE, ref value);
  37. }
  38. _encryptionOption = (value == 0) ? EncryptionOptions.NOT_SUP : EncryptionOptions.OFF;
  39. base.handle = (IntPtr) 1; // Initialize to non-zero dummy variable.
  40. }
  41. }
  42. public override bool IsInvalid {
  43. get {
  44. return (IntPtr.Zero == base.handle);
  45. }
  46. }
  47. override protected bool ReleaseHandle() {
  48. if (base.handle != IntPtr.Zero) {
  49. if (TdsEnums.SNI_SUCCESS == _sniStatus) {
  50. LocalDBAPI.ReleaseDLLHandles();
  51. SNINativeMethodWrapper.SNITerminate();
  52. }
  53. base.handle = IntPtr.Zero;
  54. }
  55. return true;
  56. }
  57. public UInt32 SNIStatus {
  58. get {
  59. return _sniStatus;
  60. }
  61. }
  62. public EncryptionOptions Options {
  63. get {
  64. return _encryptionOption;
  65. }
  66. }
  67. static private void ReadDispatcher(IntPtr key, IntPtr packet, UInt32 error) {
  68. // This is the app-domain dispatcher for all async read callbacks, It
  69. // simply gets the state object from the key that it is passed, and
  70. // calls the state object's read callback.
  71. Debug.Assert(IntPtr.Zero != key, "no key passed to read callback dispatcher?");
  72. if (IntPtr.Zero != key) {
  73. // NOTE: we will get a null ref here if we don't get a key that
  74. // contains a GCHandle to TDSParserStateObject; that is
  75. // very bad, and we want that to occur so we can catch it.
  76. GCHandle gcHandle = (GCHandle)key;
  77. TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
  78. if (null != stateObj) {
  79. stateObj.ReadAsyncCallback(IntPtr.Zero, packet, error);
  80. }
  81. }
  82. }
  83. static private void WriteDispatcher(IntPtr key, IntPtr packet, UInt32 error) {
  84. // This is the app-domain dispatcher for all async write callbacks, It
  85. // simply gets the state object from the key that it is passed, and
  86. // calls the state object's write callback.
  87. Debug.Assert(IntPtr.Zero != key, "no key passed to write callback dispatcher?");
  88. if (IntPtr.Zero != key) {
  89. // NOTE: we will get a null ref here if we don't get a key that
  90. // contains a GCHandle to TDSParserStateObject; that is
  91. // very bad, and we want that to occur so we can catch it.
  92. GCHandle gcHandle = (GCHandle)key;
  93. TdsParserStateObject stateObj = (TdsParserStateObject)gcHandle.Target;
  94. if (null != stateObj) {
  95. stateObj.WriteAsyncCallback(IntPtr.Zero, packet, error);
  96. }
  97. }
  98. }
  99. }
  100. internal sealed class SNIHandle : SafeHandle {
  101. private readonly UInt32 _status = TdsEnums.SNI_UNINITIALIZED;
  102. private readonly bool _fSync = false;
  103. // creates a physical connection
  104. internal SNIHandle(
  105. SNINativeMethodWrapper.ConsumerInfo myInfo,
  106. string serverName,
  107. byte[] spnBuffer,
  108. bool ignoreSniOpenTimeout,
  109. int timeout,
  110. out byte[] instanceName,
  111. bool flushCache,
  112. bool fSync,
  113. bool fParallel,
  114. TransparentNetworkResolutionState transparentNetworkResolutionState,
  115. int totalTimeout)
  116. : base(IntPtr.Zero, true) {
  117. RuntimeHelpers.PrepareConstrainedRegions();
  118. try {} finally {
  119. _fSync = fSync;
  120. instanceName = new byte[256]; // Size as specified by netlibs.
  121. if (ignoreSniOpenTimeout) {
  122. //
  123. timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE
  124. }
  125. int transparentNetworkResolutionStateNo = (int)transparentNetworkResolutionState;
  126. _status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle,
  127. spnBuffer, instanceName, flushCache, fSync, timeout, fParallel, transparentNetworkResolutionStateNo, totalTimeout);
  128. }
  129. }
  130. // constructs SNI Handle for MARS session
  131. internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true) {
  132. RuntimeHelpers.PrepareConstrainedRegions();
  133. try {} finally {
  134. _status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync);
  135. }
  136. }
  137. public override bool IsInvalid {
  138. get {
  139. return (IntPtr.Zero == base.handle);
  140. }
  141. }
  142. override protected bool ReleaseHandle() {
  143. // NOTE: The SafeHandle class guarantees this will be called exactly once.
  144. IntPtr ptr = base.handle;
  145. base.handle = IntPtr.Zero;
  146. if (IntPtr.Zero != ptr) {
  147. if (0 != SNINativeMethodWrapper.SNIClose(ptr)) {
  148. return false; // SNIClose should never fail.
  149. }
  150. }
  151. return true;
  152. }
  153. internal UInt32 Status {
  154. get {
  155. return _status;
  156. }
  157. }
  158. }
  159. internal sealed class SNIPacket : SafeHandle {
  160. internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true) {
  161. SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle);
  162. if (IntPtr.Zero == base.handle) {
  163. throw SQL.SNIPacketAllocationFailure();
  164. }
  165. }
  166. public override bool IsInvalid {
  167. get {
  168. return (IntPtr.Zero == base.handle);
  169. }
  170. }
  171. override protected bool ReleaseHandle() {
  172. // NOTE: The SafeHandle class guarantees this will be called exactly once.
  173. IntPtr ptr = base.handle;
  174. base.handle = IntPtr.Zero;
  175. if (IntPtr.Zero != ptr) {
  176. SNINativeMethodWrapper.SNIPacketRelease(ptr);
  177. }
  178. return true;
  179. }
  180. }
  181. internal sealed class WritePacketCache : IDisposable {
  182. private bool _disposed;
  183. private Stack<SNIPacket> _packets;
  184. public WritePacketCache() {
  185. _disposed = false;
  186. _packets = new Stack<SNIPacket>();
  187. }
  188. public SNIPacket Take(SNIHandle sniHandle) {
  189. SNIPacket packet;
  190. if (_packets.Count > 0) {
  191. // Success - reset the packet
  192. packet = _packets.Pop();
  193. SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
  194. }
  195. else {
  196. // Failed to take a packet - create a new one
  197. packet = new SNIPacket(sniHandle);
  198. }
  199. return packet;
  200. }
  201. public void Add(SNIPacket packet) {
  202. if (!_disposed) {
  203. _packets.Push(packet);
  204. }
  205. else {
  206. // If we're disposed, then get rid of any packets added to us
  207. packet.Dispose();
  208. }
  209. }
  210. public void Clear() {
  211. while (_packets.Count > 0) {
  212. _packets.Pop().Dispose();
  213. }
  214. }
  215. public void Dispose() {
  216. if (!_disposed) {
  217. _disposed = true;
  218. Clear();
  219. }
  220. }
  221. }
  222. }