NamedPipeSocket.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. //
  2. // System.Runtime.Remoting.Channels.Ipc.Win32.NamedPipeSocket.cs
  3. //
  4. // Author: Robert Jordan ([email protected])
  5. //
  6. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  7. //
  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 NET_2_0
  29. using System;
  30. using System.IO;
  31. using System.Runtime.InteropServices;
  32. using System.Runtime.Remoting.Messaging;
  33. using System.Text;
  34. namespace System.Runtime.Remoting.Channels.Ipc.Win32
  35. {
  36. /// <summary>
  37. /// Implements a local Named Pipe socket.
  38. /// </summary>
  39. internal class NamedPipeSocket : IDisposable
  40. {
  41. IntPtr hPipe;
  42. /// <summary>
  43. /// Creates a new socket instance form the specified local Named Pipe handle.
  44. /// </summary>
  45. /// <param name="hPipe">The handle.</param>
  46. internal NamedPipeSocket(IntPtr hPipe)
  47. {
  48. this.hPipe = hPipe;
  49. this.info = new NamedPipeSocketInfo(hPipe);
  50. }
  51. ~NamedPipeSocket()
  52. {
  53. ((IDisposable)this).Dispose();
  54. }
  55. /// <summary>
  56. /// Gets the NamedPipeSocketInfo of this instance.
  57. /// </summary>
  58. /// <returns></returns>
  59. public NamedPipeSocketInfo Info
  60. {
  61. get
  62. {
  63. return info;
  64. }
  65. }
  66. NamedPipeSocketInfo info;
  67. /// <summary>
  68. /// Closes the socket.
  69. /// </summary>
  70. public void Close()
  71. {
  72. ((IDisposable)this).Dispose();
  73. }
  74. /// <summary>
  75. /// Disposes the object.
  76. /// </summary>
  77. void IDisposable.Dispose()
  78. {
  79. if (hPipe != IntPtr.Zero)
  80. {
  81. try
  82. {
  83. // disconnect the pipe
  84. if (Info.IsServer)
  85. {
  86. NamedPipeHelper.FlushFileBuffers(hPipe);
  87. NamedPipeHelper.DisconnectNamedPipe(hPipe);
  88. }
  89. }
  90. catch (NamedPipeException)
  91. {
  92. }
  93. NamedPipeHelper.CloseHandle(hPipe);
  94. hPipe = IntPtr.Zero;
  95. GC.SuppressFinalize(this);
  96. }
  97. }
  98. /// <summary>
  99. /// Returns the stream used to send and receive data.
  100. /// </summary>
  101. /// <returns></returns>
  102. public Stream GetStream()
  103. {
  104. if (hPipe == IntPtr.Zero)
  105. throw new ObjectDisposedException(GetType().FullName);
  106. return stream == null
  107. ? stream = new NamedPipeStream(this, false)
  108. : stream;
  109. }
  110. Stream stream;
  111. /// <summary>
  112. /// Returns the stream used to send and receive data. The stream disposes
  113. /// the socket on close.
  114. /// </summary>
  115. /// <returns></returns>
  116. public Stream GetClosingStream()
  117. {
  118. if (hPipe == IntPtr.Zero)
  119. throw new ObjectDisposedException(GetType().FullName);
  120. return new NamedPipeStream(this, true);
  121. }
  122. /// <summary>
  123. /// Flushes the socket.
  124. /// </summary>
  125. public void Flush()
  126. {
  127. if (hPipe == IntPtr.Zero)
  128. throw new ObjectDisposedException(GetType().FullName);
  129. NamedPipeHelper.FlushFileBuffers(hPipe);
  130. }
  131. /// <summary>
  132. /// Receives the specified number of bytes from a socket into
  133. /// the specified offset position of the receive buffer.
  134. /// </summary>
  135. /// <param name="buffer">An array of type Byte that is the storage
  136. /// location for received data.</param>
  137. /// <param name="offset">The location in buffer to store the received data.</param>
  138. /// <param name="count">The number of bytes to receive.</param>
  139. /// <returns>The number of bytes received.</returns>
  140. public int Receive(byte[] buffer, int offset, int count)
  141. {
  142. if (hPipe == IntPtr.Zero)
  143. throw new ObjectDisposedException(GetType().FullName);
  144. if (buffer == null)
  145. throw new ArgumentNullException("buffer");
  146. if (offset < 0 || count < 0)
  147. throw new ArgumentOutOfRangeException("offset and/or count");
  148. if (buffer.Length - offset < count)
  149. throw new ArgumentException();
  150. uint read = 0;
  151. GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  152. try
  153. {
  154. bool res = NamedPipeHelper.ReadFile(
  155. hPipe,
  156. Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
  157. (uint) count,
  158. out read,
  159. IntPtr.Zero
  160. );
  161. if (!res && read == 0) throw new NamedPipeException();
  162. return (int) read;
  163. }
  164. finally
  165. {
  166. gch.Free();
  167. }
  168. }
  169. delegate int ReceiveMethod(byte[] buffer, int offset, int count);
  170. public IAsyncResult BeginReceive(byte[] buffer, int offset, int count,
  171. AsyncCallback callback, object state)
  172. {
  173. return new ReceiveMethod(Receive).BeginInvoke(buffer, offset, count, callback, state);
  174. }
  175. public int EndReceive(IAsyncResult asyncResult)
  176. {
  177. AsyncResult ar = asyncResult as AsyncResult;
  178. return ((ReceiveMethod)ar.AsyncDelegate).EndInvoke(asyncResult);
  179. }
  180. /// <summary>
  181. /// Sends the specified number of bytes of data to a connected socket,
  182. /// starting at the specified offset.
  183. /// </summary>
  184. /// <param name="buffer">An array of type Byte that contains the data to be sent.</param>
  185. /// <param name="offset">The position in the data buffer at which to begin sending data. </param>
  186. /// <param name="count">The number of bytes to send.</param>
  187. /// <returns>The number of bytes sent.</returns>
  188. public int Send(byte[] buffer, int offset, int count)
  189. {
  190. if (hPipe == IntPtr.Zero)
  191. throw new ObjectDisposedException(GetType().FullName);
  192. if (buffer == null)
  193. throw new ArgumentNullException("buffer");
  194. if (offset < 0 || count < 0)
  195. throw new ArgumentOutOfRangeException("offset and/or count");
  196. if (buffer.Length - offset < count)
  197. throw new ArgumentException();
  198. uint written = 0;
  199. GCHandle gch = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  200. try
  201. {
  202. bool res = NamedPipeHelper.WriteFile(
  203. hPipe,
  204. Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset),
  205. (uint) count,
  206. out written,
  207. IntPtr.Zero
  208. );
  209. if (!res) throw new NamedPipeException();
  210. return (int) written;
  211. }
  212. finally
  213. {
  214. gch.Free();
  215. }
  216. }
  217. delegate int SendMethod(byte[] buffer, int offset, int count);
  218. public IAsyncResult BeginSend(byte[] buffer, int offset, int count,
  219. AsyncCallback callback, object state)
  220. {
  221. return new SendMethod(Send).BeginInvoke(buffer, offset, count, callback, state);
  222. }
  223. public int EndSend(IAsyncResult asyncResult)
  224. {
  225. AsyncResult ar = asyncResult as AsyncResult;
  226. return ((SendMethod)ar.AsyncDelegate).EndInvoke(asyncResult);
  227. }
  228. /// <summary>
  229. /// Returns the current NamedPipeSocketState of this instance.
  230. /// </summary>
  231. /// <returns></returns>
  232. public NamedPipeSocketState GetSocketState()
  233. {
  234. if (hPipe == IntPtr.Zero)
  235. throw new ObjectDisposedException(GetType().FullName);
  236. return new NamedPipeSocketState(hPipe);
  237. }
  238. /// <summary>
  239. /// Impersonates the client.
  240. /// </summary>
  241. public void Impersonate()
  242. {
  243. if (hPipe == IntPtr.Zero)
  244. throw new ObjectDisposedException(GetType().FullName);
  245. if (Info.IsServer)
  246. if (!NamedPipeHelper.ImpersonateNamedPipeClient(hPipe))
  247. throw new NamedPipeException();
  248. }
  249. /// <summary>
  250. /// Reverts the impersonation.
  251. /// </summary>
  252. public static bool RevertToSelf()
  253. {
  254. return NamedPipeHelper.RevertToSelf();
  255. }
  256. }
  257. /// <summary>
  258. /// Represents local Named Pipe informations.
  259. /// </summary>
  260. internal class NamedPipeSocketInfo
  261. {
  262. public readonly int Flags;
  263. public readonly int OutBufferSize;
  264. public readonly int InBufferSize;
  265. public readonly int MaxInstances;
  266. public bool IsServer
  267. {
  268. get
  269. {
  270. return (Flags & NamedPipeHelper.PIPE_SERVER_END) != 0;
  271. }
  272. }
  273. internal NamedPipeSocketInfo(IntPtr hPipe)
  274. {
  275. bool res = NamedPipeHelper.GetNamedPipeInfo(
  276. hPipe,
  277. out Flags,
  278. out OutBufferSize,
  279. out InBufferSize,
  280. out MaxInstances
  281. );
  282. if (!res)
  283. {
  284. throw new NamedPipeException();
  285. }
  286. }
  287. }
  288. /// <summary>
  289. /// Represents local Named Pipe state informations.
  290. /// </summary>
  291. internal class NamedPipeSocketState
  292. {
  293. public readonly int State;
  294. public readonly int CurrentInstances;
  295. public readonly int MaxCollectionCount;
  296. public readonly int CollectDataTimeout;
  297. public readonly string UserName;
  298. internal NamedPipeSocketState(IntPtr hPipe)
  299. {
  300. StringBuilder userName = new StringBuilder(256);
  301. bool res = NamedPipeHelper.GetNamedPipeHandleState(
  302. hPipe,
  303. out State,
  304. out CurrentInstances,
  305. out MaxCollectionCount,
  306. out CollectDataTimeout,
  307. userName,
  308. userName.Capacity
  309. );
  310. if (res)
  311. {
  312. UserName = userName.ToString();
  313. }
  314. else
  315. {
  316. throw new NamedPipeException();
  317. }
  318. }
  319. }
  320. }
  321. #endif