/// <summary>
        /// Writes the error to the pipeline or accumulates the error in an internal
        /// buffer.
        /// </summary>
        /// <param name="errorRecord">
        /// The error record to write to the pipeline or the internal buffer.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// The CmdletProvider could not stream the error because no
        /// cmdlet was specified to stream the output through.
        /// </exception>
        /// <exception cref="PipelineStoppedException">
        /// If the pipeline has been signaled for stopping but
        /// the provider calls this method.
        /// </exception>
        internal void WriteError(ErrorRecord errorRecord)
        {
            // Making sure to obey the StopProcessing by
            // throwing an exception anytime a provider tries
            // to WriteError

            if (Stopping)
            {
                PipelineStoppedException stopPipeline =
                    new PipelineStoppedException();

                throw stopPipeline;
            }

            if (_streamErrors)
            {
                if (_command != null)
                {
                    s_tracer.WriteLine("Writing error package to command error pipe");

                    _command.WriteError(errorRecord);
                }
                else
                {
                    InvalidOperationException e =
                        PSTraceSource.NewInvalidOperationException(
                            SessionStateStrings.ErrorStreamingNotEnabled);
                    throw e;
                }
            }
            else
            {
                // Since we are not streaming, just add the object to the accumulatedErrorObjects
                _accumulatedErrorObjects.Add(errorRecord);

                if (errorRecord.ErrorDetails != null &&
                    errorRecord.ErrorDetails.TextLookupError != null)
                {
                    Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
                    errorRecord.ErrorDetails.TextLookupError = null;
                    MshLog.LogProviderHealthEvent(
                        this.ExecutionContext,
                        this.ProviderInstance.ProviderInfo.Name,
                        textLookupError,
                        Severity.Warning);
                }
            }
        }
Beispiel #2
0
 internal void Push(PipelineProcessor item)
 {
     if (item == null)
     {
         throw PSTraceSource.NewArgumentNullException("item");
     }
     lock (this._syncRoot)
     {
         if (this._stopping)
         {
             PipelineStoppedException exception = new PipelineStoppedException();
             throw exception;
         }
         this._stack.Push(item);
     }
     item.LocalPipeline = this._localPipeline;
 }
 internal void WriteObject(object obj)
 {
     if (this.Stopping)
     {
         PipelineStoppedException exception = new PipelineStoppedException();
         throw exception;
     }
     if (this.streamObjects)
     {
         if (this.command == null)
         {
             throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "OutputStreamingNotEnabled", new object[0]);
         }
         tracer.WriteLine("Writing to command pipeline", new object[0]);
         this.command.WriteObject(obj);
     }
     else
     {
         tracer.WriteLine("Writing to accumulated objects", new object[0]);
         PSObject item = PSObject.AsPSObject(obj);
         this.accumulatedObjects.Add(item);
     }
 }
        /// <summary>
        /// 
        /// Implementation based on NT CredUI's GetPasswdStr.
        /// Use Win32.ReadConsole to construct a SecureString. The advantage of ReadConsole over ReadKey is
        /// Alt-ddd where d is {0-9} is allowed.
        /// It also manages the cursor as keys are entered and "backspaced". However, it is possible that
        /// while this method is running, the console buffer contents could change. Then, its cursor mgmt
        /// will likely be messed up.
        ///
        /// Secondary implementation for Unix based on Console.ReadKey(), where
        /// the advantage is portability through abstraction. Does not support
        /// arrow key movement, but supports backspace.
        /// 
        /// </summary>
        ///<param name="isSecureString">
        /// 
        /// True to specify reading a SecureString; false reading a string
        /// 
        /// </param>
        /// <param name="printToken">
        /// 
        /// string for output echo
        /// 
        /// </param>
        /// <returns></returns>
        /// <exception cref="HostException">
        /// 
        /// If obtaining a handle to the active screen buffer failed
        ///    OR
        ///    Win32's setting input buffer mode to disregard window and mouse input failed
        ///    OR
        ///    Win32's ReadConsole failed
        ///    OR
        ///    obtaining information about the buffer failed
        ///    OR
        ///    Win32's SetConsoleCursorPosition failed
        ///
        /// </exception>
        /// <exception cref="PipelineStoppedException">
        ///
        /// If Ctrl-C is entered by user
        /// 
        /// </exception>

        private object ReadLineSafe(bool isSecureString, char? printToken)
        {
            // Don't lock (instanceLock) in here -- the caller needs to do that...

            PreRead();
            string printTokenString = printToken.HasValue ?
                printToken.ToString() :
                null;
            SecureString secureResult = new SecureString();
            StringBuilder result = new StringBuilder();
#if UNIX
            bool treatControlCAsInput = Console.TreatControlCAsInput;
#else
            ConsoleHandle handle = ConsoleControl.GetConioDeviceHandle();
            ConsoleControl.ConsoleModes originalMode = ConsoleControl.GetMode(handle);
            bool isModeChanged = true; // assume ConsoleMode is changed so that if ReadLineSetMode
            // fails to return the value correctly, the original mode is
            // restored.
#endif

            try
            {
#if UNIX
                Console.TreatControlCAsInput = true;
#else
                // Ensure that we're in the proper line-input mode.

                ConsoleControl.ConsoleModes desiredMode =
                    ConsoleControl.ConsoleModes.Extended |
                    ConsoleControl.ConsoleModes.QuickEdit;

                ConsoleControl.ConsoleModes m = originalMode;
                bool shouldUnsetEchoInput = shouldUnsetMode(ConsoleControl.ConsoleModes.EchoInput, ref m);
                bool shouldUnsetLineInput = shouldUnsetMode(ConsoleControl.ConsoleModes.LineInput, ref m);
                bool shouldUnsetMouseInput = shouldUnsetMode(ConsoleControl.ConsoleModes.MouseInput, ref m);
                bool shouldUnsetProcessInput = shouldUnsetMode(ConsoleControl.ConsoleModes.ProcessedInput, ref m);

                if ((m & desiredMode) != desiredMode ||
                    shouldUnsetMouseInput ||
                    shouldUnsetEchoInput ||
                    shouldUnsetLineInput ||
                    shouldUnsetProcessInput)
                {
                    m |= desiredMode;
                    ConsoleControl.SetMode(handle, m);
                }
                else
                {
                    isModeChanged = false;
                }
                _rawui.ClearKeyCache();
#endif

                Coordinates originalCursorPos = _rawui.CursorPosition;

                do
                {
                    //
                    // read one char at a time so that we don't
                    // end up having a immutable string holding the
                    // secret in memory.
                    //
#if UNIX
                    ConsoleKeyInfo keyInfo = Console.ReadKey(true);
#else
                    uint unused = 0;
                    string key = ConsoleControl.ReadConsole(handle, string.Empty, 1, false, out unused);
#endif

#if UNIX
                    // Handle Ctrl-C ending input
                    if (keyInfo.Key == ConsoleKey.C && keyInfo.Modifiers.HasFlag(ConsoleModifiers.Control))
#else
                    if (string.IsNullOrEmpty(key) || (char)3 == key[0])
#endif
                    {
                        PipelineStoppedException e = new PipelineStoppedException();
                        throw e;
                    }
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Enter)
#else
                    if ((char)13 == key[0])
#endif
                    {
                        //
                        // we are done if user presses ENTER key
                        //
                        break;
                    }
#if UNIX
                    if (keyInfo.Key == ConsoleKey.Backspace)
#else
                    if ((char)8 == key[0])
#endif
                    {
                        //
                        // for backspace, remove last char appended
                        //
                        if (isSecureString && secureResult.Length > 0)
                        {
                            secureResult.RemoveAt(secureResult.Length - 1);
                            WriteBackSpace(originalCursorPos);
                        }
                        else if (result.Length > 0)
                        {
                            result.Remove(result.Length - 1, 1);
                            WriteBackSpace(originalCursorPos);
                        }
                    }
#if UNIX
                    else if (Char.IsControl(keyInfo.KeyChar))
                    {
                        // blacklist control characters
                        continue;
                    }
#endif
                    else
                    {
                        //
                        // append the char to our string
                        //
                        if (isSecureString)
                        {
#if UNIX
                            secureResult.AppendChar(keyInfo.KeyChar);
#else
                            secureResult.AppendChar(key[0]);
#endif
                        }
                        else
                        {
#if UNIX
                            result.Append(keyInfo.KeyChar);
#else
                            result.Append(key);
#endif
                        }
                        if (!string.IsNullOrEmpty(printTokenString))
                        {
                            WritePrintToken(printTokenString, ref originalCursorPos);
                        }
                    }
                }
                while (true);
            }
#if UNIX
            catch (InvalidOperationException)
            {
                // ReadKey() failed so we stop
                throw new PipelineStoppedException();
            }
#endif
            finally
            {
#if UNIX
                Console.TreatControlCAsInput = treatControlCAsInput;
#else
                if (isModeChanged)
                {
                    ConsoleControl.SetMode(handle, originalMode);
                }
#endif
            }
            WriteLineToConsole();
            PostRead(result.ToString());
            if (isSecureString)
            {
                return secureResult;
            }
            else
            {
                return result;
            }
        }
Beispiel #5
0
 internal PipelineStoppedException ManageInvocationException(Exception e)
 {
     PipelineStoppedException exception4;
     try
     {
         if (this.Command != null)
         {
             ProviderInvocationException innerException = e as ProviderInvocationException;
             if (innerException != null)
             {
                 e = new CmdletProviderInvocationException(innerException, this.Command.MyInvocation);
             }
             else if (((!(e is PipelineStoppedException) && !(e is CmdletInvocationException)) && (!(e is ActionPreferenceStopException) && !(e is HaltCommandException))) && (!(e is FlowControlException) && !(e is ScriptCallDepthException)))
             {
                 RuntimeException exception2 = e as RuntimeException;
                 if ((exception2 == null) || !exception2.WasThrownFromThrowStatement)
                 {
                     e = new CmdletInvocationException(e, this.Command.MyInvocation);
                 }
             }
             if (this.commandRuntime.UseTransaction != 0)
             {
                 bool flag = false;
                 for (Exception exception3 = e; exception3 != null; exception3 = exception3.InnerException)
                 {
                     if (exception3 is TimeoutException)
                     {
                         flag = true;
                         break;
                     }
                 }
                 if (flag)
                 {
                     ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(TransactionStrings.TransactionTimedOut), "TRANSACTION_TIMEOUT", ErrorCategory.InvalidOperation, e);
                     errorRecord.SetInvocationInfo(this.Command.MyInvocation);
                     e = new CmdletInvocationException(errorRecord);
                 }
                 if (this._context.TransactionManager.HasTransaction && (this._context.TransactionManager.RollbackPreference != RollbackSeverity.Never))
                 {
                     this.Context.TransactionManager.Rollback(true);
                 }
             }
             return (PipelineStoppedException) this.commandRuntime.ManageException(e);
         }
         exception4 = new PipelineStoppedException();
     }
     catch (Exception)
     {
         throw;
     }
     return exception4;
 }
 /// <summary>
 /// Helper method to create and trace PipelineStoppedException
 /// </summary>
 /// <returns></returns>
 private PipelineStoppedException NewPipelineStoppedException()
 {
     PipelineStoppedException e = new PipelineStoppedException();
     return e;
 }
Beispiel #7
0
 internal void WriteObject(object obj)
 {
     if (this.Stopping)
     {
         PipelineStoppedException exception = new PipelineStoppedException();
         throw exception;
     }
     if (this.streamObjects)
     {
         if (this.command == null)
         {
             throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "OutputStreamingNotEnabled", new object[0]);
         }
         tracer.WriteLine("Writing to command pipeline", new object[0]);
         this.command.WriteObject(obj);
     }
     else
     {
         tracer.WriteLine("Writing to accumulated objects", new object[0]);
         PSObject item = PSObject.AsPSObject(obj);
         this.accumulatedObjects.Add(item);
     }
 }
Beispiel #8
0
 internal void WriteError(ErrorRecord errorRecord)
 {
     if (this.Stopping)
     {
         PipelineStoppedException exception = new PipelineStoppedException();
         throw exception;
     }
     if (this.streamErrors)
     {
         if (this.command == null)
         {
             throw PSTraceSource.NewInvalidOperationException("SessionStateStrings", "ErrorStreamingNotEnabled", new object[0]);
         }
         tracer.WriteLine("Writing error package to command error pipe", new object[0]);
         this.command.WriteError(errorRecord);
     }
     else
     {
         this.accumulatedErrorObjects.Add(errorRecord);
         if ((errorRecord.ErrorDetails != null) && (errorRecord.ErrorDetails.TextLookupError != null))
         {
             Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
             errorRecord.ErrorDetails.TextLookupError = null;
             MshLog.LogProviderHealthEvent(this.ExecutionContext, this.ProviderInstance.ProviderInfo.Name, textLookupError, Severity.Warning);
         }
     }
 }
Beispiel #9
0
        } // WriteObject

        /// <summary>
        /// Writes the error to the pipeline or accumulates the error in an internal
        /// buffer.
        /// </summary>
        /// 
        /// <param name="errorRecord">
        /// The error record to write to the pipeline or the internal buffer.
        /// </param>
        /// 
        /// <exception cref="InvalidOperationException">
        /// The CmdletProvider could not stream the error because no 
        /// cmdlet was specified to stream the output through.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If the pipeline has been signaled for stopping but
        /// the provider calls this method.
        /// </exception>
        /// 
        internal void WriteError(ErrorRecord errorRecord)
        {
            // Making sure to obey the StopProcessing by
            // throwing an exception anytime a provider tries
            // to WriteError

            if (Stopping)
            {
                PipelineStoppedException stopPipeline =
                    new PipelineStoppedException();

                throw stopPipeline;
            }

            if (_streamErrors)
            {
                if (_command != null)
                {
                    s_tracer.WriteLine("Writing error package to command error pipe");

                    _command.WriteError(errorRecord);
                }
                else
                {
                    InvalidOperationException e =
                        PSTraceSource.NewInvalidOperationException(
                            SessionStateStrings.ErrorStreamingNotEnabled);
                    throw e;
                }
            }
            else
            {
                // Since we are not streaming, just add the object to the accumulatedErrorObjects
                _accumulatedErrorObjects.Add(errorRecord);

                if (null != errorRecord.ErrorDetails
                    && null != errorRecord.ErrorDetails.TextLookupError)
                {
                    Exception textLookupError = errorRecord.ErrorDetails.TextLookupError;
                    errorRecord.ErrorDetails.TextLookupError = null;
                    MshLog.LogProviderHealthEvent(
                        this.ExecutionContext,
                        this.ProviderInstance.ProviderInfo.Name,
                        textLookupError,
                        Severity.Warning);
                }
            }
        } // WriteError
Beispiel #10
0
        /// <summary>
        /// Writes an object to the output.
        /// </summary>
        /// 
        /// <param name="obj">
        /// The object to be written.
        /// </param>
        /// 
        /// <remarks>
        /// If streaming is on and the writeObjectHandler was specified then the object
        /// gets written to the writeObjectHandler. If streaming is on and the writeObjectHandler
        /// was not specified and the command object was specified, the object gets written to
        /// the WriteObject method of the command object. 
        /// If streaming is off the object gets written to an accumulator collection. The collection
        /// of written object can be retrieved using the AccumulatedObjects method.
        /// </remarks>
        /// 
        /// <exception cref="InvalidOperationException">
        /// The CmdletProvider could not stream the results because no 
        /// cmdlet was specified to stream the output through.
        /// </exception>
        /// 
        /// <exception cref="PipelineStoppedException">
        /// If the pipeline has been signaled for stopping but
        /// the provider calls this method.
        /// </exception>
        /// 
        internal void WriteObject(object obj)
        {
            // Making sure to obey the StopProcessing by
            // throwing an exception anytime a provider tries
            // to WriteObject

            if (Stopping)
            {
                PipelineStoppedException stopPipeline =
                    new PipelineStoppedException();

                throw stopPipeline;
            }

            if (PassThru)
            {
                if (_command != null)
                {
                    s_tracer.WriteLine("Writing to command pipeline");

                    // Since there was no writeObject handler use
                    // the command WriteObject method.

                    _command.WriteObject(obj);
                }
                else
                {
                    // The flag was set for streaming but we have no where
                    // to stream to.

                    InvalidOperationException e =
                        PSTraceSource.NewInvalidOperationException(
                            SessionStateStrings.OutputStreamingNotEnabled);
                    throw e;
                }
            }
            else
            {
                s_tracer.WriteLine("Writing to accumulated objects");

                // Convert the object to a PSObject if it's not already
                // one.

                PSObject newObj = PSObject.AsPSObject(obj);

                // Since we are not streaming, just add the object to the accumulatedObjects

                _accumulatedObjects.Add(newObj);
            }
        } // WriteObject
		private object ReadLineSafe(bool isSecureString, char? printToken)
		{
			string str;
			this.PreRead();
			if (printToken.HasValue)
			{
				str = printToken.ToString();
			}
			else
			{
				str = null;
			}
			string str1 = str;
			SecureString secureString = new SecureString();
			StringBuilder stringBuilder = new StringBuilder();
			SafeFileHandle inputHandle = ConsoleControl.GetInputHandle();
			ConsoleControl.ConsoleModes mode = ConsoleControl.GetMode(inputHandle);
			bool flag = true;
			try
			{
				ConsoleControl.ConsoleModes consoleMode = ConsoleControl.ConsoleModes.QuickEdit | ConsoleControl.ConsoleModes.Extended;
				ConsoleControl.ConsoleModes consoleMode1 = mode;
				bool flag1 = ConsoleHostUserInterface.shouldUnsetMode(ConsoleControl.ConsoleModes.EchoInput, ref consoleMode1);
				bool flag2 = ConsoleHostUserInterface.shouldUnsetMode(ConsoleControl.ConsoleModes.LineInput, ref consoleMode1);
				bool flag3 = ConsoleHostUserInterface.shouldUnsetMode(ConsoleControl.ConsoleModes.MouseInput, ref consoleMode1);
				bool flag4 = ConsoleHostUserInterface.shouldUnsetMode(ConsoleControl.ConsoleModes.ProcessedInput, ref consoleMode1);
				if ((consoleMode1 & consoleMode) != consoleMode || flag3 || flag1 || flag2 || flag4)
				{
					consoleMode1 = consoleMode1 | consoleMode;
					ConsoleControl.SetMode(inputHandle, consoleMode1);
				}
				else
				{
					flag = false;
				}
				this.rawui.ClearKeyCache();
				Coordinates cursorPosition = this.rawui.CursorPosition;
				while (true)
				{
					int num = 0;
					string str2 = ConsoleControl.ReadConsole(inputHandle, string.Empty, 1, false, out num);
					if (string.IsNullOrEmpty(str2) || 3 == str2[0])
					{
						break;
					}
					if (13 == str2[0])
					{
						goto Label1;
					}
					if (8 != str2[0])
					{
						if (!isSecureString)
						{
							stringBuilder.Append(str2);
							goto Label1;
						}
						else
						{
							foreach(var char1 in str2)
							{
								secureString.AppendChar(str2[0]);
							}
							goto Label1;
						}
						/*
						if (!string.IsNullOrEmpty(str1))
						{
							this.WritePrintToken(str1, ref cursorPosition);
						}
						*/
					}
					else
					{
						if (!isSecureString || secureString.Length <= 0)
						{
							if (stringBuilder.Length > 0)
							{
								stringBuilder.Remove(stringBuilder.Length - 1, 1);
								this.WriteBackSpace(cursorPosition);
							}
						}
						else
						{
							secureString.RemoveAt(secureString.Length - 1);
							this.WriteBackSpace(cursorPosition);
						}
					}
				}
				PipelineStoppedException pipelineStoppedException = new PipelineStoppedException();
				throw pipelineStoppedException;
			}
			finally
			{
				if (flag)
				{
					ConsoleControl.SetMode(inputHandle, mode);
				}
			}
		Label1:
			this.WriteLineToConsole();
			this.PostRead(stringBuilder.ToString());
			if (!isSecureString)
			{
				return stringBuilder;
			}
			else
			{
				return secureString;
			}
		}
		private PipelineStoppedException NewPipelineStoppedException()
		{
			PipelineStoppedException pipelineStoppedException = new PipelineStoppedException();
			return pipelineStoppedException;
		}