forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWSManTransportManager.cs
More file actions
4162 lines (3569 loc) · 181 KB
/
Copy pathWSManTransportManager.cs
File metadata and controls
4162 lines (3569 loc) · 181 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.
// Licensed under the MIT License.
/*
* Common file that contains implementation for both server and client transport
* managers based on WSMan protocol.
*
*/
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Server;
using System.Management.Automation.Runspaces.Internal;
using System.Management.Automation.Tracing;
using System.Runtime.InteropServices;
#if !UNIX
using System.Security.Principal;
#endif
using System.Xml;
using System.Threading;
using PSRemotingCryptoHelper = System.Management.Automation.Internal.PSRemotingCryptoHelper;
using WSManConnectionInfo = System.Management.Automation.Runspaces.WSManConnectionInfo;
using RunspaceConnectionInfo = System.Management.Automation.Runspaces.RunspaceConnectionInfo;
using AuthenticationMechanism = System.Management.Automation.Runspaces.AuthenticationMechanism;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting.Client
{
/// <summary>
/// WSMan TransportManager related utils.
/// </summary>
internal static class WSManTransportManagerUtils
{
#region Static Data
// Fully qualified error Id modifiers based on transport (WinRM) error codes.
private static readonly Dictionary<int, string> s_transportErrorCodeToFQEID = new Dictionary<int, string>()
{
{WSManNativeApi.ERROR_WSMAN_ACCESS_DENIED, "AccessDenied"},
{WSManNativeApi.ERROR_WSMAN_OUTOF_MEMORY, "ServerOutOfMemory"},
{WSManNativeApi.ERROR_WSMAN_NETWORKPATH_NOTFOUND, "NetworkPathNotFound"},
{WSManNativeApi.ERROR_WSMAN_COMPUTER_NOTFOUND, "ComputerNotFound"},
{WSManNativeApi.ERROR_WSMAN_AUTHENTICATION_FAILED, "AuthenticationFailed"},
{WSManNativeApi.ERROR_WSMAN_LOGON_FAILURE, "LogonFailure"},
{WSManNativeApi.ERROR_WSMAN_IMPROPER_RESPONSE, "ImproperResponse"},
{WSManNativeApi.ERROR_WSMAN_INCORRECT_PROTOCOLVERSION, "IncorrectProtocolVersion"},
{WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_COMPLETE, "WinRMOperationTimeout"},
{WSManNativeApi.ERROR_WSMAN_URL_NOTAVAILABLE, "URLNotAvailable"},
{WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_CONNECT, "CannotConnect"},
{WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI, "InvalidResourceUri"},
{WSManNativeApi.ERROR_WSMAN_INUSE_CANNOT_RECONNECT, "CannotConnectAlreadyConnected"},
{WSManNativeApi.ERROR_WSMAN_INVALID_AUTHENTICATION, "InvalidAuthentication"},
{WSManNativeApi.ERROR_WSMAN_SHUTDOWN_INPROGRESS, "ShutDownInProgress"},
{WSManNativeApi.ERROR_WSMAN_CANNOT_CONNECT_INVALID, "CannotConnectInvalidOperation"},
{WSManNativeApi.ERROR_WSMAN_CANNOT_CONNECT_MISMATCH, "CannotConnectMismatchSessions"},
{WSManNativeApi.ERROR_WSMAN_CANNOT_CONNECT_RUNASFAILED, "CannotConnectRunAsFailed"},
{WSManNativeApi.ERROR_WSMAN_CREATEFAILED_INVALIDNAME, "SessionCreateFailedInvalidName"},
{WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST, "CannotConnectTargetSessionDoesNotExist"},
{WSManNativeApi.ERROR_WSMAN_REMOTESESSION_DISALLOWED, "RemoteSessionDisallowed"},
{WSManNativeApi.ERROR_WSMAN_REMOTECONNECTION_DISALLOWED, "RemoteConnectionDisallowed"},
{WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI2, "InvalidResourceUri"},
{WSManNativeApi.ERROR_WSMAN_CORRUPTED_CONFIG, "CorruptedWinRMConfig"},
{WSManNativeApi.ERROR_WSMAN_OPERATION_ABORTED, "WinRMOperationAborted"},
{WSManNativeApi.ERROR_WSMAN_URI_LIMIT, "URIExceedsMaxAllowedSize"},
{WSManNativeApi.ERROR_WSMAN_CLIENT_KERBEROS_DISABLED, "ClientKerberosDisabled"},
{WSManNativeApi.ERROR_WSMAN_SERVER_NOTTRUSTED, "ServerNotTrusted"},
{WSManNativeApi.ERROR_WSMAN_WORKGROUP_NO_KERBEROS, "WorkgroupCannotUseKerberos"},
{WSManNativeApi.ERROR_WSMAN_EXPLICIT_CREDENTIALS_REQUIRED, "ExplicitCredentialsRequired"},
{WSManNativeApi.ERROR_WSMAN_REDIRECT_LOCATION_INVALID, "RedirectLocationInvalid"},
{WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED, "RedirectInformationRequired"},
{WSManNativeApi.ERROR_WSMAN_BAD_METHOD, "WinRMOperationNotSupportedOnServer"},
{WSManNativeApi.ERROR_WSMAN_HTTP_SERVICE_UNAVAILABLE, "CannotConnectWinRMService"},
{WSManNativeApi.ERROR_WSMAN_HTTP_SERVICE_ERROR, "WinRMHttpError"},
{WSManNativeApi.ERROR_WSMAN_TARGET_UNKNOWN, "TargetUnknown"},
{WSManNativeApi.ERROR_WSMAN_CANNOTUSE_IP, "CannotUseIPAddress"}
};
#endregion
#region Helper Methods
/// <summary>
/// Constructs a WSManTransportErrorOccuredEventArgs instance from the supplied data.
/// </summary>
/// <param name="wsmanAPIHandle">
/// WSMan API handle to use to get error messages from WSMan error id(s)
/// </param>
/// <param name="wsmanSessionTM">
/// Session Transportmanager to use to get error messages (for redirect)
/// </param>
/// <param name="errorStruct">
/// Error structure supplied by callbacks from WSMan API
/// </param>
/// <param name="transportMethodReportingError">
/// The transport method call that reported this error.
/// </param>
/// <param name="resourceString">
/// resource string that holds the message.
/// </param>
/// <param name="resourceArgs">
/// Arguments to pass to the resource
/// </param>
/// <returns>
/// An instance of WSManTransportErrorOccuredEventArgs
/// </returns>
internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle,
WSManClientSessionTransportManager wsmanSessionTM,
WSManNativeApi.WSManError errorStruct,
TransportMethodEnum transportMethodReportingError,
string resourceString,
params object[] resourceArgs)
{
PSRemotingTransportException e;
// For the first two special error conditions, it is remotely possible that the wsmanSessionTM is null when the failures are returned
// as part of command TM operations (could be returned because of RC retries under the hood)
// Not worth to handle these cases separately as there are very corner scenarios, but need to make sure wsmanSessionTM is not referenced
// Destination server is reporting that URI redirect is required for this user.
if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) && (wsmanSessionTM != null))
{
IntPtr wsmanSessionHandle = wsmanSessionTM.SessionHandle;
// populate the transport message with the redirection uri..this will
// allow caller to make a new connection.
string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION);
string winrmMessage = ParseEscapeWSManErrorMessage(
WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim();
e = new PSRemotingTransportRedirectException(redirectLocation,
PSRemotingErrorId.URIEndPointNotResolved,
RemotingErrorIdStrings.URIEndPointNotResolved,
winrmMessage,
redirectLocation);
}
else if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI) && (wsmanSessionTM != null))
{
string configurationName =
wsmanSessionTM.ConnectionInfo.ShellUri.Replace(Remoting.Client.WSManNativeApi.ResourceURIPrefix, string.Empty);
string errorMessage = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName,
configurationName,
wsmanSessionTM.ConnectionInfo.ComputerName);
e = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName,
RemotingErrorIdStrings.ConnectExCallBackError, wsmanSessionTM.ConnectionInfo.ComputerName, errorMessage);
e.TransportMessage = ParseEscapeWSManErrorMessage(
WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode));
}
else
{
// Construct specific error message and then append this message pointing to our own
// help topic. PowerShell's about help topic "about_Remote_Troubleshooting" should
// contain all the trouble shooting information.
string wsManErrorMessage = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs);
e = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic,
RemotingErrorIdStrings.TroubleShootingHelpTopic,
wsManErrorMessage);
e.TransportMessage = ParseEscapeWSManErrorMessage(
WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode));
}
e.ErrorCode = errorStruct.errorCode;
TransportErrorOccuredEventArgs eventargs =
new TransportErrorOccuredEventArgs(e, transportMethodReportingError);
return eventargs;
}
/// <summary>
/// Helper method that escapes powershell parser recognized strings like "@{" from the error message
/// string. This is needed to make error messages look authentic. Some WSMan error messages provide a
/// command line to run to fix certain issues. WSMan command line has syntax that allows use of @{}.
/// PowerShell parser treats them differently..and so when user cut and paste the command line in a
/// PowerShell console, it wont work. This escape logic works around the issue.
/// </summary>
/// <param name="errorMessage"></param>
/// <returns></returns>
internal static string ParseEscapeWSManErrorMessage(string errorMessage)
{
// currently we do special processing only for "@{" construct.
if (string.IsNullOrEmpty(errorMessage) || (!errorMessage.Contains("@{")))
{
return errorMessage;
}
string result = errorMessage.Replace("@{", "'@{").Replace("}", "}'");
return result;
/*
* Use this pattern if we need to escape other characters.
*
try
{
StringBuilder msgSB = new StringBuilder(errorMessage);
Collection<PSParseError> parserErrors = new Collection<PSParseError>();
Collection<PSToken> tokens = PSParser.Tokenize(errorMessage, out parserErrors);
if (parserErrors.Count > 0)
{
tracer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"There were errors parsing string '{errorMessage}'");
return errorMessage;
}
for (int index = tokens.Count - 1; index > 0; index--)
{
PSToken currentToken = tokens[index];
switch(currentToken.Type)
{
case PSTokenType.GroupStart:
msgSB.Insert(currentToken.StartColumn - 1, "'", 1);
break;
case PSTokenType.GroupEnd:
if (msgSB.Length <= currentToken.EndColumn)
{
msgSB.Append("'");
}
else
{
msgSB.Insert(currentToken.EndColumn - 1, ",", 1);
}
break;
}
}
return msgSB.ToString();
}
// ignore possible exceptions manipulating the string.
catch(ArgumentOutOfRangeException)
{
}
catch(RuntimeException)
{
}
return errorMessage;*/
}
internal enum tmStartModes
{
None = 1, Create = 2, Connect = 3
}
/// <summary>
/// Helper method to convert a transport error code value
/// to a fully qualified error Id string.
/// </summary>
/// <param name="transportErrorCode">Transport error code.</param>
/// <param name="defaultFQEID">Default FQEID.</param>
/// <returns>Fully qualified error Id string.</returns>
internal static string GetFQEIDFromTransportError(
int transportErrorCode,
string defaultFQEID)
{
string specificErrorId;
if (s_transportErrorCodeToFQEID.TryGetValue(transportErrorCode, out specificErrorId))
{
return specificErrorId + "," + defaultFQEID;
}
else if (transportErrorCode != 0)
{
// Provide error code to uniquely identify the error Id.
return transportErrorCode.ToString(System.Globalization.NumberFormatInfo.InvariantInfo) + "," + defaultFQEID;
}
return defaultFQEID;
}
#endregion
}
/// <summary>
/// Class that manages a server session. This doesn't implement IDisposable. Use Close method
/// to clean the resources.
/// </summary>
internal sealed class WSManClientSessionTransportManager : BaseClientSessionTransportManager
{
#region Consts
/// <summary>
/// Max uri redirection count session variable.
/// </summary>
internal const string MAX_URI_REDIRECTION_COUNT_VARIABLE = "WSManMaxRedirectionCount";
/// <summary>
/// Default max uri redirection count - wsman.
/// </summary>
internal const int MAX_URI_REDIRECTION_COUNT = 5;
#endregion
#region Enums
private enum CompletionNotification
{
DisconnectCompleted
}
#endregion
#region CompletionEventArgs
private sealed class CompletionEventArgs : EventArgs
{
internal CompletionEventArgs(CompletionNotification notification)
{
Notification = notification;
}
internal CompletionNotification Notification { get; }
}
#endregion
#region Private Data
// operation handles are owned by WSMan
private IntPtr _wsManSessionHandle;
private IntPtr _wsManShellOperationHandle;
private IntPtr _wsManReceiveOperationHandle;
private IntPtr _wsManSendOperationHandle;
// this is used with WSMan callbacks to represent a session transport manager.
private long _sessionContextID;
private WSManTransportManagerUtils.tmStartModes _startMode = WSManTransportManagerUtils.tmStartModes.None;
private readonly string _sessionName;
// callbacks
private readonly PrioritySendDataCollection.OnDataAvailableCallback _onDataAvailableToSendCallback;
// instance callback handlers
private WSManNativeApi.WSManShellAsync _createSessionCallback;
private WSManNativeApi.WSManShellAsync _receivedFromRemote;
private WSManNativeApi.WSManShellAsync _sendToRemoteCompleted;
private WSManNativeApi.WSManShellAsync _disconnectSessionCompleted;
private WSManNativeApi.WSManShellAsync _reconnectSessionCompleted;
private WSManNativeApi.WSManShellAsync _connectSessionCallback;
// TODO: This GCHandle is required as it seems WSMan is calling create callback
// after we call Close. This seems wrong. Opened bug on WSMan to track this.
private GCHandle _createSessionCallbackGCHandle;
private WSManNativeApi.WSManShellAsync _closeSessionCompleted;
// used by WSManCreateShell call to send additional data (like negotiation)
// during shell creation. This is an instance variable to allow for redirection.
private WSManNativeApi.WSManData_ManToUn _openContent;
// By default WSMan compresses data sent on the network..use this flag to not do
// this.
private bool _noCompression;
private bool _noMachineProfile;
private int _connectionRetryCount;
private const string resBaseName = "remotingerroridstrings";
// Robust connections maximum retry time value in milliseconds.
private int _maxRetryTime;
private void ProcessShellData(string data)
{
try
{
XmlReaderSettings settings = InternalDeserializer.XmlReaderSettingsForUntrustedXmlDocument.Clone();
settings.MaxCharactersFromEntities = 1024; // 1024 is a generous upperbound for shell Xml entries
settings.MaxCharactersInDocument = 1024 * 30;
settings.DtdProcessing = System.Xml.DtdProcessing.Prohibit;
using (XmlReader reader = XmlReader.Create(new StringReader(data), settings))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
if (reader.LocalName.Equals("IdleTimeOut", StringComparison.OrdinalIgnoreCase) ||
reader.LocalName.Equals("MaxIdleTimeOut", StringComparison.OrdinalIgnoreCase))
{
bool settingIdleTimeout =
!reader.LocalName.Equals("MaxIdleTimeOut", StringComparison.OrdinalIgnoreCase);
string timeoutString = reader.ReadElementContentAsString();
Dbg.Assert(timeoutString.Substring(0, 2).Equals("PT", StringComparison.OrdinalIgnoreCase),
"IdleTimeout is not in expected format");
int decimalIndex = timeoutString.IndexOf('.');
try
{
int timeout = Convert.ToInt32(timeoutString.Substring(2, decimalIndex - 2), NumberFormatInfo.InvariantInfo) * 1000 + Convert.ToInt32(timeoutString.Substring(decimalIndex + 1, 3), NumberFormatInfo.InvariantInfo);
if (settingIdleTimeout)
{
ConnectionInfo.IdleTimeout = timeout;
}
else
{
ConnectionInfo.MaxIdleTimeout = timeout;
}
}
catch (InvalidCastException)
{
Dbg.Assert(false, "IdleTimeout is not in expected format");
}
}
else if (reader.LocalName.Equals("BufferMode", StringComparison.OrdinalIgnoreCase))
{
string bufferMode = reader.ReadElementContentAsString();
if (bufferMode.Equals("Block", StringComparison.OrdinalIgnoreCase))
{
ConnectionInfo.OutputBufferingMode = Runspaces.OutputBufferingMode.Block;
}
else if (bufferMode.Equals("Drop", StringComparison.OrdinalIgnoreCase))
{
ConnectionInfo.OutputBufferingMode = Runspaces.OutputBufferingMode.Drop;
}
else
{
Dbg.Assert(false, "unexpected buffer mode");
}
}
}
}
}
}
catch (XmlException)
{
Dbg.Assert(false, "shell xml is in unexpected format");
}
}
#endregion
#region Static Data
// static callback delegate
private static WSManNativeApi.WSManShellAsyncCallback s_sessionCreateCallback;
private static WSManNativeApi.WSManShellAsyncCallback s_sessionCloseCallback;
private static WSManNativeApi.WSManShellAsyncCallback s_sessionReceiveCallback;
private static WSManNativeApi.WSManShellAsyncCallback s_sessionSendCallback;
private static WSManNativeApi.WSManShellAsyncCallback s_sessionDisconnectCallback;
private static WSManNativeApi.WSManShellAsyncCallback s_sessionReconnectCallback;
private static WSManNativeApi.WSManShellAsyncCallback s_sessionConnectCallback;
// This dictionary maintains active session transport managers to be used from various
// callbacks.
private static readonly Dictionary<long, WSManClientSessionTransportManager> s_sessionTMHandles =
new Dictionary<long, WSManClientSessionTransportManager>();
private static long s_sessionTMSeed;
// generate unique session id
private static long GetNextSessionTMHandleId()
{
return System.Threading.Interlocked.Increment(ref s_sessionTMSeed);
}
// we need a synchronized add and remove so that multiple threads
// update the data store concurrently
private static void AddSessionTransportManager(long sessnTMId,
WSManClientSessionTransportManager sessnTransportManager)
{
lock (s_sessionTMHandles)
{
s_sessionTMHandles.Add(sessnTMId, sessnTransportManager);
}
}
private static void RemoveSessionTransportManager(long sessnTMId)
{
lock (s_sessionTMHandles)
{
s_sessionTMHandles.Remove(sessnTMId);
}
}
// we need a synchronized add and remove so that multiple threads
// update the data store concurrently
private static bool TryGetSessionTransportManager(IntPtr operationContext,
out WSManClientSessionTransportManager sessnTransportManager,
out long sessnTMId)
{
sessnTMId = operationContext.ToInt64();
sessnTransportManager = null;
lock (s_sessionTMHandles)
{
return s_sessionTMHandles.TryGetValue(sessnTMId, out sessnTransportManager);
}
}
#endregion
#region SHIM: Redirection delegates for test purposes
private static readonly Delegate s_sessionSendRedirect = null;
private static readonly Delegate s_protocolVersionRedirect = null;
#endregion
#region Constructors
/// <summary>
/// Static constructor to initialize WSMan Client stack.
/// </summary>
static WSManClientSessionTransportManager()
{
// Initialize callback delegates
WSManNativeApi.WSManShellCompletionFunction createDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnCreateSessionCallback);
s_sessionCreateCallback = new WSManNativeApi.WSManShellAsyncCallback(createDelegate);
WSManNativeApi.WSManShellCompletionFunction closeDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnCloseSessionCompleted);
s_sessionCloseCallback = new WSManNativeApi.WSManShellAsyncCallback(closeDelegate);
WSManNativeApi.WSManShellCompletionFunction receiveDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionDataReceived);
s_sessionReceiveCallback = new WSManNativeApi.WSManShellAsyncCallback(receiveDelegate);
WSManNativeApi.WSManShellCompletionFunction sendDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionSendCompleted);
s_sessionSendCallback = new WSManNativeApi.WSManShellAsyncCallback(sendDelegate);
WSManNativeApi.WSManShellCompletionFunction disconnectDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionDisconnectCompleted);
s_sessionDisconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(disconnectDelegate);
WSManNativeApi.WSManShellCompletionFunction reconnectDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionReconnectCompleted);
s_sessionReconnectCallback = new WSManNativeApi.WSManShellAsyncCallback(reconnectDelegate);
WSManNativeApi.WSManShellCompletionFunction connectDelegate =
new WSManNativeApi.WSManShellCompletionFunction(OnRemoteSessionConnectCallback);
s_sessionConnectCallback = new WSManNativeApi.WSManShellAsyncCallback(connectDelegate);
}
/// <summary>
/// Constructor. This will create a new PrioritySendDataCollection which should be used to
/// send data to the server.
/// </summary>
/// <param name="runspacePoolInstanceId">
/// This is used for logging trace/operational crimson messages. Having this id in the logs
/// helps a user to map which transport is created for which runspace.
/// </param>
/// <param name="connectionInfo">
/// Connection info to use while connecting to the remote machine.
/// </param>
/// <param name="cryptoHelper">Crypto helper.</param>
/// <param name="sessionName">Session friendly name.</param>
/// <exception cref="PSInvalidOperationException">
/// 1. Create Session failed with a non-zero error code.
/// </exception>
internal WSManClientSessionTransportManager(
Guid runspacePoolInstanceId,
WSManConnectionInfo connectionInfo,
PSRemotingCryptoHelper cryptoHelper,
string sessionName)
: base(runspacePoolInstanceId, cryptoHelper)
{
// Initialize WSMan instance
WSManAPIData = new WSManAPIDataCommon();
if (WSManAPIData.WSManAPIHandle == IntPtr.Zero)
{
throw new PSRemotingTransportException(
StringUtil.Format(RemotingErrorIdStrings.WSManInitFailed, WSManAPIData.ErrorCode));
}
Dbg.Assert(connectionInfo != null, "connectionInfo cannot be null");
CryptoHelper = cryptoHelper;
dataToBeSent.Fragmentor = base.Fragmentor;
_sessionName = sessionName;
// session transport manager can receive unlimited data..however each object is limited
// by maxRecvdObjectSize. this is to allow clients to use a session for an unlimited time..
// also the messages that can be sent to a session are limited and very controlled.
// However a command transport manager can be restricted to receive only a fixed amount of data
// controlled by maxRecvdDataSizeCommand..This is because commands can accept any number of input
// objects.
ReceivedDataCollection.MaximumReceivedDataSize = null;
ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize;
_onDataAvailableToSendCallback =
new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback);
Initialize(connectionInfo.ConnectionUri, connectionInfo);
}
#endregion
#region Set Session Options
/// <summary>
/// Sets default timeout for all client operations in milliseconds.
/// TODO: Sync with WSMan and figure out what the default is if we
/// dont set.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetDefaultTimeOut(int milliseconds)
{
Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
using (tracer.TraceMethod("Setting Default timeout: {0} milliseconds", milliseconds))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_DEFAULT_OPERATION_TIMEOUTMS,
new WSManNativeApi.WSManDataDWord(milliseconds));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
/// <summary>
/// Sets timeout for Create operation in milliseconds.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetConnectTimeOut(int milliseconds)
{
Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
using (tracer.TraceMethod("Setting CreateShell timeout: {0} milliseconds", milliseconds))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_CREATE_SHELL,
new WSManNativeApi.WSManDataDWord(milliseconds));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
/// <summary>
/// Sets timeout for Close operation in milliseconds.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetCloseTimeOut(int milliseconds)
{
Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
using (tracer.TraceMethod("Setting CloseShell timeout: {0} milliseconds", milliseconds))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_CLOSE_SHELL_OPERATION,
new WSManNativeApi.WSManDataDWord(milliseconds));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
/// <summary>
/// Sets timeout for SendShellInput operation in milliseconds.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetSendTimeOut(int milliseconds)
{
Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
using (tracer.TraceMethod("Setting SendShellInput timeout: {0} milliseconds", milliseconds))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_SEND_SHELL_INPUT,
new WSManNativeApi.WSManDataDWord(milliseconds));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
/// <summary>
/// Sets timeout for Receive operation in milliseconds.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetReceiveTimeOut(int milliseconds)
{
Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
using (tracer.TraceMethod("Setting ReceiveShellOutput timeout: {0} milliseconds", milliseconds))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_RECEIVE_SHELL_OUTPUT,
new WSManNativeApi.WSManDataDWord(milliseconds));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
/// <summary>
/// Sets timeout for Signal operation in milliseconds.
/// </summary>
/// <param name="milliseconds"></param>
/// <returns></returns>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetSignalTimeOut(int milliseconds)
{
Dbg.Assert(_wsManSessionHandle != IntPtr.Zero, "Session handle cannot be null");
using (tracer.TraceMethod("Setting SignalShell timeout: {0} milliseconds", milliseconds))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
WSManNativeApi.WSManSessionOption.WSMAN_OPTION_TIMEOUTMS_SIGNAL_SHELL,
new WSManNativeApi.WSManDataDWord(milliseconds));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
/// <summary>
/// Sets a DWORD value for a WSMan Session option.
/// </summary>
/// <param name="option"></param>
/// <param name="dwordData"></param>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, int dwordData)
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
option, new WSManNativeApi.WSManDataDWord(dwordData));
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
/// <summary>
/// Sets a string value for a WSMan Session option.
/// </summary>
/// <param name="option"></param>
/// <param name="stringData"></param>
/// <exception cref="PSInvalidOperationException">
/// Setting session option failed with a non-zero error code.
/// </exception>
internal void SetWSManSessionOption(WSManNativeApi.WSManSessionOption option, string stringData)
{
using (WSManNativeApi.WSManData_ManToUn data = new WSManNativeApi.WSManData_ManToUn(stringData))
{
int result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
option, data);
if (result != 0)
{
// Get the error message from WSMan
string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);
PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
throw exception;
}
}
}
#endregion
#region Internal Methods / Properties
internal WSManAPIDataCommon WSManAPIData { get; private set; }
internal bool SupportsDisconnect { get; private set; }
internal override void DisconnectAsync()
{
Dbg.Assert(!isClosed, "object already disposed");
// Pass the WSManConnectionInfo object IdleTimeout value if it is
// valid. Otherwise pass the default value that instructs the server
// to use its default IdleTimeout value.
uint uIdleTimeout = (ConnectionInfo.IdleTimeout > 0) ?
(uint)ConnectionInfo.IdleTimeout : UseServerDefaultIdleTimeoutUInt;
// startup info
WSManNativeApi.WSManShellDisconnectInfo disconnectInfo = new WSManNativeApi.WSManShellDisconnectInfo(uIdleTimeout);
// Add ETW traces
// disconnect Callback
_disconnectSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionDisconnectCallback);
try
{
lock (syncObject)
{
if (isClosed)
{
// the transport is already closed
// anymore.
return;
}
int flags = 0;
flags |= (ConnectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Block) ?
(int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_BLOCK : 0;
flags |= (ConnectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ?
(int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0;
WSManNativeApi.WSManDisconnectShellEx(_wsManShellOperationHandle,
flags,
disconnectInfo,
_disconnectSessionCompleted);
}
}
finally
{
disconnectInfo.Dispose();
}
}
internal override void ReconnectAsync()
{
Dbg.Assert(!isClosed, "object already disposed");
ReceivedDataCollection.PrepareForStreamConnect();
// Add ETW traces
// reconnect Callback
_reconnectSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionReconnectCallback);
lock (syncObject)
{
if (isClosed)
{
// the transport is already closed
// anymore.
return;
}
int flags = 0;
flags |= (ConnectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Block) ?
(int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_BLOCK : 0;
flags |= (ConnectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ?
(int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0;
WSManNativeApi.WSManReconnectShellEx(_wsManShellOperationHandle,
flags,
_reconnectSessionCompleted);
}
}
/// <summary>
/// Starts connecting to an existing remote session. This will result in a WSManConnectShellEx WSMan
/// async call. Piggy backs available data in input stream as openXml in connect SOAP.
/// DSHandler will push negotiation related messages through the open content.
/// </summary>
/// <exception cref="PSRemotingTransportException">
/// WSManConnectShellEx failed.
/// </exception>
internal override void ConnectAsync()
{
Dbg.Assert(!isClosed, "object already disposed");
Dbg.Assert(!string.IsNullOrEmpty(ConnectionInfo.ShellUri), "shell uri cannot be null or empty.");
ReceivedDataCollection.PrepareForStreamConnect();
// additional content with connect shell call. Negotiation and connect related messages
// should be included in payload
if (_openContent == null)
{
DataPriorityType additionalDataType;
byte[] additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType);
if (additionalData != null)
{
// WSMan expects the data to be in XML format (which is text + xml tags)
// so convert byte[] into base64 encoded format
string base64EncodedDataInXml = string.Format(
CultureInfo.InvariantCulture,
"<{0} xmlns=\"{1}\">{2}</{0}>",
WSManNativeApi.PS_CONNECT_XML_TAG,
WSManNativeApi.PS_XML_NAMESPACE,
Convert.ToBase64String(additionalData));
_openContent = new WSManNativeApi.WSManData_ManToUn(base64EncodedDataInXml);
}
// THERE SHOULD BE NO ADDITIONAL DATA. If there is, it means we are not able to push all initial negotiation related data
// as part of Connect SOAP. The connect algorithm is based on this assumption. So bail out.
additionalData = dataToBeSent.ReadOrRegisterCallback(null, out additionalDataType);
if (additionalData != null)
{
// Negotiation payload does not fit in ConnectShell. bail out.
// Assert for now. should be replaced with raising an exception so upper layers can catch.
Dbg.Assert(false, "Negotiation payload does not fit in ConnectShell");
return;
}
}
// Create and store context for this shell operation. This context is used from various callbacks
_sessionContextID = GetNextSessionTMHandleId();
AddSessionTransportManager(_sessionContextID, this);
// session is implicitly assumed to support disconnect
SupportsDisconnect = true;
// Create Callback
_connectSessionCallback = new WSManNativeApi.WSManShellAsync(new IntPtr(_sessionContextID), s_sessionConnectCallback);
lock (syncObject)
{
if (isClosed)
{
// the transport is already closed..so no need to connect
// anymore.
return;
}
Dbg.Assert(_startMode == WSManTransportManagerUtils.tmStartModes.None, "startMode is not in expected state");
_startMode = WSManTransportManagerUtils.tmStartModes.Connect;
int flags = 0;
flags |= (ConnectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Block) ?
(int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_BLOCK : 0;
flags |= (ConnectionInfo.OutputBufferingMode == Runspaces.OutputBufferingMode.Drop) ?
(int)WSManNativeApi.WSManShellFlag.WSMAN_FLAG_SERVER_BUFFERING_MODE_DROP : 0;
WSManNativeApi.WSManConnectShellEx(_wsManSessionHandle,
flags,
ConnectionInfo.ShellUri,
RunspacePoolInstanceId.ToString().ToUpperInvariant(), // wsman is case sensitive wrt shellId. so consistently using upper case
IntPtr.Zero,
_openContent,
_connectSessionCallback,
ref _wsManShellOperationHandle);
}
if (_wsManShellOperationHandle == IntPtr.Zero)
{
TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManAPIData.WSManAPIHandle,
this,
new WSManNativeApi.WSManError(),
TransportMethodEnum.ConnectShellEx,
RemotingErrorIdStrings.ConnectExFailed, this.ConnectionInfo.ComputerName);
ProcessWSManTransportError(eventargs);
return;
}
}
internal override void StartReceivingData()
{
lock (syncObject)
{
// make sure the transport is not closed.
if (isClosed)
{
tracer.WriteLine("Client Session TM: Transport manager is closed. So returning");