Ejemplo n.º 1
0
 internal OutOfProcessClientCommandTransportManager(ClientRemotePowerShell cmd, bool noInput, OutOfProcessClientSessionTransportManager sessnTM, OutOfProcessTextWriter stdInWriter) : base(cmd, sessnTM.CryptoHelper, sessnTM)
 {
     this.stdInWriter = stdInWriter;
     this.onDataAvailableToSendCallback = new System.Management.Automation.Remoting.PrioritySendDataCollection.OnDataAvailableCallback(this.OnDataAvailableCallback);
     this.signalTimeOutTimer            = new Timer(60000.0);
     this.signalTimeOutTimer.Elapsed   += new ElapsedEventHandler(this.OnSignalTimeOutTimerElapsed);
 }
        private NamedPipeProcessMediator(
            RemoteSessionNamedPipeServer namedPipeServer) : base(false)
        {
            if (namedPipeServer == null)
            {
                throw new PSArgumentNullException("namedPipeServer");
            }

            _namedPipeServer = namedPipeServer;

            // Create transport reader/writers from named pipe.
            originalStdIn  = namedPipeServer.TextReader;
            originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
            originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter);

            // Flow impersonation if requested.
            WindowsIdentity currentIdentity = null;

            try
            {
                currentIdentity = WindowsIdentity.GetCurrent();
            }
            catch (System.Security.SecurityException) { }
            _windowsIdentityToImpersonate = ((currentIdentity != null) && (currentIdentity.ImpersonationLevel == TokenImpersonationLevel.Impersonation)) ?
                                            currentIdentity : null;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// The mediator will take actions from the StdIn stream and responds to them.
        /// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null. This is
        /// to make sure these streams are totally used by our Mediator.
        /// </summary>
        /// <param name="combineErrOutStream">Redirects remoting errors to the Out stream.</param>
        private StdIOProcessMediator(bool combineErrOutStream) : base(exitProcessOnError: true)
        {
            // Create input stream reader from Console standard input stream.
            // We don't use the provided Console.In TextReader because it can have
            // an incorrect encoding, e.g., Hyper-V Container console where the
            // TextReader has incorrect default console encoding instead of the actual
            // stream encoding.  This way the stream encoding is determined by the
            // stream BOM as needed.
            originalStdIn = new StreamReader(Console.OpenStandardInput(), true);

            // Remoting errors can optionally be written to stdErr or stdOut with
            // special formatting.
            originalStdOut = new OutOfProcessTextWriter(Console.Out);
            if (combineErrOutStream)
            {
                originalStdErr = new FormattedErrorTextWriter(Console.Out);
            }
            else
            {
                originalStdErr = new OutOfProcessTextWriter(Console.Error);
            }

            // Replacing StdIn, StdOut, StdErr with Null so that no other app messes with the
            // original streams.
            Console.SetIn(TextReader.Null);
            Console.SetOut(TextWriter.Null);
            Console.SetError(TextWriter.Null);
        }
Ejemplo n.º 4
0
        private HyperVSocketMediator()
            : base(false)
        {
            _hypervSocketServer = new RemoteSessionHyperVSocketServer(false);

            originalStdIn  = _hypervSocketServer.TextReader;
            originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
            originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
        }
Ejemplo n.º 5
0
 internal OutOfProcessServerTransportManager(
     OutOfProcessTextWriter stdOutWriter,
     Guid powershellInstanceId,
     TypeTable typeTableToUse,
     int fragmentSize,
     PSRemotingCryptoHelper cryptoHelper)
     : base(fragmentSize, cryptoHelper)
 {
     this.stdOutWriter         = stdOutWriter;
     this.powershellInstanceId = powershellInstanceId;
     this.TypeTable            = typeTableToUse;
 }
Ejemplo n.º 6
0
        private SSHProcessMediator() : base(true)
        {
            originalStdIn  = new StreamReader(Console.OpenStandardInput(), true);
            originalStdOut = new OutOfProcessTextWriter(
                new StreamWriter(Console.OpenStandardOutput()));
            originalStdErr = new OutOfProcessTextWriter(
                new StreamWriter(Console.OpenStandardError()));

            // Disable console from writing to the PSRP streams.
            Console.SetIn(TextReader.Null);
            Console.SetOut(TextWriter.Null);
            Console.SetError(TextWriter.Null);
        }
Ejemplo n.º 7
0
 private OutOfProcessMediator()
 {
     Console.SetIn(TextReader.Null);
     this.originalStdOut = new OutOfProcessTextWriter(Console.Out);
     Console.SetOut(TextWriter.Null);
     this.originalStdErr = new OutOfProcessTextWriter(Console.Error);
     Console.SetError(TextWriter.Null);
     this.callbacks = new OutOfProcessUtils.DataProcessingDelegates();
     this.callbacks.DataPacketReceived            = (OutOfProcessUtils.DataPacketReceived)Delegate.Combine(this.callbacks.DataPacketReceived, new OutOfProcessUtils.DataPacketReceived(this.OnDataPacketReceived));
     this.callbacks.DataAckPacketReceived         = (OutOfProcessUtils.DataAckPacketReceived)Delegate.Combine(this.callbacks.DataAckPacketReceived, new OutOfProcessUtils.DataAckPacketReceived(this.OnDataAckPacketReceived));
     this.callbacks.CommandCreationPacketReceived = (OutOfProcessUtils.CommandCreationPacketReceived)Delegate.Combine(this.callbacks.CommandCreationPacketReceived, new OutOfProcessUtils.CommandCreationPacketReceived(this.OnCommandCreationPacketReceived));
     this.callbacks.CommandCreationAckReceived    = (OutOfProcessUtils.CommandCreationAckReceived)Delegate.Combine(this.callbacks.CommandCreationAckReceived, new OutOfProcessUtils.CommandCreationAckReceived(this.OnCommandCreationAckReceived));
     this.callbacks.ClosePacketReceived           = (OutOfProcessUtils.ClosePacketReceived)Delegate.Combine(this.callbacks.ClosePacketReceived, new OutOfProcessUtils.ClosePacketReceived(this.OnClosePacketReceived));
     this.callbacks.CloseAckPacketReceived        = (OutOfProcessUtils.CloseAckPacketReceived)Delegate.Combine(this.callbacks.CloseAckPacketReceived, new OutOfProcessUtils.CloseAckPacketReceived(this.OnCloseAckPacketReceived));
     this.callbacks.SignalPacketReceived          = (OutOfProcessUtils.SignalPacketReceived)Delegate.Combine(this.callbacks.SignalPacketReceived, new OutOfProcessUtils.SignalPacketReceived(this.OnSignalPacketReceived));
     this.callbacks.SignalAckPacketReceived       = (OutOfProcessUtils.SignalAckPacketReceived)Delegate.Combine(this.callbacks.SignalAckPacketReceived, new OutOfProcessUtils.SignalAckPacketReceived(this.OnSignalAckPacketReceived));
     this.allcmdsClosedEvent = new ManualResetEvent(true);
 }
Ejemplo n.º 8
0
 private OutOfProcessMediator()
 {
     this.originalStdIn = Console.In;
     Console.SetIn(TextReader.Null);
     this.originalStdOut = new OutOfProcessTextWriter(Console.Out);
     Console.SetOut(TextWriter.Null);
     this.originalStdErr = new OutOfProcessTextWriter(Console.Error);
     Console.SetError(TextWriter.Null);
     this.callbacks = new OutOfProcessUtils.DataProcessingDelegates();
     this.callbacks.DataPacketReceived            += new OutOfProcessUtils.DataPacketReceived(this.OnDataPacketReceived);
     this.callbacks.DataAckPacketReceived         += new OutOfProcessUtils.DataAckPacketReceived(this.OnDataAckPacketReceived);
     this.callbacks.CommandCreationPacketReceived += new OutOfProcessUtils.CommandCreationPacketReceived(this.OnCommandCreationPacketReceived);
     this.callbacks.CommandCreationAckReceived    += new OutOfProcessUtils.CommandCreationAckReceived(this.OnCommandCreationAckReceived);
     this.callbacks.ClosePacketReceived           += new OutOfProcessUtils.ClosePacketReceived(this.OnClosePacketReceived);
     this.callbacks.CloseAckPacketReceived        += new OutOfProcessUtils.CloseAckPacketReceived(this.OnCloseAckPacketReceived);
     this.callbacks.SignalPacketReceived          += new OutOfProcessUtils.SignalPacketReceived(this.OnSignalPacketReceived);
     this.callbacks.SignalAckPacketReceived       += new OutOfProcessUtils.SignalAckPacketReceived(this.OnSignalAckPacketReceived);
 }
Ejemplo n.º 9
0
        private NamedPipeProcessMediator(
            RemoteSessionNamedPipeServer namedPipeServer) : base(false)
        {
            if (namedPipeServer == null)
            {
                throw new PSArgumentNullException("namedPipeServer");
            }

            _namedPipeServer = namedPipeServer;

            // Create transport reader/writers from named pipe.
            originalStdIn  = namedPipeServer.TextReader;
            originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
            originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter);

#if !UNIX
            // Flow impersonation as needed.
            Utils.TryGetWindowsImpersonatedIdentity(out _windowsIdentityToImpersonate);
#endif
        }
Ejemplo n.º 10
0
        /// <summary>
        /// The mediator will take actions from the StdIn stream and responds to them.
        /// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null. This is
        /// to make sure these streams are totally used by our Mediator.
        /// </summary>
        private StdIOProcessMediator() : base(true)
        {
            // Create input stream reader from Console standard input stream.
            // We don't use the provided Console.In TextReader because it can have
            // an incorrect encoding, e.g., Hyper-V Container console where the
            // TextReader has incorrect default console encoding instead of the actual
            // stream encoding.  This way the stream encoding is determined by the
            // stream BOM as needed.
            originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
            Console.SetIn(TextReader.Null);

            // replacing StdOut with Null so that no other app messes with the
            // original stream
            originalStdOut = new OutOfProcessTextWriter(Console.Out);
            Console.SetOut(TextWriter.Null);

            // replacing StdErr with Null so that no other app messes with the
            // original stream
            originalStdErr = new OutOfProcessTextWriter(Console.Error);
            Console.SetError(TextWriter.Null);
        }
Ejemplo n.º 11
0
        private SSHProcessMediator() : base(true)
        {
#if !UNIX
            var inputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Input);
            originalStdIn = new StreamReader(
                new FileStream(new SafeFileHandle(inputHandle, false), FileAccess.Read));

            var outputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Output);
            originalStdOut = new OutOfProcessTextWriter(
                new StreamWriter(
                    new FileStream(new SafeFileHandle(outputHandle, false), FileAccess.Write)));

            var errorHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Error);
            originalStdErr = new OutOfProcessTextWriter(
                new StreamWriter(
                    new FileStream(new SafeFileHandle(errorHandle, false), FileAccess.Write)));
#else
            originalStdIn  = new StreamReader(Console.OpenStandardInput(), true);
            originalStdOut = new OutOfProcessTextWriter(
                new StreamWriter(Console.OpenStandardOutput()));
            originalStdErr = new OutOfProcessTextWriter(
                new StreamWriter(Console.OpenStandardError()));
#endif
        }
Ejemplo n.º 12
0
 internal OutOfProcessServerSessionTransportManager(OutOfProcessTextWriter outWriter) : base(0x8000, new PSRemotingCryptoHelperServer())
 {
     this.syncObject           = new object();
     this.stdOutWriter         = outWriter;
     this.cmdTransportManagers = new Dictionary <Guid, OutOfProcessServerTransportManager>();
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Create a named pipe connection to the target process in target container and set up
        /// transport reader/writer.
        /// </summary>
        internal override void CreateAsync()
        {
            _clientPipe = new ContainerSessionNamedPipeClient(
                _connectionInfo.ContainerProc.ProcessId,
                string.Empty, // AppDomainName
                _connectionInfo.ContainerProc.ContainerObRoot);

            // Wait for named pipe to connect.
            _clientPipe.Connect(_connectionInfo.OpenTimeout);

            // Create writer for named pipe.
            stdInWriter = new OutOfProcessTextWriter(_clientPipe.TextWriter);

            // Create reader thread for named pipe.
            StartReaderThread(_clientPipe.TextReader);
        }
Ejemplo n.º 14
0
        private HyperVSocketMediator()
            : base(false)
        {
            _hypervSocketServer = new RemoteSessionHyperVSocketServer(false);

            originalStdIn = _hypervSocketServer.TextReader;
            originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter);
            originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter);
        }
Ejemplo n.º 15
0
        private NamedPipeProcessMediator(
            RemoteSessionNamedPipeServer namedPipeServer) : base(false)
        {
            if (namedPipeServer == null)
            {
                throw new PSArgumentNullException("namedPipeServer");
            }

            _namedPipeServer = namedPipeServer;

            // Create transport reader/writers from named pipe.
            originalStdIn = namedPipeServer.TextReader;
            originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter);
            originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter);

            // Flow impersonation if requested.
            WindowsIdentity currentIdentity = null;
            try
            {
                currentIdentity = WindowsIdentity.GetCurrent();
            }
            catch (System.Security.SecurityException) { }
            _windowsIdentityToImpersonate = ((currentIdentity != null) && (currentIdentity.ImpersonationLevel == TokenImpersonationLevel.Impersonation)) ?
                currentIdentity : null;
        }
 internal override void CreateAsync()
 {
     if (this.connectionInfo != null)
     {
         this._processInstance = this.connectionInfo.Process ?? new PowerShellProcessInstance(this.connectionInfo.PSVersion, this.connectionInfo.Credential, this.connectionInfo.InitializationScript, this.connectionInfo.RunAs32);
         if (this.connectionInfo.Process != null)
         {
             this._processCreated = false;
         }
     }
     PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString() });
     try
     {
         lock (base.syncObject)
         {
             if (base.isClosed)
             {
                 return;
             }
             this.serverProcess = this._processInstance.Process;
             if (this._processInstance.RunspacePool != null)
             {
                 this._processInstance.RunspacePool.Close();
                 this._processInstance.RunspacePool.Dispose();
             }
             this.stdInWriter = this._processInstance.StdInWriter;
             this.serverProcess.OutputDataReceived += new DataReceivedEventHandler(this.OnOutputDataReceived);
             this.serverProcess.ErrorDataReceived  += new DataReceivedEventHandler(this.OnErrorDataReceived);
             this.serverProcess.Exited             += new EventHandler(this.OnExited);
             this._processInstance.Start();
             if (this.stdInWriter != null)
             {
                 this.serverProcess.CancelErrorRead();
                 this.serverProcess.CancelOutputRead();
             }
             this.serverProcess.BeginOutputReadLine();
             this.serverProcess.BeginErrorReadLine();
             this.stdInWriter = new OutOfProcessTextWriter(this.serverProcess.StandardInput);
             this._processInstance.StdInWriter = this.stdInWriter;
         }
     }
     catch (Win32Exception exception)
     {
         PSRemotingTransportException e = new PSRemotingTransportException(exception, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, new object[] { exception.Message })
         {
             ErrorCode = exception.ErrorCode
         };
         TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CreateShellEx);
         this.RaiseErrorHandler(eventArgs);
         return;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
         PSRemotingTransportException   exception4 = new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, new object[] { exception3.Message });
         TransportErrorOccuredEventArgs args2      = new TransportErrorOccuredEventArgs(exception4, TransportMethodEnum.CreateShellEx);
         this.RaiseErrorHandler(args2);
         return;
     }
     this.SendOneItem();
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Create a Hyper-V socket connection to the target process and set up
        /// transport reader/writer.
        /// </summary>
        internal override void CreateAsync()
        {
            _client = new RemoteSessionHyperVSocketClient(_vmGuid, true);
            if (!_client.Connect(_networkCredential, _configurationName, true))
            {
                _client.Dispose();
                throw new PSInvalidOperationException(
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.VMSessionConnectFailed),
                    null,
                    PSRemotingErrorId.VMSessionConnectFailed.ToString(),
                    ErrorCategory.InvalidOperation,
                    null);
            }

            // TODO: remove below 3 lines when Hyper-V socket duplication is supported in .NET framework.
            _client.Dispose();
            _client = new RemoteSessionHyperVSocketClient(_vmGuid, false);
            if (!_client.Connect(_networkCredential, _configurationName, false))
            {
                _client.Dispose();
                throw new PSInvalidOperationException(
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.VMSessionConnectFailed),
                    null,
                    PSRemotingErrorId.VMSessionConnectFailed.ToString(),
                    ErrorCategory.InvalidOperation,
                    null);
            }

            // Create writer for Hyper-V socket.
            stdInWriter = new OutOfProcessTextWriter(_client.TextWriter);

            // Create reader thread for Hyper-V socket.
            StartReaderThread(_client.TextReader);
        }
Ejemplo n.º 18
0
 internal OutOfProcessServerSessionTransportManager(OutOfProcessTextWriter outWriter)
     : base(32768, (PSRemotingCryptoHelper) new PSRemotingCryptoHelperServer())
 {
     this.stdOutWriter         = outWriter;
     this.cmdTransportManagers = new Dictionary <Guid, OutOfProcessServerTransportManager>();
 }
Ejemplo n.º 19
0
        internal override void ConnectAsync()
        {
            string path = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), "powershell.exe");

            if (this.connectionInfo != null && this.connectionInfo.RunAs32)
            {
                string environmentVariable = Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE");
                if (environmentVariable.Equals("amd64", StringComparison.OrdinalIgnoreCase) || environmentVariable.Equals("ia64", StringComparison.OrdinalIgnoreCase))
                {
                    path = path.ToLowerInvariant().Replace("\\system32\\", "\\syswow64\\");
                    if (!System.IO.File.Exists(path))
                    {
                        throw new PSInvalidOperationException(PSRemotingErrorInvariants.FormatResourceString(PSRemotingErrorId.IPCWowComponentNotPresent, (object)path));
                    }
                }
            }
            string str = string.Format((IFormatProvider)CultureInfo.InvariantCulture, "-s -NoLogo -NoProfile");

            if (this.connectionInfo.InitializationScript != null && !string.IsNullOrEmpty(this.connectionInfo.InitializationScript.ToString()))
            {
                string base64String = Convert.ToBase64String(Encoding.Unicode.GetBytes(this.connectionInfo.InitializationScript.ToString()));
                str = string.Format((IFormatProvider)CultureInfo.InvariantCulture, "{0} -EncodedCommand {1}", (object)str, (object)base64String);
            }
            ProcessStartInfo processStartInfo = new ProcessStartInfo();

            processStartInfo.FileName               = path;
            processStartInfo.Arguments              = str;
            processStartInfo.UseShellExecute        = false;
            processStartInfo.RedirectStandardInput  = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError  = true;
            processStartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
            processStartInfo.CreateNoWindow         = true;
            processStartInfo.LoadUserProfile        = true;
            if (this.connectionInfo.Credential != null)
            {
                NetworkCredential networkCredential = this.connectionInfo.Credential.GetNetworkCredential();
                processStartInfo.UserName = networkCredential.UserName;
                processStartInfo.Domain   = !string.IsNullOrEmpty(networkCredential.Domain) ? networkCredential.Domain : ".";
                processStartInfo.Password = this.connectionInfo.Credential.Password;
            }
            BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, (object)this.RunspacePoolInstanceId);
            try
            {
                lock (this.syncObject)
                {
                    if (this.isClosed)
                    {
                        return;
                    }
                    this.serverProcess                     = new Process();
                    this.serverProcess.StartInfo           = processStartInfo;
                    this.serverProcess.EnableRaisingEvents = true;
                    this.serverProcess.OutputDataReceived += new DataReceivedEventHandler(this.OnOutputDataReceived);
                    this.serverProcess.ErrorDataReceived  += new DataReceivedEventHandler(this.OnErrorDataReceived);
                    this.serverProcess.Exited             += new EventHandler(this.OnExited);
                    this.serverProcess.Start();
                    this.serverProcess.BeginOutputReadLine();
                    this.serverProcess.BeginErrorReadLine();
                    this.stdInWriter = new OutOfProcessTextWriter((TextWriter)this.serverProcess.StandardInput);
                }
            }
            catch (Win32Exception ex)
            {
                this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, new object[1]
                {
                    (object)ex.Message
                })
                {
                    ErrorCode = ex.ErrorCode
                }, TransportMethodEnum.CreateShellEx));
                return;
            }
            catch (Exception ex)
            {
                CommandProcessorBase.CheckForSevereException(ex);
                this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, new object[1]
                {
                    (object)ex.Message
                }), TransportMethodEnum.CreateShellEx));
                return;
            }
            this.SendOneItem();
        }
Ejemplo n.º 20
0
        internal OutOfProcessServerTransportManager(OutOfProcessTextWriter stdOutWriter, OutOfProcessTextWriter stdErrWriter,
            Guid powershellInstanceId,
            TypeTable typeTableToUse,
            int fragmentSize,
            PSRemotingCryptoHelper cryptoHelper)
            : base(fragmentSize, cryptoHelper)
        {
            _stdOutWriter = stdOutWriter;
            _stdErrWriter = stdErrWriter;
            _powershellInstanceId = powershellInstanceId;
            this.TypeTable = typeTableToUse;

            this.WSManTransportErrorOccured += HandleWSManTransportError;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Launch a new Process (PowerShell.exe -s) to perform remoting. This is used by *-Job cmdlets
        /// to support background jobs without depending on WinRM (WinRM has complex requirements like
        /// elevation to support local machine remoting)
        /// </summary>
        /// <exception cref="System.InvalidOperationException">
        /// </exception>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// 1. There was an error in opening the associated file. 
        /// </exception>
        internal override void CreateAsync()
        {
            if (null != _connectionInfo)
            {
                _processInstance = _connectionInfo.Process ?? new PowerShellProcessInstance(_connectionInfo.PSVersion,
                                                                                           _connectionInfo.Credential,
                                                                                           _connectionInfo.InitializationScript,
                                                                                           _connectionInfo.RunAs32);
                if (_connectionInfo.Process != null)
                {
                    _processCreated = false;
                }
                // _processInstance.Start();
            }

            PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect,
                            PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                            RunspacePoolInstanceId.ToString());

            try
            {
                lock (syncObject)
                {
                    if (isClosed)
                    {
                        return;
                    }

                    // Attach handlers and start the process
                    _serverProcess = _processInstance.Process;

                    if (_processInstance.RunspacePool != null)
                    {
                        _processInstance.RunspacePool.Close();
                        _processInstance.RunspacePool.Dispose();
                    }

                    stdInWriter = _processInstance.StdInWriter;
                    //if (stdInWriter == null)
                    {
                        _serverProcess.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived);
                        _serverProcess.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived);
                    }
                    _serverProcess.Exited += new EventHandler(OnExited);

                    //serverProcess.Start();
                    _processInstance.Start();

                    if (stdInWriter != null)
                    {
                        _serverProcess.CancelErrorRead();
                        _serverProcess.CancelOutputRead();
                    }

                    // Start asynchronous reading of output/errors
                    _serverProcess.BeginOutputReadLine();
                    _serverProcess.BeginErrorReadLine();

                    stdInWriter = new OutOfProcessTextWriter(_serverProcess.StandardInput);
                    _processInstance.StdInWriter = stdInWriter;
                }
            }
            catch (System.ComponentModel.Win32Exception w32e)
            {
                PSRemotingTransportException psrte = new PSRemotingTransportException(w32e, RemotingErrorIdStrings.IPCExceptionLaunchingProcess,
                    w32e.Message);
                psrte.ErrorCode = w32e.HResult;
                TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.CreateShellEx);
                RaiseErrorHandler(eventargs);
                return;
            }
            catch (Exception e)
            {
                CommandProcessorBase.CheckForSevereException(e);

                PSRemotingTransportException psrte = new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess,
                RemotingErrorIdStrings.IPCExceptionLaunchingProcess,
                    e.Message);
                TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.CreateShellEx);
                RaiseErrorHandler(eventargs);
                return;
            }

            // Send one fragment
            SendOneItem();
        }
Ejemplo n.º 22
0
 internal OutOfProcessServerSessionTransportManager(OutOfProcessTextWriter outWriter, OutOfProcessTextWriter errWriter, PSRemotingCryptoHelperServer cryptoHelper)
     : base(BaseTransportManager.DefaultFragmentSize, cryptoHelper)
 {
     Dbg.Assert(null != outWriter, "outWriter cannot be null.");
     Dbg.Assert(null != errWriter, "errWriter cannot be null.");
     _stdOutWriter = outWriter;
     _stdErrWriter = errWriter;
     _cmdTransportManagers = new Dictionary<Guid, OutOfProcessServerTransportManager>();
 }
Ejemplo n.º 23
0
        private SSHProcessMediator() : base(true)
        {
#if !UNIX
            var inputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Input);
            originalStdIn = new StreamReader(
                new FileStream(new SafeFileHandle(inputHandle, false), FileAccess.Read));

            var outputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Output);
            originalStdOut = new OutOfProcessTextWriter(
                new StreamWriter(
                    new FileStream(new SafeFileHandle(outputHandle, false), FileAccess.Write)));

            var errorHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Error);
            originalStdErr = new OutOfProcessTextWriter(
                new StreamWriter(
                    new FileStream(new SafeFileHandle(errorHandle, false), FileAccess.Write)));
#else
            originalStdIn = new StreamReader(Console.OpenStandardInput(), true);
            originalStdOut = new OutOfProcessTextWriter(
                new StreamWriter(Console.OpenStandardOutput()));
            originalStdErr = new OutOfProcessTextWriter(
                new StreamWriter(Console.OpenStandardError()));
#endif
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Create a Hyper-V socket connection to the target process and set up
        /// transport reader/writer.
        /// </summary>
        internal override void CreateAsync()
        {
            _client = new RemoteSessionHyperVSocketClient(_targetGuid, false, true);
            if (!_client.Connect(null, String.Empty, false))
            {
                _client.Dispose();
                throw new PSInvalidOperationException(
                    PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ContainerSessionConnectFailed),
                    null,
                    PSRemotingErrorId.ContainerSessionConnectFailed.ToString(),
                    ErrorCategory.InvalidOperation,
                    null);
            }

            // Create writer for Hyper-V socket.
            stdInWriter = new OutOfProcessTextWriter(_client.TextWriter);

            // Create reader thread for Hyper-V socket.
            StartReaderThread(_client.TextReader);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Create a named pipe connection to the target process and set up
        /// transport reader/writer.
        /// </summary>
        internal override void CreateAsync()
        {
            _clientPipe = new RemoteSessionNamedPipeClient(_connectionInfo.ProcessId, _connectionInfo.AppDomainName);

            // Wait for named pipe to connect.
            _clientPipe.Connect(_connectionInfo.OpenTimeout);

            // Create writer for named pipe.
            stdInWriter = new OutOfProcessTextWriter(_clientPipe.TextWriter);

            // Create reader thread for named pipe.
            StartReaderThread(_clientPipe.TextReader);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Create an SSH connection to the target host and set up
        /// transport reader/writer.
        /// </summary>
        internal override void CreateAsync()
        {
            // Create the ssh client process with connection to host target.
            _sshProcess = _connectionInfo.StartSSHProcess(
                out _stdInWriter,
                out _stdOutReader,
                out _stdErrReader);

            _sshProcess.Exited += (sender, args) =>
            {
                CloseConnection();
            };

            // Start error reader thread.
            StartErrorThread(_stdErrReader);

            // Create writer for named pipe.
            stdInWriter = new OutOfProcessTextWriter(_stdInWriter);

            // Create reader thread and send first PSRP message.
            StartReaderThread(_stdOutReader);
        }
Ejemplo n.º 27
0
 internal OutOfProcessClientCommandTransportManager(
     ClientRemotePowerShell cmd,
     bool noInput,
     OutOfProcessClientSessionTransportManagerBase sessnTM,
     OutOfProcessTextWriter stdInWriter) : base(cmd, sessnTM.CryptoHelper, sessnTM)
 {
     _stdInWriter = stdInWriter;
     _onDataAvailableToSendCallback =
         new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback);
     _signalTimeOutTimer = new Timer(OnSignalTimeOutTimerElapsed, null, Timeout.Infinite, Timeout.Infinite);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// The mediator will take actions from the StdIn stream and responds to them. 
        /// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null's. This is 
        /// to make sure these streams are totally used by our Mediator.
        /// </summary>
        private OutOfProcessMediator() : base(true)
        {
            // Create input stream reader from Console standard input stream.
            // We don't use the provided Console.In TextReader because it can have
            // an incorrect encoding, e.g., Hyper-V Container console where the
            // TextReader has incorrect default console encoding instead of the actual
            // stream encoding.  This way the stream encoding is determined by the 
            // stream BOM as needed.
            originalStdIn = new StreamReader(Console.OpenStandardInput(), true);

            // replacing StdIn with Null so that no other app messes with the 
            // original stream.
            Console.SetIn(TextReader.Null);

            // replacing StdOut with Null so that no other app messes with the 
            // original stream
            originalStdOut = new OutOfProcessTextWriter(Console.Out);
            Console.SetOut(TextWriter.Null);

            // replacing StdErr with Null so that no other app messes with the 
            // original stream
            originalStdErr = new OutOfProcessTextWriter(Console.Error);
            Console.SetError(TextWriter.Null);
        }