File: PipeWin32.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (386 lines) | stat: -rw-r--r-- 11,442 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
//
// PipeWin32.cs
//
// Author:
//	Atsushi Enomoto <atsushi@ximian.com>
//
// Copyright (C) 2009 Novell, Inc.  http://www.novell.com
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

#if !BOOTSTRAP_BASIC

using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Permissions;
using System.Security.Principal;
using System.Text;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

namespace System.IO.Pipes
{
	static class Win32PipeError
	{
		public static Exception GetException ()
		{
			return GetException (Marshal.GetLastWin32Error ());
		}
		
		public static Exception GetException (int errorCode)
		{
			switch (errorCode) {
			case 5: return new UnauthorizedAccessException ();
			default: return new Win32Exception (errorCode);
			}
		}
	}
	
	abstract class Win32AnonymousPipe : IPipe
	{
		protected Win32AnonymousPipe ()
		{
		}

		public abstract SafePipeHandle Handle { get; }

		public void WaitForPipeDrain ()
		{
			throw new NotImplementedException ();
		}
	}

	class Win32AnonymousPipeClient : Win32AnonymousPipe, IAnonymousPipeClient
	{
		// AnonymousPipeClientStream owner;

		public Win32AnonymousPipeClient (AnonymousPipeClientStream owner, SafePipeHandle handle)
		{
			// this.owner = owner;

			this.handle = handle;
		}

		SafePipeHandle handle;

		public override SafePipeHandle Handle {
			get { return handle; }
		}
	}

	class Win32AnonymousPipeServer : Win32AnonymousPipe, IAnonymousPipeServer
	{
		// AnonymousPipeServerStream owner;

		public unsafe Win32AnonymousPipeServer (AnonymousPipeServerStream owner, PipeDirection direction,
							HandleInheritability inheritability, int bufferSize,
							PipeSecurity pipeSecurity)
		{
			IntPtr r, w;
			
			byte[] securityDescriptor = null;
			if (pipeSecurity != null)
				securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm ();
				
			fixed (byte* securityDescriptorPtr = securityDescriptor) {
				SecurityAttributes att = new SecurityAttributes (inheritability, (IntPtr)securityDescriptorPtr);
				if (!Win32Marshal.CreatePipe (out r, out w, ref att, bufferSize))
					throw Win32PipeError.GetException ();
			}

			var rh = new SafePipeHandle (r, true);
			var wh = new SafePipeHandle (w, true);

			if (direction == PipeDirection.Out) {
				server_handle = wh;
				client_handle = rh;
			} else {
				server_handle = rh;
				client_handle = wh;
			}
		}

		public Win32AnonymousPipeServer (AnonymousPipeServerStream owner, SafePipeHandle serverHandle, SafePipeHandle clientHandle)
		{
			// this.owner = owner;
			this.server_handle = serverHandle;
			this.client_handle = clientHandle;
		}

		SafePipeHandle server_handle, client_handle;

		public override SafePipeHandle Handle {
			get { return server_handle; }
		}

		public SafePipeHandle ClientHandle {
			get { return client_handle; }
		}

		public void DisposeLocalCopyOfClientHandle ()
		{
			throw new NotImplementedException ();
		}
	}

	abstract class Win32NamedPipe : IPipe
	{
		string name_cache;

		public string Name {
			get {
				if (name_cache != null)
					return name_cache;

				int s, c, m, t;
				byte [] un = new byte [200];
				while (true) {
					if (!Win32Marshal.GetNamedPipeHandleState (Handle, out s, out c, out m, out t, un, un.Length))
						throw Win32PipeError.GetException ();

					if (un [un.Length - 1] == 0)
						break;
					un = new byte [un.Length * 10];
				}
				name_cache = Encoding.Default.GetString (un);
				return name_cache;
			}
		}

		public abstract SafePipeHandle Handle { get; }

		public void WaitForPipeDrain ()
		{
			throw new NotImplementedException ();
		}
	}

	class Win32NamedPipeClient : Win32NamedPipe, INamedPipeClient
	{
		NamedPipeClientStream owner;

		// .ctor with existing handle
		public Win32NamedPipeClient (NamedPipeClientStream owner, SafePipeHandle safePipeHandle)
		{
			this.handle = safePipeHandle;
			this.owner = owner;

			// FIXME: retrieve is_async from state?
		}

		// .ctor without handle - create new
		public Win32NamedPipeClient (NamedPipeClientStream owner, string serverName, string pipeName,
					     PipeAccessRights desiredAccessRights, PipeOptions options,
					     HandleInheritability inheritability)
		{
			name = String.Format ("\\\\{0}\\pipe\\{1}", serverName, pipeName);
			var att = new SecurityAttributes (inheritability, IntPtr.Zero);
			is_async = (options & PipeOptions.Asynchronous) != PipeOptions.None;

			opener = delegate {
				var ret = Win32Marshal.CreateFile (name, desiredAccessRights, 0, ref att, 3, 0, IntPtr.Zero);
				if (ret == new IntPtr (-1L))
					throw Win32PipeError.GetException ();

				return new SafePipeHandle (ret, true);
			};
			this.owner = owner;
		}

		Func<SafePipeHandle> opener;
		bool is_async;
		string name;
		SafePipeHandle handle;

		public override SafePipeHandle Handle {
			get { return handle; }
		}

		public bool IsAsync {
			get { return is_async; }
		}

		public void Connect ()
		{
			if (owner.IsConnected)
				throw new InvalidOperationException ("The named pipe is already connected");

			handle = opener ();
		}

		public void Connect (int timeout)
		{
			if (owner.IsConnected)
				throw new InvalidOperationException ("The named pipe is already connected");

			if (!Win32Marshal.WaitNamedPipe (name, timeout))
				throw Win32PipeError.GetException ();
			Connect ();
		}

		public int NumberOfServerInstances {
			get {
				int s, c, m, t;
				byte [] un = null;
				if (!Win32Marshal.GetNamedPipeHandleState (Handle, out s, out c, out m, out t, un, 0))
					throw Win32PipeError.GetException ();
				return c;
			}
		}
	}

	class Win32NamedPipeServer : Win32NamedPipe, INamedPipeServer
	{
		//NamedPipeServerStream owner;

		// .ctor with existing handle
		public Win32NamedPipeServer (NamedPipeServerStream owner, SafePipeHandle safePipeHandle)
		{
			handle = safePipeHandle;
			//this.owner = owner;
		}

		// .ctor without handle - create new
		public unsafe Win32NamedPipeServer (NamedPipeServerStream owner, string pipeName, int maxNumberOfServerInstances,
						    PipeTransmissionMode transmissionMode, PipeAccessRights rights,
						    PipeOptions options, int inBufferSize, int outBufferSize,
						    PipeSecurity pipeSecurity, HandleInheritability inheritability)
		{
			string name = String.Format ("\\\\.\\pipe\\{0}", pipeName);

			uint openMode;
			openMode = (uint)rights | (uint)options; // Enum values match Win32 flags exactly.
			
			int pipeMode = 0;
			if ((owner.TransmissionMode & PipeTransmissionMode.Message) != 0)
				pipeMode |= 4;
			//if ((readTransmissionMode & PipeTransmissionMode.Message) != 0)
			//	pipeMode |= 2;
			if ((options & PipeOptions.Asynchronous) != 0)
				pipeMode |= 1;

			byte[] securityDescriptor = null;
			if (pipeSecurity != null)
				securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm ();
			
			fixed (byte* securityDescriptorPtr = securityDescriptor) {
				// FIXME: is nDefaultTimeout = 0 ok?
				var att = new SecurityAttributes (inheritability, (IntPtr)securityDescriptorPtr);
				var ret = Win32Marshal.CreateNamedPipe (name, openMode, pipeMode, maxNumberOfServerInstances,
									outBufferSize, inBufferSize, 0, ref att, IntPtr.Zero);
				if (ret == new IntPtr (-1L))
					throw Win32PipeError.GetException ();
				handle = new SafePipeHandle (ret, true);
			}
		}

		SafePipeHandle handle;

		public override SafePipeHandle Handle {
			get { return handle; }
		}

		public void Disconnect ()
		{
			Win32Marshal.DisconnectNamedPipe (Handle);
		}

		public void WaitForConnection ()
		{
			if (!Win32Marshal.ConnectNamedPipe (Handle, IntPtr.Zero))
				throw Win32PipeError.GetException ();
		}
	}

	[StructLayout (LayoutKind.Sequential)]
	struct SecurityAttributes
	{
		public readonly int Length;
		public readonly IntPtr SecurityDescriptor;
		public readonly bool Inheritable;

		public SecurityAttributes (HandleInheritability inheritability, IntPtr securityDescriptor)
		{
			Length = Marshal.SizeOf (typeof (SecurityAttributes));
			SecurityDescriptor = securityDescriptor;
			Inheritable = inheritability == HandleInheritability.Inheritable;
		}
	}

	static class Win32Marshal
	{
		internal static bool IsWindows {
			get {
				switch (Environment.OSVersion.Platform) {
				case PlatformID.Win32S:
				case PlatformID.Win32Windows:
				case PlatformID.Win32NT:
				case PlatformID.WinCE:
					return true;
				default:
					return false;
				}
			}
		}

		// http://msdn.microsoft.com/en-us/library/aa365152%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern bool CreatePipe (out IntPtr readHandle, out IntPtr writeHandle,
							ref SecurityAttributes pipeAtts, int size);

		// http://msdn.microsoft.com/en-us/library/aa365150%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern IntPtr CreateNamedPipe (string name, uint openMode, int pipeMode, int maxInstances,
							       int outBufferSize, int inBufferSize, int defaultTimeout,
							       ref SecurityAttributes securityAttributes, IntPtr atts);

		// http://msdn.microsoft.com/en-us/library/aa365146%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern bool ConnectNamedPipe (SafePipeHandle handle, IntPtr overlapped);

		// http://msdn.microsoft.com/en-us/library/aa365166%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern bool DisconnectNamedPipe (SafePipeHandle handle);

		// http://msdn.microsoft.com/en-us/library/aa365443%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern bool GetNamedPipeHandleState (SafePipeHandle handle,
								     out int state, out int curInstances,
								     out int maxCollectionCount, out int collectDateTimeout,
								     byte [] userName, int maxUserNameSize);

		// http://msdn.microsoft.com/en-us/library/aa365800%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern bool WaitNamedPipe (string name, int timeout);

		// http://msdn.microsoft.com/en-us/library/aa363858%28VS.85%29.aspx
		[DllImport ("kernel32", SetLastError=true)]
		internal static extern IntPtr CreateFile (string name, PipeAccessRights desiredAccess, FileShare fileShare,
					      ref SecurityAttributes atts, int creationDisposition, int flags, IntPtr templateHandle);

	}
}

#endif