/// <summary>
        /// Create a new ClientMethodExecutor object and then dispatch it.
        /// </summary>
        internal static void Dispatch(
            BaseClientTransportManager transportManager,
            PSHost clientHost,
            PSDataCollectionStream <ErrorRecord> errorStream,
            ObjectStream methodExecutorStream,
            bool isMethodExecutorStreamEnabled,
            RemoteRunspacePoolInternal runspacePool,
            Guid clientPowerShellId,
            RemoteHostCall remoteHostCall)
        {
            ClientMethodExecutor methodExecutor =
                new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId,
                                         clientPowerShellId, remoteHostCall);

            // If the powershell id is not specified, this message is for the runspace pool, execute
            // it immediately and return
            if (clientPowerShellId == Guid.Empty)
            {
                methodExecutor.Execute(errorStream);
                return;
            }

            // Check client host to see if SetShouldExit should be allowed
            bool hostAllowSetShouldExit = false;

            if (clientHost != null)
            {
                PSObject hostPrivateData = clientHost.PrivateData as PSObject;
                if (hostPrivateData != null)
                {
                    PSNoteProperty allowSetShouldExit = hostPrivateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty;
                    hostAllowSetShouldExit = allowSetShouldExit != null && allowSetShouldExit.Value is bool && (bool)allowSetShouldExit.Value;
                }
            }

            // Should we kill remote runspace? Check if "SetShouldExit" and if we are in the
            // cmdlet case. In the API case (when we are invoked from an API not a cmdlet) we
            // should not interpret "SetShouldExit" but should pass it on to the host. The
            // variable IsMethodExecutorStreamEnabled is only true in the cmdlet case. In the
            // API case it is false.

            if (remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled && !hostAllowSetShouldExit)
            {
                runspacePool.Close();
                return;
            }

            // Cmdlet case: queue up the executor in the pipeline stream.
            if (isMethodExecutorStreamEnabled)
            {
                Dbg.Assert(methodExecutorStream != null, "method executor stream can't be null when enabled");
                methodExecutorStream.Write(methodExecutor);
            }

            // API case: execute it immediately.
            else
            {
                methodExecutor.Execute(errorStream);
            }
        }
Exemplo n.º 2
0
        internal static void Dispatch(
            BaseClientTransportManager transportManager,
            PSHost clientHost,
            PSDataCollectionStream <ErrorRecord> errorStream,
            ObjectStream methodExecutorStream,
            bool isMethodExecutorStreamEnabled,
            RemoteRunspacePoolInternal runspacePool,
            Guid clientPowerShellId,
            RemoteHostCall remoteHostCall)
        {
            ClientMethodExecutor clientMethodExecutor = new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId, clientPowerShellId, remoteHostCall);

            if (clientPowerShellId == Guid.Empty)
            {
                clientMethodExecutor.Execute(errorStream);
            }
            else if (remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled)
            {
                runspacePool.Close();
            }
            else if (isMethodExecutorStreamEnabled)
            {
                methodExecutorStream.Write((object)clientMethodExecutor);
            }
            else
            {
                clientMethodExecutor.Execute(errorStream);
            }
        }
Exemplo n.º 3
0
        internal void ProcessNonSessionMessages(RemoteDataObject <PSObject> rcvdData)
        {
            using (ClientRemoteSessionDSHandlerImpl._trace.TraceMethod())
            {
                if (rcvdData == null)
                {
                    throw ClientRemoteSessionDSHandlerImpl._trace.NewArgumentNullException(nameof(rcvdData));
                }
                switch (rcvdData.TargetInterface)
                {
                case RemotingTargetInterface.RunspacePool:
                    Guid runspacePoolId = rcvdData.RunspacePoolId;
                    RemoteRunspacePoolInternal runspacePool = this._session.GetRunspacePool(runspacePoolId);
                    if (runspacePool != null)
                    {
                        runspacePool.DataStructureHandler.ProcessReceivedData(rcvdData);
                        break;
                    }
                    ClientRemoteSessionDSHandlerImpl._trace.WriteLine("Client received data for Runspace (id: {0}), \r\n                                but the Runspace cannot be found", (object)runspacePoolId);
                    break;

                case RemotingTargetInterface.PowerShell:
                    this._session.GetRunspacePool(rcvdData.RunspacePoolId).DataStructureHandler.DispatchMessageToPowerShell(rcvdData);
                    break;
                }
            }
        }
Exemplo n.º 4
0
        internal void ProcessNonSessionMessages(RemoteDataObject <PSObject> rcvdData)
        {
            Guid runspacePoolId;

            if (rcvdData == null)
            {
                throw PSTraceSource.NewArgumentNullException("rcvdData");
            }
            switch (rcvdData.TargetInterface)
            {
            case RemotingTargetInterface.Session:
                break;

            case RemotingTargetInterface.RunspacePool:
            {
                runspacePoolId = rcvdData.RunspacePoolId;
                RemoteRunspacePoolInternal runspacePool = this._session.GetRunspacePool(runspacePoolId);
                if (runspacePool == null)
                {
                    _trace.WriteLine("Client received data for Runspace (id: {0}), \r\n                            but the Runspace cannot be found", new object[] { runspacePoolId });
                    return;
                }
                runspacePool.DataStructureHandler.ProcessReceivedData(rcvdData);
                return;
            }

            case RemotingTargetInterface.PowerShell:
                runspacePoolId = rcvdData.RunspacePoolId;
                this._session.GetRunspacePool(runspacePoolId).DataStructureHandler.DispatchMessageToPowerShell(rcvdData);
                break;

            default:
                return;
            }
        }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
0
        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);
        }
Exemplo n.º 7
0
        private static void CheckScriptCallOnRemoteRunspace(RemoteRunspace remoteRunspace)
        {
            RemoteRunspacePoolInternal remoteRunspacePoolInternal = remoteRunspace.RunspacePool.RemoteRunspacePoolInternal;

            if (remoteRunspacePoolInternal != null)
            {
                BaseClientSessionTransportManager transportManager = remoteRunspacePoolInternal.DataStructureHandler.TransportManager;
                if ((transportManager != null) && (transportManager.TypeTable == null))
                {
                    throw PSTraceSource.NewInvalidOperationException("TabCompletionStrings", "CannotDeserializeTabCompletionResult", new object[0]);
                }
            }
        }
Exemplo n.º 8
0
        internal static Runspace[] GetRemoteRunspaces(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
        {
            List <Runspace> list = new List <Runspace>();

            foreach (System.Management.Automation.Runspaces.RunspacePool pool in RemoteRunspacePoolInternal.GetRemoteRunspacePools(connectionInfo, host, typeTable))
            {
                if (pool.RemoteRunspacePoolInternal.ConnectCommands.Length < 2)
                {
                    list.Add(new RemoteRunspace(pool));
                }
            }
            return(list.ToArray());
        }
 internal ClientRunspacePoolDataStructureHandler(RemoteRunspacePoolInternal clientRunspacePool, TypeTable typeTable)
 {
     this.clientRunspacePoolId = clientRunspacePool.InstanceId;
     this.minRunspaces         = clientRunspacePool.GetMinRunspaces();
     this.maxRunspaces         = clientRunspacePool.GetMaxRunspaces();
     this.host = clientRunspacePool.Host;
     this.applicationArguments        = clientRunspacePool.ApplicationArguments;
     this.remoteSession               = this.CreateClientRemoteSession(clientRunspacePool);
     this.transportManager            = this.remoteSession.SessionDataStructureHandler.TransportManager;
     this.transportManager.TypeTable  = typeTable;
     this.remoteSession.StateChanged += new EventHandler <RemoteSessionStateEventArgs>(this.HandleClientRemoteSessionStateChanged);
     this._reconnecting               = false;
     this.transportManager.RobustConnectionNotification += new EventHandler <ConnectionStatusEventArgs>(this.HandleRobustConnectionNotification);
     this.transportManager.CreateCompleted += new EventHandler <CreateCompleteEventArgs>(this.HandleSessionCreateCompleted);
 }
Exemplo n.º 10
0
 internal ClientRunspacePoolDataStructureHandler(
     RemoteRunspacePoolInternal clientRunspacePool,
     TypeTable typeTable)
 {
     using (ClientRunspacePoolDataStructureHandler.tracer.TraceConstructor((object)this))
     {
         this.clientRunspacePoolId = clientRunspacePool.InstanceId;
         this.minRunspaces         = clientRunspacePool.GetMinRunspaces();
         this.maxRunspaces         = clientRunspacePool.GetMaxRunspaces();
         this.host = clientRunspacePool.Host;
         this.applicationArguments        = clientRunspacePool.ApplicationArguments;
         this.remoteSession               = (ClientRemoteSession)this.CreateClientRemoteSession(clientRunspacePool);
         this.transportManager            = this.remoteSession.SessionDataStructureHandler.TransportManager;
         this.transportManager.TypeTable  = typeTable;
         this.remoteSession.StateChanged += new EventHandler <RemoteSessionStateEventArgs>(this.HandleClientRemoteSessionStateChanged);
     }
 }
Exemplo n.º 11
0
 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);
 }
Exemplo n.º 12
0
 internal static RemoteDataObject GenerateCreateRunspacePool(
     Guid clientRunspacePoolId,
     int minRunspaces,
     int maxRunspaces,
     RemoteRunspacePoolInternal runspacePool,
     PSHost host,
     PSPrimitiveDictionary applicationArguments)
 {
     using (RemotingEncoder._trace.TraceMethod())
     {
         PSObject emptyPsObject = RemotingEncoder.CreateEmptyPSObject();
         emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("MinRunspaces", (object)minRunspaces));
         emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("MaxRunspaces", (object)maxRunspaces));
         emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("PSThreadOptions", (object)runspacePool.ThreadOptions));
         emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApartmentState", (object)runspacePool.ApartmentState));
         emptyPsObject.Properties.Add((PSPropertyInfo) new PSNoteProperty("ApplicationArguments", (object)applicationArguments));
         emptyPsObject.Properties.Add((PSPropertyInfo)RemotingEncoder.CreateHostInfoProperty(new HostInfo(host)));
         return(RemoteDataObject.CreateFrom(RemotingDestination.Server, RemotingDataType.CreateRunspacePool, clientRunspacePoolId, Guid.Empty, (object)emptyPsObject));
     }
 }
Exemplo n.º 13
0
 private ClientRemoteSessionImpl CreateClientRemoteSession(
     RemoteRunspacePoolInternal rsPoolInternal)
 {
     ClientRemoteSession.URIDirectionReported uriRedirectionHandler = new ClientRemoteSession.URIDirectionReported(this.HandleURIDirectionReported);
     return(new ClientRemoteSessionImpl(rsPoolInternal, uriRedirectionHandler));
 }
Exemplo n.º 14
0
 /// <summary>
 /// Queries the server for disconnected runspace pools and creates an array of runspace
 /// pool objects associated with each disconnected runspace pool on the server.  Each
 /// runspace pool object in the returned array is in the Disconnected state and can be
 /// connected to the server by calling the Connect() method on the runspace pool.
 /// </summary>
 /// <param name="connectionInfo">Connection object for the target server.</param>
 /// <param name="host">Client host object.</param>
 /// <param name="typeTable">TypeTable object.</param>
 /// <returns>Array of RunspacePool objects each in the Disconnected state.</returns>
 public static RunspacePool[] GetRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable)
 {
     return(RemoteRunspacePoolInternal.GetRemoteRunspacePools(connectionInfo, host, typeTable));
 }
Exemplo n.º 15
0
        internal static void Dispatch(BaseClientTransportManager transportManager, PSHost clientHost, PSDataCollectionStream <ErrorRecord> errorStream, ObjectStream methodExecutorStream, bool isMethodExecutorStreamEnabled, RemoteRunspacePoolInternal runspacePool, Guid clientPowerShellId, System.Management.Automation.Remoting.RemoteHostCall remoteHostCall)
        {
            ClientMethodExecutor executor = new ClientMethodExecutor(transportManager, clientHost, runspacePool.InstanceId, clientPowerShellId, remoteHostCall);

            if (clientPowerShellId == Guid.Empty)
            {
                executor.Execute(errorStream);
            }
            else
            {
                bool flag = false;
                if (clientHost != null)
                {
                    PSObject privateData = clientHost.PrivateData;
                    if (privateData != null)
                    {
                        PSNoteProperty property = privateData.Properties["AllowSetShouldExitFromRemote"] as PSNoteProperty;
                        flag = ((property != null) && (property.Value is bool)) ? ((bool)property.Value) : false;
                    }
                }
                if ((remoteHostCall.IsSetShouldExit && isMethodExecutorStreamEnabled) && !flag)
                {
                    runspacePool.Close();
                }
                else if (isMethodExecutorStreamEnabled)
                {
                    methodExecutorStream.Write(executor);
                }
                else
                {
                    executor.Execute(errorStream);
                }
            }
        }
 private ClientRemoteSessionImpl CreateClientRemoteSession(RemoteRunspacePoolInternal rsPoolInternal)
 {
     return(new ClientRemoteSessionImpl(rsPoolInternal, new ClientRemoteSession.URIDirectionReported(this.HandleURIDirectionReported)));
 }
Exemplo n.º 17
0
        internal static RemoteDataObject GenerateCreateRunspacePool(Guid clientRunspacePoolId, int minRunspaces, int maxRunspaces, RemoteRunspacePoolInternal runspacePool, PSHost host, PSPrimitiveDictionary applicationArguments)
        {
            PSObject data = CreateEmptyPSObject();

            data.Properties.Add(new PSNoteProperty("MinRunspaces", minRunspaces));
            data.Properties.Add(new PSNoteProperty("MaxRunspaces", maxRunspaces));
            data.Properties.Add(new PSNoteProperty("PSThreadOptions", runspacePool.ThreadOptions));
            data.Properties.Add(new PSNoteProperty("ApartmentState", runspacePool.ApartmentState));
            data.Properties.Add(new PSNoteProperty("ApplicationArguments", applicationArguments));
            data.Properties.Add(CreateHostInfoProperty(new HostInfo(host)));
            return(RemoteDataObject.CreateFrom(RemotingDestination.InvalidDestination | RemotingDestination.Server, RemotingDataType.CreateRunspacePool, clientRunspacePoolId, Guid.Empty, data));
        }