TdsParserSafeHandles.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  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. : base(IntPtr.Zero, true) {
  115. RuntimeHelpers.PrepareConstrainedRegions();
  116. try {} finally {
  117. _fSync = fSync;
  118. instanceName = new byte[256]; // Size as specified by netlibs.
  119. if (ignoreSniOpenTimeout) {
  120. //
  121. timeout = Timeout.Infinite; // -1 == native SNIOPEN_TIMEOUT_VALUE / INFINITE
  122. }
  123. _status = SNINativeMethodWrapper.SNIOpenSyncEx(myInfo, serverName, ref base.handle,
  124. spnBuffer, instanceName, flushCache, fSync, timeout, fParallel);
  125. }
  126. }
  127. // constructs SNI Handle for MARS session
  128. internal SNIHandle(SNINativeMethodWrapper.ConsumerInfo myInfo, SNIHandle parent) : base(IntPtr.Zero, true) {
  129. RuntimeHelpers.PrepareConstrainedRegions();
  130. try {} finally {
  131. _status = SNINativeMethodWrapper.SNIOpenMarsSession(myInfo, parent, ref base.handle, parent._fSync);
  132. }
  133. }
  134. public override bool IsInvalid {
  135. get {
  136. return (IntPtr.Zero == base.handle);
  137. }
  138. }
  139. override protected bool ReleaseHandle() {
  140. // NOTE: The SafeHandle class guarantees this will be called exactly once.
  141. IntPtr ptr = base.handle;
  142. base.handle = IntPtr.Zero;
  143. if (IntPtr.Zero != ptr) {
  144. if (0 != SNINativeMethodWrapper.SNIClose(ptr)) {
  145. return false; // SNIClose should never fail.
  146. }
  147. }
  148. return true;
  149. }
  150. internal UInt32 Status {
  151. get {
  152. return _status;
  153. }
  154. }
  155. }
  156. internal sealed class SNIPacket : SafeHandle {
  157. internal SNIPacket(SafeHandle sniHandle) : base(IntPtr.Zero, true) {
  158. SNINativeMethodWrapper.SNIPacketAllocate(sniHandle, SNINativeMethodWrapper.IOType.WRITE, ref base.handle);
  159. if (IntPtr.Zero == base.handle) {
  160. throw SQL.SNIPacketAllocationFailure();
  161. }
  162. }
  163. public override bool IsInvalid {
  164. get {
  165. return (IntPtr.Zero == base.handle);
  166. }
  167. }
  168. override protected bool ReleaseHandle() {
  169. // NOTE: The SafeHandle class guarantees this will be called exactly once.
  170. IntPtr ptr = base.handle;
  171. base.handle = IntPtr.Zero;
  172. if (IntPtr.Zero != ptr) {
  173. SNINativeMethodWrapper.SNIPacketRelease(ptr);
  174. }
  175. return true;
  176. }
  177. }
  178. internal sealed class WritePacketCache : IDisposable {
  179. private bool _disposed;
  180. private Stack<SNIPacket> _packets;
  181. public WritePacketCache() {
  182. _disposed = false;
  183. _packets = new Stack<SNIPacket>();
  184. }
  185. public SNIPacket Take(SNIHandle sniHandle) {
  186. SNIPacket packet;
  187. if (_packets.Count > 0) {
  188. // Success - reset the packet
  189. packet = _packets.Pop();
  190. SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
  191. }
  192. else {
  193. // Failed to take a packet - create a new one
  194. packet = new SNIPacket(sniHandle);
  195. }
  196. return packet;
  197. }
  198. public void Add(SNIPacket packet) {
  199. if (!_disposed) {
  200. _packets.Push(packet);
  201. }
  202. else {
  203. // If we're disposed, then get rid of any packets added to us
  204. packet.Dispose();
  205. }
  206. }
  207. public void Clear() {
  208. while (_packets.Count > 0) {
  209. _packets.Pop().Dispose();
  210. }
  211. }
  212. public void Dispose() {
  213. if (!_disposed) {
  214. _disposed = true;
  215. Clear();
  216. }
  217. }
  218. }
  219. }