コード例 #1
0
        internal IEnumerator <DSResource> InvokeCmdletAsync(System.Management.Automation.PowerShell powerShell, Expression expression, EventHandler <DataAddedEventArgs> dataAddedEventHandler, AsyncCallback executionCompletionCallback, bool noStreamingResponse)
        {
            Tracer tracer = new Tracer();

            this.dataStore = new AsyncDataStore <DSResource>(expression, noStreamingResponse);
            this.output    = new PSDataCollection <PSObject>();
            tracer.CommandInvocationStart(this.cmdletInfo.CmdletName);
            powerShell.Runspace = this.runspace.Item.Runspace;
            powerShell.AddCommand(this.cmdletInfo.CmdletName);
            foreach (string key in this.parameters.Keys)
            {
                if (!this.cmdletInfo.IsSwitch(key))
                {
                    powerShell.AddParameter(key, this.parameters[key]);
                }
                else
                {
                    powerShell.AddParameter(key);
                }
            }
            this.isExecutionCompleted = false;
            using (OperationTracer operationTracer = new OperationTracer(new Action <string>(TraceHelper.Current.CmdletExecutionStart), new Action <string>(TraceHelper.Current.CmdletExecutionEnd), powerShell.Commands.ToTraceMessage()))
            {
                try
                {
                    this.timer.Start();
                    powerShell.Invoke <PSObject>(null, this.output, Utils.GetPSInvocationSettings());
                }
                catch (CommandNotFoundException commandNotFoundException1)
                {
                    CommandNotFoundException commandNotFoundException = commandNotFoundException1;
                    throw new CommandInvocationFailedException(powerShell.Commands.Commands[0].CommandText, commandNotFoundException);
                }
                catch (ParameterBindingException parameterBindingException1)
                {
                    ParameterBindingException parameterBindingException = parameterBindingException1;
                    throw new CommandInvocationFailedException(powerShell.Commands.Commands[0].CommandText, parameterBindingException);
                }
                catch (CmdletInvocationException cmdletInvocationException1)
                {
                    CmdletInvocationException cmdletInvocationException = cmdletInvocationException1;
                    throw new CommandInvocationFailedException(powerShell.Commands.Commands[0].CommandText, cmdletInvocationException);
                }
            }
            return(new BlockingEnumerator <DSResource>(this.dataStore));
        }
コード例 #2
0
ファイル: SetAclCommand.cs プロジェクト: modulexcite/pash-1
        protected override void ProcessRecord()
        {
            string         sddlForm;
            ObjectSecurity objectSecurity = this.securityDescriptor as ObjectSecurity;

            if (this.inputObject == null)
            {
                if (this.Path != null)
                {
                    if (objectSecurity != null)
                    {
                        if ((this.CentralAccessPolicy != null || this.ClearCentralAccessPolicy) && !DownLevelHelper.IsWin8AndAbove())
                        {
                            Exception parameterBindingException = new ParameterBindingException();
                            base.WriteError(new ErrorRecord(parameterBindingException, "SetAcl_OperationNotSupported", ErrorCategory.InvalidArgument, null));
                            return;
                        }
                        else
                        {
                            if (this.CentralAccessPolicy == null || !this.ClearCentralAccessPolicy)
                            {
                                IntPtr zero = IntPtr.Zero;
                                NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE = new NativeMethods.TOKEN_PRIVILEGE();
                                try
                                {
                                    if (this.CentralAccessPolicy == null)
                                    {
                                        if (this.ClearCentralAccessPolicy)
                                        {
                                            zero = this.GetEmptySacl();
                                            if (zero == IntPtr.Zero)
                                            {
                                                SystemException systemException = new SystemException(UtilsStrings.GetEmptySaclFail);
                                                base.WriteError(new ErrorRecord(systemException, "SetAcl_ClearCentralAccessPolicy", ErrorCategory.InvalidResult, null));
                                                return;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        zero = this.GetSaclWithCapId(this.CentralAccessPolicy);
                                        if (zero == IntPtr.Zero)
                                        {
                                            SystemException systemException1 = new SystemException(UtilsStrings.GetSaclWithCapIdFail);
                                            base.WriteError(new ErrorRecord(systemException1, "SetAcl_CentralAccessPolicy", ErrorCategory.InvalidResult, null));
                                            return;
                                        }
                                    }
                                    string[] path = this.Path;
                                    for (int i = 0; i < (int)path.Length; i++)
                                    {
                                        string str = path[i];
                                        Collection <PathInfo> pathInfos             = new Collection <PathInfo>();
                                        CmdletProviderContext cmdletProviderContext = base.CmdletProviderContext;
                                        cmdletProviderContext.PassThru = this.Passthru;
                                        if (!this.isLiteralPath)
                                        {
                                            pathInfos = base.SessionState.Path.GetResolvedPSPathFromPSPath(str, base.CmdletProviderContext);
                                        }
                                        else
                                        {
                                            ProviderInfo providerInfo = null;
                                            PSDriveInfo  pSDriveInfo  = null;
                                            string       unresolvedProviderPathFromPSPath = base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(str, out providerInfo, out pSDriveInfo);
                                            pathInfos.Add(new PathInfo(pSDriveInfo, providerInfo, unresolvedProviderPathFromPSPath, base.SessionState));
                                            cmdletProviderContext.SuppressWildcardExpansion = true;
                                        }
                                        foreach (PathInfo pathInfo in pathInfos)
                                        {
                                            if (!base.ShouldProcess(pathInfo.Path))
                                            {
                                                continue;
                                            }
                                            try
                                            {
                                                base.InvokeProvider.SecurityDescriptor.Set(pathInfo.Path, objectSecurity, cmdletProviderContext);
                                                if (this.CentralAccessPolicy != null || this.ClearCentralAccessPolicy)
                                                {
                                                    if (pathInfo.Provider.NameEquals(base.Context.ProviderNames.FileSystem))
                                                    {
                                                        IntPtr tokenWithEnabledPrivilege = this.GetTokenWithEnabledPrivilege("SeSecurityPrivilege", tOKENPRIVILEGE);
                                                        if (tokenWithEnabledPrivilege != IntPtr.Zero)
                                                        {
                                                            int num = NativeMethods.SetNamedSecurityInfo(pathInfo.ProviderPath, NativeMethods.SeObjectType.SE_FILE_OBJECT, NativeMethods.SecurityInformation.SCOPE_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, zero);
                                                            if (tokenWithEnabledPrivilege != IntPtr.Zero)
                                                            {
                                                                NativeMethods.TOKEN_PRIVILEGE tOKENPRIVILEGE1 = new NativeMethods.TOKEN_PRIVILEGE();
                                                                uint num1 = 0;
                                                                NativeMethods.AdjustTokenPrivileges(tokenWithEnabledPrivilege, false, ref tOKENPRIVILEGE, Marshal.SizeOf(tOKENPRIVILEGE1), ref tOKENPRIVILEGE1, ref num1);
                                                                NativeMethods.CloseHandle(tokenWithEnabledPrivilege);
                                                            }
                                                            if (num != 0)
                                                            {
                                                                SystemException win32Exception = new Win32Exception(num, UtilsStrings.SetCentralAccessPolicyFail);
                                                                base.WriteError(new ErrorRecord(win32Exception, "SetAcl_SetNamedSecurityInfo", ErrorCategory.InvalidResult, null));
                                                            }
                                                        }
                                                        else
                                                        {
                                                            SystemException systemException2 = new SystemException(UtilsStrings.GetTokenWithEnabledPrivilegeFail);
                                                            base.WriteError(new ErrorRecord(systemException2, "SetAcl_AdjustTokenPrivileges", ErrorCategory.InvalidResult, null));
                                                            return;
                                                        }
                                                    }
                                                    else
                                                    {
                                                        Exception argumentException = new ArgumentException("Path");
                                                        base.WriteError(new ErrorRecord(argumentException, "SetAcl_Path", ErrorCategory.InvalidArgument, this.AclObject));
                                                        continue;
                                                    }
                                                }
                                            }
                                            catch (NotSupportedException notSupportedException)
                                            {
                                                object[] objArray = new object[1];
                                                objArray[0] = pathInfo.Path;
                                                ErrorRecord errorRecord = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.OperationNotSupportedOnPath, "SetAcl_OperationNotSupported", objArray);
                                                base.WriteError(errorRecord);
                                            }
                                        }
                                    }
                                    return;
                                }
                                finally
                                {
                                    Marshal.FreeHGlobal(zero);
                                }
                            }
                            else
                            {
                                Exception   exception    = new ArgumentException(UtilsStrings.InvalidCentralAccessPolicyParameters);
                                ErrorRecord errorRecord1 = SecurityUtils.CreateInvalidArgumentErrorRecord(exception, "SetAcl_OperationNotSupported");
                                base.WriteError(errorRecord1);
                                return;
                            }
                        }
                    }
                    else
                    {
                        Exception argumentException1 = new ArgumentException("AclObject");
                        base.WriteError(new ErrorRecord(argumentException1, "SetAcl_AclObject", ErrorCategory.InvalidArgument, this.AclObject));
                        return;
                    }
                }
                else
                {
                    Exception exception1 = new ArgumentException("Path");
                    base.WriteError(new ErrorRecord(exception1, "SetAcl_Path", ErrorCategory.InvalidArgument, this.AclObject));
                }
            }
            else
            {
                PSMethodInfo item = this.inputObject.Methods["SetSecurityDescriptor"];
                if (item == null)
                {
                    ErrorRecord errorRecord2 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.SetMethodNotFound, "SetAcl_OperationNotSupported", new object[0]);
                    base.WriteError(errorRecord2);
                    return;
                }
                else
                {
                    CommonSecurityDescriptor commonSecurityDescriptor = this.securityDescriptor as CommonSecurityDescriptor;
                    if (objectSecurity == null)
                    {
                        if (commonSecurityDescriptor == null)
                        {
                            Exception argumentException2 = new ArgumentException("AclObject");
                            base.WriteError(new ErrorRecord(argumentException2, "SetAcl_AclObject", ErrorCategory.InvalidArgument, this.AclObject));
                            return;
                        }
                        else
                        {
                            sddlForm = commonSecurityDescriptor.GetSddlForm(AccessControlSections.All);
                        }
                    }
                    else
                    {
                        sddlForm = objectSecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
                    }
                    try
                    {
                        object[] objArray1 = new object[1];
                        objArray1[0] = sddlForm;
                        item.Invoke(objArray1);
                        return;
                    }
                    catch (Exception exception3)
                    {
                        Exception exception2 = exception3;
                        CommandProcessorBase.CheckForSevereException(exception2);
                        ErrorRecord errorRecord3 = SecurityUtils.CreateNotSupportedErrorRecord(UtilsStrings.MethodInvokeFail, "SetAcl_OperationNotSupported", new object[0]);
                        base.WriteError(errorRecord3);
                    }
                }
            }
        }
コード例 #3
0
        private void AddDuplicateParameterBindingException(CommandParameterAst duplicateParameter)
        {
            if (duplicateParameter == null)
            {
                return;
            }

            ParameterBindingException bindingException =
                new ParameterBindingException(
                    ErrorCategory.InvalidArgument,
                    null,
                    duplicateParameter.ErrorPosition,
                    duplicateParameter.ParameterName,
                    null,
                    null,
                    ParameterBinderStrings.ParameterAlreadyBound,
                    "ParameterAlreadyBound");
            // if the duplicated Parameter Name appears more than twice, we will ignore as we already have similar bindingException.
            if (!BindingExceptions.ContainsKey(duplicateParameter.ParameterName))
            {
                BindingExceptions.Add(duplicateParameter.ParameterName, new StaticBindingError(duplicateParameter, bindingException));
            }
        }
コード例 #4
0
 /// <summary>
 /// Creates a StaticBindingException
 /// </summary>
 /// <param name="commandElement">The element associated with the exception</param>
 /// <param name="exception">The parameter binding exception that got raised</param>
 internal StaticBindingError(CommandElementAst commandElement, ParameterBindingException exception)
 {
     this.CommandElement = commandElement;
     this.BindingException = exception;
 }
コード例 #5
0
        private void CreateBindingResultForSuccessfulBind(CommandAst commandAst, PseudoBindingInfo bindingInfo)
        {
            _bindingInfo = bindingInfo;

            // Check if there is exactly one parameter set valid. In that case,
            // ValidParameterSetFlags is exactly a power of two. Otherwise,
            // add to the binding exceptions.
            bool parameterSetSpecified = bindingInfo.ValidParameterSetsFlags != UInt32.MaxValue;
            bool remainingParameterSetIncludesDefault =
                (bindingInfo.DefaultParameterSetFlag != 0) &&
                ((bindingInfo.ValidParameterSetsFlags & bindingInfo.DefaultParameterSetFlag) ==
                bindingInfo.DefaultParameterSetFlag);

            // (x & (x -1 ) == 0) is a bit hack to determine if something is
            // exactly a power of two.
            bool onlyOneRemainingParameterSet =
                (bindingInfo.ValidParameterSetsFlags != 0) &&
                (bindingInfo.ValidParameterSetsFlags &
                        (bindingInfo.ValidParameterSetsFlags - 1)) == 0;

            if (parameterSetSpecified &&
                (!remainingParameterSetIncludesDefault) &&
                (!onlyOneRemainingParameterSet))
            {
                ParameterBindingException bindingException =
                    new ParameterBindingException(
                        ErrorCategory.InvalidArgument,
                        null,
                        null,
                        null,
                        null,
                        null,
                        ParameterBinderStrings.AmbiguousParameterSet,
                        "AmbiguousParameterSet");
                BindingExceptions.Add(commandAst.CommandElements[0].Extent.Text,
                    new StaticBindingError(commandAst.CommandElements[0], bindingException));
            }

            // Add error for duplicate parameters
            if (bindingInfo.DuplicateParameters != null)
            {
                foreach (AstParameterArgumentPair duplicateParameter in bindingInfo.DuplicateParameters)
                {
                    AddDuplicateParameterBindingException(duplicateParameter.Parameter);
                }
            }

            // Add error for parameters not found
            if (bindingInfo.ParametersNotFound != null)
            {
                foreach (CommandParameterAst parameterNotFound in bindingInfo.ParametersNotFound)
                {
                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            null,
                            parameterNotFound.ErrorPosition,
                            parameterNotFound.ParameterName,
                            null,
                            null,
                            ParameterBinderStrings.NamedParameterNotFound,
                            "NamedParameterNotFound");
                    BindingExceptions.Add(parameterNotFound.ParameterName, new StaticBindingError(parameterNotFound, bindingException));
                }
            }

            // Add error for ambiguous parameters
            if (bindingInfo.AmbiguousParameters != null)
            {
                foreach (CommandParameterAst ambiguousParameter in bindingInfo.AmbiguousParameters)
                {
                    ParameterBindingException bindingException = bindingInfo.BindingExceptions[ambiguousParameter];
                    BindingExceptions.Add(ambiguousParameter.ParameterName, new StaticBindingError(ambiguousParameter, bindingException));
                }
            }

            // Add error for unbound positional parameters
            if (bindingInfo.UnboundArguments != null)
            {
                foreach (AstParameterArgumentPair unboundArgument in bindingInfo.UnboundArguments)
                {
                    AstPair argument = unboundArgument as AstPair;

                    ParameterBindingException bindingException =
                        new ParameterBindingException(
                            ErrorCategory.InvalidArgument,
                            null,
                            argument.Argument.Extent,
                            argument.Argument.Extent.Text,
                            null,
                            null,
                            ParameterBinderStrings.PositionalParameterNotFound,
                            "PositionalParameterNotFound");
                    BindingExceptions.Add(argument.Argument.Extent.Text, new StaticBindingError(argument.Argument, bindingException));
                }
            }

            // Process the bound parameters
            if (bindingInfo.BoundParameters != null)
            {
                foreach (KeyValuePair<string, MergedCompiledCommandParameter> item in bindingInfo.BoundParameters)
                {
                    CompiledCommandParameter parameter = item.Value.Parameter;
                    CommandElementAst value = null;
                    Object constantValue = null;

                    // This is a single argument
                    AstPair argumentAstPair = bindingInfo.BoundArguments[item.Key] as AstPair;
                    if (argumentAstPair != null)
                    {
                        value = argumentAstPair.Argument;
                    }

                    // This is a parameter that took an argument, as well as ValueFromRemainingArguments.
                    // Merge the arguments into a single fake argument.
                    AstArrayPair argumentAstArrayPair = bindingInfo.BoundArguments[item.Key] as AstArrayPair;
                    if (argumentAstArrayPair != null)
                    {
                        List<ExpressionAst> arguments = new List<ExpressionAst>();
                        foreach (ExpressionAst expression in argumentAstArrayPair.Argument)
                        {
                            ArrayLiteralAst expressionArray = expression as ArrayLiteralAst;
                            if (expressionArray != null)
                            {
                                foreach (ExpressionAst newExpression in expressionArray.Elements)
                                {
                                    arguments.Add((ExpressionAst)newExpression.Copy());
                                }
                            }
                            else
                            {
                                arguments.Add((ExpressionAst)expression.Copy());
                            }
                        }

                        // Define the virtual extent and virtual ArrayLiteral.
                        IScriptExtent fakeExtent = arguments[0].Extent;
                        ArrayLiteralAst fakeArguments = new ArrayLiteralAst(fakeExtent, arguments);
                        value = fakeArguments;
                    }

                    // Special handling of switch parameters
                    if (parameter.Type == typeof(SwitchParameter))
                    {
                        if ((value != null) &&
                            (String.Equals("$false", value.Extent.Text, StringComparison.OrdinalIgnoreCase)))
                        {
                            continue;
                        }

                        constantValue = true;
                    }

                    // We got a parameter and a value
                    if ((value != null) || (constantValue != null))
                    {
                        BoundParameters.Add(item.Key, new ParameterBindingResult(parameter, value, constantValue));
                    }
                    else
                    {
                        bool takesValueFromPipeline = false;
                        foreach (ParameterSetSpecificMetadata parameterSet in parameter.GetMatchingParameterSetData(bindingInfo.ValidParameterSetsFlags))
                        {
                            if (parameterSet.ValueFromPipeline)
                            {
                                takesValueFromPipeline = true;
                                break;
                            }
                        }

                        if (!takesValueFromPipeline)
                        {
                            // We have a parameter with no value that isn't a switch parameter, or input parameter
                            ParameterBindingException bindingException =
                                new ParameterBindingException(
                                    ErrorCategory.InvalidArgument,
                                    null,
                                    commandAst.CommandElements[0].Extent,
                                    parameter.Name,
                                    parameter.Type,
                                    null,
                                    ParameterBinderStrings.MissingArgument,
                                    "MissingArgument");

                            BindingExceptions.Add(commandAst.CommandElements[0].Extent.Text,
                                new StaticBindingError(commandAst.CommandElements[0], bindingException));
                        }
                    }
                }
            }
        }