Exemple #1
0
        /// <summary>
        /// Creates a new instance of ClientRemoteSessionImpl
        /// </summary>
        /// <param name="rsPool">
        /// The RunspacePool object this session should map to.
        /// </param>
        /// <param name="uriRedirectionHandler">
        /// </param>
        internal ClientRemoteSessionImpl(RemoteRunspacePoolInternal rsPool,
                                         URIDirectionReported uriRedirectionHandler)
        {
            Dbg.Assert(rsPool != null, "RunspacePool cannot be null");
            base.RemoteRunspacePoolInternal = rsPool;
            Context.RemoteAddress           = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(rsPool.ConnectionInfo,
                                                                                                             "ConnectionUri", null);
            _cryptoHelper            = new PSRemotingCryptoHelperClient();
            _cryptoHelper.Session    = this;
            Context.ClientCapability = RemoteSessionCapability.CreateClientCapability();
            Context.UserCredential   = rsPool.ConnectionInfo.Credential;

            // shellName validation is not performed on the client side.
            // This is recommended by the WinRS team: for the reason that the rules may change in the future.
            Context.ShellName = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(rsPool.ConnectionInfo,
                                                                                                  "ShellUri", string.Empty);

            MySelf = RemotingDestination.Client;
            //Create session data structure handler for this session
            SessionDataStructureHandler = new ClientRemoteSessionDSHandlerImpl(this,
                                                                               _cryptoHelper,
                                                                               rsPool.ConnectionInfo,
                                                                               uriRedirectionHandler);
            BaseSessionDataStructureHandler     = SessionDataStructureHandler;
            _waitHandleForConfigurationReceived = new ManualResetEvent(false);

            //Register handlers for various ClientSessiondata structure handler events
            SessionDataStructureHandler.NegotiationReceived         += HandleNegotiationReceived;
            SessionDataStructureHandler.ConnectionStateChanged      += HandleConnectionStateChanged;
            SessionDataStructureHandler.EncryptedSessionKeyReceived +=
                new EventHandler <RemoteDataEventArgs <string> >(HandleEncryptedSessionKeyReceived);
            SessionDataStructureHandler.PublicKeyRequestReceived +=
                new EventHandler <RemoteDataEventArgs <string> >(HandlePublicKeyRequestReceived);
        }
        private List <RemoteRunspace> CreateRunspacesWhenRunspaceParameterSpecified()
        {
            List <RemoteRunspace> list = new List <RemoteRunspace>();

            base.ValidateRemoteRunspacesSpecified();
            int rsIndex = 0;

            foreach (PSSession session in this.remoteRunspaceInfos)
            {
                if ((session == null) || (session.Runspace == null))
                {
                    base.ThrowTerminatingError(new ErrorRecord(new ArgumentNullException("PSSession"), "PSSessionArgumentNull", ErrorCategory.InvalidArgument, null));
                }
                else
                {
                    try
                    {
                        int                 num2;
                        RemoteRunspace      runspace       = (RemoteRunspace)session.Runspace;
                        WSManConnectionInfo connectionInfo = runspace.ConnectionInfo as WSManConnectionInfo;
                        WSManConnectionInfo info2          = null;
                        if (connectionInfo != null)
                        {
                            info2 = connectionInfo.Copy();
                            info2.EnableNetworkAccess = info2.EnableNetworkAccess || (this.EnableNetworkAccess != false);
                        }
                        else
                        {
                            Uri    uri      = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(runspace.ConnectionInfo, "ConnectionUri", null);
                            string shellUri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(runspace.ConnectionInfo, "ShellUri", string.Empty);
                            info2 = new WSManConnectionInfo(uri, shellUri, runspace.ConnectionInfo.Credential);
                            base.UpdateConnectionInfo(info2);
                            info2.EnableNetworkAccess = (bool)this.EnableNetworkAccess;
                        }
                        RemoteRunspacePoolInternal remoteRunspacePoolInternal = runspace.RunspacePool.RemoteRunspacePoolInternal;
                        TypeTable typeTable = null;
                        if (((remoteRunspacePoolInternal != null) && (remoteRunspacePoolInternal.DataStructureHandler != null)) && (remoteRunspacePoolInternal.DataStructureHandler.TransportManager != null))
                        {
                            typeTable = remoteRunspacePoolInternal.DataStructureHandler.TransportManager.Fragmentor.TypeTable;
                        }
                        string         runspaceName = this.GetRunspaceName(rsIndex, out num2);
                        RemoteRunspace item         = new RemoteRunspace(typeTable, info2, base.Host, this.SessionOption.ApplicationArguments, runspaceName, num2);
                        list.Add(item);
                    }
                    catch (UriFormatException exception)
                    {
                        PipelineWriter  objectWriter = this.stream.ObjectWriter;
                        ErrorRecord     errorRecord  = new ErrorRecord(exception, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, session);
                        Action <Cmdlet> action       = delegate(Cmdlet cmdlet) {
                            cmdlet.WriteError(errorRecord);
                        };
                        objectWriter.Write(action);
                    }
                }
                rsIndex++;
            }
            return(list);
        }
 internal ClientRemoteSessionImpl(RemoteRunspacePoolInternal rsPool, ClientRemoteSession.URIDirectionReported uriRedirectionHandler)
 {
     base.RemoteRunspacePoolInternal = rsPool;
     base.Context.RemoteAddress      = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(rsPool.ConnectionInfo, "ConnectionUri", null);
     this._cryptoHelper            = new PSRemotingCryptoHelperClient();
     this._cryptoHelper.Session    = this;
     base.Context.ClientCapability = RemoteSessionCapability.CreateClientCapability();
     base.Context.UserCredential   = rsPool.ConnectionInfo.Credential;
     base.Context.ShellName        = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <string>(rsPool.ConnectionInfo, "ShellUri", string.Empty);
     this._mySelf = RemotingDestination.InvalidDestination | RemotingDestination.Client;
     base.SessionDataStructureHandler                              = new ClientRemoteSessionDSHandlerImpl(this, this._cryptoHelper, rsPool.ConnectionInfo, uriRedirectionHandler);
     base.BaseSessionDataStructureHandler                          = base.SessionDataStructureHandler;
     this._waitHandleForConfigurationReceived                      = new ManualResetEvent(false);
     base.SessionDataStructureHandler.NegotiationReceived         += new EventHandler <RemoteSessionNegotiationEventArgs>(this.HandleNegotiationReceived);
     base.SessionDataStructureHandler.ConnectionStateChanged      += new EventHandler <RemoteSessionStateEventArgs>(this.HandleConnectionStateChanged);
     base.SessionDataStructureHandler.EncryptedSessionKeyReceived += new EventHandler <RemoteDataEventArgs <string> >(this.HandleEncryptedSessionKeyReceived);
     base.SessionDataStructureHandler.PublicKeyRequestReceived    += new EventHandler <RemoteDataEventArgs <string> >(this.HandlePublicKeyRequestReceived);
 }
        private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs)
        {
            ErrorRecord errorRecord;
            PSRemotingTransportException exception2;
            string str;

            if (sender == null)
            {
                throw PSTraceSource.NewArgumentNullException("sender");
            }
            if (stateEventArgs == null)
            {
                throw PSTraceSource.NewArgumentNullException("stateEventArgs");
            }
            RunspaceStateEventArgs baseEvent        = stateEventArgs.BaseEvent as RunspaceStateEventArgs;
            RunspaceState          state            = baseEvent.RunspaceStateInfo.State;
            OpenRunspaceOperation  operation        = sender as OpenRunspaceOperation;
            RemoteRunspace         operatedRunspace = operation.OperatedRunspace;

            if (operatedRunspace != null)
            {
                operatedRunspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported);
            }
            PipelineWriter objectWriter = this.stream.ObjectWriter;
            Exception      reason       = baseEvent.RunspaceStateInfo.Reason;

            switch (state)
            {
            case RunspaceState.Opened:
            {
                PSSession remoteRunspaceInfo = new PSSession(operatedRunspace);
                base.RunspaceRepository.Add(remoteRunspaceInfo);
                Action <Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo);
                if (objectWriter.IsOpen)
                {
                    objectWriter.Write(action);
                }
                return;
            }

            case RunspaceState.Closed:
            {
                Uri             uri     = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null);
                string          message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty });
                Action <Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message);
                if (objectWriter.IsOpen)
                {
                    objectWriter.Write(action3);
                }
                if (reason != null)
                {
                    ErrorRecord     errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace);
                    Action <Cmdlet> action4      = cmdlet => cmdlet.WriteError(errorRecord2);
                    if (objectWriter.IsOpen)
                    {
                        objectWriter.Write(action4);
                    }
                }
                return;
            }

            case RunspaceState.Closing:
                return;

            case RunspaceState.Broken:
                exception2 = reason as PSRemotingTransportException;
                str        = null;
                if (exception2 != null)
                {
                    OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation;
                    if (operation2 != null)
                    {
                        string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName;
                        if (exception2.ErrorCode != -2144108135)
                        {
                            str = "[" + computerName + "] ";
                            if (!string.IsNullOrEmpty(exception2.Message))
                            {
                                str = str + exception2.Message;
                            }
                            else if (!string.IsNullOrEmpty(exception2.TransportMessage))
                            {
                                str = str + exception2.TransportMessage;
                            }
                            break;
                        }
                        string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" });
                        str = "[" + computerName + "] " + str3;
                    }
                }
                break;

            default:
                return;
            }
            PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException;

            if (exception3 != null)
            {
                OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation;
                if (operation3 != null)
                {
                    string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName;
                    str = "[" + str4 + "] " + exception3.Message;
                }
            }
            if (reason == null)
            {
                reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state }));
            }
            string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID);

            errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null);
            Action <Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord);

            if (objectWriter.IsOpen)
            {
                objectWriter.Write(action2);
            }
            this.toDispose.Add(operatedRunspace);
        }