Beispiel #1
0
 internal ScopeTracer(PSTraceSource tracer, PSTraceSourceOptions flag, string scopeOutputFormatter, string leavingScopeFormatter, string scopeName, string format, params object[] args)
 {
     this._tracer = tracer;
     if (format != null)
     {
         this.ScopeTracerHelper(flag, scopeOutputFormatter, leavingScopeFormatter, scopeName, format, args);
     }
     else
     {
         this.ScopeTracerHelper(flag, scopeOutputFormatter, leavingScopeFormatter, scopeName, "", new object[0]);
     }
 }
Beispiel #2
0
		static CertificateProvider()
		{
			CertificateProvider.tracer = PSTraceSource.GetTracer("CertificateProvider", "The core command provider for certificates");
			CertificateProvider.staticLock = new object();
			CertificateProvider.storeLocations = null;
			CertificateProvider.pathCache = null;
			CertificateProvider.fIsWin8AndAbove = DownLevelHelper.IsWin8AndAbove();
			char[] chrArray = new char[2];
			chrArray[0] = '/';
			chrArray[1] = '\\';
			CertificateProvider.pathSeparators = chrArray;
			CertificateProvider.storeCache = null;
			CertificateProvider.certPathRegex = null;
		}
Beispiel #3
0
        /// <summary>
        /// Set a function in the current scope of session state.
        /// </summary>
        /// <param name="name">
        /// The name of the function to set.
        /// </param>
        /// <param name="function">
        /// The new value of the function being set.
        /// </param>
        /// <param name="originalFunction">
        /// The original function (if any) from which the ScriptBlock is derived.
        /// </param>
        /// <param name="force">
        /// If true, the function will be set even if its ReadOnly.
        /// </param>
        /// <param name="origin">
        /// The origin of the caller
        /// </param>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// or
        /// If <paramref name="function"/> is not a <see cref="FilterInfo">FilterInfo</see>
        /// or <see cref="FunctionInfo">FunctionInfo</see>
        /// </exception>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="function"/> is null.
        /// </exception>
        /// <exception cref="SessionStateUnauthorizedAccessException">
        /// If the function is read-only or constant.
        /// </exception>
        internal FunctionInfo SetFunction(
            string name,
            ScriptBlock function,
            FunctionInfo originalFunction,
            bool force,
            CommandOrigin origin)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            if (function == null)
            {
                throw PSTraceSource.NewArgumentNullException("function");
            }

            string originalName = name;

            FunctionLookupPath path = new FunctionLookupPath(name);

            name = path.UnqualifiedPath;

            if (String.IsNullOrEmpty(name))
            {
                SessionStateException exception =
                    new SessionStateException(
                        originalName,
                        SessionStateCategory.Function,
                        "ScopedFunctionMustHaveName",
                        SessionStateStrings.ScopedFunctionMustHaveName,
                        ErrorCategory.InvalidArgument);

                throw exception;
            }

            ScopedItemOptions options = ScopedItemOptions.None;

            if (path.IsPrivate)
            {
                options |= ScopedItemOptions.Private;
            }

            FunctionScopeItemSearcher searcher =
                new FunctionScopeItemSearcher(
                    this,
                    path,
                    origin);

            FunctionInfo result = null;

            SessionStateScope scope = searcher.InitialScope;

            if (searcher.MoveNext())
            {
                scope = searcher.CurrentLookupScope;
                name  = searcher.Name;

                if (path.IsPrivate)
                {
                    // Need to add the Private flag
                    FunctionInfo existingFunction = scope.GetFunction(name);
                    options |= existingFunction.Options;
                    result   = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }
            else
            {
                if (path.IsPrivate)
                {
                    result = scope.SetFunction(name, function, originalFunction, options, force, origin, ExecutionContext);
                }
                else
                {
                    result = scope.SetFunction(name, function, force, origin, ExecutionContext);
                }
            }

            return(result);
        }
Beispiel #4
0
        /// <summary>
        /// retrieve the encoding parameter from the command line
        /// it throws if the encoding does not match the known ones
        /// </summary>
        /// <returns>a System.Text.Encoding object (null if no encoding specified)</returns>
        internal static Encoding Convert(Cmdlet cmdlet, string encoding)
        {
            if (string.IsNullOrEmpty(encoding))
            {
                // no parameter passed, default to Unicode (OS preferred)
                return(System.Text.Encoding.Unicode);
            }

            // Default to unicode (this matches Get-Content)
            if (string.Equals(encoding, Unknown, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.Unicode);
            }

            if (string.Equals(encoding, String, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.Unicode);
            }

            // these are the encodings the CLR supports
            if (string.Equals(encoding, Unicode, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.Unicode);
            }

            if (string.Equals(encoding, BigEndianUnicode, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.BigEndianUnicode);
            }

            if (string.Equals(encoding, Utf8, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.UTF8);
            }

            if (string.Equals(encoding, Ascii, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.ASCII);
            }

            if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.UTF7);
            }

            if (string.Equals(encoding, Utf32, StringComparison.OrdinalIgnoreCase))
            {
                return(System.Text.Encoding.UTF32);
            }

            if (string.Equals(encoding, Default, StringComparison.OrdinalIgnoreCase))
            {
                return(ClrFacade.GetDefaultEncoding());
            }

            if (string.Equals(encoding, OEM, StringComparison.OrdinalIgnoreCase))
            {
                return(ClrFacade.GetOEMEncoding());
            }

            // error condition: unknown encoding value
            string validEncodingValues = string.Join(
                ", ",
                new string[] { Unknown, String, Unicode, BigEndianUnicode, Ascii, Utf8, Utf7, Utf32, Default, OEM });
            string msg = StringUtil.Format(PathUtilsStrings.OutFile_WriteToFileEncodingUnknown,
                                           encoding, validEncodingValues);

            ErrorRecord errorRecord = new ErrorRecord(
                PSTraceSource.NewArgumentException("Encoding"),
                "WriteToFileEncodingUnknown",
                ErrorCategory.InvalidArgument,
                null);

            errorRecord.ErrorDetails = new ErrorDetails(msg);
            cmdlet.ThrowTerminatingError(errorRecord);

            return(null);
        }
Beispiel #5
0
        internal Uri LookupUriFromCommandInfo()
        {
            CommandTypes cmdTypesToLookFor = CommandTypes.Cmdlet;

            switch (this.HelpCategory)
            {
            case Automation.HelpCategory.Cmdlet:
                cmdTypesToLookFor = CommandTypes.Cmdlet;
                break;

            case Automation.HelpCategory.Function:
                cmdTypesToLookFor = CommandTypes.Function;
                break;

            case Automation.HelpCategory.ScriptCommand:
                cmdTypesToLookFor = CommandTypes.Script;
                break;

            case Automation.HelpCategory.ExternalScript:
                cmdTypesToLookFor = CommandTypes.ExternalScript;
                break;

            case Automation.HelpCategory.Filter:
                cmdTypesToLookFor = CommandTypes.Filter;
                break;

            case Automation.HelpCategory.Configuration:
                cmdTypesToLookFor = CommandTypes.Configuration;
                break;

            default:
                return(null);
            }

            string commandName = this.Name;
            string moduleName  = string.Empty;

            if (this.FullHelp.Properties["ModuleName"] != null)
            {
                PSNoteProperty moduleNameNP = this.FullHelp.Properties["ModuleName"] as PSNoteProperty;
                if (moduleNameNP != null)
                {
                    LanguagePrimitives.TryConvertTo <string>(moduleNameNP.Value, CultureInfo.InvariantCulture,
                                                             out moduleName);
                }
            }

            string commandToSearch = commandName;

            if (!string.IsNullOrEmpty(moduleName))
            {
                commandToSearch = string.Format(CultureInfo.InvariantCulture,
                                                "{0}\\{1}", moduleName, commandName);
            }

            ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS();

            if (context == null)
            {
                return(null);
            }

            try
            {
                CommandInfo cmdInfo = null;

                if (cmdTypesToLookFor == CommandTypes.Cmdlet)
                {
                    cmdInfo = context.SessionState.InvokeCommand.GetCmdlet(commandToSearch);
                }
                else
                {
                    cmdInfo = context.SessionState.InvokeCommand.GetCommands(commandToSearch, cmdTypesToLookFor, false).FirstOrDefault();
                }

                if ((cmdInfo == null) || (cmdInfo.CommandMetadata == null))
                {
                    return(null);
                }

                string uriString = cmdInfo.CommandMetadata.HelpUri;
                if (!string.IsNullOrEmpty(uriString))
                {
                    if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
                    {
                        // WinBlue: 545315 Online help links are broken with localized help
                        // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (moglicherwei se auf Englisch)
                        // Split the string based on <s> (space). We decided to go with this approach as
                        // UX localization authors use spaces. Correctly extracting only the wellformed URI
                        // is out-of-scope for this fix.
                        string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space);
                        uriString = tempUriSplitArray[0];
                    }

                    try
                    {
                        return(new System.Uri(uriString));
                        // return only the first Uri (ignore other uris)
                    }
                    catch (UriFormatException)
                    {
                        throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI,
                                                                         cmdInfo.CommandMetadata.HelpUri);
                    }
                }
            }
            catch (CommandNotFoundException)
            {
            }

            return(null);
        }
Beispiel #6
0
        internal Uri LookupUriFromCommandInfo()
        {
            CommandTypes cmdlet = CommandTypes.Cmdlet;

            switch (this.HelpCategory)
            {
            case System.Management.Automation.HelpCategory.Function:
                cmdlet = CommandTypes.Function;
                break;

            case System.Management.Automation.HelpCategory.Filter:
                cmdlet = CommandTypes.Filter;
                break;

            case System.Management.Automation.HelpCategory.ExternalScript:
                cmdlet = CommandTypes.ExternalScript;
                break;

            case System.Management.Automation.HelpCategory.Cmdlet:
                cmdlet = CommandTypes.Cmdlet;
                break;

            case System.Management.Automation.HelpCategory.ScriptCommand:
                cmdlet = CommandTypes.Script;
                break;

            default:
                return(null);
            }
            string name   = this.Name;
            string result = string.Empty;

            if (this.FullHelp.Properties["ModuleName"] != null)
            {
                PSNoteProperty property = this.FullHelp.Properties["ModuleName"] as PSNoteProperty;
                if (property != null)
                {
                    LanguagePrimitives.TryConvertTo <string>(property.Value, CultureInfo.InvariantCulture, out result);
                }
            }
            string commandName = name;

            if (!string.IsNullOrEmpty(result))
            {
                commandName = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", new object[] { result, name });
            }
            ExecutionContext executionContextFromTLS = LocalPipeline.GetExecutionContextFromTLS();

            if (executionContextFromTLS != null)
            {
                try
                {
                    CommandInfo info = null;
                    if (cmdlet == CommandTypes.Cmdlet)
                    {
                        info = executionContextFromTLS.SessionState.InvokeCommand.GetCmdlet(commandName);
                    }
                    else
                    {
                        info = executionContextFromTLS.SessionState.InvokeCommand.GetCommands(commandName, cmdlet, false).FirstOrDefault <CommandInfo>();
                    }
                    if ((info == null) || (info.CommandMetadata == null))
                    {
                        return(null);
                    }
                    if (!string.IsNullOrEmpty(info.CommandMetadata.HelpUri))
                    {
                        try
                        {
                            return(new Uri(info.CommandMetadata.HelpUri));
                        }
                        catch (UriFormatException)
                        {
                            throw PSTraceSource.NewInvalidOperationException("HelpErrors", "InvalidURI", new object[] { info.CommandMetadata.HelpUri });
                        }
                    }
                }
                catch (CommandNotFoundException)
                {
                }
            }
            return(null);
        }
 public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase)
 {
     throw PSTraceSource.NewNotSupportedException();
 }
Beispiel #8
0
 internal static void SetTracer(PSTraceSource t)
 {
     s_activeTracer = t;
 }
        } // SetLocation

        /// <summary>
        /// Changes the current working directory to the path specified
        /// </summary>
        ///
        /// <param name="path">
        /// The path of the new current working directory
        /// </param>
        ///
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        ///
        /// <returns>
        /// The PathInfo object representing the path of the location
        /// that was set.
        /// </returns>
        ///
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        ///
        /// <exception cref="ArgumentException">
        /// If <paramref name="path"/> does not exist, is not a container, or
        /// resolved to multiple containers.
        /// </exception>
        ///
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> refers to a provider that does not exist.
        /// </exception>
        ///
        /// <exception cref="DriveNotFoundException">
        /// If <paramref name="path"/> refers to a drive that does not exist.
        /// </exception>
        ///
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with <paramref name="path"/> threw an
        /// exception.
        /// </exception>
        ///
        /// <exception cref="ItemNotFoundException">
        /// If the <paramref name="path"/> could not be resolved.
        /// </exception>
        ///
        internal PathInfo SetLocation(string path, CmdletProviderContext context)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException("path");
            }

            string       originalPath = path;
            string       driveName    = null;
            ProviderInfo provider     = null;
            string       providerId   = null;

            PSDriveInfo previousWorkingDrive = CurrentDrive;

            // First check to see if the path is a home path

            if (LocationGlobber.IsHomePath(path))
            {
                path = Globber.GetHomeRelativePath(path);
            }

            if (LocationGlobber.IsProviderDirectPath(path))
            {
                // The path is a provider-direct path so use the current
                // provider and its hidden drive but don't modify the path
                // at all.

                provider     = CurrentLocation.Provider;
                CurrentDrive = provider.HiddenDrive;
            }
            else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId))
            {
                provider     = GetSingleProvider(providerId);
                CurrentDrive = provider.HiddenDrive;
            }
            else
            {
                // See if the path is a relative or absolute
                // path.

                if (Globber.IsAbsolutePath(path, out driveName))
                {
                    // Since the path is an absolute path
                    // we need to change the current working
                    // drive

                    PSDriveInfo newWorkingDrive = GetDrive(driveName);
                    CurrentDrive = newWorkingDrive;

                    // Now that the current working drive is set,
                    // process the rest of the path as a relative path.
                }
            }

            if (context == null)
            {
                context = new CmdletProviderContext(this.ExecutionContext);
            }

            if (CurrentDrive != null)
            {
                context.Drive = CurrentDrive;
            }

            CmdletProvider providerInstance = null;

            Collection <PathInfo> workingPath = null;

            try
            {
                workingPath =
                    Globber.GetGlobbedMonadPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out providerInstance);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception e) // Catch-all OK, 3rd party callout
            {
                CommandProcessorBase.CheckForSevereException(e);

                // Reset the drive to the previous drive and
                // then rethrow the error

                CurrentDrive = previousWorkingDrive;
                throw;
            }

            if (workingPath.Count == 0)
            {
                // Set the current working drive back to the previous
                // one in case it was changed.

                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // We allow globbing the location as long as it only resolves a single container.

            bool foundContainer                     = false;
            bool pathIsContainer                    = false;
            bool pathIsProviderQualifiedPath        = false;
            bool currentPathisProviderQualifiedPath = false;

            for (int index = 0; index < workingPath.Count; ++index)
            {
                CmdletProviderContext normalizePathContext =
                    new CmdletProviderContext(context);

                PathInfo resolvedPath = workingPath[index];
                string   currentPath  = path;
                try
                {
                    string providerName = null;
                    currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName);
                    if (currentPathisProviderQualifiedPath)
                    {
                        // The path should be the provider-qualified path without the provider ID
                        // or ::

                        string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path);

                        try
                        {
                            currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, String.Empty, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception e) // Catch-all OK, 3rd party callout
                        {
                            CommandProcessorBase.CheckForSevereException(e);

                            // Reset the drive to the previous drive and
                            // then rethrow the error

                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }
                    else
                    {
                        try
                        {
                            currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception e) // Catch-all OK, 3rd party callout
                        {
                            CommandProcessorBase.CheckForSevereException(e);

                            // Reset the drive to the previous drive and
                            // then rethrow the error

                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }

                    // Now see if there was errors while normalizing the path

                    if (normalizePathContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        normalizePathContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                // Check to see if the path is a container

                bool isContainer = false;

                CmdletProviderContext itemContainerContext =
                    new CmdletProviderContext(context);
                itemContainerContext.SuppressWildcardExpansion = true;

                try
                {
                    isContainer =
                        IsItemContainer(
                            resolvedPath.Path,
                            itemContainerContext);

                    if (itemContainerContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        itemContainerContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                catch (NotSupportedException)
                {
                    if (currentPath.Length == 0)
                    {
                        // Treat this as a container because providers that only
                        // support the ContainerCmdletProvider interface are really
                        // containers at their root.

                        isContainer = true;
                    }
                }
                finally
                {
                    itemContainerContext.RemoveStopReferral();
                }

                if (isContainer)
                {
                    if (foundContainer)
                    {
                        // The path resolved to more than one container

                        // Set the current working drive back to the previous
                        // one in case it was changed.

                        CurrentDrive = previousWorkingDrive;

                        throw
                            PSTraceSource.NewArgumentException(
                                "path",
                                SessionStateStrings.PathResolvedToMultiple,
                                originalPath);
                    }
                    else
                    {
                        // Set the path to use
                        path = currentPath;

                        // Mark it as a container
                        pathIsContainer = true;

                        // Mark whether or not it was provider-qualified
                        pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath;

                        // Mark that we have already found one container. Finding additional
                        // should be an error
                        foundContainer = true;
                    }
                }
            }

            if (pathIsContainer)
            {
                // Remove the root slash since it is implied that the
                // current working directory is relative to the root.

                if (!LocationGlobber.IsProviderDirectPath(path) &&
                    path.StartsWith(StringLiterals.DefaultPathSeparatorString, StringComparison.CurrentCulture) &&
                    !pathIsProviderQualifiedPath)
                {
                    path = path.Substring(1);
                }

                s_tracer.WriteLine(
                    "New working path = {0}",
                    path);

                CurrentDrive.CurrentLocation = path;
            }
            else
            {
                // Set the current working drive back to the previous
                // one in case it was changed.

                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        originalPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // Now make sure the current drive is set in the provider's
            // current working drive hashtable

            ProvidersCurrentWorkingDrive[CurrentDrive.Provider] =
                CurrentDrive;

            // Set the $PWD variable to the new location

            this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal);
            return(this.CurrentLocation);
        } // SetLocation
Beispiel #10
0
		static ConsoleControl()
		{
			ConsoleControl._inputHandle = new Lazy<SafeFileHandle>(() => {
				IntPtr intPtr = ConsoleControl.NativeMethods.CreateFile("CONIN$", -1073741824, 1, (IntPtr)0, 3, 0, (IntPtr)0);
				if (intPtr != ConsoleControl.NativeMethods.INVALID_HANDLE_VALUE)
				{
					return new SafeFileHandle(intPtr, true);
				}
				else
				{
					int lastWin32Error = Marshal.GetLastWin32Error();
					HostException hostException = ConsoleControl.CreateHostException(lastWin32Error, "RetreiveInputConsoleHandle", ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetInputModeExceptionTemplate);
					throw hostException;
				}
			}
			);
			ConsoleControl._outputHandle = new Lazy<SafeFileHandle>(() => {
				IntPtr intPtr = IntPtr.Zero; //ConsoleControl.NativeMethods.CreateFile("CONOUT$", -1073741824, 2, (IntPtr)0, 3, 0, (IntPtr)0);
				//Type t = typeof(System.ConsoleDriver);
				//var fields = t.GetFields (System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static);
				if (intPtr != ConsoleControl.NativeMethods.INVALID_HANDLE_VALUE)
				{
					return new SafeFileHandle(intPtr, true);
				}
				else
				{
					int lastWin32Error = Marshal.GetLastWin32Error();
					HostException hostException = ConsoleControl.CreateHostException(lastWin32Error, "RetreiveActiveScreenBufferConsoleHandle", ErrorCategory.ResourceUnavailable, ConsoleControlStrings.GetActiveScreenBufferHandleExceptionTemplate);
					throw hostException;
				}
			}
			);
			ConsoleControl.tracer = PSTraceSource.GetTracer("ConsoleControl", "Console control methods");
		}
Beispiel #11
0
 internal static void ResetTracer()
 {
     activeTracer = classTracer;
 }
Beispiel #12
0
		static ConsoleHost()
		{
			ConsoleHost.tracer = PSTraceSource.GetTracer("ConsoleHost", "ConsoleHost subclass of S.M.A.PSHost");
			ConsoleHost.runspaceInitTracer = PSTraceSource.GetTracer("ConsoleHostRunspaceInit", "Initialization code for ConsoleHost's Runspace", false);
		}
        /// <summary>
        /// Load help file provided.
        /// </summary>
        /// <remarks>
        /// This will load providerHelpInfo from help file into help cache.
        /// </remarks>
        /// <param name="providerInfo">ProviderInfo for which to locate help.</param>
        private void LoadHelpFile(ProviderInfo providerInfo)
        {
            if (providerInfo == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(providerInfo));
            }

            string helpFile = providerInfo.HelpFile;

            if (string.IsNullOrEmpty(helpFile) || _helpFiles.Contains(helpFile))
            {
                return;
            }

            string helpFileToLoad = helpFile;

            // Get the mshsnapinfo object for this cmdlet.
            PSSnapInInfo mshSnapInInfo = providerInfo.PSSnapIn;

            // Search fallback
            // 1. If PSSnapInInfo exists, then always look in the application base
            //    of the mshsnapin
            // Otherwise,
            //    Look in the default search path and cmdlet assembly path
            Collection <string> searchPaths = new Collection <string>();

            if (mshSnapInInfo != null)
            {
                Diagnostics.Assert(!string.IsNullOrEmpty(mshSnapInInfo.ApplicationBase),
                                   "Application Base is null or empty.");
                // not minishell case..
                // we have to search only in the application base for a mshsnapin...
                // if you create an absolute path for helpfile, then MUIFileSearcher
                // will look only in that path.
                helpFileToLoad = Path.Combine(mshSnapInInfo.ApplicationBase, helpFile);
            }
            else if ((providerInfo.Module != null) && (!string.IsNullOrEmpty(providerInfo.Module.Path)))
            {
                helpFileToLoad = Path.Combine(providerInfo.Module.ModuleBase, helpFile);
            }
            else
            {
                searchPaths.Add(GetDefaultShellSearchPath());
                searchPaths.Add(GetProviderAssemblyPath(providerInfo));
            }

            string location = MUIFileSearcher.LocateFile(helpFileToLoad, searchPaths);

            if (string.IsNullOrEmpty(location))
            {
                throw new FileNotFoundException(helpFile);
            }

            XmlDocument doc = InternalDeserializer.LoadUnsafeXmlDocument(
                new FileInfo(location),
                false, /* ignore whitespace, comments, etc. */
                null); /* default maxCharactersInDocument */

            // Add this file into _helpFiles hashtable to prevent it to be loaded again.
            _helpFiles[helpFile] = 0;

            XmlNode helpItemsNode = null;

            if (doc.HasChildNodes)
            {
                for (int i = 0; i < doc.ChildNodes.Count; i++)
                {
                    XmlNode node = doc.ChildNodes[i];
                    if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "helpItems", StringComparison.OrdinalIgnoreCase))
                    {
                        helpItemsNode = node;
                        break;
                    }
                }
            }

            if (helpItemsNode == null)
            {
                return;
            }

            using (this.HelpSystem.Trace(location))
            {
                if (helpItemsNode.HasChildNodes)
                {
                    for (int i = 0; i < helpItemsNode.ChildNodes.Count; i++)
                    {
                        XmlNode node = helpItemsNode.ChildNodes[i];
                        if (node.NodeType == XmlNodeType.Element && string.Equals(node.Name, "providerHelp", StringComparison.OrdinalIgnoreCase))
                        {
                            HelpInfo helpInfo = ProviderHelpInfo.Load(node);

                            if (helpInfo != null)
                            {
                                this.HelpSystem.TraceErrors(helpInfo.Errors);
                                // Add snapin qualified type name for this command..
                                // this will enable customizations of the help object.
                                helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture,
                                                                                    "ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name));

                                if (!string.IsNullOrEmpty(providerInfo.PSSnapInName))
                                {
                                    helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn));
                                    helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture,
                                                                                        "ProviderHelpInfo#{0}", providerInfo.PSSnapInName));
                                }

                                AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo);
                            }
                        }
                    }
                }
            }
        }
Beispiel #14
0
        /// <summary>
        /// Unescapes any escaped characters in the input string.
        /// </summary>
        /// <param name="pattern">
        /// The input string containing the text to convert.
        /// </param>
        /// <returns>
        /// A string of characters with any escaped characters
        /// converted to their unescaped form.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="pattern" /> is null.
        /// </exception>
        public static string Unescape(string pattern)
        {
            if (pattern == null)
            {
                throw PSTraceSource.NewArgumentNullException("pattern");
            }

            char[] temp                  = new char[pattern.Length];
            int    tempIndex             = 0;
            bool   prevCharWasEscapeChar = false;

            for (int i = 0; i < pattern.Length; i++)
            {
                char ch = pattern[i];

                if (ch == escapeChar)
                {
                    if (prevCharWasEscapeChar)
                    {
                        temp[tempIndex++]     = ch;
                        prevCharWasEscapeChar = false;
                    }
                    else
                    {
                        prevCharWasEscapeChar = true;
                    }

                    continue;
                }

                if (prevCharWasEscapeChar)
                {
                    if (!IsWildcardChar(ch))
                    {
                        temp[tempIndex++] = escapeChar;
                    }
                }

                temp[tempIndex++]     = ch;
                prevCharWasEscapeChar = false;
            }

            // Need to account for a trailing escape character as a real
            // character

            if (prevCharWasEscapeChar)
            {
                temp[tempIndex++]     = escapeChar;
                prevCharWasEscapeChar = false;
            }

            string s = null;

            if (tempIndex > 0)
            {
                s = new string(temp, 0, tempIndex);
            }
            else
            {
                s = string.Empty;
            }

            return(s);
        }
Beispiel #15
0
        internal virtual bool BindParameter(CommandParameterInternal parameter, CompiledCommandParameter parameterMetadata, ParameterBindingFlags flags)
        {
            bool flag  = false;
            bool flag2 = (flags & ParameterBindingFlags.ShouldCoerceType) != ParameterBindingFlags.None;

            if (parameter == null)
            {
                throw PSTraceSource.NewArgumentNullException("parameter");
            }
            if (parameterMetadata == null)
            {
                throw PSTraceSource.NewArgumentNullException("parameterMetadata");
            }
            using (bindingTracer.TraceScope("BIND arg [{0}] to parameter [{1}]", new object[] { parameter.ArgumentValue, parameterMetadata.Name }))
            {
                parameter.ParameterName = parameterMetadata.Name;
                object argumentValue         = parameter.ArgumentValue;
                ScriptParameterBinder binder = this as ScriptParameterBinder;
                bool bindingScriptCmdlet     = false;
                if (binder != null)
                {
                    bindingScriptCmdlet = binder.Script.UsesCmdletBinding;
                }
                foreach (ArgumentTransformationAttribute attribute in parameterMetadata.ArgumentTransformationAttributes)
                {
                    using (bindingTracer.TraceScope("Executing DATA GENERATION metadata: [{0}]", new object[] { attribute.GetType() }))
                    {
                        try
                        {
                            ArgumentTypeConverterAttribute attribute2 = attribute as ArgumentTypeConverterAttribute;
                            if (attribute2 != null)
                            {
                                if (flag2)
                                {
                                    argumentValue = attribute2.Transform(this.engine, argumentValue, true, bindingScriptCmdlet);
                                }
                            }
                            else
                            {
                                argumentValue = attribute.Transform(this.engine, argumentValue);
                            }
                            bindingTracer.WriteLine("result returned from DATA GENERATION: {0}", new object[] { argumentValue });
                        }
                        catch (Exception exception)
                        {
                            CommandProcessorBase.CheckForSevereException(exception);
                            bindingTracer.WriteLine("ERROR: DATA GENERATION: {0}", new object[] { exception.Message });
                            ParameterBindingException exception2 = new ParameterBindingArgumentTransformationException(exception, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentTransformationError", new object[] { exception.Message });
                            throw exception2;
                        }
                    }
                }
                if (flag2)
                {
                    argumentValue = this.CoerceTypeAsNeeded(parameter, parameterMetadata.Name, parameterMetadata.Type, parameterMetadata.CollectionTypeInformation, argumentValue);
                }
                else if (!this.ShouldContinueUncoercedBind(parameter, parameterMetadata, flags, ref argumentValue))
                {
                    goto Label_040E;
                }
                if ((parameterMetadata.PSTypeName != null) && (argumentValue != null))
                {
                    IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue);
                    if (enumerable != null)
                    {
                        foreach (object obj3 in enumerable)
                        {
                            this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, obj3);
                        }
                    }
                    else
                    {
                        this.ValidatePSTypeName(parameter, parameterMetadata, !flag2, argumentValue);
                    }
                }
                if ((flags & ParameterBindingFlags.IsDefaultValue) == ParameterBindingFlags.None)
                {
                    foreach (ValidateArgumentsAttribute attribute3 in parameterMetadata.ValidationAttributes)
                    {
                        using (bindingTracer.TraceScope("Executing VALIDATION metadata: [{0}]", new object[] { attribute3.GetType() }))
                        {
                            try
                            {
                                attribute3.InternalValidate(argumentValue, this.engine);
                            }
                            catch (Exception exception3)
                            {
                                CommandProcessorBase.CheckForSevereException(exception3);
                                bindingTracer.WriteLine("ERROR: VALIDATION FAILED: {0}", new object[] { exception3.Message });
                                ParameterBindingValidationException exception4 = new ParameterBindingValidationException(exception3, ErrorCategory.InvalidData, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, (argumentValue == null) ? null : argumentValue.GetType(), "ParameterBinderStrings", "ParameterArgumentValidationError", new object[] { exception3.Message });
                                throw exception4;
                            }
                            tracer.WriteLine("Validation attribute on {0} returned {1}.", new object[] { parameterMetadata.Name, flag });
                        }
                    }
                    if (IsParameterMandatory(parameterMetadata))
                    {
                        this.ValidateNullOrEmptyArgument(parameter, parameterMetadata, parameterMetadata.Type, argumentValue, true);
                    }
                }
                Exception innerException = null;
                try
                {
                    this.BindParameter(parameter.ParameterName, argumentValue);
                    flag = true;
                }
                catch (SetValueException exception6)
                {
                    innerException = exception6;
                }
                if (innerException != null)
                {
                    Type typeSpecified = (argumentValue == null) ? null : argumentValue.GetType();
                    ParameterBindingException exception7 = new ParameterBindingException(innerException, ErrorCategory.WriteError, this.InvocationInfo, this.GetErrorExtent(parameter), parameterMetadata.Name, parameterMetadata.Type, typeSpecified, "ParameterBinderStrings", "ParameterBindingFailed", new object[] { innerException.Message });
                    throw exception7;
                }
                Label_040E :;
                bindingTracer.WriteLine("BIND arg [{0}] to param [{1}] {2}", new object[] { argumentValue, parameter.ParameterName, flag ? "SUCCESSFUL" : "SKIPPED" });
                if (flag)
                {
                    if (this.RecordBoundParameters)
                    {
                        this.CommandLineParameters.Add(parameter.ParameterName, argumentValue);
                    }
                    MshCommandRuntime commandRuntime = this.Command.commandRuntime as MshCommandRuntime;
                    if ((commandRuntime != null) && commandRuntime.LogPipelineExecutionDetail)
                    {
                        IEnumerable source = LanguagePrimitives.GetEnumerable(argumentValue);
                        if (source != null)
                        {
                            string parameterValue = string.Join(", ", source.Cast <object>().ToArray <object>());
                            commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, parameterValue);
                        }
                        else
                        {
                            commandRuntime.PipelineProcessor.LogExecutionParameterBinding(this.InvocationInfo, parameter.ParameterName, (argumentValue == null) ? "" : argumentValue.ToString());
                        }
                    }
                }
                return(flag);
            }
        }
Beispiel #16
0
        private object CoerceTypeAsNeeded(CommandParameterInternal argument, string parameterName, Type toType, ParameterCollectionTypeInformation collectionTypeInfo, object currentValue)
        {
            if (argument == null)
            {
                throw PSTraceSource.NewArgumentNullException("argument");
            }
            if (toType == null)
            {
                throw PSTraceSource.NewArgumentNullException("toType");
            }
            if (collectionTypeInfo == null)
            {
                collectionTypeInfo = new ParameterCollectionTypeInformation(toType);
            }
            object result = currentValue;

            using (bindingTracer.TraceScope("COERCE arg to [{0}]", new object[] { toType }))
            {
                Type c = null;
                try
                {
                    if (IsNullParameterValue(currentValue))
                    {
                        return(this.HandleNullParameterForSpecialTypes(argument, parameterName, toType, currentValue));
                    }
                    c = currentValue.GetType();
                    if (toType.IsAssignableFrom(c))
                    {
                        bindingTracer.WriteLine("Parameter and arg types the same, no coercion is needed.", new object[0]);
                        return(currentValue);
                    }
                    bindingTracer.WriteLine("Trying to convert argument value from {0} to {1}", new object[] { c, toType });
                    if (toType == typeof(PSObject))
                    {
                        if ((this.command != null) && (currentValue == this.command.CurrentPipelineObject.BaseObject))
                        {
                            currentValue = this.command.CurrentPipelineObject;
                        }
                        bindingTracer.WriteLine("The parameter is of type [{0}] and the argument is an PSObject, so the parameter value is the argument value wrapped into an PSObject.", new object[] { toType });
                        return(LanguagePrimitives.AsPSObjectOrNull(currentValue));
                    }
                    if ((toType == typeof(string)) && (c == typeof(PSObject)))
                    {
                        PSObject obj3 = (PSObject)currentValue;
                        if (obj3 == AutomationNull.Value)
                        {
                            bindingTracer.WriteLine("CONVERT a null PSObject to a null string.", new object[0]);
                            return(null);
                        }
                    }
                    if (((toType == typeof(bool)) || (toType == typeof(SwitchParameter))) || (toType == typeof(bool?)))
                    {
                        Type type = null;
                        if (c == typeof(PSObject))
                        {
                            PSObject obj4 = (PSObject)currentValue;
                            currentValue = obj4.BaseObject;
                            if (currentValue is SwitchParameter)
                            {
                                SwitchParameter parameter = (SwitchParameter)currentValue;
                                currentValue = parameter.IsPresent;
                            }
                            type = currentValue.GetType();
                        }
                        else
                        {
                            type = c;
                        }
                        if (type == typeof(bool))
                        {
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject((bool)currentValue));
                            }
                            return(new SwitchParameter((bool)currentValue));
                        }
                        if (type == typeof(int))
                        {
                            if (((int)LanguagePrimitives.ConvertTo(currentValue, typeof(int), CultureInfo.InvariantCulture)) != 0)
                            {
                                if (LanguagePrimitives.IsBooleanType(toType))
                                {
                                    return(ParserOps.BoolToObject(true));
                                }
                                return(new SwitchParameter(true));
                            }
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject(false));
                            }
                            return(new SwitchParameter(false));
                        }
                        if (LanguagePrimitives.IsNumeric(Type.GetTypeCode(type)))
                        {
                            double num = (double)LanguagePrimitives.ConvertTo(currentValue, typeof(double), CultureInfo.InvariantCulture);
                            if (num == 0.0)
                            {
                                if (LanguagePrimitives.IsBooleanType(toType))
                                {
                                    return(ParserOps.BoolToObject(false));
                                }
                                return(new SwitchParameter(false));
                            }
                            if (LanguagePrimitives.IsBooleanType(toType))
                            {
                                return(ParserOps.BoolToObject(true));
                            }
                            return(new SwitchParameter(true));
                        }
                        ParameterBindingException exception = new ParameterBindingException(ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { type, "" });
                        throw exception;
                    }
                    if ((collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.ICollectionGeneric) || (collectionTypeInfo.ParameterCollectionType == ParameterCollectionType.IList))
                    {
                        object obj5 = PSObject.Base(currentValue);
                        if (obj5 != null)
                        {
                            ConversionRank conversionRank = LanguagePrimitives.GetConversionRank(obj5.GetType(), toType);
                            if ((((conversionRank == ConversionRank.Constructor) || (conversionRank == ConversionRank.ImplicitCast)) || (conversionRank == ConversionRank.ExplicitCast)) && LanguagePrimitives.TryConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture, out result))
                            {
                                return(result);
                            }
                        }
                    }
                    if (collectionTypeInfo.ParameterCollectionType != ParameterCollectionType.NotCollection)
                    {
                        bindingTracer.WriteLine("ENCODING arg into collection", new object[0]);
                        bool coercionRequired = false;
                        return(this.EncodeCollection(argument, parameterName, collectionTypeInfo, toType, currentValue, collectionTypeInfo.ElementType != null, out coercionRequired));
                    }
                    if (((((GetIList(currentValue) != null) && (toType != typeof(object))) && ((toType != typeof(PSObject)) && (toType != typeof(PSListModifier)))) && ((!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(PSListModifier <>))) && (!toType.IsGenericType || (toType.GetGenericTypeDefinition() != typeof(FlagsExpression <>))))) && !toType.IsEnum)
                    {
                        throw new NotSupportedException();
                    }
                    bindingTracer.WriteLine("CONVERT arg type to param type using LanguagePrimitives.ConvertTo", new object[0]);
                    bool flag2 = false;
                    if (this.context.LanguageMode == PSLanguageMode.ConstrainedLanguage)
                    {
                        object obj6  = PSObject.Base(currentValue);
                        bool   flag3 = obj6 is PSObject;
                        bool   flag4 = (obj6 != null) && typeof(IDictionary).IsAssignableFrom(obj6.GetType());
                        flag2 = ((((PSLanguageMode)this.Command.CommandInfo.DefiningLanguageMode) == PSLanguageMode.FullLanguage) && !flag3) && !flag4;
                    }
                    try
                    {
                        if (flag2)
                        {
                            this.context.LanguageMode = PSLanguageMode.FullLanguage;
                        }
                        result = LanguagePrimitives.ConvertTo(currentValue, toType, Thread.CurrentThread.CurrentCulture);
                    }
                    finally
                    {
                        if (flag2)
                        {
                            this.context.LanguageMode = PSLanguageMode.ConstrainedLanguage;
                        }
                    }
                    bindingTracer.WriteLine("CONVERT SUCCESSFUL using LanguagePrimitives.ConvertTo: [{0}]", new object[] { (result == null) ? "null" : result.ToString() });
                    return(result);
                }
                catch (NotSupportedException exception2)
                {
                    bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", new object[] { (result == null) ? "null" : result, toType });
                    ParameterBindingException exception3 = new ParameterBindingException(exception2, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgument", new object[] { (result == null) ? "null" : result, exception2.Message });
                    throw exception3;
                }
                catch (PSInvalidCastException exception4)
                {
                    object[] args = new object[] { result ?? "null", toType };
                    bindingTracer.TraceError("ERROR: COERCE FAILED: arg [{0}] could not be converted to the parameter type [{1}]", args);
                    ParameterBindingException exception5 = new ParameterBindingException(exception4, ErrorCategory.InvalidArgument, this.InvocationInfo, this.GetErrorExtent(argument), parameterName, toType, c, "ParameterBinderStrings", "CannotConvertArgumentNoMessage", new object[] { exception4.Message });
                    throw exception5;
                }
            }
            return(result);
        }
Beispiel #17
0
        internal static Signature SignFile(SigningOption option,
                                           string fileName,
                                           X509Certificate2 certificate,
                                           string timeStampServerUrl,
                                           string hashAlgorithm)
        {
            bool      result    = false;
            Signature signature = null;
            IntPtr    pSignInfo = IntPtr.Zero;
            DWORD     error     = 0;
            string    hashOid   = null;

            Utils.CheckArgForNullOrEmpty(fileName, "fileName");
            Utils.CheckArgForNull(certificate, "certificate");

            // If given, TimeStamp server URLs must begin with http://
            if (!String.IsNullOrEmpty(timeStampServerUrl))
            {
                if ((timeStampServerUrl.Length <= 7) ||
                    (timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0))
                {
                    throw PSTraceSource.NewArgumentException(
                              "certificate",
                              Authenticode.TimeStampUrlRequired);
                }
            }

            // Validate that the hash algorithm is valid
            if (!String.IsNullOrEmpty(hashAlgorithm))
            {
                IntPtr intptrAlgorithm = Marshal.StringToHGlobalUni(hashAlgorithm);

                IntPtr oidPtr = NativeMethods.CryptFindOIDInfo(NativeConstants.CRYPT_OID_INFO_NAME_KEY,
                                                               intptrAlgorithm,
                                                               0);

                // If we couldn't find an OID for the hash
                // algorithm, it was invalid.
                if (oidPtr == IntPtr.Zero)
                {
                    throw PSTraceSource.NewArgumentException(
                              "certificate",
                              Authenticode.InvalidHashAlgorithm);
                }
                else
                {
                    NativeMethods.CRYPT_OID_INFO oidInfo =
                        Marshal.PtrToStructure <NativeMethods.CRYPT_OID_INFO>(oidPtr);

                    hashOid = oidInfo.pszOID;
                }
            }

            if (!SecuritySupport.CertIsGoodForSigning(certificate))
            {
                throw PSTraceSource.NewArgumentException(
                          "certificate",
                          Authenticode.CertNotGoodForSigning);
            }

            SecuritySupport.CheckIfFileExists(fileName);
            //SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName);

            try
            {
                // CryptUI is not documented either way, but does not
                // support empty strings for the timestamp server URL.
                // It expects null, only.  Instead, it randomly AVs if you
                // try.
                string timeStampServerUrlForCryptUI = null;
                if (!String.IsNullOrEmpty(timeStampServerUrl))
                {
                    timeStampServerUrlForCryptUI = timeStampServerUrl;
                }

                //
                // first initialize the struct to pass to
                // CryptUIWizDigitalSign() function
                //
                NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO si = NativeMethods.InitSignInfoStruct(fileName,
                                                                                                  certificate,
                                                                                                  timeStampServerUrlForCryptUI,
                                                                                                  hashOid,
                                                                                                  option);

                pSignInfo = Marshal.AllocCoTaskMem(Marshal.SizeOf(si));
                Marshal.StructureToPtr(si, pSignInfo, false);

                //
                // sign the file
                //
                // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be
                // able to see that.
#pragma warning disable 56523
                result = NativeMethods.CryptUIWizDigitalSign(
                    (DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI,
                    IntPtr.Zero,
                    IntPtr.Zero,
                    pSignInfo,
                    IntPtr.Zero);
#pragma warning enable 56523

                if (si.pSignExtInfo != null)
                {
                    Marshal.DestroyStructure <NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO>(si.pSignExtInfo);
                    Marshal.FreeCoTaskMem(si.pSignExtInfo);
                }

                if (!result)
                {
                    error = GetLastWin32Error();

                    //
                    // ISSUE-2004/05/08-kumarp : there seems to be a bug
                    // in CryptUIWizDigitalSign().
                    // It returns 80004005 or 80070001
                    // but it signs the file correctly. Mask this error
                    // till we figure out this odd behavior.
                    //
                    if ((error == 0x80004005) ||
                        (error == 0x80070001) ||

                        // CryptUIWizDigitalSign introduced a breaking change in Win8 to return this
                        // error code (ERROR_INTERNET_NAME_NOT_RESOLVED) when you provide an invalid
                        // timestamp server. It used to be 0x80070001.
                        // Also masking this out so that we don't introduce a breaking change ourselves.
                        (error == 0x80072EE7)
                        )
                    {
                        result = true;
                    }
                    else
                    {
                        if (error == Win32Errors.NTE_BAD_ALGID)
                        {
                            throw PSTraceSource.NewArgumentException(
                                      "certificate",
                                      Authenticode.InvalidHashAlgorithm);
                        }

                        s_tracer.TraceError("CryptUIWizDigitalSign: failed: {0:x}",
                                            error);
                    }
                }

                if (result)
                {
                    signature = GetSignature(fileName, null);
                }
                else
                {
                    signature = new Signature(fileName, (DWORD)error);
                }
            }
            finally
            {
                Marshal.DestroyStructure <NativeMethods.CRYPTUI_WIZ_DIGITAL_SIGN_INFO>(pSignInfo);
                Marshal.FreeCoTaskMem(pSignInfo);
            }

            return(signature);
        }
Beispiel #18
0
        /// <summary>
        /// Unescapes any escaped characters in the input string.
        /// </summary>
        /// <param name="pattern">
        /// The input string containing the text to convert.
        /// </param>
        /// <returns>
        /// A string of characters with any escaped characters
        /// converted to their unescaped form.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="pattern" /> is null.
        /// </exception>
        public static string Unescape(string pattern)
        {
            if (pattern == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(pattern));
            }

            if (pattern == string.Empty)
            {
                return(pattern);
            }

            Span <char> temp = pattern.Length < StackAllocThreshold ? stackalloc char[pattern.Length] : new char[pattern.Length];

            int  tempIndex             = 0;
            bool prevCharWasEscapeChar = false;

            for (int i = 0; i < pattern.Length; i++)
            {
                char ch = pattern[i];

                if (ch == escapeChar)
                {
                    if (prevCharWasEscapeChar)
                    {
                        temp[tempIndex++]     = ch;
                        prevCharWasEscapeChar = false;
                    }
                    else
                    {
                        prevCharWasEscapeChar = true;
                    }

                    continue;
                }

                if (prevCharWasEscapeChar)
                {
                    if (!IsWildcardChar(ch))
                    {
                        temp[tempIndex++] = escapeChar;
                    }
                }

                temp[tempIndex++]     = ch;
                prevCharWasEscapeChar = false;
            }

            // Need to account for a trailing escape character as a real
            // character

            if (prevCharWasEscapeChar)
            {
                temp[tempIndex++]     = escapeChar;
                prevCharWasEscapeChar = false;
            }

            string s = null;

            if (tempIndex == pattern.Length)
            {
                s = pattern;
            }
            else
            {
                s = new string(temp.Slice(0, tempIndex));
            }

            return(s);
        }
        /// <summary>
        /// Process the data received from the runspace pool on
        /// the server.
        /// </summary>
        /// <param name="receivedData">Data received.</param>
        internal void ProcessReceivedData(RemoteDataObject <PSObject> receivedData)
        {
            if (receivedData == null)
            {
                throw PSTraceSource.NewArgumentNullException("receivedData");
            }

            Dbg.Assert(receivedData.TargetInterface == RemotingTargetInterface.RunspacePool,
                       "RemotingTargetInterface must be Runspace");

            switch (receivedData.DataType)
            {
            case RemotingDataType.CreatePowerShell:
            {
                Dbg.Assert(CreateAndInvokePowerShell != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events");

                CreateAndInvokePowerShell.SafeInvoke(this, new RemoteDataEventArgs <RemoteDataObject <PSObject> >(receivedData));
            }

            break;

            case RemotingDataType.GetCommandMetadata:
            {
                Dbg.Assert(GetCommandMetadata != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events");

                GetCommandMetadata.SafeInvoke(this, new RemoteDataEventArgs <RemoteDataObject <PSObject> >(receivedData));
            }

            break;

            case RemotingDataType.RemoteRunspaceHostResponseData:
            {
                Dbg.Assert(HostResponseReceived != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events");

                RemoteHostResponse remoteHostResponse = RemoteHostResponse.Decode(receivedData.Data);

                // part of host message robustness algo. Now the host response is back, report to transport that
                // execution status is back to running
                _transportManager.ReportExecutionStatusAsRunning();

                HostResponseReceived.SafeInvoke(this, new RemoteDataEventArgs <RemoteHostResponse>(remoteHostResponse));
            }

            break;

            case RemotingDataType.SetMaxRunspaces:
            {
                Dbg.Assert(SetMaxRunspacesReceived != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events");

                SetMaxRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs <PSObject>(receivedData.Data));
            }

            break;

            case RemotingDataType.SetMinRunspaces:
            {
                Dbg.Assert(SetMinRunspacesReceived != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events");

                SetMinRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs <PSObject>(receivedData.Data));
            }

            break;

            case RemotingDataType.AvailableRunspaces:
            {
                Dbg.Assert(GetAvailableRunspacesReceived != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events");

                GetAvailableRunspacesReceived.SafeInvoke(this, new RemoteDataEventArgs <PSObject>(receivedData.Data));
            }

            break;

            case RemotingDataType.ResetRunspaceState:
            {
                Dbg.Assert(ResetRunspaceState != null,
                           "The ServerRunspacePoolDriver should subscribe to all data structure handler events.");

                ResetRunspaceState.SafeInvoke(this, new RemoteDataEventArgs <PSObject>(receivedData.Data));
            }

            break;
            }
        }
Beispiel #20
0
 internal ScopeTracer(PSTraceSource tracer, PSTraceSourceOptions flag, string scopeOutputFormatter, string leavingScopeFormatter, string scopeName)
 {
     this._tracer = tracer;
     this.ScopeTracerHelper(flag, scopeOutputFormatter, leavingScopeFormatter, scopeName, "", new object[0]);
 }
Beispiel #21
0
        /// <summary>
        /// Constructor that traces the scope name
        /// and raises the indent level in thread
        /// local storage.
        /// </summary>
        /// 
        /// <param name="tracer">
        /// The trace object that is to be used for output
        /// </param>
        /// 
        /// <param name="flag">
        /// The PSTraceSourceOptions that is causing the scope object to 
        /// be created.
        /// </param>
        /// 
        /// <param name="scopeOutputFormatter">
        /// This format string is used to determine the
        /// general output format for the scope. For instance,
        /// TraceMethod would probably provide a formatter similar
        /// to "Entering: {0}: {1}" where {0} is the name of the
        /// method and {1} is the additional formatted info provided.
        /// </param>
        /// 
        /// <param name="leavingScopeFormatter">
        /// The format string used to determine the general output
        /// format for the scope when the Dispose method is called.
        /// </param>
        /// 
        /// <param name="scopeName">
        /// The name of the scope that is being traced
        /// </param>
        /// 
        internal ScopeTracer(
            PSTraceSource tracer,
            PSTraceSourceOptions flag,
            string scopeOutputFormatter,
            string leavingScopeFormatter,
            string scopeName)
        {
            _tracer = tracer;

            // Call the helper

            ScopeTracerHelper(
                flag,
                scopeOutputFormatter,
                leavingScopeFormatter,
                scopeName,
                "");
        }
Beispiel #22
0
        /// <summary>
        /// Constructs an instance of the CompiledCommandAttribute using the reflection information retrieved
        /// from the enclosing bindable object type.
        /// </summary>
        /// <param name="member">
        /// The member information for the parameter
        /// </param>
        /// <param name="processingDynamicParameters">
        /// True if dynamic parameters are being processed, or false otherwise.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="member"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="member"/> is not a field or a property.
        /// </exception>
        /// <exception cref="MetadataException">
        /// If the member has more than one <see cref="ParameterAttribute">ParameterAttribute</see>
        /// that defines the same parameter-set name.
        /// </exception>
        internal CompiledCommandParameter(MemberInfo member, bool processingDynamicParameters)
        {
            if (member == null)
            {
                throw PSTraceSource.NewArgumentNullException("member");
            }

            this.Name          = member.Name;
            this.DeclaringType = member.DeclaringType;
            this.IsDynamic     = processingDynamicParameters;

            var propertyInfo = member as PropertyInfo;

            if (propertyInfo != null)
            {
                this.Type = propertyInfo.PropertyType;
            }
            else
            {
                var fieldInfo = member as FieldInfo;
                if (fieldInfo != null)
                {
                    this.Type = fieldInfo.FieldType;
                }
                else
                {
                    ArgumentException e =
                        PSTraceSource.NewArgumentException(
                            "member",
                            DiscoveryExceptions.CompiledCommandParameterMemberMustBeFieldOrProperty);

                    throw e;
                }
            }

            this.CollectionTypeInformation = new ParameterCollectionTypeInformation(this.Type);
            this.CompiledAttributes        = new Collection <Attribute>();
            this.ParameterSetData          = new Dictionary <string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase);

            // We do not want to get the inherited custom attributes, only the attributes exposed
            // directly on the member

            var memberAttributes = member.GetCustomAttributes(false);

            Collection <ValidateArgumentsAttribute>      validationAttributes        = null;
            Collection <ArgumentTransformationAttribute> argTransformationAttributes = null;

            string[] aliases = null;

            foreach (Attribute attr in memberAttributes)
            {
                switch (attr)
                {
                case ExperimentalAttribute _:
                case ParameterAttribute param when param.ToHide:
                    break;

                default:
                    ProcessAttribute(member.Name, attr, ref validationAttributes, ref argTransformationAttributes, ref aliases);
                    break;
                }
            }

            this.ValidationAttributes = validationAttributes == null
                ? Utils.EmptyArray <ValidateArgumentsAttribute>()
                : validationAttributes.ToArray();

            this.ArgumentTransformationAttributes = argTransformationAttributes == null
                ? Utils.EmptyArray <ArgumentTransformationAttribute>()
                : argTransformationAttributes.ToArray();

            this.Aliases = aliases ?? Utils.EmptyArray <string>();
        }
        /// <summary>
        /// A helper to get an instance of the PSTraceSource class.
        /// </summary>
        /// <param name="name">
        /// The name of the category that this class
        /// will control the tracing for.
        /// </param>
        /// <param name="description">
        /// The description to describe what the category
        /// is used for.
        /// </param>
        /// <param name="traceHeaders">
        /// If true, the line headers will be traced, if false, only the trace message will be traced.
        /// </param>
        /// <returns>
        /// An instance of the PSTraceSource class which is initialized
        /// to trace for the specified category. If multiple callers ask for the same category,
        /// the same PSTraceSource will be returned.
        /// </returns>
        internal static PSTraceSource GetTracer(
            string name,
            string description,
            bool traceHeaders)
        {
            if (string.IsNullOrEmpty(name))
            {
                // 2005/04/13-JonN In theory this should be ArgumentException,
                // but I don't want to deal with loading the string in this
                // low-level code.
                throw new ArgumentNullException(nameof(name));
            }

            lock (PSTraceSource.s_getTracerLock)
            {
                PSTraceSource result = null;

                // See if we can find an PSTraceSource for this category in the catalog.
                PSTraceSource.TraceCatalog.TryGetValue(name, out result);

                // If it's not already in the catalog, see if we can find it in the
                // pre-configured trace source list

                if (result is null)
                {
                    string keyName = name;
                    if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(keyName))
                    {
                        if (keyName.Length > 16)
                        {
                            keyName = keyName.Substring(0, 16);
                            if (!PSTraceSource.PreConfiguredTraceSource.ContainsKey(keyName))
                            {
                                keyName = null;
                            }
                        }
                        else
                        {
                            keyName = null;
                        }
                    }

                    if (keyName != null)
                    {
                        // Get the pre-configured trace source from the catalog
                        PSTraceSource preconfiguredSource = PSTraceSource.PreConfiguredTraceSource[keyName];

                        result         = PSTraceSource.GetNewTraceSource(keyName, description, traceHeaders);
                        result.Options = preconfiguredSource.Options;
                        result.Listeners.Clear();
                        result.Listeners.AddRange(preconfiguredSource.Listeners);

                        // Add it to the TraceCatalog
                        PSTraceSource.TraceCatalog.Add(keyName, result);

                        // Remove it from the pre-configured catalog
                        PSTraceSource.PreConfiguredTraceSource.Remove(keyName);
                    }
                }

                // Even if there was a PSTraceSource in the catalog, let's replace
                // it with an PSTraceSource to get the added functionality. Anyone using
                // a StructuredTraceSource should be able to do so even with the PSTraceSource
                // instance.

                if (result is null)
                {
                    result = PSTraceSource.GetNewTraceSource(name, description, traceHeaders);
                    PSTraceSource.TraceCatalog[result.FullName] = result;
                }

                if (result.Options != PSTraceSourceOptions.None &&
                    traceHeaders)
                {
                    result.TraceGlobalAppDomainHeader();

                    // Trace the object specific tracer information
                    result.TracerObjectHeader(Assembly.GetCallingAssembly());
                }

                return(result);
            }
        }
Beispiel #24
0
        private Collection <PSObject> InvokeScript(ScriptBlock sb, bool useNewScope,
                                                   PipelineResultTypes writeToPipeline, IList input, params object[] args)
        {
            if (_cmdlet != null)
            {
                _cmdlet.ThrowIfStopping();
            }

            Cmdlet cmdletToUse = null;

            ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe;

            // Check if they want output
            if ((writeToPipeline & PipelineResultTypes.Output) == PipelineResultTypes.Output)
            {
                cmdletToUse      = _cmdlet;
                writeToPipeline &= (~PipelineResultTypes.Output);
            }

            // Check if they want error
            if ((writeToPipeline & PipelineResultTypes.Error) == PipelineResultTypes.Error)
            {
                errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe;
                writeToPipeline      &= (~PipelineResultTypes.Error);
            }

            if (writeToPipeline != PipelineResultTypes.None)
            {
                // The only output types are Output and Error.
                throw PSTraceSource.NewNotImplementedException();
            }

            // If the cmdletToUse is not null, then the result of the evaluation will be
            // streamed out the output pipe of the cmdlet.
            object rawResult;

            if (cmdletToUse != null)
            {
                sb.InvokeUsingCmdlet(
                    contextCmdlet: cmdletToUse,
                    useLocalScope: useNewScope,
                    errorHandlingBehavior: errorHandlingBehavior,
                    dollarUnder: AutomationNull.Value,
                    input: input,
                    scriptThis: AutomationNull.Value,
                    args: args);
                rawResult = AutomationNull.Value;
            }
            else
            {
                rawResult = sb.DoInvokeReturnAsIs(
                    useLocalScope: useNewScope,
                    errorHandlingBehavior: errorHandlingBehavior,
                    dollarUnder: AutomationNull.Value,
                    input: input,
                    scriptThis: AutomationNull.Value,
                    args: args);
            }

            if (rawResult == AutomationNull.Value)
            {
                return(new Collection <PSObject>());
            }

            // If the result is already a collection of PSObjects, just return it...
            Collection <PSObject> result = rawResult as Collection <PSObject>;

            if (result != null)
            {
                return(result);
            }

            result = new Collection <PSObject>();

            IEnumerator list = null;

            list = LanguagePrimitives.GetEnumerator(rawResult);

            if (list != null)
            {
                while (list.MoveNext())
                {
                    object val = list.Current;

                    result.Add(LanguagePrimitives.AsPSObjectOrNull(val));
                }
            }
            else
            {
                result.Add(LanguagePrimitives.AsPSObjectOrNull(rawResult));
            }

            return(result);
        }
        /// <summary>
        /// Gets the parameters by matching its name.
        /// </summary>
        /// <param name="name">
        /// The name of the parameter.
        /// </param>
        /// <param name="throwOnParameterNotFound">
        /// If true and a matching parameter is not found, an exception will be
        /// throw. If false and a matching parameter is not found, null is returned.
        /// </param>
        /// <param name="tryExactMatching">
        /// If true we do exact matching, otherwise we do not.
        /// </param>
        /// <param name="invocationInfo">
        /// The invocation information about the code being run.
        /// </param>
        /// <returns>
        /// The a collection of the metadata associated with the parameters that
        /// match the specified name. If no matches were found, an empty collection
        /// is returned.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        internal MergedCompiledCommandParameter GetMatchingParameter(
            string name,
            bool throwOnParameterNotFound,
            bool tryExactMatching,
            InvocationInfo invocationInfo)
        {
            if (string.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException(nameof(name));
            }

            Collection <MergedCompiledCommandParameter> matchingParameters =
                new Collection <MergedCompiledCommandParameter>();

            // Skip the leading '-' if present
            if (name.Length > 0 && CharExtensions.IsDash(name[0]))
            {
                name = name.Substring(1);
            }

            // First try to match the bindable parameters

            foreach (string parameterName in _bindableParameters.Keys)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
                {
                    // If it is an exact match then only return the exact match
                    // as the result

                    if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(_bindableParameters[parameterName]);
                    }
                    else
                    {
                        matchingParameters.Add(_bindableParameters[parameterName]);
                    }
                }
            }

            // Now check the aliases

            foreach (string parameterName in _aliasedParameters.Keys)
            {
                if (CultureInfo.InvariantCulture.CompareInfo.IsPrefix(parameterName, name, CompareOptions.IgnoreCase))
                {
                    // If it is an exact match then only return the exact match
                    // as the result

                    if (tryExactMatching && string.Equals(parameterName, name, StringComparison.OrdinalIgnoreCase))
                    {
                        return(_aliasedParameters[parameterName]);
                    }
                    else
                    {
                        if (!matchingParameters.Contains(_aliasedParameters[parameterName]))
                        {
                            matchingParameters.Add(_aliasedParameters[parameterName]);
                        }
                    }
                }
            }

            if (matchingParameters.Count > 1)
            {
                // Prefer parameters in the cmdlet over common parameters
                Collection <MergedCompiledCommandParameter> filteredParameters =
                    new Collection <MergedCompiledCommandParameter>();

                foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
                {
                    if ((matchingParameter.BinderAssociation == ParameterBinderAssociation.DeclaredFormalParameters) ||
                        (matchingParameter.BinderAssociation == ParameterBinderAssociation.DynamicParameters))
                    {
                        filteredParameters.Add(matchingParameter);
                    }
                }

                if (tryExactMatching && filteredParameters.Count == 1)
                {
                    matchingParameters = filteredParameters;
                }
                else
                {
                    StringBuilder possibleMatches = new StringBuilder();

                    foreach (MergedCompiledCommandParameter matchingParameter in matchingParameters)
                    {
                        possibleMatches.Append(" -");
                        possibleMatches.Append(matchingParameter.Parameter.Name);
                    }

                    ParameterBindingException exception =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            invocationInfo,
                            null,
                            name,
                            null,
                            null,
                            ParameterBinderStrings.AmbiguousParameter,
                            "AmbiguousParameter",
                            possibleMatches);

                    throw exception;
                }
            }
            else if (matchingParameters.Count == 0)
            {
                if (throwOnParameterNotFound)
                {
                    ParameterBindingException exception =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            invocationInfo,
                            null,
                            name,
                            null,
                            null,
                            ParameterBinderStrings.NamedParameterNotFound,
                            "NamedParameterNotFound");

                    throw exception;
                }
            }

            MergedCompiledCommandParameter result = null;

            if (matchingParameters.Count > 0)
            {
                result = matchingParameters[0];
            }

            return(result);
        }
		static ConsoleHostUserInterface()
		{
			ConsoleHostUserInterface.tracer = PSTraceSource.GetTracer("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console");
		}
Beispiel #27
0
        /// <summary>
        /// Constructs an instance of the CompiledCommandAttribute using the specified
        /// runtime-defined parameter.
        /// </summary>
        /// <param name="runtimeDefinedParameter">
        /// A runtime defined parameter that contains the definition of the parameter and its metadata.
        /// </param>
        /// <param name="processingDynamicParameters">
        /// True if dynamic parameters are being processed, or false otherwise.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="runtimeDefinedParameter"/> is null.
        /// </exception>
        /// <exception cref="MetadataException">
        /// If the parameter has more than one <see cref="ParameterAttribute">ParameterAttribute</see>
        /// that defines the same parameter-set name.
        /// </exception>
        internal CompiledCommandParameter(RuntimeDefinedParameter runtimeDefinedParameter, bool processingDynamicParameters)
        {
            if (runtimeDefinedParameter == null)
            {
                throw PSTraceSource.NewArgumentNullException("runtimeDefinedParameter");
            }

            this.Name      = runtimeDefinedParameter.Name;
            this.Type      = runtimeDefinedParameter.ParameterType;
            this.IsDynamic = processingDynamicParameters;

            this.CollectionTypeInformation = new ParameterCollectionTypeInformation(runtimeDefinedParameter.ParameterType);

            this.CompiledAttributes = new Collection <Attribute>();

            this.ParameterSetData = new Dictionary <string, ParameterSetSpecificMetadata>(StringComparer.OrdinalIgnoreCase);

            Collection <ValidateArgumentsAttribute>      validationAttributes        = null;
            Collection <ArgumentTransformationAttribute> argTransformationAttributes = null;

            string[] aliases = null;

            // First, process attributes that aren't type conversions
            foreach (Attribute attribute in runtimeDefinedParameter.Attributes)
            {
                if (processingDynamicParameters)
                {
                    // When processing dynamic parameters, the attribute list may contain experimental attributes
                    // and disabled parameter attributes. We should ignore those attributes.
                    // When processing non-dynamic parameters, the experimental attributes and disabled parameter
                    // attributes have already been filtered out when constructing the RuntimeDefinedParameter.
                    if (attribute is ExperimentalAttribute || attribute is ParameterAttribute param && param.ToHide)
                    {
                        continue;
                    }
                }

                if (!(attribute is ArgumentTypeConverterAttribute))
                {
                    ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases);
                }
            }

            // If this is a PSCredential type and they haven't added any argument transformation attributes,
            // add one for credential transformation
            if ((this.Type == typeof(PSCredential)) && argTransformationAttributes == null)
            {
                ProcessAttribute(runtimeDefinedParameter.Name, new CredentialAttribute(), ref validationAttributes, ref argTransformationAttributes, ref aliases);
            }

            // Now process type converters
            foreach (var attribute in runtimeDefinedParameter.Attributes.OfType <ArgumentTypeConverterAttribute>())
            {
                ProcessAttribute(runtimeDefinedParameter.Name, attribute, ref validationAttributes, ref argTransformationAttributes, ref aliases);
            }

            this.ValidationAttributes = validationAttributes == null
                ? Utils.EmptyArray <ValidateArgumentsAttribute>()
                : validationAttributes.ToArray();

            this.ArgumentTransformationAttributes = argTransformationAttributes == null
                ? Utils.EmptyArray <ArgumentTransformationAttribute>()
                : argTransformationAttributes.ToArray();

            this.Aliases = aliases == null
                ? Utils.EmptyArray <string>()
                : aliases.ToArray();
        }
        /// <summary>
        /// Merges the specified metadata with the other metadata already defined
        /// in this object.
        /// </summary>
        /// <param name="parameterMetadata">
        /// The compiled metadata for the type to be merged.
        /// </param>
        /// <param name="binderAssociation">
        /// The type of binder that the CommandProcessor will use to bind
        /// the parameters for <paramref name="parameterMetadata"/>
        /// </param>
        /// <returns>
        /// A collection of the merged parameter metadata that was added.
        /// </returns>
        /// <exception cref="MetadataException">
        /// If a parameter name or alias described in the <paramref name="parameterMetadata"/> already
        /// exists.
        /// </exception>
        internal Collection <MergedCompiledCommandParameter> AddMetadataForBinder(
            InternalParameterMetadata parameterMetadata,
            ParameterBinderAssociation binderAssociation)
        {
            if (parameterMetadata == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(parameterMetadata));
            }

            Collection <MergedCompiledCommandParameter> result =
                new Collection <MergedCompiledCommandParameter>();

            // Merge in the bindable parameters

            foreach (KeyValuePair <string, CompiledCommandParameter> bindableParameter in parameterMetadata.BindableParameters)
            {
                if (_bindableParameters.ContainsKey(bindableParameter.Key))
                {
                    MetadataException exception =
                        new MetadataException(
                            "ParameterNameAlreadyExistsForCommand",
                            null,
                            Metadata.ParameterNameAlreadyExistsForCommand,
                            bindableParameter.Key);
                    throw exception;
                }

                // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN
                if (_aliasedParameters.ContainsKey(bindableParameter.Key))
                {
                    MetadataException exception =
                        new MetadataException(
                            "ParameterNameConflictsWithAlias",
                            null,
                            Metadata.ParameterNameConflictsWithAlias,
                            bindableParameter.Key,
                            RetrieveParameterNameForAlias(bindableParameter.Key, _aliasedParameters));
                    throw exception;
                }

                MergedCompiledCommandParameter mergedParameter =
                    new MergedCompiledCommandParameter(bindableParameter.Value, binderAssociation);

                _bindableParameters.Add(bindableParameter.Key, mergedParameter);
                result.Add(mergedParameter);

                // Merge in the aliases

                foreach (string aliasName in bindableParameter.Value.Aliases)
                {
                    if (_aliasedParameters.ContainsKey(aliasName))
                    {
                        MetadataException exception =
                            new MetadataException(
                                "AliasParameterNameAlreadyExistsForCommand",
                                null,
                                Metadata.AliasParameterNameAlreadyExistsForCommand,
                                aliasName);
                        throw exception;
                    }

                    // NTRAID#Windows Out Of Band Releases-926371-2005/12/27-JonN
                    if (_bindableParameters.ContainsKey(aliasName))
                    {
                        MetadataException exception =
                            new MetadataException(
                                "ParameterNameConflictsWithAlias",
                                null,
                                Metadata.ParameterNameConflictsWithAlias,
                                RetrieveParameterNameForAlias(aliasName, _bindableParameters),
                                bindableParameter.Value.Name);
                        throw exception;
                    }

                    _aliasedParameters.Add(aliasName, mergedParameter);
                }
            }

            return(result);
        }
        /// <summary>
        /// Gets the ResourceManager from the cache or gets an instance of the ResourceManager
        /// and returns it if it isn't already present in the cache.
        /// </summary>
        /// <param name="assembly">
        /// The assembly to be used as the base for resource lookup.
        /// </param>
        /// <param name="baseName">
        /// The base name of the resources to get the ResourceManager for.
        /// </param>
        /// <returns>
        /// A ResourceManager instance for the assembly and base name that were specified.
        /// </returns>
        internal static ResourceManager GetResourceManager(
            Assembly assembly,
            string baseName)
        {
            if (assembly == null)
            {
                throw PSTraceSource.NewArgumentNullException("assembly");
            }

            if (string.IsNullOrEmpty(baseName))
            {
                throw PSTraceSource.NewArgumentException("baseName");
            }

            // Check to see if the manager is already in the cache

            ResourceManager manager = null;
            Dictionary <string, ResourceManager> baseNameCache;

            string assemblyManifestFileLocation = assembly.Location;

            lock (s_syncRoot)
            {
                // First do the lookup based on the assembly location

                if (s_resourceManagerCache.TryGetValue(assemblyManifestFileLocation, out baseNameCache) && baseNameCache != null)
                {
                    // Now do the lookup based on the resource base name
                    baseNameCache.TryGetValue(baseName, out manager);
                }
            }

            // If it's not in the cache, create it an add it.
            if (manager == null)
            {
                manager = InitRMWithAssembly(baseName, assembly);

                // Add the new resource manager to the hash

                if (baseNameCache != null)
                {
                    lock (s_syncRoot)
                    {
                        // Since the assembly is already cached, we just have
                        // to cache the base name entry

                        baseNameCache[baseName] = manager;
                    }
                }
                else
                {
                    // Since the assembly wasn't cached, we have to create base name
                    // cache entry and then add it into the cache keyed by the assembly
                    // location

                    var baseNameCacheEntry = new Dictionary <string, ResourceManager>();

                    baseNameCacheEntry[baseName] = manager;

                    lock (s_syncRoot)
                    {
                        s_resourceManagerCache[assemblyManifestFileLocation] = baseNameCacheEntry;
                    }
                }
            }

            Diagnostics.Assert(
                manager != null,
                "If the manager was not already created, it should have been dynamically created or an exception should have been thrown");

            return(manager);
        }
Beispiel #30
0
        /// <summary>
        /// Given a scope identifier, returns the proper session state scope.
        /// </summary>
        /// <param name="scopeID">
        /// A scope identifier that is either one of the "special" scopes like
        /// "global", "local", or "private, or a numeric ID of a relative scope
        /// to the current scope.
        /// </param>
        /// <returns>
        /// The scope identified by the scope ID or the current scope if the
        /// scope ID is not defined as a special or numeric scope identifier.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If <paramref name="scopeID"/> is less than zero, or not
        /// a number and not "script", "global", "local", or "private"
        /// </exception>
        /// <exception cref="ArgumentOutOfRangeException">
        /// If <paramref name="scopeID"/> is less than zero or greater than the number of currently
        /// active scopes.
        /// </exception>
        internal SessionStateScope GetScopeByID(string scopeID)
        {
            SessionStateScope result = _currentScope;

            if (!string.IsNullOrEmpty(scopeID))
            {
                if (string.Equals(
                        scopeID,
                        StringLiterals.Global,
                        StringComparison.OrdinalIgnoreCase))
                {
                    result = GlobalScope;
                }
                else if (string.Equals(
                             scopeID,
                             StringLiterals.Local,
                             StringComparison.OrdinalIgnoreCase))
                {
                    result = _currentScope;
                }
                else if (string.Equals(
                             scopeID,
                             StringLiterals.Private,
                             StringComparison.OrdinalIgnoreCase))
                {
                    result = _currentScope;
                }
                else if (string.Equals(
                             scopeID,
                             StringLiterals.Script,
                             StringComparison.OrdinalIgnoreCase))
                {
                    // Get the current script scope from the stack.
                    result = _currentScope.ScriptScope;
                }
                else
                {
                    // Since the scope is not any of the special scopes
                    // try parsing it as an ID

                    try
                    {
                        int scopeNumericID = Int32.Parse(scopeID, System.Globalization.CultureInfo.CurrentCulture);

                        if (scopeNumericID < 0)
                        {
                            throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID);
                        }

                        result = GetScopeByID(scopeNumericID) ?? _currentScope;
                    }
                    catch (FormatException)
                    {
                        throw PSTraceSource.NewArgumentException(ScopeParameterName, AutomationExceptions.InvalidScopeIdArgument, ScopeParameterName);
                    }
                    catch (OverflowException)
                    {
                        throw PSTraceSource.NewArgumentOutOfRangeException(ScopeParameterName, scopeID);
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Constructor for the ProviderInfo class.
        /// </summary>
        /// 
        /// <param name="sessionState">
        /// The instance of session state that the provider is being added to.
        /// </param>
        /// 
        /// <param name="implementingType">
        /// The type that implements the provider
        /// </param>
        /// 
        /// <param name="name">
        /// The alternate name to use for the provider instead of the one specified
        /// in the .cmdletprovider file.
        /// </param>
        /// 
        /// <param name="description">
        /// The description of the provider.
        /// </param>
        /// 
        /// <param name="home">
        /// The home path for the provider. This must be an MSH path.
        /// </param>
        /// 
        /// <param name="helpFile">
        /// The help file for the provider.
        /// </param>
        /// 
        /// <param name="psSnapIn">
        /// The Snap-In for the provider.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="implementingType"/> or <paramref name="sessionState"/> is null.
        /// </exception>
        /// 
        /// <exception cref="ArgumentException">
        /// If <paramref name="name"/> is null or empty.
        /// </exception>
        /// 
        internal ProviderInfo(
            SessionState sessionState,
            Type implementingType,
            string name,
            string description,
            string home,
            string helpFile,
            PSSnapInInfo psSnapIn)
        {
            // Verify parameters
            if (sessionState == null)
            {
                throw PSTraceSource.NewArgumentNullException("sessionState");
            }

            if (implementingType == null)
            {
                throw PSTraceSource.NewArgumentNullException("implementingType");
            }

            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }


            if (String.IsNullOrEmpty(name))
            {
                throw PSTraceSource.NewArgumentException("name");
            }

            _sessionState = sessionState;

            Name = name;
            Description = description;
            Home = home;
            ImplementingType = implementingType;
            HelpFile = helpFile;
            PSSnapIn = psSnapIn;

#if SUPPORTS_CMDLETPROVIDER_FILE
            LoadProviderFromPath(path);
#endif
            // Create the hidden drive. The name doesn't really
            // matter since we are not adding this drive to a scope.

            _hiddenDrive =
                new PSDriveInfo(
                    this.FullName,
                    this,
                    "",
                    "",
                    null);

            _hiddenDrive.Hidden = true;

            // TODO:PSL
            // this is probably not right here
            if (implementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider) && !Platform.IsWindows)
            {
                VolumeSeparatedByColon = false;
            }
        }
Beispiel #32
0
        /// <summary>
        /// Changes the current working directory to the path specified.
        /// </summary>
        /// <param name="path">
        /// The path of the new current working directory.
        /// </param>
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        /// <param name="literalPath">
        /// Indicate if the path is a literal path.
        /// </param>
        /// <returns>
        /// The PathInfo object representing the path of the location
        /// that was set.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If <paramref name="path"/> does not exist, is not a container, or
        /// resolved to multiple containers.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If <paramref name="path"/> refers to a provider that does not exist.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If <paramref name="path"/> refers to a drive that does not exist.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with <paramref name="path"/> threw an
        /// exception.
        /// </exception>
        /// <exception cref="ItemNotFoundException">
        /// If the <paramref name="path"/> could not be resolved.
        /// </exception>
        internal PathInfo SetLocation(string path, CmdletProviderContext context, bool literalPath)
        {
            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            PathInfo     current      = CurrentLocation;
            string       originalPath = path;
            string       driveName    = null;
            ProviderInfo provider     = null;
            string       providerId   = null;

            switch (originalPath)
            {
            case string originalPathSwitch when !literalPath && originalPathSwitch.Equals("-", StringComparison.Ordinal):
                if (_setLocationHistory.UndoCount <= 0)
                {
                    throw new InvalidOperationException(SessionStateStrings.LocationUndoStackIsEmpty);
                }

                path = _setLocationHistory.Undo(this.CurrentLocation).Path;
                break;

            case string originalPathSwitch when !literalPath && originalPathSwitch.Equals("+", StringComparison.Ordinal):
                if (_setLocationHistory.RedoCount <= 0)
                {
                    throw new InvalidOperationException(SessionStateStrings.LocationRedoStackIsEmpty);
                }

                path = _setLocationHistory.Redo(this.CurrentLocation).Path;
                break;

            default:
                var pushPathInfo = GetNewPushPathInfo();
                _setLocationHistory.Push(pushPathInfo);
                break;
            }

            PSDriveInfo previousWorkingDrive = CurrentDrive;

            // First check to see if the path is a home path
            if (LocationGlobber.IsHomePath(path))
            {
                path = Globber.GetHomeRelativePath(path);
            }

            if (LocationGlobber.IsProviderDirectPath(path))
            {
                // The path is a provider-direct path so use the current
                // provider and its hidden drive but don't modify the path
                // at all.
                provider     = CurrentLocation.Provider;
                CurrentDrive = provider.HiddenDrive;
            }
            else if (LocationGlobber.IsProviderQualifiedPath(path, out providerId))
            {
                provider     = GetSingleProvider(providerId);
                CurrentDrive = provider.HiddenDrive;
            }
            else
            {
                // See if the path is a relative or absolute
                // path.
                if (Globber.IsAbsolutePath(path, out driveName))
                {
                    // Since the path is an absolute path
                    // we need to change the current working
                    // drive
                    PSDriveInfo newWorkingDrive = GetDrive(driveName);
                    CurrentDrive = newWorkingDrive;

                    // If the path is simply a colon-terminated drive,
                    // not a slash-terminated path to the root of a drive,
                    // set the path to the current working directory of that drive.
                    string colonTerminatedVolume = CurrentDrive.Name + ':';
                    if (CurrentDrive.VolumeSeparatedByColon && (path.Length == colonTerminatedVolume.Length))
                    {
                        path = Path.Combine(colonTerminatedVolume + Path.DirectorySeparatorChar, CurrentDrive.CurrentLocation);
                    }

                    // Now that the current working drive is set,
                    // process the rest of the path as a relative path.
                }
            }

            if (context == null)
            {
                context = new CmdletProviderContext(this.ExecutionContext);
            }

            if (CurrentDrive != null)
            {
                context.Drive = CurrentDrive;
            }

            CmdletProvider providerInstance = null;

            Collection <PathInfo> workingPath = null;

            try
            {
                workingPath =
                    Globber.GetGlobbedMonadPathsFromMonadPath(
                        path,
                        false,
                        context,
                        out providerInstance);
            }
            catch (LoopFlowException)
            {
                throw;
            }
            catch (PipelineStoppedException)
            {
                throw;
            }
            catch (ActionPreferenceStopException)
            {
                throw;
            }
            catch (Exception)
            {
                // Reset the drive to the previous drive and
                // then rethrow the error
                CurrentDrive = previousWorkingDrive;
                throw;
            }

            if (workingPath.Count == 0)
            {
                // Set the current working drive back to the previous
                // one in case it was changed.
                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        path,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // We allow globbing the location as long as it only resolves a single container.
            bool foundContainer                     = false;
            bool pathIsContainer                    = false;
            bool pathIsProviderQualifiedPath        = false;
            bool currentPathisProviderQualifiedPath = false;

            for (int index = 0; index < workingPath.Count; ++index)
            {
                CmdletProviderContext normalizePathContext =
                    new CmdletProviderContext(context);

                PathInfo resolvedPath = workingPath[index];
                string   currentPath  = path;
                try
                {
                    string providerName = null;
                    currentPathisProviderQualifiedPath = LocationGlobber.IsProviderQualifiedPath(resolvedPath.Path, out providerName);
                    if (currentPathisProviderQualifiedPath)
                    {
                        // The path should be the provider-qualified path without the provider ID
                        // or ::
                        string providerInternalPath = LocationGlobber.RemoveProviderQualifier(resolvedPath.Path);

                        try
                        {
                            currentPath = NormalizeRelativePath(GetSingleProvider(providerName), providerInternalPath, string.Empty, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception)
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error
                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }
                    else
                    {
                        try
                        {
                            currentPath = NormalizeRelativePath(resolvedPath.Path, CurrentDrive.Root, normalizePathContext);
                        }
                        catch (NotSupportedException)
                        {
                            // Since the provider does not support normalizing the path, just
                            // use the path we currently have.
                        }
                        catch (LoopFlowException)
                        {
                            throw;
                        }
                        catch (PipelineStoppedException)
                        {
                            throw;
                        }
                        catch (ActionPreferenceStopException)
                        {
                            throw;
                        }
                        catch (Exception)
                        {
                            // Reset the drive to the previous drive and
                            // then rethrow the error
                            CurrentDrive = previousWorkingDrive;
                            throw;
                        }
                    }

                    // Now see if there was errors while normalizing the path
                    if (normalizePathContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        normalizePathContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                bool isContainer = false;

                CmdletProviderContext itemContainerContext =
                    new CmdletProviderContext(context);
                itemContainerContext.SuppressWildcardExpansion = true;

                try
                {
                    isContainer =
                        IsItemContainer(
                            resolvedPath.Path,
                            itemContainerContext);

                    if (itemContainerContext.HasErrors())
                    {
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        itemContainerContext.ThrowFirstErrorOrDoNothing();
                    }
                }
                catch (NotSupportedException)
                {
                    if (currentPath.Length == 0)
                    {
                        // Treat this as a container because providers that only
                        // support the ContainerCmdletProvider interface are really
                        // containers at their root.
                        isContainer = true;
                    }
                }
                finally
                {
                    itemContainerContext.RemoveStopReferral();
                }

                if (isContainer)
                {
                    if (foundContainer)
                    {
                        // The path resolved to more than one container
                        // Set the current working drive back to the previous
                        // one in case it was changed.
                        CurrentDrive = previousWorkingDrive;

                        throw
                            PSTraceSource.NewArgumentException(
                                nameof(path),
                                SessionStateStrings.PathResolvedToMultiple,
                                originalPath);
                    }
                    else
                    {
                        // Set the path to use
                        path = currentPath;

                        // Mark it as a container
                        pathIsContainer = true;

                        // Mark whether or not it was provider-qualified
                        pathIsProviderQualifiedPath = currentPathisProviderQualifiedPath;

                        // Mark that we have already found one container. Finding additional
                        // should be an error
                        foundContainer = true;
                    }
                }
            }

            if (pathIsContainer)
            {
                // Remove the root slash since it is implied that the
                // current working directory is relative to the root.
                if (!LocationGlobber.IsProviderDirectPath(path) &&
                    path.StartsWith(StringLiterals.DefaultPathSeparator) &&
                    !pathIsProviderQualifiedPath)
                {
                    path = path.Substring(1);
                }

                s_tracer.WriteLine(
                    "New working path = {0}",
                    path);

                CurrentDrive.CurrentLocation = path;
            }
            else
            {
                // Set the current working drive back to the previous
                // one in case it was changed.
                CurrentDrive = previousWorkingDrive;

                throw
                    new ItemNotFoundException(
                        originalPath,
                        "PathNotFound",
                        SessionStateStrings.PathNotFound);
            }

            // Now make sure the current drive is set in the provider's
            // current working drive hashtable
            ProvidersCurrentWorkingDrive[CurrentDrive.Provider] =
                CurrentDrive;

            // Set the $PWD variable to the new location
            this.SetVariable(SpecialVariables.PWDVarPath, this.CurrentLocation, false, true, CommandOrigin.Internal);

            // If an action has been defined for location changes, invoke it now.
            if (PublicSessionState.InvokeCommand.LocationChangedAction != null)
            {
                var eventArgs = new LocationChangedEventArgs(PublicSessionState, current, CurrentLocation);
                PublicSessionState.InvokeCommand.LocationChangedAction.Invoke(ExecutionContext.CurrentRunspace, eventArgs);
                s_tracer.WriteLine("Invoked LocationChangedAction");
            }

            return(this.CurrentLocation);
        }
Beispiel #33
0
        internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp)
        {
            // this object knows Maml format...
            // So retrieve Uri information as per the format..
            if ((commandFullHelp == null) ||
                (commandFullHelp.Properties["relatedLinks"] == null) ||
                (commandFullHelp.Properties["relatedLinks"].Value == null))
            {
                // return the default..
                return(null);
            }

            PSObject relatedLinks = PSObject.AsPSObject(commandFullHelp.Properties["relatedLinks"].Value);

            if (relatedLinks.Properties["navigationLink"] == null)
            {
                return(null);
            }

            object[] navigationLinks = (object[])LanguagePrimitives.ConvertTo(
                relatedLinks.Properties["navigationLink"].Value,
                typeof(object[]),
                CultureInfo.InvariantCulture);
            foreach (object navigationLinkAsObject in navigationLinks)
            {
                if (navigationLinkAsObject == null)
                {
                    continue;
                }

                PSObject       navigationLink = PSObject.AsPSObject(navigationLinkAsObject);
                PSNoteProperty uriNP          = navigationLink.Properties["uri"] as PSNoteProperty;
                if (uriNP != null)
                {
                    string uriString = string.Empty;
                    LanguagePrimitives.TryConvertTo <string>(uriNP.Value, CultureInfo.InvariantCulture, out uriString);
                    if (!string.IsNullOrEmpty(uriString))
                    {
                        if (!System.Uri.IsWellFormedUriString(uriString, UriKind.RelativeOrAbsolute))
                        {
                            // WinBlue: 545315 Online help links are broken with localized help
                            // Example: https://go.microsoft.com/fwlink/?LinkID=113324 (moglicherwei se auf Englisch)
                            // Split the string based on <s> (space). We decided to go with this approach as
                            // UX localization authors use spaces. Correctly extracting only the wellformed URI
                            // is out-of-scope for this fix.
                            string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space);
                            uriString = tempUriSplitArray[0];
                        }

                        try
                        {
                            return(new System.Uri(uriString));
                            // return only the first Uri (ignore other uris)
                        }
                        catch (UriFormatException)
                        {
                            throw PSTraceSource.NewInvalidOperationException(HelpErrors.InvalidURI, uriString);
                        }
                    }
                }
            }

            return(null);
        }
Beispiel #34
0
        /// <summary>
        /// Determines if the specified path is the current working directory
        /// or a parent of the current working directory.
        /// </summary>
        /// <param name="path">
        /// A monad namespace absolute or relative path.
        /// </param>
        /// <param name="context">
        /// The context the provider uses when performing the operation.
        /// </param>
        /// <returns>
        /// true, if the path is the current working directory or a parent of the current
        /// working directory. false, otherwise.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If the path is a provider-qualified path for a provider that is
        /// not loaded into the system.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If the <paramref name="path"/> refers to a drive that could not be found.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider used to build the path threw an exception.
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// If the provider that the <paramref name="path"/> represents is not a NavigationCmdletProvider
        /// or ContainerCmdletProvider.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// If the <paramref name="path"/> starts with "~" and the home location is not set for
        /// the provider.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider specified by <paramref name="providerId"/> threw an
        /// exception when its GetParentPath or MakePath was called while
        /// processing the <paramref name="path"/>.
        /// </exception>
        internal bool IsCurrentLocationOrAncestor(string path, CmdletProviderContext context)
        {
            bool result = false;

            if (path == null)
            {
                throw PSTraceSource.NewArgumentNullException(nameof(path));
            }

            PSDriveInfo  drive    = null;
            ProviderInfo provider = null;

            string providerSpecificPath =
                Globber.GetProviderPath(
                    path,
                    context,
                    out provider,
                    out drive);

            if (drive != null)
            {
                s_tracer.WriteLine("Tracing drive");
                drive.Trace();
            }

            Dbg.Diagnostics.Assert(
                providerSpecificPath != null,
                "There should always be a way to generate a provider path for a " +
                "given path");

            if (drive != null)
            {
                context.Drive = drive;
            }

            // Check to see if the path that was specified is within the current
            // working drive
            if (drive == CurrentDrive)
            {
                // The path needs to be normalized to get rid of relative path tokens
                // so they don't interfere with our path comparisons below
                CmdletProviderContext normalizePathContext
                    = new CmdletProviderContext(context);

                try
                {
                    providerSpecificPath = NormalizeRelativePath(path, null, normalizePathContext);
                }
                catch (NotSupportedException)
                {
                    // Since the provider does not support normalizing the path, just
                    // use the path we currently have.
                }
                catch (LoopFlowException)
                {
                    throw;
                }
                catch (PipelineStoppedException)
                {
                    throw;
                }
                catch (ActionPreferenceStopException)
                {
                    throw;
                }
                finally
                {
                    normalizePathContext.RemoveStopReferral();
                }

                if (normalizePathContext.HasErrors())
                {
                    normalizePathContext.ThrowFirstErrorOrDoNothing();
                }

                s_tracer.WriteLine("Provider path = {0}", providerSpecificPath);

                // Get the current working directory provider specific path
                PSDriveInfo  currentWorkingDrive  = null;
                ProviderInfo currentDriveProvider = null;

                string currentWorkingPath =
                    Globber.GetProviderPath(
                        ".",
                        context,
                        out currentDriveProvider,
                        out currentWorkingDrive);

                Dbg.Diagnostics.Assert(
                    currentWorkingDrive == CurrentDrive,
                    "The current working drive should be the CurrentDrive.");

                s_tracer.WriteLine(
                    "Current working path = {0}",
                    currentWorkingPath);

                // See if the path is the current working directory or a parent
                // of the current working directory
                s_tracer.WriteLine(
                    "Comparing {0} to {1}",
                    providerSpecificPath,
                    currentWorkingPath);

                if (string.Equals(providerSpecificPath, currentWorkingPath, StringComparison.OrdinalIgnoreCase))
                {
                    // The path is the current working directory so
                    // return true
                    s_tracer.WriteLine("The path is the current working directory");

                    result = true;
                }
                else
                {
                    // Check to see if the specified path is a parent
                    // of the current working directory
                    string lockedDirectory = currentWorkingPath;

                    while (lockedDirectory.Length > 0)
                    {
                        // We need to allow the provider to go as far up the tree
                        // as it can even if that means it has to traverse higher
                        // than the mount point for this drive. That is
                        // why we are passing the empty string as the root here.
                        lockedDirectory =
                            GetParentPath(
                                drive.Provider,
                                lockedDirectory,
                                string.Empty,
                                context);

                        s_tracer.WriteLine(
                            "Comparing {0} to {1}",
                            lockedDirectory,
                            providerSpecificPath);

                        if (string.Equals(lockedDirectory, providerSpecificPath, StringComparison.OrdinalIgnoreCase))
                        {
                            // The path is a parent of the current working
                            // directory
                            s_tracer.WriteLine(
                                "The path is a parent of the current working directory: {0}",
                                lockedDirectory);

                            result = true;
                            break;
                        }
                    }
                }
            }
            else
            {
                s_tracer.WriteLine("Drives are not the same");
            }

            return(result);
        }
Beispiel #35
0
        /// <summary>
        /// Get a Hashtable object out of a PowerShell data file (.psd1)
        /// </summary>
        /// <param name="parameterName">
        /// Name of the parameter that takes the specified .psd1 file as a value
        /// </param>
        /// <param name="psDataFilePath">
        /// Path to the powershell data file
        /// </param>
        /// <param name="context">
        /// ExecutionContext to use
        /// </param>
        /// <param name="allowedCommands">
        /// Set of command names that are allowed to use in the .psd1 file
        /// </param>
        /// <param name="allowedVariables">
        /// Set of variable names that are allowed to use in the .psd1 file
        /// </param>
        /// <param name="allowEnvironmentVariables">
        /// If true, allow to use environment variables in the .psd1 file
        /// </param>
        /// <param name="skipPathValidation">
        /// If true, caller guarantees the path is valid
        /// </param>
        /// <returns></returns>
        internal static Hashtable EvaluatePowerShellDataFile(
            string parameterName,
            string psDataFilePath,
            ExecutionContext context,
            IEnumerable <string> allowedCommands,
            IEnumerable <string> allowedVariables,
            bool allowEnvironmentVariables,
            bool skipPathValidation)
        {
            if (!skipPathValidation && string.IsNullOrEmpty(parameterName))
            {
                throw PSTraceSource.NewArgumentNullException("parameterName");
            }
            if (string.IsNullOrEmpty(psDataFilePath))
            {
                throw PSTraceSource.NewArgumentNullException("psDataFilePath");
            }
            if (context == null)
            {
                throw PSTraceSource.NewArgumentNullException("context");
            }

            string resolvedPath;

            if (skipPathValidation)
            {
                resolvedPath = psDataFilePath;
            }
            else
            {
                #region "ValidatePowerShellDataFilePath"

                bool isPathValid = true;

                // File extension needs to be .psd1
                string pathExt = Path.GetExtension(psDataFilePath);
                if (string.IsNullOrEmpty(pathExt) ||
                    !StringLiterals.PowerShellDataFileExtension.Equals(pathExt, StringComparison.OrdinalIgnoreCase))
                {
                    isPathValid = false;
                }

                ProviderInfo provider;
                var          resolvedPaths = context.SessionState.Path.GetResolvedProviderPathFromPSPath(psDataFilePath, out provider);

                // ConfigPath should be resolved as FileSystem provider
                if (provider == null || !Microsoft.PowerShell.Commands.FileSystemProvider.ProviderName.Equals(provider.Name, StringComparison.OrdinalIgnoreCase))
                {
                    isPathValid = false;
                }

                // ConfigPath should be resolved to a single path
                if (resolvedPaths.Count != 1)
                {
                    isPathValid = false;
                }

                if (!isPathValid)
                {
                    throw PSTraceSource.NewArgumentException(
                              parameterName,
                              ParserStrings.CannotResolvePowerShellDataFilePath,
                              psDataFilePath);
                }

                resolvedPath = resolvedPaths[0];

                #endregion "ValidatePowerShellDataFilePath"
            }

            #region "LoadAndEvaluatePowerShellDataFile"

            object evaluationResult;
            try
            {
                // Create the scriptInfo for the .psd1 file
                string      dataFileName       = Path.GetFileName(resolvedPath);
                var         dataFileScriptInfo = new ExternalScriptInfo(dataFileName, resolvedPath, context);
                ScriptBlock scriptBlock        = dataFileScriptInfo.ScriptBlock;

                // Validate the scriptblock
                scriptBlock.CheckRestrictedLanguage(allowedCommands, allowedVariables, allowEnvironmentVariables);

                // Evaluate the scriptblock
                object oldPsScriptRoot = context.GetVariableValue(SpecialVariables.PSScriptRootVarPath);
                try
                {
                    // Set the $PSScriptRoot before the evaluation
                    context.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(resolvedPath));
                    evaluationResult = PSObject.Base(scriptBlock.InvokeReturnAsIs());
                }
                finally
                {
                    context.SetVariable(SpecialVariables.PSScriptRootVarPath, oldPsScriptRoot);
                }
            }
            catch (RuntimeException ex)
            {
                throw PSTraceSource.NewInvalidOperationException(
                          ex,
                          ParserStrings.CannotLoadPowerShellDataFile,
                          psDataFilePath,
                          ex.Message);
            }

            var retResult = evaluationResult as Hashtable;
            if (retResult == null)
            {
                throw PSTraceSource.NewInvalidOperationException(
                          ParserStrings.InvalidPowerShellDataFile,
                          psDataFilePath);
            }

            #endregion "LoadAndEvaluatePowerShellDataFile"

            return(retResult);
        }
Beispiel #36
0
        /// <summary>
        /// Resets the current working drive and directory to the first
        /// entry on the working directory stack and removes that entry
        /// from the stack.
        /// </summary>
        /// <param name="stackName">
        /// The ID of the stack to pop the location from. If it is null or
        /// empty the default stack is used.
        /// </param>
        /// <returns>
        /// A PathInfo object representing the location that was popped
        /// from the location stack and set as the new location.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// If the path on the stack does not exist, is not a container, or
        /// resolved to multiple containers.
        /// or
        /// If <paramref name="stackName"/> contains wildcard characters and resolves
        /// to multiple location stacks.
        /// or
        /// A stack was not found with the specified name.
        /// </exception>
        /// <exception cref="ProviderNotFoundException">
        /// If the path on the stack refers to a provider that does not exist.
        /// </exception>
        /// <exception cref="DriveNotFoundException">
        /// If the path on the stack refers to a drive that does not exist.
        /// </exception>
        /// <exception cref="ProviderInvocationException">
        /// If the provider associated with the path on the stack threw an
        /// exception.
        /// </exception>
        internal PathInfo PopLocation(string stackName)
        {
            if (string.IsNullOrEmpty(stackName))
            {
                stackName = _defaultStackName;
            }

            if (WildcardPattern.ContainsWildcardCharacters(stackName))
            {
                // Need to glob the stack name, but it can only glob to a single.
                bool haveMatch = false;

                WildcardPattern stackNamePattern =
                    WildcardPattern.Get(stackName, WildcardOptions.IgnoreCase);

                foreach (string key in _workingLocationStack.Keys)
                {
                    if (stackNamePattern.IsMatch(key))
                    {
                        if (haveMatch)
                        {
                            throw
                                PSTraceSource.NewArgumentException(
                                    nameof(stackName),
                                    SessionStateStrings.StackNameResolvedToMultiple,
                                    stackName);
                        }

                        haveMatch = true;
                        stackName = key;
                    }
                }
            }

            PathInfo result = CurrentLocation;

            try
            {
                Stack <PathInfo> locationStack = null;
                if (!_workingLocationStack.TryGetValue(stackName, out locationStack))
                {
                    if (!string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                    {
                        throw
                            PSTraceSource.NewArgumentException(
                                nameof(stackName),
                                SessionStateStrings.StackNotFound,
                                stackName);
                    }

                    return(null);
                }

                PathInfo poppedWorkingDirectory = locationStack.Pop();

                Dbg.Diagnostics.Assert(
                    poppedWorkingDirectory != null,
                    "All items in the workingLocationStack should be " +
                    "of type PathInfo");

                string newPath =
                    LocationGlobber.GetMshQualifiedPath(
                        WildcardPattern.Escape(poppedWorkingDirectory.Path),
                        poppedWorkingDirectory.GetDrive());

                result = SetLocation(newPath);

                if (locationStack.Count == 0 &&
                    !string.Equals(stackName, startingDefaultStackName, StringComparison.OrdinalIgnoreCase))
                {
                    // Remove the stack from the stack list if it
                    // no longer contains any paths.
                    _workingLocationStack.Remove(stackName);
                }
            }
            catch (InvalidOperationException)
            {
                // This is a no-op. We stay with the current working
                // directory.
            }

            return(result);
        }
        /// <summary>
        /// Check if anyother pipeline is executing.
        /// In case of nested pipeline, checks that it is called
        /// from currently executing pipeline's thread.
        /// </summary>
        /// <param name="syncCall">True if method is called from Invoke, false
        /// if called from InvokeAsync</param>
        /// <exception cref="InvalidOperationException">
        /// 1) A pipeline is already executing. Pipeline cannot execute
        /// concurrently.
        /// 2) InvokeAsync is called on nested pipeline. Nested pipeline
        /// cannot be executed Asynchronously.
        /// 3) Attempt is made to invoke a nested pipeline directly. Nested
        /// pipeline must be invoked from a running pipeline.
        /// </exception>
        internal void DoConcurrentCheck(bool syncCall)
        {
            RemotePipeline currentPipeline =
                (RemotePipeline)((RemoteRunspace)_runspace).GetCurrentlyRunningPipeline();

            if (_isNested == false)
            {
                if (currentPipeline == null &&
                    ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.Busy &&
                    ((RemoteRunspace)_runspace).RunspaceAvailability != RunspaceAvailability.RemoteDebug)
                {
                    // We can add a new pipeline to the runspace only if it is
                    // available (not busy).
                    return;
                }

                if (currentPipeline == null &&
                    ((RemoteRunspace)_runspace).RemoteCommand != null &&
                    _connectCmdInfo != null &&
                    Guid.Equals(((RemoteRunspace)_runspace).RemoteCommand.CommandId, _connectCmdInfo.CommandId))
                {
                    // Connect case.  We can add a pipeline to a busy runspace when
                    // that pipeline represents the same command as is currently
                    // running.
                    return;
                }

                if (currentPipeline != null &&
                    ReferenceEquals(currentPipeline, this))
                {
                    // Reconnect case.  We can add a pipeline to a busy runspace when the
                    // pipeline is the same (reconnecting).
                    return;
                }

                if (!_isSteppable)
                {
                    throw PSTraceSource.NewInvalidOperationException(
                              RunspaceStrings.ConcurrentInvokeNotAllowed);
                }
            }
            else
            {
                if (_performNestedCheck)
                {
                    if (_isSteppable)
                    {
                        return;
                    }

                    if (syncCall == false)
                    {
                        throw PSTraceSource.NewInvalidOperationException(
                                  RunspaceStrings.NestedPipelineInvokeAsync);
                    }

                    if (currentPipeline == null)
                    {
                        if (!_isSteppable)
                        {
                            throw PSTraceSource.NewInvalidOperationException(
                                      RunspaceStrings.NestedPipelineNoParentPipeline);
                        }
                    }
                }
            }
        }
Beispiel #38
0
		static PendingProgress()
		{
			PendingProgress.tracer = PSTraceSource.GetTracer("PendingProgress", "Console Host Progress");
		}
Beispiel #39
0
        internal static PSTraceSource GetNewTraceSource(
            string name,
            string description,
            bool traceHeaders)
        {
            if (String.IsNullOrEmpty(name))
            {
                // Note, all callers should have already verified the name before calling this
                // API, so this exception should never be exposed to an end-user.

                throw new ArgumentException("name");
            }

            // Keep the fullName as it was passed, but truncate or pad
            // the category name to 16 characters.  This allows for 
            // uniform output

            string fullName = name;
            /*
                            // This is here to ensure all the trace category names are 16 characters,
                            // the problem is that the app-config file would need to contain the same
                            // trailing spaces if this actually does pad the name.

                            name =
                                String.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    "{0,-16}",
                                    name);
            */
            PSTraceSource result =
                new PSTraceSource(
                    fullName,
                    name,
                    description,
                    traceHeaders);
            return result;
        }
Beispiel #40
0
        /// <summary>
        /// Constructs a scoped item lookup path.
        /// </summary>
        /// <param name="path">The path to parse.</param>
        /// <param name="knownFlags">
        /// These flags for anything known about the path (such as, is it a function) before
        /// being scanned.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If <paramref name="path"/> is null.
        /// </exception>
        internal VariablePath(string path, VariablePathFlags knownFlags)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw PSTraceSource.NewArgumentException("path");
            }

            _userPath = path;
            _flags    = knownFlags;

            string            candidateScope      = null;
            string            candidateScopeUpper = null;
            VariablePathFlags candidateFlags      = VariablePathFlags.Unqualified;

            int currentCharIndex = 0;
            int lastScannedColon = -1;

scanScope:
            switch (path[0])
            {
            case 'g':
            case 'G':
                candidateScope      = "lobal";
                candidateScopeUpper = "LOBAL";
                candidateFlags      = VariablePathFlags.Global;
                break;

            case 'l':
            case 'L':
                candidateScope      = "ocal";
                candidateScopeUpper = "OCAL";
                candidateFlags      = VariablePathFlags.Local;
                break;

            case 'p':
            case 'P':
                candidateScope      = "rivate";
                candidateScopeUpper = "RIVATE";
                candidateFlags      = VariablePathFlags.Private;
                break;

            case 's':
            case 'S':
                candidateScope      = "cript";
                candidateScopeUpper = "CRIPT";
                candidateFlags      = VariablePathFlags.Script;
                break;

            case 'v':
            case 'V':
                if (knownFlags == VariablePathFlags.None)
                {
                    // If we see 'variable:', our namespaceId will be empty, and
                    // we'll also need to scan for the scope again.
                    candidateScope      = "ariable";
                    candidateScopeUpper = "ARIABLE";
                    candidateFlags      = VariablePathFlags.Variable;
                }

                break;
            }

            if (candidateScope != null)
            {
                currentCharIndex += 1; // First character already matched.
                int j;
                for (j = 0; currentCharIndex < path.Length && j < candidateScope.Length; ++j, ++currentCharIndex)
                {
                    if (path[currentCharIndex] != candidateScope[j] && path[currentCharIndex] != candidateScopeUpper[j])
                    {
                        break;
                    }
                }

                if (j == candidateScope.Length &&
                    currentCharIndex < path.Length &&
                    path[currentCharIndex] == ':')
                {
                    if (_flags == VariablePathFlags.None)
                    {
                        _flags = VariablePathFlags.Variable;
                    }

                    _flags           |= candidateFlags;
                    lastScannedColon  = currentCharIndex;
                    currentCharIndex += 1;

                    // If saw 'variable:', we need to look for a scope after 'variable:'.
                    if (candidateFlags == VariablePathFlags.Variable)
                    {
                        knownFlags     = VariablePathFlags.Variable;
                        candidateScope = candidateScopeUpper = null;
                        candidateFlags = VariablePathFlags.None;
                        goto scanScope;
                    }
                }
            }

            if (_flags == VariablePathFlags.None)
            {
                lastScannedColon = path.IndexOf(':', currentCharIndex);
                // No colon, or a colon as the first character means we have
                // a simple variable, otherwise it's a drive.
                if (lastScannedColon > 0)
                {
                    _flags = VariablePathFlags.DriveQualified;
                }
            }

            if (lastScannedColon == -1)
            {
                _unqualifiedPath = _userPath;
            }
            else
            {
                _unqualifiedPath = _userPath.Substring(lastScannedColon + 1);
            }

            if (_flags == VariablePathFlags.None)
            {
                _flags = VariablePathFlags.Unqualified | VariablePathFlags.Variable;
            }
        }
Beispiel #41
0
 internal static void ResetTracer()
 {
     s_activeTracer = s_classTracer;
 }
 /// <summary>
 /// A helper to get an instance of the PSTraceSource class.
 /// </summary>
 /// <param name="name">
 /// The name of the category that this class
 /// will control the tracing for.
 /// </param>
 /// <param name="description">
 /// The description to describe what the category
 /// is used for.
 /// </param>
 /// <returns>
 /// An instance of the PSTraceSource class which is initialized
 /// to trace for the specified category. If multiple callers ask for the same category,
 /// the same PSTraceSource will be returned.
 /// </returns>
 internal static PSTraceSource GetTracer(
     string name,
     string description)
 {
     return(PSTraceSource.GetTracer(name, description, true));
 }
Beispiel #43
0
        /// <summary>
        /// Constructor that traces the scope name
        /// and raises the indent level in thread
        /// local storage.
        /// </summary>
        /// 
        /// <param name="tracer">
        /// The trace object that is to be used for output
        /// </param>
        /// 
        /// <param name="flag">
        /// The PSTraceSourceOptions that is causing the scope object to 
        /// be created.
        /// </param>
        /// 
        /// <param name="scopeOutputFormatter">
        /// This format string is used to determine the
        /// general output format for the scope. For instance,
        /// TraceMethod would probably provide a formatter similar
        /// to "Entering: {0}: {1}" where {0} is the name of the
        /// method and {1} is the additional formatted info provided.
        /// </param>
        /// 
        /// <param name="leavingScopeFormatter">
        /// The format string used to determine the general output
        /// format for the scope when the Dispose method is called.
        /// </param>
        /// 
        /// <param name="scopeName">
        /// The name of the scope that is being traced
        /// </param>
        /// 
        /// <param name="format">
        /// The format of any additional arguments which will be appended
        /// to the line of trace output
        /// </param>
        /// 
        /// <param name="args">
        /// Arguments to the format string.
        /// </param>
        /// 
        internal ScopeTracer(
            PSTraceSource tracer,
            PSTraceSourceOptions flag,
            string scopeOutputFormatter,
            string leavingScopeFormatter,
            string scopeName,
            string format,
            params object[] args)
        {
            _tracer = tracer;

            // Call the helper

            if (format != null)
            {
                ScopeTracerHelper(
                    flag,
                    scopeOutputFormatter,
                    leavingScopeFormatter,
                    scopeName,
                    format,
                    args);
            }
            else
            {
                ScopeTracerHelper(
                    flag,
                    scopeOutputFormatter,
                    leavingScopeFormatter,
                    scopeName,
                    "");
            }
        }
Beispiel #44
0
		static CoreCommandBase()
		{
			CoreCommandBase.tracer = PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer");
		}