forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRemoteSessionNamedPipe.cs
More file actions
1275 lines (1082 loc) · 45.4 KB
/
Copy pathRemoteSessionNamedPipe.cs
File metadata and controls
1275 lines (1082 loc) · 45.4 KB
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/********************************************************************++
Copyright (c) Microsoft Corporation. All rights reserved.
--********************************************************************/
using System.Management.Automation.Tracing;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Server;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Threading;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
using System.Diagnostics.CodeAnalysis;
using Dbg = System.Diagnostics.Debug;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Shared named pipe utilities.
/// </summary>
internal static class NamedPipeUtils
{
#region Strings
internal const string DefaultAppDomainName = "DefaultAppDomain";
internal const string NamedPipeNamePrefix = "PSHost.";
internal const string NamedPipeNamePrefixSearch = "PSHost*";
#endregion
#region Static Methods
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id</param>
/// <returns>Pipe name</returns>
internal static string CreateProcessPipeName(
int procId)
{
return CreateProcessPipeName(
System.Diagnostics.Process.GetProcessById(procId));
}
/// <summary>
/// Create a pipe name based on process information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object</param>
/// <returns>Pipe name</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc)
{
return CreateProcessPipeName(proc, DefaultAppDomainName);
}
/// <summary>
/// Create a pipe name based on process Id and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="procId">Process Id</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name</returns>
internal static string CreateProcessPipeName(
int procId,
string appDomainName)
{
return CreateProcessPipeName(System.Diagnostics.Process.GetProcessById(procId), appDomainName);
}
/// <summary>
/// Create a pipe name based on process and appdomain name information.
/// E.g., "PSHost.ProcessStartTime.ProcessId.DefaultAppDomain.ProcessName"
/// </summary>
/// <param name="proc">Process object</param>
/// <param name="appDomainName">Name of process app domain to connect to.</param>
/// <returns>Pipe name</returns>
internal static string CreateProcessPipeName(
System.Diagnostics.Process proc,
string appDomainName)
{
if (proc == null)
{
throw new PSArgumentNullException("proc");
}
if (string.IsNullOrEmpty(appDomainName))
{
appDomainName = DefaultAppDomainName;
}
return NamedPipeNamePrefix +
proc.StartTime.ToFileTime().ToString(CultureInfo.InvariantCulture) + "." +
proc.Id.ToString(CultureInfo.InvariantCulture) + "." +
CleanAppDomainNameForPipeName(appDomainName) + "." +
proc.ProcessName;
}
private static string CleanAppDomainNameForPipeName(string appDomainName)
{
// Pipe names cannot contain the ':' character. Remove unwanted characters.
return appDomainName.Replace(":", "").Replace(" ", "");
}
/// <summary>
/// Returns the current process AppDomain name.
/// </summary>
/// <returns>AppDomain Name string</returns>
internal static string GetCurrentAppDomainName()
{
#if CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
return DefaultAppDomainName;
#else // Use the AppDomain in which current powershell is running
return AppDomain.CurrentDomain.IsDefaultAppDomain() ? DefaultAppDomainName : AppDomain.CurrentDomain.FriendlyName;
#endif
}
#endregion
}
/// <summary>
/// Native API for Named Pipes
/// </summary>
internal static class NamedPipeNative
{
#region Pipe constants
// Pipe open modes
internal const uint PIPE_ACCESS_DUPLEX = 0x00000003;
internal const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
internal const uint PIPE_ACCESS_INBOUND = 0x00000001;
// Pipe modes
internal const uint PIPE_TYPE_BYTE = 0x00000000;
internal const uint PIPE_TYPE_MESSAGE = 0x00000004;
internal const uint FILE_FLAG_OVERLAPPED = 0x40000000;
internal const uint FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000;
internal const uint PIPE_WAIT = 0x00000000;
internal const uint PIPE_NOWAIT = 0x00000001;
internal const uint PIPE_READMODE_BYTE = 0x00000000;
internal const uint PIPE_READMODE_MESSAGE = 0x00000002;
internal const uint PIPE_ACCEPT_REMOTE_CLIENTS = 0x00000000;
internal const uint PIPE_REJECT_REMOTE_CLIENTS = 0x00000008;
// Pipe errors
internal const uint ERROR_FILE_NOT_FOUND = 2;
internal const uint ERROR_BROKEN_PIPE = 109;
internal const uint ERROR_PIPE_BUSY = 231;
internal const uint ERROR_NO_DATA = 232;
internal const uint ERROR_MORE_DATA = 234;
internal const uint ERROR_PIPE_CONNECTED = 535;
internal const uint ERROR_IO_INCOMPLETE = 996;
internal const uint ERROR_IO_PENDING = 997;
// File function constants
internal const uint GENERIC_READ = 0x80000000;
internal const uint GENERIC_WRITE = 0x40000000;
internal const uint GENERIC_EXECUTE = 0x20000000;
internal const uint GENERIC_ALL = 0x10000000;
internal const uint CREATE_NEW = 1;
internal const uint CREATE_ALWAYS = 2;
internal const uint OPEN_EXISTING = 3;
internal const uint OPEN_ALWAYS = 4;
internal const uint TRUNCATE_EXISTING = 5;
internal const uint SECURITY_IMPERSONATIONLEVEL_ANONYMOUS = 0;
internal const uint SECURITY_IMPERSONATIONLEVEL_IDENTIFCATION = 1;
internal const uint SECURITY_IMPERSONATIONLEVEL_IMPERSONATION = 2;
internal const uint SECURITY_IMPERSONATIONLEVEL_DELEGATION = 3;
// Infinite timeout
internal const uint INFINITE = 0xFFFFFFFF;
#endregion
#region Data structures
[StructLayout(LayoutKind.Sequential)]
internal class SECURITY_ATTRIBUTES
{
/// <summary>
/// The size, in bytes, of this structure. Set this value to the size of the SECURITY_ATTRIBUTES structure.
/// </summary>
public int NLength;
/// <summary>
/// A pointer to a security descriptor for the object that controls the sharing of it.
/// </summary>
public IntPtr LPSecurityDescriptor = IntPtr.Zero;
/// <summary>
/// A Boolean value that specifies whether the returned handle is inherited when a new process is created.
/// </summary>
public bool InheritHandle;
/// <summary>
/// Initializes a new instance of the SECURITY_ATTRIBUTES class
/// </summary>
public SECURITY_ATTRIBUTES()
{
this.NLength = 12;
}
}
#endregion
#region Pipe methods
[DllImport(PinvokeDllNames.CreateNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern SafePipeHandle CreateNamedPipe(
string lpName,
uint dwOpenMode,
uint dwPipeMode,
uint nMaxInstances,
uint nOutBufferSize,
uint nInBufferSize,
uint nDefaultTimeOut,
SECURITY_ATTRIBUTES securityAttributes);
internal static SECURITY_ATTRIBUTES GetSecurityAttributes(GCHandle securityDescriptorPinnedHandle, bool inheritHandle = false)
{
SECURITY_ATTRIBUTES securityAttributes = new NamedPipeNative.SECURITY_ATTRIBUTES();
securityAttributes.InheritHandle = inheritHandle;
securityAttributes.NLength = (int)Marshal.SizeOf(securityAttributes);
securityAttributes.LPSecurityDescriptor = securityDescriptorPinnedHandle.AddrOfPinnedObject();
return securityAttributes;
}
[DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)]
internal static extern SafePipeHandle CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr SecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
[DllImport(PinvokeDllNames.WaitNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool WaitNamedPipe(string lpNamedPipeName, uint nTimeOut);
[DllImport(PinvokeDllNames.ImpersonateNamedPipeClientDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
[DllImport(PinvokeDllNames.RevertToSelfDllName, SetLastError = true, CharSet = CharSet.Unicode)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool RevertToSelf();
#endregion
}
/// <summary>
/// Event arguments for listener thread end event.
/// </summary>
internal sealed class ListenerEndedEventArgs : EventArgs
{
#region Properties
/// <summary>
/// Exception reson for listener end event. Can be null
/// which indicates listener thread end is not due to an error.
/// </summary>
public Exception Reason
{
private set;
get;
}
/// <summary>
/// True if listener should be restarted after ending.
/// </summary>
public bool RestartListener
{
private set;
get;
}
#endregion
#region Constructors
private ListenerEndedEventArgs() { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="reason">Listener end reason</param>
/// <param name="restartListener">Restart listener</param>
public ListenerEndedEventArgs(
Exception reason,
bool restartListener)
{
Reason = reason;
RestartListener = restartListener;
}
#endregion
}
/// <summary>
/// Light wrapper class for BCL NamedPipeServerStream class, that
/// creates the named pipe server with process named pipe name,
/// having correct access restrictions, and provides a listener
/// thread loop.
/// </summary>
internal sealed class RemoteSessionNamedPipeServer : IDisposable
{
#region Members
private readonly object _syncObject;
private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
private const string _threadName = "IPC Listener Thread";
private const int _namedPipeBufferSizeForRemoting = 32768;
// Singleton server.
private static object s_syncObject;
internal static RemoteSessionNamedPipeServer IPCNamedPipeServer;
internal static bool IPCNamedPipeServerEnabled;
// Access mask constant taken from PipeSecurity access rights and is equivalent to
// PipeAccessRights.FullControl.
// See: https://msdn.microsoft.com/en-us/library/vstudio/bb348408(v=vs.100).aspx
//
private const int _pipeAccessMaskFullControl = 0x1f019f;
#endregion
#region Properties
/// <summary>
/// Returns the Named Pipe stream object.
/// </summary>
public NamedPipeServerStream Stream { get; }
/// <summary>
/// Returns the Named Pipe name.
/// </summary>
public string PipeName { get; }
/// <summary>
/// Returns true if listener is currently running.
/// </summary>
public bool IsListenerRunning { get; private set; }
/// <summary>
/// Name of session configuration.
/// </summary>
public string ConfigurationName { get; set; }
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Returns true if object is currently disposed.
/// </summary>
public bool IsDisposed { get; private set; }
/// <summary>
/// Buffer size for PSRP fragmentor.
/// </summary>
internal static int NamedPipeBufferSizeForRemoting
{
get { return _namedPipeBufferSizeForRemoting; }
}
#endregion
#region Events
/// <summary>
/// Event raised when the named pipe server listening thread
/// ends.
/// </summary>
public event EventHandler<ListenerEndedEventArgs> ListenerEnded;
#endregion
#region Constructors
/// <summary>
/// Creates a RemoteSessionNamedPipeServer with the current process and AppDomain information.
/// </summary>
/// <returns>RemoteSessionNamedPipeServer</returns>
public static RemoteSessionNamedPipeServer CreateRemoteSessionNamedPipeServer()
{
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
return new RemoteSessionNamedPipeServer(NamedPipeUtils.CreateProcessPipeName(
System.Diagnostics.Process.GetCurrentProcess(), appDomainName));
}
/// <summary>
/// Constructor. Creates named pipe server with provided pipe name.
/// </summary>
/// <param name="pipeName">Named Pipe name</param>
internal RemoteSessionNamedPipeServer(
string pipeName)
{
if (pipeName == null)
{
throw new PSArgumentNullException("pipeName");
}
_syncObject = new object();
PipeName = pipeName;
Stream = CreateNamedPipe(
serverName: ".",
namespaceName: "pipe",
coreName: pipeName,
securityDesc: GetServerPipeSecurity());
}
/// <summary>
/// Helper method to create a PowerShell transport named pipe via native API, along
/// with a returned .Net NamedPipeServerStream object wrapping the named pipe.
/// </summary>
/// <param name="serverName">Named pipe server name.</param>
/// <param name="namespaceName">Named pipe namespace name.</param>
/// <param name="coreName">Named pipe core name.</param>
/// <param name="securityDesc"></param>
/// <returns>NamedPipeServerStream</returns>
private NamedPipeServerStream CreateNamedPipe(
string serverName,
string namespaceName,
string coreName,
CommonSecurityDescriptor securityDesc)
{
if (serverName == null) { throw new PSArgumentNullException("serverName"); }
if (namespaceName == null) { throw new PSArgumentNullException("namespaceName"); }
if (coreName == null) { throw new PSArgumentNullException("coreName"); }
string fullPipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName;
// Create optional security attributes based on provided PipeSecurity.
NamedPipeNative.SECURITY_ATTRIBUTES securityAttributes = null;
GCHandle? securityDescHandle = null;
if (securityDesc != null)
{
byte[] securityDescBuffer = new byte[securityDesc.BinaryLength];
securityDesc.GetBinaryForm(securityDescBuffer, 0);
securityDescHandle = GCHandle.Alloc(securityDescBuffer, GCHandleType.Pinned);
securityAttributes = NamedPipeNative.GetSecurityAttributes(securityDescHandle.Value);
}
// Create named pipe.
SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe(
fullPipeName,
NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED,
NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE,
1,
_namedPipeBufferSizeForRemoting,
_namedPipeBufferSizeForRemoting,
0,
securityAttributes);
int lastError = Marshal.GetLastWin32Error();
if (securityDescHandle != null)
{
securityDescHandle.Value.Free();
}
if (pipeHandle.IsInvalid)
{
throw new PSInvalidOperationException(
StringUtil.Format(RemotingErrorIdStrings.CannotCreateNamedPipe, lastError));
}
// Create the .Net NamedPipeServerStream wrapper.
try
{
return new NamedPipeServerStream(
PipeDirection.InOut,
true, // IsAsync
false, // IsConnected
pipeHandle);
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
pipeHandle.Dispose();
throw;
}
}
static RemoteSessionNamedPipeServer()
{
s_syncObject = new object();
// All PowerShell instances will start with the named pipe
// and listner created and running.
if (Platform.IsWindows)
{
IPCNamedPipeServerEnabled = true;
}
CreateIPCNamedPipeServerSingleton();
#if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
CreateAppDomainUnloadHandler();
#endif
}
#endregion
#region IDisposable
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
lock (_syncObject)
{
if (IsDisposed) { return; }
IsDisposed = true;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (Stream != null)
{
try { Stream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Public Methods
/// <summary>
/// Starts named pipe server listening thread. When a client connects this thread
/// makes a callback to implement the client communication. When the thread ends
/// this object is disposed and a new RemoteSessionNamedPipeServer must be created
/// and a new listening thread started to handle subsequent client connections.
/// </summary>
/// <param name="clientConnectCallback">Connection callback.</param>
public void StartListening(
Action<RemoteSessionNamedPipeServer> clientConnectCallback)
{
if (clientConnectCallback == null)
{
throw new PSArgumentNullException("clientConnectCallback");
}
lock (_syncObject)
{
if (IsListenerRunning)
{
throw new InvalidOperationException(RemotingErrorIdStrings.NamedPipeAlreadyListening);
}
IsListenerRunning = true;
// Create listener thread.
Thread listenterThread = new Thread(ProcessListeningThread);
listenterThread.Name = _threadName;
listenterThread.IsBackground = true;
listenterThread.Start(clientConnectCallback);
} // Lock _syncObject.
}
#endregion
#region Private Methods
internal static CommonSecurityDescriptor GetServerPipeSecurity()
{
// Built-in Admin SID
SecurityIdentifier adminSID = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
DiscretionaryAcl dacl = new DiscretionaryAcl(false, false, 1);
dacl.AddAccess(
AccessControlType.Allow,
adminSID,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
CommonSecurityDescriptor securityDesc = new CommonSecurityDescriptor(
false, false,
ControlFlags.DiscretionaryAclPresent | ControlFlags.OwnerDefaulted | ControlFlags.GroupDefaulted,
null, null, null, dacl);
// Conditionally add User SID
bool isAdminElevated = new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
if (!isAdminElevated)
{
securityDesc.DiscretionaryAcl.AddAccess(
AccessControlType.Allow,
WindowsIdentity.GetCurrent().User,
_pipeAccessMaskFullControl,
InheritanceFlags.None,
PropagationFlags.None);
}
return securityDesc;
}
/// <summary>
/// Wait for client connection.
/// </summary>
private void WaitForConnection()
{
Stream.WaitForConnection();
}
/// <summary>
/// Process listening thread.
/// </summary>
/// <param name="state">client callback delegate</param>
[SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Runtime.InteropServices.SafeHandle.DangerousGetHandle")]
private void ProcessListeningThread(object state)
{
string processId = System.Diagnostics.Process.GetCurrentProcess().Id.ToString(CultureInfo.InvariantCulture);
string appDomainName = NamedPipeUtils.GetCurrentAppDomainName();
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread started on Process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerListenerStarted, PSOpcode.Open, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
Exception ex = null;
string userName = string.Empty;
bool restartListenerThread = true;
// Wait for connection.
try
{
// Begin listening for a client connect.
this.WaitForConnection();
try
{
userName = WindowsIdentity.GetCurrent().Name;
}
catch (System.Security.SecurityException) { }
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection started on Process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerConnect, PSOpcode.Connect, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
// Create reader/writer streams.
TextReader = new StreamReader(Stream);
TextWriter = new StreamWriter(Stream);
TextWriter.AutoFlush = true;
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
ex = e;
}
if (ex != null)
{
// Error during connection handling. Don't try to restart listening thread.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
Dispose();
return;
}
// Start server session on new connection.
ex = null;
try
{
Action<RemoteSessionNamedPipeServer> clientConnectCallback = state as Action<RemoteSessionNamedPipeServer>;
Dbg.Assert(clientConnectCallback != null, "Client callback should never be null.");
// Handle a new client connect by making the callback.
// The callback must handle all exceptions except
// for a named pipe disposed or disconnected exception
// which propagates up to the thread listener loop.
clientConnectCallback(this);
}
catch (IOException)
{
// Expected connection terminated.
}
catch (ObjectDisposedException)
{
// Expected from PS transport close/dispose.
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
ex = e;
restartListenerThread = false;
}
// Logging.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Client connection ended on process {0} in AppDomainName {1} for User {2}.", processId, appDomainName, userName);
PSEtwLog.LogOperationalInformation(
PSEventId.NamedPipeIPC_ServerDisconnect, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, userName);
if (ex == null)
{
// Normal listener exit.
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Listener thread ended on process {0} in AppDomainName {1}.", processId, appDomainName);
PSEtwLog.LogOperationalInformation(PSEventId.NamedPipeIPC_ServerListenerEnded, PSOpcode.Close, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName);
}
else
{
// Unexpected error.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionNamedPipeServer", "StartListening", Guid.Empty,
"Unexpected error in listener thread on process {0} in AppDomainName {1}. Error Message: {2}", processId, appDomainName, errorMessage);
PSEtwLog.LogOperationalError(PSEventId.NamedPipeIPC_ServerListenerError, PSOpcode.Exception, PSTask.NamedPipe,
PSKeyword.UseAlwaysOperational,
processId, appDomainName, errorMessage);
}
lock (_syncObject)
{
IsListenerRunning = false;
}
// Ensure this named pipe server object is disposed.
Dispose();
ListenerEnded.SafeInvoke(
this,
new ListenerEndedEventArgs(ex, restartListenerThread));
}
#endregion
#region Static Methods
/// <summary>
/// Ensures the namedpipe singleton server is running and waits for a client connection.
/// This is a blocking call that returns after the client connection ends.
/// This method supports PowerShell running in "NamedPipeServerMode", which is used for
/// PowerShell Direct Windows Server Container connection and management.
/// </summary>
/// <param name="configurationName">name of the configuration to use</param>
internal static void RunServerMode(string configurationName)
{
IPCNamedPipeServerEnabled = true;
CreateIPCNamedPipeServerSingleton();
if (IPCNamedPipeServer == null)
{
throw new RuntimeException(RemotingErrorIdStrings.NamedPipeServerCannotStart);
}
IPCNamedPipeServer.ConfigurationName = configurationName;
ManualResetEventSlim clientConnectionEnded = new ManualResetEventSlim(false);
IPCNamedPipeServer.ListenerEnded -= OnIPCNamedPipeServerEnded;
IPCNamedPipeServer.ListenerEnded += (sender, e) =>
{
clientConnectionEnded.Set();
};
// Wait for server to service a single client connection.
clientConnectionEnded.Wait();
clientConnectionEnded.Dispose();
IPCNamedPipeServerEnabled = false;
}
/// <summary>
/// Creates the process named pipe server object singleton and
/// starts the client listening thread.
/// </summary>
internal static void CreateIPCNamedPipeServerSingleton()
{
lock (s_syncObject)
{
if (!IPCNamedPipeServerEnabled) { return; }
if (IPCNamedPipeServer == null || IPCNamedPipeServer.IsDisposed)
{
try
{
try
{
IPCNamedPipeServer = CreateRemoteSessionNamedPipeServer();
}
catch (IOException)
{
// Expected when named pipe server for this process already exists.
// This can happen if process has multiple AppDomains hosting PowerShell (SMA.dll).
return;
}
// Listener ended callback, used to create listening new pipe server.
IPCNamedPipeServer.ListenerEnded += OnIPCNamedPipeServerEnded;
// Start the pipe server listening thread, and provide client connection callback.
IPCNamedPipeServer.StartListening(ClientConnectionCallback);
}
catch (Exception e)
{
CommandProcessorBase.CheckForSevereException(e);
IPCNamedPipeServer = null;
}
}
}
}
#if !CORECLR // There is only one AppDomain per application in CoreCLR, which would be the default
private static void CreateAppDomainUnloadHandler()
{
// Subscribe to the app domain unload event.
AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
{
IPCNamedPipeServerEnabled = false;
RemoteSessionNamedPipeServer namedPipeServer = IPCNamedPipeServer;
if (namedPipeServer != null)
{
try
{
// Terminate the IPC thread.
namedPipeServer.Dispose();
}
catch (ObjectDisposedException) { }
catch (Exception e)
{
// Don't throw an exception on the app domain unload event thread.
CommandProcessorBase.CheckForSevereException(e);
}
}
};
}
#endif
private static void OnIPCNamedPipeServerEnded(object sender, ListenerEndedEventArgs args)
{
if (args.RestartListener)
{
CreateIPCNamedPipeServerSingleton();
}
}
private static void ClientConnectionCallback(RemoteSessionNamedPipeServer pipeServer)
{
// Create server mediator object and begin remote session with client.
NamedPipeProcessMediator.Run(
string.Empty,
pipeServer);
}
#endregion
}
/// <summary>
/// Base class for RemoteSessionNamedPipeClient and ContainerSessionNamedPipeClient.
/// </summary>
internal class NamedPipeClientBase : IDisposable
{
#region Members
private NamedPipeClientStream _clientPipeStream;
private PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
protected string _pipeName;
#endregion
#region Properties
/// <summary>
/// Accessor for the named pipe reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the named pipe writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Name of pipe.
/// </summary>
public string PipeName
{
get { return _pipeName; }
}
#endregion
#region Constructor
public NamedPipeClientBase()
{ }
#endregion
#region IDisposable
/// <summary>
/// Dispose
/// </summary>
public void Dispose()
{
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (_clientPipeStream != null)
{
try { _clientPipeStream.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Methods
/// <summary>
/// Connect to named pipe server. This is a blocking call until a
/// connection occurs or the timeout time has ellapsed.
/// </summary>
/// <param name="timeout">Connection attempt timeout in milliseconds</param>
public void Connect(
int timeout)
{
// Uses Native API to connect to pipe and return NamedPipeClientStream object.
_clientPipeStream = DoConnect(timeout);
// Create reader/writer streams.
TextReader = new StreamReader(_clientPipeStream);
TextWriter = new StreamWriter(_clientPipeStream);
TextWriter.AutoFlush = true;
_tracer.WriteMessage("NamedPipeClientBase", "Connect", Guid.Empty,
"Connection started on pipe: {0}", _pipeName);
}
/// <summary>
/// Closes the named pipe.
/// </summary>
public void Close()
{
if (_clientPipeStream != null)
{
_clientPipeStream.Dispose();
}
}
public virtual void AbortConnect()
{ }
protected virtual NamedPipeClientStream DoConnect(int timeout)
{
return null;
}