File size: 32,675 Bytes
8c763fb | 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 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Management.Automation.Internal;
using System.Management.Automation.Remoting.Client;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Runspaces.Internal;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
/// <summary>
/// Implements ServerRemoteSessionDataStructureHandler.
/// </summary>
internal sealed class ClientRemoteSessionDSHandlerImpl : ClientRemoteSessionDataStructureHandler, IDisposable
{
[TraceSource("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl")]
private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl");
private const string resBaseName = "remotingerroridstrings";
private readonly BaseClientSessionTransportManager _transportManager;
private readonly ClientRemoteSessionDSHandlerStateMachine _stateMachine;
private readonly ClientRemoteSession _session;
private readonly RunspaceConnectionInfo _connectionInfo;
// used for connection redirection.
private Uri _redirectUri;
private int _maxUriRedirectionCount;
private bool _isCloseCalled;
private readonly object _syncObject = new object();
private readonly PSRemotingCryptoHelper _cryptoHelper;
private readonly ClientRemoteSession.URIDirectionReported _uriRedirectionHandler;
internal override BaseClientSessionTransportManager TransportManager
{
get
{
return _transportManager;
}
}
internal override BaseClientCommandTransportManager CreateClientCommandTransportManager(
System.Management.Automation.Runspaces.Internal.ClientRemotePowerShell cmd,
bool noInput)
{
BaseClientCommandTransportManager cmdTransportMgr =
_transportManager.CreateClientCommandTransportManager(_connectionInfo, cmd, noInput);
// listen to data ready events.
cmdTransportMgr.DataReceived += DispatchInputQueueData;
return cmdTransportMgr;
}
#region constructors
/// <summary>
/// Creates an instance of ClientRemoteSessionDSHandlerImpl.
/// </summary>
internal ClientRemoteSessionDSHandlerImpl(ClientRemoteSession session,
PSRemotingCryptoHelper cryptoHelper,
RunspaceConnectionInfo connectionInfo,
ClientRemoteSession.URIDirectionReported uriRedirectionHandler)
{
Dbg.Assert(_maxUriRedirectionCount >= 0, "maxUriRedirectionCount cannot be less than 0.");
if (session == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(session));
}
_session = session;
// Create state machine
_stateMachine = new ClientRemoteSessionDSHandlerStateMachine();
_stateMachine.StateChanged += HandleStateChanged;
_connectionInfo = connectionInfo;
// Create transport manager
_cryptoHelper = cryptoHelper;
_transportManager = _connectionInfo.CreateClientSessionTransportManager(
_session.RemoteRunspacePoolInternal.InstanceId,
_session.RemoteRunspacePoolInternal.Name,
cryptoHelper);
_transportManager.DataReceived += DispatchInputQueueData;
_transportManager.WSManTransportErrorOccured += HandleTransportError;
_transportManager.CloseCompleted += HandleCloseComplete;
_transportManager.DisconnectCompleted += HandleDisconnectComplete;
_transportManager.ReconnectCompleted += HandleReconnectComplete;
_transportManager.RobustConnectionNotification += HandleRobustConnectionNotification;
WSManConnectionInfo wsmanConnectionInfo = _connectionInfo as WSManConnectionInfo;
if (wsmanConnectionInfo != null)
{
// only WSMan transport supports redirection
// store the uri redirection handler and authmechanism
// for uri redirection.
_uriRedirectionHandler = uriRedirectionHandler;
_maxUriRedirectionCount = wsmanConnectionInfo.MaximumConnectionRedirectionCount;
}
}
#endregion constructors
#region create
/// <summary>
/// Makes a create call asynchronously.
/// </summary>
internal override void CreateAsync()
{
// errors are reported through WSManTransportErrorOccured event on
// the transport manager.
_transportManager.CreateCompleted += HandleCreateComplete;
_transportManager.CreateAsync();
}
/// <summary>
/// This callback is called on complete of async connect call.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void HandleCreateComplete(object sender, EventArgs args)
{
// This is a no-op at the moment..as we dont need to inform anything to
// state machine here..StateMachine must already have reached NegotiationSent
// state and waiting for Negotiation Received which will happen only from
// DataReceived event.
}
private void HandleConnectComplete(object sender, EventArgs args)
{
// No-OP. Once the negotiation messages are exchanged and the session gets into established state,
// it will take care of spawning the receive operation on the connected session
// There is however a caveat.
// A rouge remote server if it does not send the required negotiation data in the Connect Response,
// then the state machine can never get into the established state and the runspace can never get into a opened state
// Living with this for now.
}
#endregion create
#region disconnect
internal override void DisconnectAsync()
{
_transportManager.DisconnectAsync();
}
private void HandleDisconnectComplete(object sender, EventArgs args)
{
// Set statemachine event
RemoteSessionStateMachineEventArgs disconnectCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.DisconnectCompleted);
StateMachine.RaiseEvent(disconnectCompletedArg);
}
#endregion disconnect
#region RobustConnection events
private void HandleRobustConnectionNotification(object sender, ConnectionStatusEventArgs e)
{
RemoteSessionStateMachineEventArgs eventArgument = null;
switch (e.Notification)
{
case ConnectionStatus.AutoDisconnectStarting:
eventArgument = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.RCDisconnectStarted);
break;
case ConnectionStatus.AutoDisconnectSucceeded:
eventArgument = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.DisconnectCompleted,
new RuntimeException(
StringUtil.Format(RemotingErrorIdStrings.RCAutoDisconnectingError,
_session.RemoteRunspacePoolInternal.ConnectionInfo.ComputerName)));
break;
case ConnectionStatus.InternalErrorAbort:
eventArgument = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError);
break;
}
if (eventArgument != null)
{
StateMachine.RaiseEvent(eventArgument);
}
}
#endregion
#region reconnect
internal override void ReconnectAsync()
{
_transportManager.ReconnectAsync();
}
private void HandleReconnectComplete(object sender, EventArgs args)
{
// Set statemachine event
RemoteSessionStateMachineEventArgs reconnectCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.ReconnectCompleted);
StateMachine.RaiseEvent(reconnectCompletedArg);
}
#endregion reconnect
#region close
/// <summary>
/// Close the connection asynchronously.
/// </summary>
internal override void CloseConnectionAsync()
{
lock (_syncObject)
{
if (_isCloseCalled)
{
return;
}
_transportManager.CloseAsync();
_isCloseCalled = true;
}
}
private void HandleCloseComplete(object sender, EventArgs args)
{
// This event gets raised only when the connection is closed successfully.
RemoteSessionStateMachineEventArgs closeCompletedArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.CloseCompleted);
_stateMachine.RaiseEvent(closeCompletedArg);
}
#endregion close
#region negotiation
/// <summary>
/// Sends the negotiation package asynchronously.
/// </summary>
internal override void SendNegotiationAsync(RemoteSessionState sessionState)
{
// This state change is made before the call to CreateAsync to ensure the state machine
// is prepared for a NegotiationReceived response. Otherwise a race condition can
// occur when the transport NegotiationReceived arrives too soon, breaking the session.
// This race condition was observed for OutOfProc transport when reusing the OutOfProc process.
// this will change StateMachine to NegotiationSent.
RemoteSessionStateMachineEventArgs negotiationSendCompletedArg =
new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationSendCompleted);
_stateMachine.RaiseEvent(negotiationSendCompletedArg);
if (sessionState == RemoteSessionState.NegotiationSending)
{
_transportManager.CreateAsync();
}
else if (sessionState == RemoteSessionState.NegotiationSendingOnConnect)
{
_transportManager.ConnectCompleted += HandleConnectComplete;
_transportManager.ConnectAsync();
}
else
{
Dbg.Assert(false, "SendNegotiationAsync called in unexpected session state");
}
}
internal override event EventHandler<RemoteSessionNegotiationEventArgs> NegotiationReceived;
#endregion negotiation
#region state change
/// <summary>
/// This event indicates that the connection state has changed.
/// </summary>
internal override event EventHandler<RemoteSessionStateEventArgs> ConnectionStateChanged;
private void HandleStateChanged(object sender, RemoteSessionStateEventArgs arg)
{
if (arg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(arg));
}
// Enqueue session related negotiation packets first
if ((arg.SessionStateInfo.State == RemoteSessionState.NegotiationSending) || (arg.SessionStateInfo.State == RemoteSessionState.NegotiationSendingOnConnect))
{
HandleNegotiationSendingStateChange();
}
// this will enable top-layers to enqueue any packets during NegotiationSending and
// during other states.
ConnectionStateChanged.SafeInvoke(this, arg);
if ((arg.SessionStateInfo.State == RemoteSessionState.NegotiationSending) || (arg.SessionStateInfo.State == RemoteSessionState.NegotiationSendingOnConnect))
{
SendNegotiationAsync(arg.SessionStateInfo.State);
}
// once session is established.. start receiving data (if not already done and only apples to wsmanclientsessionTM)
if (arg.SessionStateInfo.State == RemoteSessionState.Established)
{
WSManClientSessionTransportManager tm = _transportManager as WSManClientSessionTransportManager;
if (tm != null)
{
tm.AdjustForProtocolVariations(_session.ServerProtocolVersion);
tm.StartReceivingData();
}
}
// Close the transport manager only after powershell's close their transports
// Powershell's close their transport using the ConnectionStateChanged event notification.
if (arg.SessionStateInfo.State == RemoteSessionState.ClosingConnection)
{
CloseConnectionAsync();
}
// process disconnect
if (arg.SessionStateInfo.State == RemoteSessionState.Disconnecting)
{
DisconnectAsync();
}
// process reconnect
if (arg.SessionStateInfo.State == RemoteSessionState.Reconnecting)
{
ReconnectAsync();
}
}
/// <summary>
/// Clubbing negotiation packet + runspace creation and then doing transportManager.ConnectAsync().
/// This will save us 2 network calls by doing all the work in one network call.
/// </summary>
private void HandleNegotiationSendingStateChange()
{
RemoteSessionCapability clientCapability = _session.Context.ClientCapability;
Dbg.Assert(clientCapability.RemotingDestination == RemotingDestination.Server, "Expected clientCapability.RemotingDestination == RemotingDestination.Server");
// Encode and send the negotiation reply
RemoteDataObject data = RemotingEncoder.GenerateClientSessionCapability(
clientCapability, _session.RemoteRunspacePoolInternal.InstanceId);
RemoteDataObject<PSObject> dataAsPSObject = RemoteDataObject<PSObject>.CreateFrom(
data.Destination, data.DataType, data.RunspacePoolId, data.PowerShellId, (PSObject)data.Data);
_transportManager.DataToBeSentCollection.Add<PSObject>(dataAsPSObject);
}
#endregion state change
internal override ClientRemoteSessionDSHandlerStateMachine StateMachine
{
get
{
return _stateMachine;
}
}
#region URI Redirection
/// <summary>
/// Transport reported an error saying that uri is redirected. This method
/// will perform the redirection to the new URI by doing the following:
/// 1. Close the current transport manager to clean resources
/// 2. Raise a warning that URI is getting redirected.
/// 3. Using the new URI, ask the same transport manager to redirect
/// Step 1 is performed here. Step2-3 is performed in another method.
/// </summary>
/// <param name="newURIString"></param>
/// <exception cref="ArgumentNullException">
/// newURIString is a null reference.
/// </exception>
/// <exception cref="UriFormatException">
/// uriString is empty.
/// The scheme specified in uriString is invalid.
/// uriString contains too many slashes.
/// The password specified in uriString is invalid.
/// The host name specified in uriString is invalid.
/// </exception>
private void PerformURIRedirection(string newURIString)
{
_redirectUri = new Uri(newURIString);
// make sure connection is not closed while we are handling the redirection.
lock (_syncObject)
{
// if connection is closed by the user..no need to redirect
if (_isCloseCalled)
{
return;
}
// clear our current close complete & Error handlers
_transportManager.CloseCompleted -= HandleCloseComplete;
_transportManager.WSManTransportErrorOccured -= HandleTransportError;
// perform other steps only after transport manager is closed.
_transportManager.CloseCompleted += HandleTransportCloseCompleteForRedirection;
// Handle errors happened while redirecting differently..We need to reset the
// original handlers in this case.
_transportManager.WSManTransportErrorOccured += HandleTransportErrorForRedirection;
_transportManager.PrepareForRedirection();
}
}
private void HandleTransportCloseCompleteForRedirection(object source, EventArgs args)
{
_transportManager.CloseCompleted -= HandleTransportCloseCompleteForRedirection;
_transportManager.WSManTransportErrorOccured -= HandleTransportErrorForRedirection;
// reattach the close complete and error handlers
_transportManager.CloseCompleted += HandleCloseComplete;
_transportManager.WSManTransportErrorOccured += HandleTransportError;
PerformURIRedirectionStep2(_redirectUri);
}
private void HandleTransportErrorForRedirection(object sender, TransportErrorOccuredEventArgs e)
{
_transportManager.CloseCompleted -= HandleTransportCloseCompleteForRedirection;
_transportManager.WSManTransportErrorOccured -= HandleTransportErrorForRedirection;
// reattach the close complete and error handlers
_transportManager.CloseCompleted += HandleCloseComplete;
_transportManager.WSManTransportErrorOccured += HandleTransportError;
HandleTransportError(sender, e);
}
/// <summary>
/// This is step 2 of URI redirection. This is called after the current transport manager
/// is closed. This is usually called from the close complete callback.
/// </summary>
/// <param name="newURI"></param>
private void PerformURIRedirectionStep2(System.Uri newURI)
{
Dbg.Assert(newURI != null, "Uri cannot be null");
lock (_syncObject)
{
// if connection is closed by the user..no need to redirect
if (_isCloseCalled)
{
return;
}
// raise warning to report the redirection
_uriRedirectionHandler?.Invoke(newURI);
// start a new connection
_transportManager.Redirect(newURI, _connectionInfo);
}
}
#endregion
#region data handling
/// <summary>
/// Handler which handles transport errors.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e)
{
Dbg.Assert(e != null, "HandleTransportError expects non-null eventargs");
// handle uri redirections
PSRemotingTransportRedirectException redirectException = e.Exception as PSRemotingTransportRedirectException;
if ((redirectException != null) && (_maxUriRedirectionCount > 0))
{
Exception exception = null;
try
{
// honor max redirection count given by the user.
_maxUriRedirectionCount--;
PerformURIRedirection(redirectException.RedirectLocation);
return;
}
catch (ArgumentNullException argumentException)
{
exception = argumentException;
}
catch (UriFormatException uriFormatException)
{
exception = uriFormatException;
}
// if we are here, there must be an exception constructing a uri
if (exception != null)
{
PSRemotingTransportException newException =
new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted,
_session.Context.RemoteAddress.OriginalString,
redirectException.RedirectLocation);
newException.TransportMessage = e.Exception.TransportMessage;
e.Exception = newException;
}
}
RemoteSessionEvent sessionEvent = RemoteSessionEvent.ConnectFailed;
switch (e.ReportingTransportMethod)
{
case TransportMethodEnum.CreateShellEx:
sessionEvent = RemoteSessionEvent.ConnectFailed;
break;
case TransportMethodEnum.SendShellInputEx:
case TransportMethodEnum.CommandInputEx:
sessionEvent = RemoteSessionEvent.SendFailed;
break;
case TransportMethodEnum.ReceiveShellOutputEx:
case TransportMethodEnum.ReceiveCommandOutputEx:
sessionEvent = RemoteSessionEvent.ReceiveFailed;
break;
case TransportMethodEnum.CloseShellOperationEx:
sessionEvent = RemoteSessionEvent.CloseFailed;
break;
case TransportMethodEnum.DisconnectShellEx:
sessionEvent = RemoteSessionEvent.DisconnectFailed;
break;
case TransportMethodEnum.ReconnectShellEx:
sessionEvent = RemoteSessionEvent.ReconnectFailed;
break;
}
RemoteSessionStateMachineEventArgs errorArgs =
new RemoteSessionStateMachineEventArgs(sessionEvent, e.Exception);
_stateMachine.RaiseEvent(errorArgs);
}
/// <summary>
/// Dispatches data when it arrives from the input queue.
/// </summary>
/// <param name="sender"></param>
/// <param name="dataArg">
/// arg which contains the data received from input queue
/// </param>
internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataArg)
{
if (dataArg == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(dataArg));
}
RemoteDataObject<PSObject> rcvdData = dataArg.ReceivedData;
if (rcvdData == null)
{
throw PSTraceSource.NewArgumentException(nameof(dataArg));
}
RemotingDestination destination = rcvdData.Destination;
if ((destination & RemotingDestination.Client) != RemotingDestination.Client)
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RemotingDestinationNotForMe, RemotingDestination.Client, destination);
}
RemotingTargetInterface targetInterface = rcvdData.TargetInterface;
switch (targetInterface)
{
case RemotingTargetInterface.Session:
{
// Messages for session can cause statemachine state to change.
// These messages are first processed by Sessiondata structure handler and depending
// on the type of message, appropriate event is raised in state machine
ProcessSessionMessages(dataArg);
break;
}
case RemotingTargetInterface.RunspacePool:
case RemotingTargetInterface.PowerShell:
// Non Session messages do not change the state of the statemachine.
// However instead of forwarding them to Runspace/pipeline here, an
// event is raised in state machine which verified that state is
// suitable for accepting these messages. if state is suitable statemachine
// will call DoMessageForwading which will forward the messages appropriately
RemoteSessionStateMachineEventArgs msgRcvArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.MessageReceived, null);
if (StateMachine.CanByPassRaiseEvent(msgRcvArg))
{
ProcessNonSessionMessages(dataArg.ReceivedData);
}
else
{
StateMachine.RaiseEvent(msgRcvArg);
}
break;
default:
{
Dbg.Assert(false, "we should not be encountering this");
}
break;
}
}
// TODO: If this is not used remove this
// internal override event EventHandler<RemoteDataEventArgs> DataReceived;
/// <summary>
/// This processes the object received from transport which are
/// targeted for session.
/// </summary>
/// <param name="arg">
/// argument contains the data object
/// </param>
private void ProcessSessionMessages(RemoteDataEventArgs arg)
{
if (arg == null || arg.ReceivedData == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(arg));
}
RemoteDataObject<PSObject> rcvdData = arg.ReceivedData;
RemotingTargetInterface targetInterface = rcvdData.TargetInterface;
Dbg.Assert(targetInterface == RemotingTargetInterface.Session, "targetInterface must be Session");
RemotingDataType dataType = rcvdData.DataType;
switch (dataType)
{
case RemotingDataType.CloseSession:
PSRemotingDataStructureException reasonOfClose = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerRequestedToCloseSession);
RemoteSessionStateMachineEventArgs closeSessionArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, reasonOfClose);
_stateMachine.RaiseEvent(closeSessionArg);
break;
case RemotingDataType.SessionCapability:
RemoteSessionCapability capability = null;
try
{
capability = RemotingDecoder.GetSessionCapability(rcvdData.Data);
}
catch (PSRemotingDataStructureException dse)
{
// this will happen if expected properties are not
// received for session capability
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientNotFoundCapabilityProperties,
dse.Message, PSVersionInfo.GitCommitId, RemotingConstants.ProtocolVersion);
}
RemoteSessionStateMachineEventArgs capabilityArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationReceived);
capabilityArg.RemoteSessionCapability = capability;
_stateMachine.RaiseEvent(capabilityArg);
RemoteSessionNegotiationEventArgs negotiationArg = new RemoteSessionNegotiationEventArgs(capability);
NegotiationReceived.SafeInvoke(this, negotiationArg);
break;
case RemotingDataType.EncryptedSessionKey:
{
string encryptedSessionKey = RemotingDecoder.GetEncryptedSessionKey(rcvdData.Data);
EncryptedSessionKeyReceived.SafeInvoke(this, new RemoteDataEventArgs<string>(encryptedSessionKey));
}
break;
case RemotingDataType.PublicKeyRequest:
{
PublicKeyRequestReceived.SafeInvoke(this, new RemoteDataEventArgs<string>(string.Empty));
}
break;
default:
{
throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType);
}
}
}
/// <summary>
/// This processes the object received from transport which are
/// not targeted for session.
/// </summary>
/// <param name="rcvdData">
/// received data.
/// </param>
internal void ProcessNonSessionMessages(RemoteDataObject<PSObject> rcvdData)
{
// TODO: Consider changing to Dbg.Assert()
if (rcvdData == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(rcvdData));
}
RemotingTargetInterface targetInterface = rcvdData.TargetInterface;
Guid clientRunspacePoolId;
RemoteRunspacePoolInternal runspacePool;
switch (targetInterface)
{
case RemotingTargetInterface.Session:
Dbg.Assert(false,
"The session remote data is handled my session data structure handler, not here");
break;
case RemotingTargetInterface.RunspacePool:
clientRunspacePoolId = rcvdData.RunspacePoolId;
runspacePool = _session.GetRunspacePool(clientRunspacePoolId);
if (runspacePool != null)
{
// GETBACK
runspacePool.DataStructureHandler.ProcessReceivedData(rcvdData);
}
else
{
// The runspace pool may have been removed on the client side,
// so, we should just ignore the message.
s_trace.WriteLine(@"Client received data for Runspace (id: {0}),
but the Runspace cannot be found", clientRunspacePoolId);
}
break;
case RemotingTargetInterface.PowerShell:
clientRunspacePoolId = rcvdData.RunspacePoolId;
runspacePool = _session.GetRunspacePool(clientRunspacePoolId);
// GETBACK
runspacePool.DataStructureHandler.DispatchMessageToPowerShell(rcvdData);
break;
default:
break;
}
}
#endregion data handling
#region IDisposable
/// <summary>
/// Release all resources.
/// </summary>
public void Dispose()
{
_transportManager.Dispose();
}
#endregion IDisposable
#region Key Exchange
internal override event EventHandler<RemoteDataEventArgs<string>> EncryptedSessionKeyReceived;
internal override event EventHandler<RemoteDataEventArgs<string>> PublicKeyRequestReceived;
/// <summary>
/// Send the specified local public key to the remote end.
/// </summary>
/// <param name="localPublicKey">Local public key as a string.</param>
internal override void SendPublicKeyAsync(string localPublicKey)
{
_transportManager.DataToBeSentCollection.Add<object>(
RemotingEncoder.GenerateMyPublicKey(_session.RemoteRunspacePoolInternal.InstanceId,
localPublicKey, RemotingDestination.Server));
}
/// <summary>
/// Raise the public key received event.
/// </summary>
/// <param name="receivedData">Received data.</param>
/// <remarks>This method is a hook to be called
/// from the transport manager</remarks>
internal override void RaiseKeyExchangeMessageReceived(RemoteDataObject<PSObject> receivedData)
{
ProcessSessionMessages(new RemoteDataEventArgs(receivedData));
}
#endregion Key Exchange
}
}
|