-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathNamedPipeServerStream.Windows.cs
372 lines (319 loc) · 15.9 KB
/
NamedPipeServerStream.Windows.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32.SafeHandles;
namespace System.IO.Pipes
{
/// <summary>
/// Named pipe server
/// </summary>
public sealed partial class NamedPipeServerStream : PipeStream
{
private ConnectionValueTaskSource? _reusableConnectionValueTaskSource; // reusable ConnectionValueTaskSource that is currently NOT being used
internal NamedPipeServerStream(
string pipeName,
PipeDirection direction,
int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode,
PipeOptions options,
int inBufferSize,
int outBufferSize,
PipeSecurity? pipeSecurity,
HandleInheritability inheritability = HandleInheritability.None,
PipeAccessRights additionalAccessRights = default)
: base(direction, transmissionMode, outBufferSize)
{
ValidateParameters(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, inheritability);
if (pipeSecurity != null && IsCurrentUserOnly)
{
throw new ArgumentException(SR.NotSupported_PipeSecurityIsCurrentUserOnly, nameof(pipeSecurity));
}
Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize, outBufferSize, pipeSecurity, inheritability, additionalAccessRights);
}
protected override void Dispose(bool disposing)
{
try
{
Interlocked.Exchange(ref _reusableConnectionValueTaskSource, null)?.Dispose();
}
finally
{
base.Dispose(disposing);
}
}
internal override void TryToReuse(PipeValueTaskSource source)
{
base.TryToReuse(source);
if (source is ConnectionValueTaskSource connectionSource)
{
if (Interlocked.CompareExchange(ref _reusableConnectionValueTaskSource, connectionSource, null) is not null)
{
source._preallocatedOverlapped.Dispose();
}
}
}
private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
HandleInheritability inheritability)
{
Create(pipeName, direction, maxNumberOfServerInstances, transmissionMode, options, inBufferSize,
outBufferSize, null, inheritability, 0);
}
// This overload is used in Mono to implement public constructors.
private void Create(string pipeName, PipeDirection direction, int maxNumberOfServerInstances,
PipeTransmissionMode transmissionMode, PipeOptions options, int inBufferSize, int outBufferSize,
PipeSecurity? pipeSecurity, HandleInheritability inheritability, PipeAccessRights additionalAccessRights)
{
Debug.Assert(pipeName != null && pipeName.Length != 0, "fullPipeName is null or empty");
Debug.Assert(direction >= PipeDirection.In && direction <= PipeDirection.InOut, "invalid pipe direction");
Debug.Assert(inBufferSize >= 0, "inBufferSize is negative");
Debug.Assert(outBufferSize >= 0, "outBufferSize is negative");
Debug.Assert((maxNumberOfServerInstances >= 1 && maxNumberOfServerInstances <= 254) || (maxNumberOfServerInstances == MaxAllowedServerInstances), "maxNumberOfServerInstances is invalid");
Debug.Assert(transmissionMode >= PipeTransmissionMode.Byte && transmissionMode <= PipeTransmissionMode.Message, "transmissionMode is out of range");
string fullPipeName = Path.GetFullPath(@"\\.\pipe\" + pipeName);
// Make sure the pipe name isn't one of our reserved names for anonymous pipes.
if (string.Equals(fullPipeName, @"\\.\pipe\anonymous", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved);
}
if (IsCurrentUserOnly)
{
Debug.Assert(pipeSecurity == null);
using (WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent())
{
SecurityIdentifier identifier = currentIdentity.Owner!;
// Grant full control to the owner so multiple servers can be opened.
// Full control is the default per MSDN docs for CreateNamedPipe.
PipeAccessRule rule = new PipeAccessRule(identifier, PipeAccessRights.FullControl, AccessControlType.Allow);
pipeSecurity = new PipeSecurity();
pipeSecurity.AddAccessRule(rule);
pipeSecurity.SetOwner(identifier);
}
// PipeOptions.CurrentUserOnly is special since it doesn't match directly to a corresponding Win32 valid flag.
// Remove it, while keeping others untouched since historically this has been used as a way to pass flags to CreateNamedPipe
// that were not defined in the enumeration.
options &= ~PipeOptions.CurrentUserOnly;
}
int openMode = ((int)direction) |
(maxNumberOfServerInstances == 1 ? Interop.Kernel32.FileOperations.FILE_FLAG_FIRST_PIPE_INSTANCE : 0) |
(int)options |
(int)additionalAccessRights;
// We automatically set the ReadMode to match the TransmissionMode.
int pipeModes = (int)transmissionMode << 2 | (int)transmissionMode << 1;
// Convert -1 to 255 to match win32 (we asserted that it is between -1 and 254).
if (maxNumberOfServerInstances == MaxAllowedServerInstances)
{
maxNumberOfServerInstances = 255;
}
GCHandle pinningHandle = default;
try
{
Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability, pipeSecurity, ref pinningHandle);
SafePipeHandle handle = Interop.Kernel32.CreateNamedPipe(fullPipeName, openMode, pipeModes,
maxNumberOfServerInstances, outBufferSize, inBufferSize, 0, ref secAttrs);
if (handle.IsInvalid)
{
Exception e = Win32Marshal.GetExceptionForLastWin32Error();
handle.Dispose();
throw e;
}
InitializeHandle(handle, false, (options & PipeOptions.Asynchronous) != 0);
}
finally
{
if (pinningHandle.IsAllocated)
{
pinningHandle.Free();
}
}
}
// This will wait until the client calls Connect(). If we return from this method, we guarantee that
// the client has returned from its Connect call. The client may have done so before this method
// was called (but not before this server is been created, or, if we were servicing another client,
// not before we called Disconnect), in which case, there may be some buffer already in the pipe waiting
// for us to read. See NamedPipeClientStream.Connect for more information.
public void WaitForConnection()
{
CheckConnectOperationsServerWithHandle();
if (IsAsync)
{
WaitForConnectionCoreAsync(CancellationToken.None).AsTask().GetAwaiter().GetResult();
}
else
{
if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle!, IntPtr.Zero))
{
int errorCode = Marshal.GetLastPInvokeError();
if (errorCode != Interop.Errors.ERROR_PIPE_CONNECTED)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
// pipe already connected
if (State == PipeState.Connected)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected);
}
// If we reach here then a connection has been established. This can happen if a client
// connects in the interval between the call to CreateNamedPipe and the call to ConnectNamedPipe.
// In this situation, there is still a good connection between client and server, even though
// ConnectNamedPipe returns zero.
}
State = PipeState.Connected;
}
}
public Task WaitForConnectionAsync(CancellationToken cancellationToken) =>
cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) :
IsAsync ? WaitForConnectionCoreAsync(cancellationToken).AsTask() :
AsyncOverSyncWithIoCancellation.InvokeAsync(static s => s.WaitForConnection(), this, cancellationToken).AsTask();
public void Disconnect()
{
CheckDisconnectOperations();
// Disconnect the pipe.
if (!Interop.Kernel32.DisconnectNamedPipe(InternalHandle!))
{
throw Win32Marshal.GetExceptionForLastWin32Error();
}
State = PipeState.Disconnected;
}
// Gets the username of the connected client. Note that we will not have access to the client's
// username until it has written at least once to the pipe (and has set its impersonationLevel
// argument appropriately).
public unsafe string GetImpersonationUserName()
{
CheckWriteOperations();
const uint UserNameMaxLength = Interop.Kernel32.CREDUI_MAX_USERNAME_LENGTH + 1;
char* userName = stackalloc char[(int)UserNameMaxLength]; // ~1K
if (Interop.Kernel32.GetNamedPipeHandleStateW(InternalHandle!, null, null, null, null, userName, UserNameMaxLength))
{
return new string(userName);
}
return HandleGetImpersonationUserNameError(Marshal.GetLastPInvokeError(), UserNameMaxLength, userName);
}
// This method calls a delegate while impersonating the client. Note that we will not have
// access to the client's security token until it has written at least once to the pipe
// (and has set its impersonationLevel argument appropriately).
public void RunAsClient(PipeStreamImpersonationWorker impersonationWorker)
{
CheckWriteOperations();
ExecuteHelper execHelper = new ExecuteHelper(impersonationWorker, InternalHandle);
bool exceptionThrown = true;
try
{
ImpersonateAndTryCode(execHelper);
exceptionThrown = false;
}
finally
{
RevertImpersonationOnBackout(execHelper, exceptionThrown);
}
// now handle win32 impersonate/revert specific errors by throwing corresponding exceptions
if (execHelper._impersonateErrorCode != 0)
{
throw WinIOError(execHelper._impersonateErrorCode);
}
else if (execHelper._revertImpersonateErrorCode != 0)
{
throw WinIOError(execHelper._revertImpersonateErrorCode);
}
}
private static void ImpersonateAndTryCode(object? helper)
{
ExecuteHelper execHelper = (ExecuteHelper)helper!;
if (Interop.Advapi32.ImpersonateNamedPipeClient(execHelper._handle!))
{
execHelper._mustRevert = true;
}
else
{
execHelper._impersonateErrorCode = Marshal.GetLastPInvokeError();
}
if (execHelper._mustRevert)
{
// impersonate passed so run user code
execHelper._userCode();
}
}
private static void RevertImpersonationOnBackout(object? helper, bool exceptionThrown)
{
ExecuteHelper execHelper = (ExecuteHelper)helper!;
if (execHelper._mustRevert)
{
if (!Interop.Advapi32.RevertToSelf())
{
execHelper._revertImpersonateErrorCode = Marshal.GetLastPInvokeError();
}
}
}
internal sealed class ExecuteHelper
{
internal PipeStreamImpersonationWorker _userCode;
internal SafePipeHandle? _handle;
internal bool _mustRevert;
internal int _impersonateErrorCode;
internal int _revertImpersonateErrorCode;
internal ExecuteHelper(PipeStreamImpersonationWorker userCode, SafePipeHandle? handle)
{
_userCode = userCode;
_handle = handle;
}
}
// Async version of WaitForConnection. See the comments above for more info.
private unsafe ValueTask WaitForConnectionCoreAsync(CancellationToken cancellationToken)
{
CheckConnectOperationsServerWithHandle();
Debug.Assert(IsAsync);
ConnectionValueTaskSource? vts = Interlocked.Exchange(ref _reusableConnectionValueTaskSource, null) ?? new ConnectionValueTaskSource(this);
try
{
vts.PrepareForOperation();
if (!Interop.Kernel32.ConnectNamedPipe(InternalHandle!, vts._overlapped))
{
int errorCode = Marshal.GetLastPInvokeError();
switch (errorCode)
{
case Interop.Errors.ERROR_IO_PENDING:
// Common case: IO was initiated, completion will be handled by callback.
// Register for cancellation now that the operation has been initiated.
vts.RegisterForCancellation(cancellationToken);
break;
case Interop.Errors.ERROR_PIPE_CONNECTED:
// If we are here then the pipe is already connected.
// IOCompletitionCallback will not be called because we completed synchronously.
vts.Dispose();
if (State == PipeState.Connected)
{
return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(new InvalidOperationException(SR.InvalidOperation_PipeAlreadyConnected)));
}
State = PipeState.Connected;
return ValueTask.CompletedTask;
default:
vts.Dispose();
return ValueTask.FromException(ExceptionDispatchInfo.SetCurrentStackTrace(Win32Marshal.GetExceptionForWin32Error(errorCode)));
}
}
}
catch
{
vts.Dispose();
throw;
}
// Completion handled by callback.
vts.FinishedScheduling();
return new ValueTask(vts, vts.Version);
}
private void CheckConnectOperationsServerWithHandle()
{
if (InternalHandle == null)
{
throw new InvalidOperationException(SR.InvalidOperation_PipeHandleNotSet);
}
CheckConnectOperationsServer();
}
}
}