// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.ObjectModel; using System.Management.Automation.Internal; using System.Runtime.Serialization; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Runspaces { #region Exceptions /// /// Defines exception which is thrown when state of the pipeline is different /// from expected state. /// public class InvalidPipelineStateException : SystemException { /// /// Initializes a new instance of the InvalidPipelineStateException class. /// public InvalidPipelineStateException() : base(StringUtil.Format(RunspaceStrings.InvalidPipelineStateStateGeneral)) { } /// /// Initializes a new instance of the InvalidPipelineStateException class /// with a specified error message. /// /// /// The error message that explains the reason for the exception. /// public InvalidPipelineStateException(string message) : base(message) { } /// /// Initializes a new instance of the InvalidPipelineStateException class /// with a specified error message and a reference to the inner exception that is the cause of this exception. /// /// /// The error message that explains the reason for the exception. /// /// /// The exception that is the cause of the current exception. /// public InvalidPipelineStateException(string message, Exception innerException) : base(message, innerException) { } /// /// Initializes a new instance of the InvalidPipelineStateException and defines value of /// CurrentState and ExpectedState. /// /// The error message that explains the reason for the exception. /// /// Current state of pipeline. /// Expected state of pipeline. internal InvalidPipelineStateException(string message, PipelineState currentState, PipelineState expectedState) : base(message) { _expectedState = expectedState; _currentState = currentState; } #region ISerializable Members // 2005/04/20-JonN No need to implement GetObjectData // if all fields are static or [NonSerialized] /// /// Initializes a new instance of the /// class with serialized data. /// /// /// The that holds the serialized object /// data about the exception being thrown. /// /// /// The that contains contextual information /// about the source or destination. /// [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] private InvalidPipelineStateException(SerializationInfo info, StreamingContext context) { throw new NotSupportedException(); } #endregion /// /// Gets CurrentState of the pipeline. /// public PipelineState CurrentState { get { return _currentState; } } /// /// Gets ExpectedState of the pipeline. /// public PipelineState ExpectedState { get { return _expectedState; } } /// /// State of pipeline when exception was thrown. /// [NonSerialized] private readonly PipelineState _currentState = 0; /// /// States of the pipeline expected in method which throws this exception. /// [NonSerialized] private readonly PipelineState _expectedState = 0; } #endregion Exceptions #region PipelineState /// /// Enumerated type defining the state of the Pipeline. /// public enum PipelineState { /// /// The pipeline has not been started. /// NotStarted = 0, /// /// The pipeline is executing. /// Running = 1, /// /// The pipeline is stoping execution. /// Stopping = 2, /// /// The pipeline is completed due to a stop request. /// Stopped = 3, /// /// The pipeline has completed. /// Completed = 4, /// /// The pipeline completed abnormally due to an error. /// Failed = 5, /// /// The pipeline is disconnected from remote running command. /// Disconnected = 6 } /// /// Type which has information about PipelineState and Exception /// associated with PipelineState. /// public sealed class PipelineStateInfo { #region constructors /// /// Constructor for state changes not resulting from an error. /// /// Execution state. internal PipelineStateInfo(PipelineState state) : this(state, null) { } /// /// Constructor for state changes with an optional error. /// /// The new state. /// A non-null exception if the state change was /// caused by an error,otherwise; null. /// internal PipelineStateInfo(PipelineState state, Exception reason) { State = state; Reason = reason; } /// /// Copy constructor to support cloning. /// /// Source information. /// /// ArgumentNullException when is null. /// internal PipelineStateInfo(PipelineStateInfo pipelineStateInfo) { Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); State = pipelineStateInfo.State; Reason = pipelineStateInfo.Reason; } #endregion constructors #region public_properties /// /// The state of the runspace. /// /// /// This value indicates the state of the pipeline after the change. /// public PipelineState State { get; } /// /// The reason for the state change, if caused by an error. /// /// /// The value of this property is non-null if the state /// changed due to an error. Otherwise, the value of this /// property is null. /// public Exception Reason { get; } #endregion public_properties /// /// Clones this object. /// /// Cloned object. internal PipelineStateInfo Clone() { return new PipelineStateInfo(this); } } /// /// Event arguments passed to PipelineStateEvent handlers /// event. /// public sealed class PipelineStateEventArgs : EventArgs { #region constructors /// /// Constructor PipelineStateEventArgs from PipelineStateInfo. /// /// The current state of the /// pipeline. /// /// ArgumentNullException when is null. /// internal PipelineStateEventArgs(PipelineStateInfo pipelineStateInfo) { Dbg.Assert(pipelineStateInfo != null, "caller should validate the parameter"); PipelineStateInfo = pipelineStateInfo; } #endregion constructors #region public_properties /// /// Info about current state of pipeline. /// public PipelineStateInfo PipelineStateInfo { get; } #endregion public_properties } #endregion ExecutionState /// /// Defines a class which can be used to invoke a pipeline of commands. /// public abstract class Pipeline : IDisposable { #region constructor /// /// Explicit default constructor. /// internal Pipeline(Runspace runspace) : this(runspace, new CommandCollection()) { } /// /// Constructor to initialize both Runspace and Command to invoke. /// Caller should make sure that "command" is not null. /// /// /// Runspace to use for the command invocation. /// /// /// command to Invoke. /// Caller should make sure that "command" is not null. /// internal Pipeline(Runspace runspace, CommandCollection command) { if (runspace == null) { PSTraceSource.NewArgumentNullException(nameof(runspace)); } // This constructor is used only internally. // Caller should make sure the input is valid Dbg.Assert(command != null, "Command cannot be null"); InstanceId = runspace.GeneratePipelineId(); Commands = command; // Reset the AMSI session so that it is re-initialized // when the next script block is parsed. AmsiUtils.CloseSession(); } #endregion constructor #region properties /// /// Gets the runspace this pipeline is created on. /// public abstract Runspace Runspace { get; } /// /// Gets the property which indicates if this pipeline is nested. /// public abstract bool IsNested { get; } /// /// Gets the property which indicates if this pipeline is a child pipeline. /// /// IsChild flag makes it possible for the pipeline to differentiate between /// a true v1 nested pipeline and the cmdlets calling cmdlets case. See bug /// 211462. /// internal virtual bool IsChild { get { return false; } set { } } /// /// Gets input writer for this pipeline. /// /// /// When the caller calls Input.Write(), the caller writes to the /// input of the pipeline. Thus, /// is a PipelineWriter or "thing which can be written to". /// Note:Input must be closed after Pipeline.InvokeAsync for InvokeAsync to /// finish. /// public abstract PipelineWriter Input { get; } /// /// Gets the output reader for this pipeline. /// /// /// When the caller calls Output.Read(), the caller reads from the /// output of the pipeline. Thus, /// is a PipelineReader or "thing which can be read from". /// public abstract PipelineReader Output { get; } /// /// Gets the error output reader for this pipeline. /// /// /// When the caller calls Error.Read(), the caller reads from the /// output of the pipeline. Thus, /// is a PipelineReader or "thing which can be read from". /// /// This is the non-terminating error stream from the command. /// In this release, the objects read from this PipelineReader /// are PSObjects wrapping ErrorRecords. /// public abstract PipelineReader Error { get; } /// /// Gets Info about current state of the pipeline. /// /// /// This value indicates the state of the pipeline after the change. /// public abstract PipelineStateInfo PipelineStateInfo { get; } /// /// True if pipeline execution encountered and error. /// It will always be true if _reason is non-null /// since an exception occurred. For other error types, /// It has to be set manually. /// public virtual bool HadErrors { get { return _hadErrors; } } private bool _hadErrors; internal void SetHadErrors(bool status) { _hadErrors = _hadErrors || status; } /// /// Gets the unique identifier for this pipeline. This identifier is unique with in /// the scope of Runspace. /// public long InstanceId { get; } /// /// Gets the collection of commands for this pipeline. /// public CommandCollection Commands { get; private set; } /// /// If this property is true, SessionState is updated for this /// pipeline state. /// public bool SetPipelineSessionState { get; set; } = true; /// /// Settings for the pipeline invocation thread. /// internal PSInvocationSettings InvocationSettings { get; set; } /// /// If this flag is true, the commands in this Pipeline will redirect the global error output pipe /// (ExecutionContext.ShellFunctionErrorOutputPipe) to the command's error output pipe. /// /// When the global error output pipe is not set, $ErrorActionPreference is not checked and all /// errors are treated as terminating errors. /// /// On V1, the global error output pipe is redirected to the command's error output pipe only when /// it has already been redirected. The command-line host achieves this redirection by merging the /// error output into the output pipe so it checks $ErrorActionPreference all right. However, when /// the Pipeline class is used programmatically the global error output pipe is not set and the first /// error terminates the pipeline. /// /// This flag is used to force the redirection. By default it is false to maintain compatibility with /// V1, but the V2 hosting interface (PowerShell class) sets this flag to true to ensure the global /// error output pipe is always set and $ErrorActionPreference is checked when invoking the Pipeline. /// internal bool RedirectShellErrorOutputPipe { get; set; } = false; #endregion properties #region events /// /// Event raised when Pipeline's state changes. /// public abstract event EventHandler StateChanged; #endregion events #region methods /// /// Invoke the pipeline, synchronously, returning the results as an array of /// objects. /// /// If using synchronous invoke, do not close /// input objectWriter. Synchronous invoke will always close the input /// objectWriter. /// /// /// No command is added to pipeline /// /// /// PipelineState is not NotStarted. /// /// /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// /// /// RunspaceState is not Open /// /// /// Pipeline already disposed /// /// /// The script recursed too deeply into script functions. /// There is a fixed limit on the depth of recursion. /// /// /// A CLR security violation occurred. Typically, this happens /// because the current CLR permissions do not allow adequate /// reflection access to a cmdlet assembly. /// /// /// Pipeline.Invoke can throw a variety of exceptions derived /// from RuntimeException. The most likely of these exceptions /// are listed below. /// /// /// One of more parameters or parameter values specified for /// a cmdlet are not valid, or mandatory parameters for a cmdlet /// were not specified. /// /// /// A cmdlet generated a terminating error. /// /// /// A provider generated a terminating error. /// /// /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. /// /// /// The pipeline was terminated asynchronously. /// /// /// If there is an error generating the metadata for dynamic parameters. /// public Collection Invoke() { return Invoke(null); } /// /// Invoke the pipeline, synchronously, returning the results as an array of objects. /// /// an array of input objects to pass to the pipeline. /// Array may be empty but may not be null /// An array of zero or more result objects. /// If using synchronous exectute, do not close /// input objectWriter. Synchronous invoke will always close the input /// objectWriter. /// /// /// No command is added to pipeline /// /// /// PipelineState is not NotStarted. /// /// /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) Attempt is made to invoke a nested pipeline directly. Nested /// pipeline must be invoked from a running pipeline. /// /// /// RunspaceState is not Open /// /// /// Pipeline already disposed /// /// /// The script recursed too deeply into script functions. /// There is a fixed limit on the depth of recursion. /// /// /// A CLR security violation occurred. Typically, this happens /// because the current CLR permissions do not allow adequate /// reflection access to a cmdlet assembly. /// /// /// Pipeline.Invoke can throw a variety of exceptions derived /// from RuntimeException. The most likely of these exceptions /// are listed below. /// /// /// One of more parameters or parameter values specified for /// a cmdlet are not valid, or mandatory parameters for a cmdlet /// were not specified. /// /// /// A cmdlet generated a terminating error. /// /// /// A provider generated a terminating error. /// /// /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. /// /// /// The pipeline was terminated asynchronously. /// /// /// If there is an error generating the metadata for dynamic parameters. /// public abstract Collection Invoke(IEnumerable input); /// /// Invoke the pipeline asynchronously. /// /// /// 1) Results are returned through the reader. /// 2) When pipeline is invoked using InvokeAsync, invocation doesn't /// finish until Input to pipeline is closed. Caller of InvokeAsync must close /// the input pipe after all input has been written to input pipe. Input pipe /// is closed by calling Pipeline.Input.Close(); /// /// If you want this pipeline to execute as a standalone command /// (that is, using command-line parameters only), /// be sure to call Pipeline.Input.Close() before calling /// InvokeAsync(). Otherwise, the command will be executed /// as though it had external input. If you observe that the /// command isn't doing anything, this may be the reason. /// /// /// No command is added to pipeline /// /// /// PipelineState is not NotStarted. /// /// /// 1) A pipeline is already executing. Pipeline cannot execute /// concurrently. /// 2) InvokeAsync is called on nested pipeline. Nested pipeline /// cannot be executed Asynchronously. /// /// /// RunspaceState is not Open /// /// /// Pipeline already disposed /// public abstract void InvokeAsync(); /// /// Synchronous call to stop the running pipeline. /// public abstract void Stop(); /// /// Asynchronous call to stop the running pipeline. /// public abstract void StopAsync(); /// /// Creates a new that is a copy of the current instance. /// /// A new that is a copy of this instance. public abstract Pipeline Copy(); /// /// Connects synchronously to a running command on a remote server. /// The pipeline object must be in the disconnected state. /// /// A collection of result objects. public abstract Collection Connect(); /// /// Connects asynchronously to a running command on a remote server. /// public abstract void ConnectAsync(); /// /// Sets the command collection. /// /// Command collection to set. /// called by ClientRemotePipeline internal void SetCommandCollection(CommandCollection commands) { Commands = commands; } /// /// Sets the history string to the one that is specified. /// /// History string to set. internal abstract void SetHistoryString(string historyString); /// /// Invokes a remote command and immediately disconnects if /// transport layer supports it. /// internal abstract void InvokeAsyncAndDisconnect(); #endregion methods #region Remote data drain/block methods /// /// Blocks data arriving from remote session. /// internal virtual void SuspendIncomingData() { throw new PSNotImplementedException(); } /// /// Resumes data arrive from remote session. /// internal virtual void ResumeIncomingData() { throw new PSNotImplementedException(); } /// /// Blocking call that waits until the current remote data /// queue is empty. /// internal virtual void DrainIncomingData() { throw new PSNotImplementedException(); } #endregion #region IDisposable Members /// /// Disposes the pipeline. If pipeline is running, dispose first /// stops the pipeline. /// public void Dispose() { Dispose(!IsChild); GC.SuppressFinalize(this); } /// /// Protected dispose which can be overridden by derived classes. /// /// protected virtual void Dispose(bool disposing) { } #endregion IDisposable Members } }