PipeWin32.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. //
  2. // PipeWin32.cs
  3. //
  4. // Author:
  5. // Atsushi Enomoto <[email protected]>
  6. //
  7. // Copyright (C) 2009 Novell, Inc. http://www.novell.com
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining
  10. // a copy of this software and associated documentation files (the
  11. // "Software"), to deal in the Software without restriction, including
  12. // without limitation the rights to use, copy, modify, merge, publish,
  13. // distribute, sublicense, and/or sell copies of the Software, and to
  14. // permit persons to whom the Software is furnished to do so, subject to
  15. // the following conditions:
  16. //
  17. // The above copyright notice and this permission notice shall be
  18. // included in all copies or substantial portions of the Software.
  19. //
  20. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  21. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  22. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  23. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  24. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  25. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  26. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  27. //
  28. #if !BOOTSTRAP_BASIC
  29. using System;
  30. using System.ComponentModel;
  31. using System.IO;
  32. using System.Linq;
  33. using System.Runtime.InteropServices;
  34. using System.Security.AccessControl;
  35. using System.Security.Permissions;
  36. using System.Security.Principal;
  37. using System.Text;
  38. using Microsoft.Win32;
  39. using Microsoft.Win32.SafeHandles;
  40. namespace System.IO.Pipes
  41. {
  42. abstract class Win32AnonymousPipe : IPipe
  43. {
  44. protected Win32AnonymousPipe ()
  45. {
  46. }
  47. public abstract SafePipeHandle Handle { get; }
  48. public void WaitForPipeDrain ()
  49. {
  50. throw new NotImplementedException ();
  51. }
  52. }
  53. class Win32AnonymousPipeClient : Win32AnonymousPipe, IAnonymousPipeClient
  54. {
  55. // AnonymousPipeClientStream owner;
  56. public Win32AnonymousPipeClient (AnonymousPipeClientStream owner, SafePipeHandle handle)
  57. {
  58. // this.owner = owner;
  59. this.handle = handle;
  60. }
  61. SafePipeHandle handle;
  62. public override SafePipeHandle Handle {
  63. get { return handle; }
  64. }
  65. }
  66. class Win32AnonymousPipeServer : Win32AnonymousPipe, IAnonymousPipeServer
  67. {
  68. // AnonymousPipeServerStream owner;
  69. public Win32AnonymousPipeServer (AnonymousPipeServerStream owner, PipeDirection direction, HandleInheritability inheritability, int bufferSize)
  70. {
  71. IntPtr r, w;
  72. SecurityAttributesHack att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable);
  73. if (!Win32Marshal.CreatePipe (out r, out w, ref att, bufferSize))
  74. throw new Win32Exception (Marshal.GetLastWin32Error ());
  75. var rh = new SafePipeHandle (r, true);
  76. var wh = new SafePipeHandle (w, true);
  77. if (direction == PipeDirection.Out) {
  78. server_handle = wh;
  79. client_handle = rh;
  80. } else {
  81. server_handle = rh;
  82. client_handle = wh;
  83. }
  84. }
  85. public Win32AnonymousPipeServer (AnonymousPipeServerStream owner, SafePipeHandle serverHandle, SafePipeHandle clientHandle)
  86. {
  87. // this.owner = owner;
  88. this.server_handle = serverHandle;
  89. this.client_handle = clientHandle;
  90. }
  91. SafePipeHandle server_handle, client_handle;
  92. public override SafePipeHandle Handle {
  93. get { return server_handle; }
  94. }
  95. public SafePipeHandle ClientHandle {
  96. get { return client_handle; }
  97. }
  98. public void DisposeLocalCopyOfClientHandle ()
  99. {
  100. throw new NotImplementedException ();
  101. }
  102. }
  103. abstract class Win32NamedPipe : IPipe
  104. {
  105. string name_cache;
  106. public string Name {
  107. get {
  108. if (name_cache != null)
  109. return name_cache;
  110. int s, c, m, t;
  111. byte [] un = new byte [200];
  112. while (true) {
  113. if (!Win32Marshal.GetNamedPipeHandleState (Handle, out s, out c, out m, out t, un, un.Length)) {
  114. var xxx = Marshal.GetLastWin32Error ();
  115. throw new Win32Exception (xxx);
  116. }
  117. if (un [un.Length - 1] == 0)
  118. break;
  119. un = new byte [un.Length * 10];
  120. }
  121. name_cache = Encoding.Default.GetString (un);
  122. return name_cache;
  123. }
  124. }
  125. public abstract SafePipeHandle Handle { get; }
  126. public void WaitForPipeDrain ()
  127. {
  128. throw new NotImplementedException ();
  129. }
  130. }
  131. class Win32NamedPipeClient : Win32NamedPipe, INamedPipeClient
  132. {
  133. NamedPipeClientStream owner;
  134. // .ctor with existing handle
  135. public Win32NamedPipeClient (NamedPipeClientStream owner, SafePipeHandle safePipeHandle)
  136. {
  137. this.handle = safePipeHandle;
  138. this.owner = owner;
  139. // FIXME: retrieve is_async from state?
  140. }
  141. // .ctor without handle - create new
  142. public Win32NamedPipeClient (NamedPipeClientStream owner, string serverName, string pipeName, PipeAccessRights desiredAccessRights, PipeOptions options, HandleInheritability inheritability)
  143. {
  144. name = String.Format ("\\\\{0}\\pipe\\{1}", serverName, pipeName);
  145. var att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable);
  146. is_async = (options & PipeOptions.Asynchronous) != PipeOptions.None;
  147. opener = delegate {
  148. var ret = Win32Marshal.CreateFile (name, desiredAccessRights, 0, ref att, 3, 0, IntPtr.Zero);
  149. if (ret == new IntPtr (-1L))
  150. throw new Win32Exception (Marshal.GetLastWin32Error ());
  151. return new SafePipeHandle (ret, true);
  152. };
  153. this.owner = owner;
  154. }
  155. Func<SafePipeHandle> opener;
  156. bool is_async;
  157. string name;
  158. SafePipeHandle handle;
  159. public override SafePipeHandle Handle {
  160. get { return handle; }
  161. }
  162. public bool IsAsync {
  163. get { return is_async; }
  164. }
  165. public void Connect ()
  166. {
  167. if (owner.IsConnected)
  168. throw new InvalidOperationException ("The named pipe is already connected");
  169. handle = opener ();
  170. }
  171. public void Connect (int timeout)
  172. {
  173. if (owner.IsConnected)
  174. throw new InvalidOperationException ("The named pipe is already connected");
  175. if (!Win32Marshal.WaitNamedPipe (name, timeout))
  176. throw new Win32Exception (Marshal.GetLastWin32Error ());
  177. Connect ();
  178. }
  179. public int NumberOfServerInstances {
  180. get {
  181. int s, c, m, t;
  182. byte [] un = null;
  183. if (!Win32Marshal.GetNamedPipeHandleState (Handle, out s, out c, out m, out t, un, 0))
  184. throw new Win32Exception (Marshal.GetLastWin32Error ());
  185. return c;
  186. }
  187. }
  188. }
  189. class Win32NamedPipeServer : Win32NamedPipe, INamedPipeServer
  190. {
  191. //NamedPipeServerStream owner;
  192. // .ctor with existing handle
  193. public Win32NamedPipeServer (NamedPipeServerStream owner, SafePipeHandle safePipeHandle)
  194. {
  195. handle = safePipeHandle;
  196. //this.owner = owner;
  197. }
  198. // .ctor without handle - create new
  199. public Win32NamedPipeServer (NamedPipeServerStream owner, string pipeName, int maxNumberOfServerInstances, PipeTransmissionMode transmissionMode, PipeAccessRights rights, PipeOptions options, int inBufferSize, int outBufferSize, HandleInheritability inheritability)
  200. {
  201. string name = String.Format ("\\\\.\\pipe\\{0}", pipeName);
  202. uint openMode = 0;
  203. if ((rights & PipeAccessRights.ReadData) != 0)
  204. openMode |= 1;
  205. if ((rights & PipeAccessRights.WriteData) != 0)
  206. openMode |= 2;
  207. if ((options & PipeOptions.WriteThrough) != 0)
  208. openMode |= 0x80000000;
  209. int pipeMode = 0;
  210. if ((owner.TransmissionMode & PipeTransmissionMode.Message) != 0)
  211. pipeMode |= 4;
  212. //if ((readTransmissionMode & PipeTransmissionMode.Message) != 0)
  213. // pipeMode |= 2;
  214. if ((options & PipeOptions.Asynchronous) != 0)
  215. pipeMode |= 1;
  216. // FIXME: is nDefaultTimeout = 0 ok?
  217. var att = new SecurityAttributesHack (inheritability == HandleInheritability.Inheritable);
  218. var ret = Win32Marshal.CreateNamedPipe (name, openMode, pipeMode, maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref att, IntPtr.Zero);
  219. if (ret == new IntPtr (-1L))
  220. throw new Win32Exception (Marshal.GetLastWin32Error ());
  221. handle = new SafePipeHandle (ret, true);
  222. }
  223. SafePipeHandle handle;
  224. public override SafePipeHandle Handle {
  225. get { return handle; }
  226. }
  227. public void Disconnect ()
  228. {
  229. Win32Marshal.DisconnectNamedPipe (Handle);
  230. }
  231. public void WaitForConnection ()
  232. {
  233. if (!Win32Marshal.ConnectNamedPipe (Handle, IntPtr.Zero))
  234. throw new Win32Exception (Marshal.GetLastWin32Error ());
  235. }
  236. }
  237. [StructLayout (LayoutKind.Sequential)]
  238. struct SecurityAttributesHack
  239. {
  240. public readonly int Length;
  241. public readonly IntPtr SecurityDescriptor;
  242. public readonly bool Inheritable;
  243. public SecurityAttributesHack (bool inheritable)
  244. {
  245. Length = 0;
  246. SecurityDescriptor = IntPtr.Zero;
  247. Inheritable = inheritable;
  248. }
  249. }
  250. static class Win32Marshal
  251. {
  252. internal static bool IsWindows {
  253. get {
  254. switch (Environment.OSVersion.Platform) {
  255. case PlatformID.Win32S:
  256. case PlatformID.Win32Windows:
  257. case PlatformID.Win32NT:
  258. case PlatformID.WinCE:
  259. return true;
  260. default:
  261. return false;
  262. }
  263. }
  264. }
  265. // http://msdn.microsoft.com/en-us/library/aa365152%28VS.85%29.aspx
  266. [DllImport ("kernel32")]
  267. internal static extern bool CreatePipe (out IntPtr readHandle, out IntPtr writeHandle, ref SecurityAttributesHack pipeAtts, int size);
  268. // http://msdn.microsoft.com/en-us/library/aa365150%28VS.85%29.aspx
  269. [DllImport ("kernel32")]
  270. internal static extern IntPtr CreateNamedPipe (string name, uint openMode, int pipeMode, int maxInstances, int outBufferSize, int inBufferSize, int defaultTimeout, ref SecurityAttributesHack securityAttributes, IntPtr atts);
  271. // http://msdn.microsoft.com/en-us/library/aa365146%28VS.85%29.aspx
  272. [DllImport ("kernel32")]
  273. internal static extern bool ConnectNamedPipe (SafePipeHandle handle, IntPtr overlapped);
  274. // http://msdn.microsoft.com/en-us/library/aa365166%28VS.85%29.aspx
  275. [DllImport ("kernel32")]
  276. internal static extern bool DisconnectNamedPipe (SafePipeHandle handle);
  277. // http://msdn.microsoft.com/en-us/library/aa365443%28VS.85%29.aspx
  278. [DllImport ("kernel32")]
  279. internal static extern bool GetNamedPipeHandleState (SafePipeHandle handle, out int state, out int curInstances, out int maxCollectionCount, out int collectDateTimeout, byte [] userName, int maxUserNameSize);
  280. // http://msdn.microsoft.com/en-us/library/aa365800%28VS.85%29.aspx
  281. [DllImport ("kernel32")]
  282. internal static extern bool WaitNamedPipe (string name, int timeout);
  283. // http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx
  284. [DllImport ("kernel32")]
  285. internal static extern IntPtr CreateFile (string name, PipeAccessRights desiredAccess, FileShare fileShare, ref SecurityAttributesHack atts, int creationDisposition, int flags, IntPtr templateHandle);
  286. }
  287. }
  288. #endif