/// <summary> /// Copy constructor to support cloning. /// </summary> /// <param name="pipeline">The source pipeline.</param> /// <remarks> /// The copy constructor's intent is to support the scenario /// where a host needs to run the same set of commands multiple /// times. This is accomplished via creating a master pipeline /// then cloning it and executing the cloned copy. /// </remarks> protected PipelineBase(PipelineBase pipeline) : this(pipeline.Runspace, null, false, pipeline.IsNested) { // NTRAID#Windows Out Of Band Releases-915851-2005/09/13 if (pipeline is null) { throw PSTraceSource.NewArgumentNullException(nameof(pipeline)); } if (pipeline._disposed) { throw PSTraceSource.NewObjectDisposedException("pipeline"); } AddToHistory = pipeline.AddToHistory; HistoryString = pipeline.HistoryString; foreach (Command command in pipeline.Commands) { Command clone = command.Clone(); // Attach the cloned Command to this pipeline. Commands.Add(clone); } }
Start(RunspaceConfiguration configuration, string bannerText, string helpText, string preStartWarning, string[] args) { if (args == null) { throw PSTraceSource.NewArgumentNullException("args"); } // The default font face used for Powershell Console is Lucida Console. // However certain CJK locales dont support Lucida Console font. Hence for such // locales the console font is updated to Raster dynamically. // For NanoServer: // 1. There is no GetCurrentConsoleFontEx / SetCurrentConsoleFontEx on NanoServer; // 2. We don't handle CJK locales on NanoServer due to lack of win32 API supports on NanoServer. #if !CORECLR ConsoleControl.UpdateLocaleSpecificFont(); #endif return(ConsoleHost.Start(configuration, bannerText, helpText, preStartWarning, args)); }
InternalHostUserInterface(PSHostUserInterface externalUI, InternalHost parentHost) { // externalUI may be null _externalUI = externalUI; // parent may not be null, however Dbg.Assert(parentHost != null, "parent may not be null"); if (parentHost == null) { throw PSTraceSource.NewArgumentNullException("parentHost"); } _parent = parentHost; PSHostRawUserInterface rawui = null; if (externalUI != null) { rawui = externalUI.RawUI; } _internalRawUI = new InternalHostRawUserInterface(rawui, _parent); }
/// <summary> /// Gets the security descriptor for the item specified by <paramref name="path"/>. /// </summary> /// <param name="path"> /// The path to the item. /// </param> /// <param name="sections"> /// Specifies the parts of a security descriptor to retrieve. /// </param> /// <returns> /// Nothing. An object that represents the security descriptor for the item /// specified by path is written to the WriteSecurityDescriptorObject method. /// </returns> public void GetSecurityDescriptor(string path, AccessControlSections sections) { ObjectSecurity sd = null; IRegistryWrapper key = null; // Validate input first. if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentNullException(nameof(path)); } if ((sections & ~AccessControlSections.All) != 0) { throw PSTraceSource.NewArgumentException(nameof(sections)); } path = NormalizePath(path); key = GetRegkeyForPathWriteIfError(path, false); if (key != null) { try { sd = key.GetAccessControl(sections); } catch (System.Security.SecurityException e) { WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } WriteSecurityDescriptorObject(sd, path); } }
// TODO: If this is not used remove this // internal override event EventHandler<RemoteDataEventArgs> DataReceived; /// <summary> /// This processes the object received from transport which are /// targeted for session /// </summary> /// <param name="arg"> /// argument contains the data object /// </param> private void ProcessSessionMessages(RemoteDataEventArgs arg) { if (arg == null || arg.ReceivedData == null) { throw PSTraceSource.NewArgumentNullException("arg"); } RemoteDataObject <PSObject> rcvdData = arg.ReceivedData; RemotingTargetInterface targetInterface = rcvdData.TargetInterface; Dbg.Assert(targetInterface == RemotingTargetInterface.Session, "targetInterface must be Session"); RemotingDataType dataType = rcvdData.DataType; switch (dataType) { case RemotingDataType.CloseSession: PSRemotingDataStructureException reasonOfClose = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerRequestedToCloseSession); RemoteSessionStateMachineEventArgs closeSessionArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, reasonOfClose); _stateMachine.RaiseEvent(closeSessionArg); break; case RemotingDataType.SessionCapability: RemoteSessionCapability capability = null; try { capability = RemotingDecoder.GetSessionCapability(rcvdData.Data); } catch (PSRemotingDataStructureException dse) { // this will happen if expected properties are not // received for session capability throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientNotFoundCapabilityProperties, dse.Message, PSVersionInfo.GitCommitId, RemotingConstants.ProtocolVersion); } RemoteSessionStateMachineEventArgs capabilityArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationReceived); capabilityArg.RemoteSessionCapability = capability; _stateMachine.RaiseEvent(capabilityArg); RemoteSessionNegotiationEventArgs negotiationArg = new RemoteSessionNegotiationEventArgs(capability); NegotiationReceived.SafeInvoke(this, negotiationArg); break; case RemotingDataType.EncryptedSessionKey: { String encryptedSessionKey = RemotingDecoder.GetEncryptedSessionKey(rcvdData.Data); EncryptedSessionKeyReceived.SafeInvoke(this, new RemoteDataEventArgs <string>(encryptedSessionKey)); } break; case RemotingDataType.PublicKeyRequest: { PublicKeyRequestReceived.SafeInvoke(this, new RemoteDataEventArgs <string>(String.Empty)); } break; default: { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType); } } }
private bool LoadCommonViewData(XmlNode viewNode, ViewDefinition view, List <XmlNode> unprocessedNodes) { if (viewNode == null) { throw PSTraceSource.NewArgumentNullException("viewNode"); } if (view == null) { throw PSTraceSource.NewArgumentNullException("view"); } // set loading information view.loadingInfo = this.LoadingInfo; view.loadingInfo.xPath = this.ComputeCurrentXPath(); // start the loading process bool nameNodeFound = false; // cardinality 1 bool appliesToNodeFound = false; // cardinality 1 bool groupByFound = false; // cardinality 0..1 foreach (XmlNode n in viewNode.ChildNodes) { if (MatchNodeName(n, XmlTags.NameNode)) { if (nameNodeFound) { this.ProcessDuplicateNode(n); return(false); } nameNodeFound = true; view.name = GetMandatoryInnerText(n); if (view.name == null) { return(false); } } else if (MatchNodeName(n, XmlTags.ViewSelectedByNode)) { if (appliesToNodeFound) { this.ProcessDuplicateNode(n); return(false); } appliesToNodeFound = true; // if null, we invalidate the view view.appliesTo = LoadAppliesToSection(n, false); if (view.appliesTo == null) { return(false); } } else if (MatchNodeName(n, XmlTags.GroupByNode)) { if (groupByFound) { this.ProcessDuplicateNode(n); return(false); } groupByFound = true; view.groupBy = LoadGroupBySection(n); if (view.groupBy == null) { return(false); } } else { // save for further processing unprocessedNodes.Add(n); } } // for if (!nameNodeFound) { this.ReportMissingNode(XmlTags.NameNode); return(false); } if (!appliesToNodeFound) { this.ReportMissingNode(XmlTags.ViewSelectedByNode); return(false); } return(true); }
/// <summary> /// Loads a Monad Console file specified by <paramref name="path"/> /// </summary> /// <param name="path"> /// The absolute path from which the content is loaded. /// </param> /// <param name="cle"> /// PSConsoleLoadException occurred while loading this console file. This object /// also contains specific PSSnapInExceptions that occurred while loading. /// </param> /// <returns> /// A list of <see cref="PSSnapInInfo"/> objects specified in the console file. /// </returns> /// <exception cref="PSArgumentNullException"> /// Path is null. /// </exception> /// <exception cref="PSArgumentException"> /// 1. Path does not specify proper file extension. /// 2. PSSnapInId doesnt contain valid characters. /// 3. Path is not an Absolute Path. /// Example of valid paths:"\\MyDir\\MyFile.txt" and "C:\\MyDir". /// </exception> /// <exception cref="ArgumentException"> /// path contains one or more of the invalid characters defined in System.IO.Path.InvalidPathChars. /// </exception> /// <exception cref="XmlException"> /// Unable to load/parse the file specified by path. /// </exception> private Collection <PSSnapInInfo> Load(string path, out PSConsoleLoadException cle) { // Initialize the out parameter.. cle = null; s_mshsnapinTracer.WriteLine("Load mshsnapins from console file {0}", path); if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentNullException("path"); } // Check whether the path is an absolute path if (!Path.IsPathRooted(path)) { s_mshsnapinTracer.TraceError("Console file {0} needs to be a absolute path.", path); throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.PathNotAbsolute, path); } if (!path.EndsWith(StringLiterals.PowerShellConsoleFileExtension, StringComparison.OrdinalIgnoreCase)) { s_mshsnapinTracer.TraceError("Console file {0} needs to have {1} extension.", path, StringLiterals.PowerShellConsoleFileExtension); throw PSTraceSource.NewArgumentException("path", ConsoleInfoErrorStrings.BadConsoleExtension); } PSConsoleFileElement consoleFileElement; // exceptions are thrown to the caller consoleFileElement = PSConsoleFileElement.CreateFromFile(path); // consoleFileElement will never be null.. if (!Utils.IsPSVersionSupported(consoleFileElement.MonadVersion)) { s_mshsnapinTracer.TraceError("Console version {0} is not supported in current monad session.", consoleFileElement.MonadVersion); throw PSTraceSource.NewArgumentException("PSVersion", ConsoleInfoErrorStrings.BadMonadVersion, consoleFileElement.MonadVersion, PSVersion.ToString()); } // Create a store for exceptions Collection <PSSnapInException> exceptions = new Collection <PSSnapInException>(); foreach (string mshsnapin in consoleFileElement.PSSnapIns) { try { this.AddPSSnapIn(mshsnapin); } catch (PSArgumentException ae) { PSSnapInException sle = new PSSnapInException(mshsnapin, ae.Message, ae); // Eat ArgumentException and continue.. exceptions.Add(sle); } catch (System.Security.SecurityException se) { string message = ConsoleInfoErrorStrings.PSSnapInReadError; PSSnapInException sle = new PSSnapInException(mshsnapin, message, se); // Eat SecurityException and continue.. exceptions.Add(sle); } } // Before returning check whether there are any exceptions if (exceptions.Count > 0) { cle = new PSConsoleLoadException(this, exceptions); } // We are able to load console file and currently monad engine // can service this. So mark the isdirty flag. IsDirty = false; return(_externalPSSnapIns); }
/// <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(nameof(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 not 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 ? Array.Empty <ValidateArgumentsAttribute>() : validationAttributes.ToArray(); this.ArgumentTransformationAttributes = argTransformationAttributes == null ? Array.Empty <ArgumentTransformationAttribute>() : argTransformationAttributes.ToArray(); this.Aliases = aliases == null ? Array.Empty <string>() : aliases.ToArray(); }
internal int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue) { if (commandProcessor == null) { throw PSTraceSource.NewArgumentNullException("commandProcessor"); } if (this._commands == null) { throw PSTraceSource.NewInvalidOperationException(); } if (this.disposed) { throw PSTraceSource.NewObjectDisposedException("PipelineProcessor"); } if (this.executionStarted) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "ExecutionAlreadyStarted", new object[0]); } if (commandProcessor.AddedToPipelineAlready) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "CommandProcessorAlreadyUsed", new object[0]); } if (this._commands.Count == 0) { if (readFromCommand != 0) { throw PSTraceSource.NewArgumentException("readFromCommand", "PipelineStrings", "FirstCommandCannotHaveInput", new object[0]); } commandProcessor.AddedToPipelineAlready = true; } else { if ((readFromCommand > this._commands.Count) || (readFromCommand <= 0)) { throw PSTraceSource.NewArgumentException("readFromCommand", "PipelineStrings", "InvalidCommandNumber", new object[0]); } CommandProcessorBase base2 = this._commands[readFromCommand - 1]; if ((base2 == null) || (base2.CommandRuntime == null)) { throw PSTraceSource.NewInvalidOperationException(); } Pipe pipe = readErrorQueue ? base2.CommandRuntime.ErrorOutputPipe : base2.CommandRuntime.OutputPipe; if (pipe == null) { throw PSTraceSource.NewInvalidOperationException(); } if (pipe.DownstreamCmdlet != null) { throw PSTraceSource.NewInvalidOperationException("PipelineStrings", "PipeAlreadyTaken", new object[0]); } commandProcessor.AddedToPipelineAlready = true; commandProcessor.CommandRuntime.InputPipe = pipe; pipe.DownstreamCmdlet = commandProcessor; if (commandProcessor.CommandRuntime.MergeUnclaimedPreviousErrorResults) { for (int i = 0; i < this._commands.Count; i++) { base2 = this._commands[i]; if ((base2 == null) || (base2.CommandRuntime == null)) { throw PSTraceSource.NewInvalidOperationException(); } if ((base2.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null) && (base2.CommandRuntime.ErrorOutputPipe.ExternalWriter == null)) { base2.CommandRuntime.ErrorOutputPipe = pipe; } } } } this._commands.Add(commandProcessor); commandProcessor.CommandRuntime.PipelineProcessor = this; return(this._commands.Count); }
/// <summary> /// Sets the digital signature on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { SigningOption option = GetSigningOption(IncludeChain); if (Certificate == null) { throw PSTraceSource.NewArgumentNullException("certificate"); } // // if the cert is not good for signing, we cannot // process any more files. Exit the command. // if (!SecuritySupport.CertIsGoodForSigning(Certificate)) { Exception e = PSTraceSource.NewArgumentException( "certificate", SignatureCommands.CertNotGoodForSigning); throw e; } if (!ShouldProcess(filePath)) { return(null); } FileInfo readOnlyFileInfo = null; try { if (this.Force) { try { // remove readonly attributes on the file FileInfo fInfo = new(filePath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // remember to reset the read-only attribute later readOnlyFileInfo = fInfo; // Make sure the file is not read only fInfo.Attributes &= ~(FileAttributes.ReadOnly); } } } // These are the known exceptions for File.Load and StreamWriter.ctor catch (ArgumentException e) { ErrorRecord er = new( e, "ForceArgumentException", ErrorCategory.WriteError, filePath); WriteError(er); return(null); } catch (IOException e) { ErrorRecord er = new( e, "ForceIOException", ErrorCategory.WriteError, filePath); WriteError(er); return(null); } catch (UnauthorizedAccessException e) { ErrorRecord er = new( e, "ForceUnauthorizedAccessException", ErrorCategory.PermissionDenied, filePath); WriteError(er); return(null); } catch (NotSupportedException e) { ErrorRecord er = new( e, "ForceNotSupportedException", ErrorCategory.WriteError, filePath); WriteError(er); return(null); } catch (System.Security.SecurityException e) { ErrorRecord er = new( e, "ForceSecurityException", ErrorCategory.PermissionDenied, filePath); WriteError(er); return(null); } } // // ProcessRecord() code in base class has already // ascertained that filePath really represents an existing // file. Thus we can safely call GetFileSize() below. // if (SecurityUtils.GetFileSize(filePath) < 4) { // Note that the message param comes first string message = string.Format( System.Globalization.CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, filePath); PSArgumentException e = new(message, nameof(filePath)); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SignatureCommandsBaseFileSmallerThan4Bytes" ); WriteError(er); return(null); } return(SignatureHelper.SignFile(option, filePath, Certificate, TimestampServer, _hashAlgorithm)); } finally { // reset the read-only attribute if (readOnlyFileInfo != null) { readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } } }
internal static CommandParameterInternal ToCommandParameterInternal(CommandParameter publicParameter, bool forNativeCommand) { if (publicParameter == null) { throw PSTraceSource.NewArgumentNullException(nameof(publicParameter)); } string name = publicParameter.Name; object value = publicParameter.Value; Debug.Assert((name == null) || (name.Trim().Length != 0), "Parameter name has to null or have some non-whitespace characters in it"); if (name == null) { return(CommandParameterInternal.CreateArgument(value)); } string parameterText; if (!name[0].IsDash()) { parameterText = forNativeCommand ? name : "-" + name; return(CommandParameterInternal.CreateParameterWithArgument( parameterAst: null, parameterName: name, parameterText: parameterText, argumentAst: null, value: value, spaceAfterParameter: true)); } // if first character of name is '-', then we try to fake the original token // reconstructing dashes, colons and followed-by-space information // find the last non-whitespace character bool spaceAfterParameter = false; int endPosition = name.Length; while ((endPosition > 0) && char.IsWhiteSpace(name[endPosition - 1])) { spaceAfterParameter = true; endPosition--; } Debug.Assert(endPosition > 0, "parameter name should have some non-whitespace characters in it"); // now make sure that parameterText doesn't have whitespace at the end, parameterText = name.Substring(0, endPosition); // parameterName should contain only the actual name of the parameter (no whitespace, colons, dashes) bool hasColon = (name[endPosition - 1] == ':'); var parameterName = parameterText.Substring(1, parameterText.Length - (hasColon ? 2 : 1)); // At this point we have rebuilt the token. There are 3 strings that might be different: // name = nameToken.Script = "-foo: " <- needed to fake FollowedBySpace=true (i.e. for "testecho.exe -a:b -c: d") // tokenString = nameToken.TokenText = "-foo:" <- needed to preserve full token text (i.e. for write-output) // nameToken.Data = "foo" <- needed to preserve name of parameter so parameter binding works // Now we just need to use the token to build appropriate CommandParameterInternal object // is this a name+value pair, or is it just a name (of a parameter)? if (!hasColon && value == null) { // just a name return(CommandParameterInternal.CreateParameter(parameterName, parameterText)); } // name+value pair return(CommandParameterInternal.CreateParameterWithArgument( parameterAst: null, parameterName, parameterText, argumentAst: null, value, spaceAfterParameter, publicParameter.FromHashtableSplatting)); }
private Collection <int> EmulatePromptForMultipleChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { if (choices == null) { throw PSTraceSource.NewArgumentNullException("choices"); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException("choices", "InternalHostUserInterfaceStrings", "EmptyChoicesError", new object[] { "choices" }); } Dictionary <int, bool> dictionary = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int num in defaultChoices) { if ((num < 0) || (num >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", num, "InternalHostUserInterfaceStrings", "InvalidDefaultChoiceForMultipleSelection", new object[] { "defaultChoice", "choices", num }); } if (!dictionary.ContainsKey(num)) { dictionary.Add(num, true); } } } StringBuilder builder = new StringBuilder(); char ch = '\n'; if (!string.IsNullOrEmpty(caption)) { builder.Append(caption); builder.Append(ch); } if (!string.IsNullOrEmpty(message)) { builder.Append(message); builder.Append(ch); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); string format = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); i++) { string str2 = string.Format(CultureInfo.InvariantCulture, format, new object[] { hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i] }); builder.Append(str2); builder.Append(ch); } string str3 = ""; if (dictionary.Count > 0) { string str4 = ""; StringBuilder builder2 = new StringBuilder(); foreach (int num3 in dictionary.Keys) { string str5 = hotkeysAndPlainLabels[0, num3]; if (string.IsNullOrEmpty(str5)) { str5 = hotkeysAndPlainLabels[1, num3]; } builder2.Append(string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { str4, str5 })); str4 = ","; } string str6 = builder2.ToString(); if (dictionary.Count == 1) { str3 = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, str6); } else { str3 = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, str6); } } string str7 = builder.ToString() + str3 + ch; Collection <int> collection = new Collection <int>(); int o = 0; while (true) { string str8 = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, o); str7 = str7 + str8; this.externalUI.WriteLine(str7); string str9 = this.externalUI.ReadLine(); if (str9.Length == 0) { if ((collection.Count == 0) && (dictionary.Keys.Count >= 0)) { foreach (int num5 in dictionary.Keys) { collection.Add(num5); } } return(collection); } int item = HostUIHelperMethods.DetermineChoicePicked(str9.Trim(), choices, hotkeysAndPlainLabels); if (item >= 0) { collection.Add(item); o++; } str7 = ""; } }
/// <summary> /// This method is used by the input queue dispatching mechanism. /// It examines the data and takes appropriate actions. /// </summary> /// <param name="dataArg"> /// The received client data. /// </param> /// /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> internal override void RaiseDataReceivedEvent(RemoteDataEventArgs dataArg) { if (dataArg == null) { throw PSTraceSource.NewArgumentNullException("dataArg"); } RemoteDataObject <PSObject> rcvdData = dataArg.ReceivedData; RemotingTargetInterface targetInterface = rcvdData.TargetInterface; RemotingDataType dataType = rcvdData.DataType; Dbg.Assert(targetInterface == RemotingTargetInterface.Session, "targetInterface must be Session"); switch (dataType) { case RemotingDataType.CreateRunspacePool: { // At this point, the negotiation is complete, so // need to import the clients public key CreateRunspacePoolReceived.SafeInvoke(this, dataArg); } break; case RemotingDataType.CloseSession: PSRemotingDataStructureException reasonOfClose = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientRequestedToCloseSession); RemoteSessionStateMachineEventArgs closeSessionArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.Close, reasonOfClose); _stateMachine.RaiseEvent(closeSessionArg); break; case RemotingDataType.SessionCapability: RemoteSessionCapability capability = null; try { capability = RemotingDecoder.GetSessionCapability(rcvdData.Data); } catch (PSRemotingDataStructureException dse) { // this will happen if expected properties are not // received for session capability throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNotFoundCapabilityProperties, dse.Message, PSVersionInfo.BuildVersion, RemotingConstants.ProtocolVersion); } RemoteSessionStateMachineEventArgs capabilityArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.NegotiationReceived); capabilityArg.RemoteSessionCapability = capability; _stateMachine.RaiseEvent(capabilityArg); if (NegotiationReceived != null) { RemoteSessionNegotiationEventArgs negotiationArg = new RemoteSessionNegotiationEventArgs(capability); negotiationArg.RemoteData = rcvdData; NegotiationReceived.SafeInvoke(this, negotiationArg); } break; case RemotingDataType.PublicKey: { string remotePublicKey = RemotingDecoder.GetPublicKey(rcvdData.Data); PublicKeyReceived.SafeInvoke(this, new RemoteDataEventArgs <string>(remotePublicKey)); } break; default: throw new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedAction, dataType); } }
internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (_trace.TraceEventHandlers()) { Guid runspacePoolId; if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } if (fsmEventArg.RemoteData == null) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } RemotingTargetInterface targetInterface = fsmEventArg.RemoteData.TargetInterface; RemotingDataType dataType = fsmEventArg.RemoteData.DataType; RemoteDataEventArgs arg = null; switch (targetInterface) { case RemotingTargetInterface.Session: switch (dataType) { case RemotingDataType.CreateRunspacePool: { arg = new RemoteDataEventArgs(fsmEventArg.RemoteData); this._session.SessionDataStructureHandler.RaiseDataReceivedEvent(arg); } break; } return; case RemotingTargetInterface.RunspacePool: { runspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; ServerRunspacePoolDriver runspacePoolDriver = this._session.GetRunspacePoolDriver(runspacePoolId); if (runspacePoolDriver == null) { break; } runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData); return; } case RemotingTargetInterface.PowerShell: runspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; this._session.GetRunspacePoolDriver(runspacePoolId).DataStructureHandler.DispatchMessageToPowerShell(fsmEventArg.RemoteData); return; default: goto Label_0151; } _trace.WriteLine("Server received data for Runspace (id: {0}), \r\n but the Runspace cannot be found", new object[] { runspacePoolId }); PSRemotingDataStructureException reason = new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceCannotBeFound, new object[] { runspacePoolId }); RemoteSessionStateMachineEventArgs args2 = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reason); this.RaiseEvent(args2); return; Label_0151 :; _trace.WriteLine("Server received data unknown targetInterface: {0}", new object[] { targetInterface }); PSRemotingDataStructureException exception2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, new object[] { targetInterface }); RemoteSessionStateMachineEventArgs args3 = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, exception2); this.RaiseEvent(args3); } }
internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session) { EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray9 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray10 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray11 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray12 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray13 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray14 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray15 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray16 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray17 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray18 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray19 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray20 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray21 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray22 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray23 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray24 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray25 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray26 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray27 = null; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray28 = null; this.processPendingEventsQueue = new Queue <RemoteSessionStateMachineEventArgs>(); if (session == null) { throw PSTraceSource.NewArgumentNullException("session"); } this._session = session; this._syncObject = new object(); this._stateMachineHandle = new EventHandler <RemoteSessionStateMachineEventArgs> [20, 0x20]; for (int i = 0; i < this._stateMachineHandle.GetLength(0); i++) { EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray = null; IntPtr ptr = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray2 = null; IntPtr ptr2 = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray3 = null; IntPtr ptr3 = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray4 = null; IntPtr ptr4 = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray5 = null; IntPtr ptr5 = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray6 = null; IntPtr ptr6 = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray7 = null; IntPtr ptr7 = IntPtr.Zero; EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray8 = null; IntPtr ptr8 = IntPtr.Zero; (handlerArray = this._stateMachineHandle)[(int)(ptr = (IntPtr)i), 0x11] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray[(int)ptr, 0x11], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoFatalError)); (handlerArray2 = this._stateMachineHandle)[(int)(ptr2 = (IntPtr)i), 9] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray2[(int)ptr2, 9], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoClose)); (handlerArray3 = this._stateMachineHandle)[(int)(ptr3 = (IntPtr)i), 11] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray3[(int)ptr3, 11], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoCloseFailed)); (handlerArray4 = this._stateMachineHandle)[(int)(ptr4 = (IntPtr)i), 10] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray4[(int)ptr4, 10], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoCloseCompleted)); (handlerArray5 = this._stateMachineHandle)[(int)(ptr5 = (IntPtr)i), 14] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray5[(int)ptr5, 14], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoNegotiationTimeout)); (handlerArray6 = this._stateMachineHandle)[(int)(ptr6 = (IntPtr)i), 15] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray6[(int)ptr6, 15], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoSendFailed)); (handlerArray7 = this._stateMachineHandle)[(int)(ptr7 = (IntPtr)i), 0x10] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray7[(int)ptr7, 0x10], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoReceiveFailed)); (handlerArray8 = this._stateMachineHandle)[(int)(ptr8 = (IntPtr)i), 2] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray8[(int)ptr8, 2], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoConnect)); } (handlerArray9 = this._stateMachineHandle)[1, 1] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray9[1, 1], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoCreateSession)); (handlerArray10 = this._stateMachineHandle)[8, 6] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray10[8, 6], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoNegotiationReceived)); (handlerArray11 = this._stateMachineHandle)[7, 3] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray11[7, 3], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoNegotiationSending)); (handlerArray12 = this._stateMachineHandle)[4, 5] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray12[4, 5], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoNegotiationCompleted)); (handlerArray13 = this._stateMachineHandle)[6, 7] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray13[6, 7], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoEstablished)); (handlerArray14 = this._stateMachineHandle)[6, 8] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray14[6, 8], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoNegotiationPending)); (handlerArray15 = this._stateMachineHandle)[11, 0x12] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray15[11, 0x12], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoMessageReceived)); (handlerArray16 = this._stateMachineHandle)[7, 13] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray16[7, 13], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoNegotiationFailed)); (handlerArray17 = this._stateMachineHandle)[2, 12] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray17[2, 12], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoConnectFailed)); (handlerArray18 = this._stateMachineHandle)[11, 0x15] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray18[11, 0x15], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray19 = this._stateMachineHandle)[11, 0x17] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray19[11, 0x17], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray20 = this._stateMachineHandle)[11, 0x16] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray20[11, 0x16], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray21 = this._stateMachineHandle)[14, 0x15] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray21[14, 0x15], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray22 = this._stateMachineHandle)[14, 0x13] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray22[14, 0x13], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray23 = this._stateMachineHandle)[14, 0x16] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray23[14, 0x16], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray24 = this._stateMachineHandle)[13, 20] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray24[13, 20], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray25 = this._stateMachineHandle)[13, 0x13] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray25[13, 0x13], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray26 = this._stateMachineHandle)[15, 0x15] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray26[15, 0x15], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray27 = this._stateMachineHandle)[15, 0x17] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray27[15, 0x17], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); (handlerArray28 = this._stateMachineHandle)[15, 0x16] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray28[15, 0x16], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoKeyExchange)); for (int j = 0; j < this._stateMachineHandle.GetLength(0); j++) { for (int k = 0; k < this._stateMachineHandle.GetLength(1); k++) { if (this._stateMachineHandle[j, k] == null) { EventHandler <RemoteSessionStateMachineEventArgs>[,] handlerArray29 = null; IntPtr ptr9 = IntPtr.Zero; IntPtr ptr10 = IntPtr.Zero; (handlerArray29 = this._stateMachineHandle)[(int)(ptr9 = (IntPtr)j), (int)(ptr10 = (IntPtr)k)] = (EventHandler <RemoteSessionStateMachineEventArgs>)Delegate.Combine(handlerArray29[(int)ptr9, (int)ptr10], new EventHandler <RemoteSessionStateMachineEventArgs>(this.DoClose)); } } } this.SetState(RemoteSessionState.Idle, null); }
/// <summary> /// See base class. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoice"></param> /// <returns></returns> /// <exception cref="ArgumentNullException"> /// If <paramref name="choices"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If <paramref name="choices"/>.Count is 0. /// </exception> /// <exception cref="ArgumentOutOfRangeException"> /// If <paramref name="defaultChoice"/> is greater than /// the length of <paramref name="choices"/>. /// </exception> /// <exception cref="PromptingException"> /// when prompt is canceled by, for example, Ctrl-c. /// </exception> public override int PromptForChoice(string caption, string message, Collection <ChoiceDescription> choices, int defaultChoice) { HandleThrowOnReadAndPrompt(); if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(choices), ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } if ((defaultChoice < -1) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(defaultChoice), defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceErrorTemplate, "defaultChoice", "choice"); } // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); } if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } int result = defaultChoice; string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); // add the default choice key only if it is valid. -1 is used to specify // no default. if (defaultChoice >= 0) { defaultChoiceKeys.Add(defaultChoice, true); } while (true) { WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, false); ReadLineResult rlResult; string response = ReadChoiceResponse(out rlResult); if (rlResult == ReadLineResult.endedOnBreak) { string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; PromptingException e = new PromptingException( msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); throw e; } if (response.Length == 0) { // they just hit enter. if (defaultChoice >= 0) { // if there's a default, pick that one. result = defaultChoice; break; } continue; } // decide which choice they made. if (response.Trim() == "?") { // show the help ShowChoiceHelp(choices, hotkeysAndPlainLabels); continue; } result = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (result >= 0) { break; } // their input matched none of the choices, so prompt again } return(result); } }
/// <summary> /// Presents a dialog allowing the user to choose options from a set of options. /// </summary> /// <param name="caption"> /// Caption to precede or title the prompt. E.g. "Parameters for get-foo (instance 1 of 2)" /// </param> /// <param name="message"> /// A message that describes what the choice is for. /// </param> /// <param name="choices"> /// An Collection of ChoiceDescription objects that describe each choice. /// </param> /// <param name="defaultChoices"> /// The index of the labels in the choices collection element to be presented to the user as /// the default choice(s). /// </param> /// <returns> /// The indices of the choice elements that corresponds to the options selected. /// </returns> /// <seealso cref="System.Management.Automation.Host.PSHostUserInterface.PromptForChoice"/> public Collection <int> PromptForChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { HandleThrowOnReadAndPrompt(); if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(choices), ConsoleHostUserInterfaceStrings.EmptyChoicesErrorTemplate, "choices"); } Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, ConsoleHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } defaultChoiceKeys.TryAdd(defaultChoice, true); } } Collection <int> result = new Collection <int>(); // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { // write caption on the console, if present. if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); } // write message if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); WriteChoicePrompt(hotkeysAndPlainLabels, defaultChoiceKeys, true); if (defaultChoiceKeys.Count > 0) { WriteLineToConsole(); } // used to display ChoiceMessage like Choice[0],Choice[1] etc int choicesSelected = 0; while (true) { // write the current prompt string choiceMsg = StringUtil.Format(ConsoleHostUserInterfaceStrings.ChoiceMessage, choicesSelected); WriteToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(choiceMsg)); ReadLineResult rlResult; string response = ReadChoiceResponse(out rlResult); if (rlResult == ReadLineResult.endedOnBreak) { string msg = ConsoleHostUserInterfaceStrings.PromptCanceledError; PromptingException e = new PromptingException( msg, null, "PromptForChoiceCanceled", ErrorCategory.OperationStopped); throw e; } // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } // decide which choice they made. if (response.Trim() == "?") { // show the help ShowChoiceHelp(choices, hotkeysAndPlainLabels); continue; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // prompt for multiple choices } return(result); } }
Prompt(string caption, string message, Collection <FieldDescription> descriptions) { // Need to implement EchoOnPrompt HandleThrowOnReadAndPrompt(); if (descriptions == null) { throw PSTraceSource.NewArgumentNullException("descriptions"); } if (descriptions.Count < 1) { throw PSTraceSource.NewArgumentException("descriptions", ConsoleHostUserInterfaceStrings.PromptEmptyDescriptionsErrorTemplate, "descriptions"); } // we lock here so that multiple threads won't interleave the various reads and writes here. lock (_instanceLock) { Dictionary <string, PSObject> results = new Dictionary <string, PSObject>(); bool cancelInput = false; if (!string.IsNullOrEmpty(caption)) { // Should be a skin lookup WriteLineToConsole(); WriteLineToConsole(PromptColor, RawUI.BackgroundColor, WrapToCurrentWindowWidth(caption)); } if (!string.IsNullOrEmpty(message)) { WriteLineToConsole(WrapToCurrentWindowWidth(message)); } if (AtLeastOneHelpMessageIsPresent(descriptions)) { WriteLineToConsole(WrapToCurrentWindowWidth(ConsoleHostUserInterfaceStrings.PromptHelp)); } int descIndex = -1; foreach (FieldDescription desc in descriptions) { descIndex++; if (desc == null) { throw PSTraceSource.NewArgumentException("descriptions", ConsoleHostUserInterfaceStrings.NullErrorTemplate, string.Format(CultureInfo.InvariantCulture, "descriptions[{0}]", descIndex)); } PSObject inputPSObject = null; string fieldPrompt = null; fieldPrompt = desc.Name; bool fieldEchoOnPrompt = true; // FieldDescription.ParameterAssemblyFullName never returns null. But this is // defense in depth. if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) { string paramName = string.Format(CultureInfo.InvariantCulture, "descriptions[{0}].AssemblyFullName", descIndex); throw PSTraceSource.NewArgumentException(paramName, ConsoleHostUserInterfaceStrings.NullOrEmptyErrorTemplate, paramName); } Type fieldType = InternalHostUserInterface.GetFieldType(desc); if (fieldType == null) { if (InternalHostUserInterface.IsSecuritySensitiveType(desc.ParameterTypeName)) { string errMsg = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptTypeLoadErrorTemplate, desc.Name, desc.ParameterTypeFullName); PromptingException e = new PromptingException(errMsg, null, "BadTypeName", ErrorCategory.InvalidType); throw e; } fieldType = typeof(string); } if (fieldType.GetInterface(typeof(IList).FullName) != null) { // field is a type implementing IList ArrayList inputList = new ArrayList(); // stores all converted user input before // assigned to an array // if the field is an array, the element type can be found; else, use Object Type elementType = typeof(object); if (fieldType.IsArray) { elementType = fieldType.GetElementType(); int rank = fieldType.GetArrayRank(); // This check may be redundant because it doesn't seem possible to create // an array of zero dimension. if (rank <= 0) { string msg = StringUtil.Format(ConsoleHostUserInterfaceStrings.RankZeroArrayErrorTemplate, desc.Name); ArgumentException innerException = PSTraceSource.NewArgumentException( string.Format(CultureInfo.InvariantCulture, "descriptions[{0}].AssemblyFullName", descIndex)); PromptingException e = new PromptingException(msg, innerException, "ZeroRankArray", ErrorCategory.InvalidOperation); throw e; } } StringBuilder fieldPromptList = new StringBuilder(fieldPrompt); // fieldPromptList = fieldPrompt + "[i] :" fieldPromptList.Append("["); while (true) { fieldPromptList.Append( string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); bool inputListEnd = false; object convertedObj = null; string inputString = PromptForSingleItem(elementType, fieldPromptList.ToString(), fieldPrompt, caption, message, desc, fieldEchoOnPrompt, true, out inputListEnd, out cancelInput, out convertedObj); if (cancelInput || inputListEnd) { break; } else if (!cancelInput) { inputList.Add(convertedObj); // Remove the indices from the prompt fieldPromptList.Length = fieldPrompt.Length + 1; } } // if cancelInput, should throw OperationCancelException? if (!cancelInput) { object tryConvertResult = null; if (LanguagePrimitives.TryConvertTo(inputList, fieldType, out tryConvertResult)) { inputPSObject = PSObject.AsPSObject(tryConvertResult); } else { inputPSObject = PSObject.AsPSObject(inputList); } } } else { string printFieldPrompt = StringUtil.Format(ConsoleHostUserInterfaceStrings.PromptFieldPromptInputSeparatorTemplate, fieldPrompt); // field is not a list object convertedObj = null; bool dummy = false; PromptForSingleItem(fieldType, printFieldPrompt, fieldPrompt, caption, message, desc, fieldEchoOnPrompt, false, out dummy, out cancelInput, out convertedObj); if (!cancelInput) { inputPSObject = PSObject.AsPSObject(convertedObj); } } if (cancelInput) { s_tracer.WriteLine("Prompt canceled"); WriteLineToConsole(); results.Clear(); break; } results.Add(desc.Name, PSObject.AsPSObject(inputPSObject)); } return(results); } }
/// <summary> /// Creates a new item if one of the same name doesn't already exist. /// </summary> /// /// <param name="path"> /// The name of the item to create. /// </param> /// /// <param name="type"> /// Ignored. /// </param> /// /// <param name="newItem"> /// The value of the new item. /// </param> /// protected override void NewItem(string path, string type, object newItem) { if (String.IsNullOrEmpty(path)) { Exception e = PSTraceSource.NewArgumentException("path"); WriteError(new ErrorRecord( e, "NewItemNullPath", ErrorCategory.InvalidArgument, path)); return; } if (newItem == null) { ArgumentNullException argException = PSTraceSource.NewArgumentNullException("value"); WriteError( new ErrorRecord( argException, "NewItemValueNotSpecified", ErrorCategory.InvalidArgument, path)); return; } if (ItemExists(path) && !Force) { PSArgumentException e = (PSArgumentException) PSTraceSource.NewArgumentException( "path", SessionStateStrings.NewItemAlreadyExists, path); WriteError( new ErrorRecord( e.ErrorRecord, e)); return; } else { // Confirm the new item with the user string action = SessionStateProviderBaseStrings.NewItemAction; string resourceTemplate = SessionStateProviderBaseStrings.NewItemResourceTemplate; string resource = String.Format( Host.CurrentCulture, resourceTemplate, path, type, newItem); if (ShouldProcess(resource, action)) { SetItem(path, newItem); } } } // NewItem
/// <summary> /// Dispatches data when it arrives from the input queue. /// </summary> /// <param name="sender"></param> /// <param name="dataArg"> /// arg which contains the data received from input queue /// </param> internal void DispatchInputQueueData(object sender, RemoteDataEventArgs dataArg) { if (dataArg is null) { throw PSTraceSource.NewArgumentNullException(nameof(dataArg)); } RemoteDataObject <PSObject> rcvdData = dataArg.ReceivedData; if (rcvdData is null) { throw PSTraceSource.NewArgumentException(nameof(dataArg)); } RemotingDestination destination = rcvdData.Destination; if ((destination & RemotingDestination.Client) != RemotingDestination.Client) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.RemotingDestinationNotForMe, RemotingDestination.Client, destination); } RemotingTargetInterface targetInterface = rcvdData.TargetInterface; switch (targetInterface) { case RemotingTargetInterface.Session: { // Messages for session can cause statemachine state to change. // These messages are first processed by Sessiondata structure handler and depending // on the type of message, appropriate event is raised in state machine ProcessSessionMessages(dataArg); break; } case RemotingTargetInterface.RunspacePool: case RemotingTargetInterface.PowerShell: // Non Session messages do not change the state of the statemachine. // However instead of forwarding them to Runspace/pipeline here, an // event is raised in state machine which verified that state is // suitable for accepting these messages. if state is suitable statemachine // will call DoMessageForwading which will forward the messages appropriately RemoteSessionStateMachineEventArgs msgRcvArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.MessageReceived, null); if (StateMachine.CanByPassRaiseEvent(msgRcvArg)) { ProcessNonSessionMessages(dataArg.ReceivedData); } else { StateMachine.RaiseEvent(msgRcvArg); } break; default: { Dbg.Assert(false, "we should not be encountering this"); } break; } }
internal string ContractRelativePath( string path, string basePath, bool allowNonExistingPaths, CmdletProviderContext context) { Context = context; if (path == null) { throw PSTraceSource.NewArgumentNullException("path"); } if (path.Length == 0) { return(String.Empty); } if (basePath == null) { basePath = String.Empty; } providerBaseTracer.WriteLine("basePath = {0}", basePath); string result = path; bool originalPathHadTrailingSlash = false; string normalizedPath = path; string normalizedBasePath = basePath; // NTRAID#Windows 7-697922-2009/06/29-leeholm // WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND // // This path normalization got moved here from the MakePath override in V2 to prevent // over-normalization of paths. This was a net-improvement for providers that use the default // implementations, but now incorrectly replaces forward slashes with back slashes during the call to // GetParentPath and GetChildName. This breaks providers that are sensitive to slash direction, the only // one we are aware of being the Active Directory provider. This change prevents this over-normalization // from being done on AD paths. // // For more information, see Win7:695292. Do not change this code without closely working with the // Active Directory team. // // WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND WORKAROUND if (!String.Equals(context.ProviderInstance.ProviderInfo.FullName, @"Microsoft.ActiveDirectory.Management\ActiveDirectory", StringComparison.OrdinalIgnoreCase)) { normalizedPath = NormalizePath(path); normalizedBasePath = NormalizePath(basePath); } do // false loop { // Convert to the correct path separators and trim trailing separators string originalPath = path; Stack <string> tokenizedPathStack = null; if (path.EndsWith(StringLiterals.DefaultPathSeparator)) { path = path.TrimEnd(StringLiterals.DefaultPathSeparator); originalPathHadTrailingSlash = true; } basePath = basePath.TrimEnd(StringLiterals.DefaultPathSeparator); // See if the base and the path are already the same. We resolve this to // ..\Leaf, since resolving "." to "." doesn't offer much information. if (String.Equals(normalizedPath, normalizedBasePath, StringComparison.OrdinalIgnoreCase) && (!originalPath.EndsWith(StringLiterals.DefaultPathSeparator))) { string childName = GetChildName(path); result = MakePath("..", childName); break; } // If the base path isn't really a base, then we resolve to a parent // path (such as ../../foo) if (!normalizedPath.StartsWith(normalizedBasePath, StringComparison.OrdinalIgnoreCase) && (basePath.Length > 0)) { result = String.Empty; string commonBase = GetCommonBase(normalizedPath, normalizedBasePath); Stack <string> parentNavigationStack = TokenizePathToStack(normalizedBasePath, commonBase); int parentPopCount = parentNavigationStack.Count; if (String.IsNullOrEmpty(commonBase)) { parentPopCount--; } for (int leafCounter = 0; leafCounter < parentPopCount; leafCounter++) { result = MakePath("..", result); } // This is true if we get passed a base path like: // c:\directory1\directory2 // and an actual path of // c:\directory1 // Which happens when the user is in c:\directory1\directory2 // and wants to resolve something like: // ..\..\dir* // In that case (as above,) we keep the ..\..\directory1 // instead of ".." as would usually be returned if (!String.IsNullOrEmpty(commonBase)) { if (String.Equals(normalizedPath, commonBase, StringComparison.OrdinalIgnoreCase) && (!normalizedPath.EndsWith(StringLiterals.DefaultPathSeparator))) { string childName = GetChildName(path); result = MakePath("..", result); result = MakePath(result, childName); } else { string[] childNavigationItems = TokenizePathToStack(normalizedPath, commonBase).ToArray(); for (int leafCounter = 0; leafCounter < childNavigationItems.Length; leafCounter++) { result = MakePath(result, childNavigationItems[leafCounter]); } } } } // Otherwise, we resolve to a child path (such as foo/bar) else { tokenizedPathStack = TokenizePathToStack(path, basePath); // Now we have to normalize the path // by processing each token on the stack Stack <string> normalizedPathStack; try { normalizedPathStack = NormalizeThePath(tokenizedPathStack, path, basePath, allowNonExistingPaths); } catch (ArgumentException argumentException) { WriteError(new ErrorRecord(argumentException, argumentException.GetType().FullName, ErrorCategory.InvalidArgument, null)); result = null; break; } // Now that the path has been normalized, create the relative path result = CreateNormalizedRelativePathFromStack(normalizedPathStack); } } while (false); if (originalPathHadTrailingSlash) { result = result + StringLiterals.DefaultPathSeparator; } return(result); }
/// <summary> /// This is the handler for MessageReceived event. It dispatches the data to various components /// that uses the data. /// </summary> /// <param name="sender"></param> /// <param name="fsmEventArg"> /// This parameter contains the FSM event. /// </param> /// /// <exception cref="ArgumentNullException"> /// If the parameter <paramref name="fsmEventArg"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// If the parameter <paramref name="fsmEventArg"/> does not contain remote data. /// </exception> internal void DoMessageReceived(object sender, RemoteSessionStateMachineEventArgs fsmEventArg) { using (s_trace.TraceEventHandlers()) { if (fsmEventArg == null) { throw PSTraceSource.NewArgumentNullException("fsmEventArg"); } if (fsmEventArg.RemoteData == null) { throw PSTraceSource.NewArgumentException("fsmEventArg"); } Dbg.Assert(_state == RemoteSessionState.Established || _state == RemoteSessionState.EstablishedAndKeyExchanged || _state == RemoteSessionState.EstablishedAndKeyReceived || _state == RemoteSessionState.EstablishedAndKeySent, //server session will never be in this state.. TODO- remove this "State must be Established or EstablishedAndKeySent or EstablishedAndKeyReceived or EstablishedAndKeyExchanged"); RemotingTargetInterface targetInterface = fsmEventArg.RemoteData.TargetInterface; RemotingDataType dataType = fsmEventArg.RemoteData.DataType; Guid clientRunspacePoolId; ServerRunspacePoolDriver runspacePoolDriver; //string errorMessage = null; RemoteDataEventArgs remoteDataForSessionArg = null; switch (targetInterface) { case RemotingTargetInterface.Session: { switch (dataType) { // GETBACK case RemotingDataType.CreateRunspacePool: remoteDataForSessionArg = new RemoteDataEventArgs(fsmEventArg.RemoteData); _session.SessionDataStructureHandler.RaiseDataReceivedEvent(remoteDataForSessionArg); break; default: Dbg.Assert(false, "Should never reach here"); break; } } break; case RemotingTargetInterface.RunspacePool: // GETBACK clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId); if (runspacePoolDriver != null) { runspacePoolDriver.DataStructureHandler.ProcessReceivedData(fsmEventArg.RemoteData); } else { s_trace.WriteLine(@"Server received data for Runspace (id: {0}), but the Runspace cannot be found", clientRunspacePoolId); PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.RunspaceCannotBeFound, clientRunspacePoolId); RemoteSessionStateMachineEventArgs runspaceNotFoundArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure); RaiseEvent(runspaceNotFoundArg); } break; case RemotingTargetInterface.PowerShell: clientRunspacePoolId = fsmEventArg.RemoteData.RunspacePoolId; runspacePoolDriver = _session.GetRunspacePoolDriver(clientRunspacePoolId); runspacePoolDriver.DataStructureHandler.DispatchMessageToPowerShell(fsmEventArg.RemoteData); break; default: s_trace.WriteLine("Server received data unknown targetInterface: {0}", targetInterface); PSRemotingDataStructureException reasonOfFailure2 = new PSRemotingDataStructureException(RemotingErrorIdStrings.ReceivedUnsupportedRemotingTargetInterfaceType, targetInterface); RemoteSessionStateMachineEventArgs unknownTargetArg = new RemoteSessionStateMachineEventArgs(RemoteSessionEvent.FatalError, reasonOfFailure2); RaiseEvent(unknownTargetArg); break; } } }
/// <summary> /// This method is added to be backward compatible with V1 hosts w.r.t /// new PromptForChoice method added in PowerShell V2. /// </summary> /// <param name="caption"></param> /// <param name="message"></param> /// <param name="choices"></param> /// <param name="defaultChoices"></param> /// <returns></returns> /// <exception cref="ArgumentException"> /// 1. Choices is null. /// 2. Choices.Count = 0 /// 3. DefaultChoice is either less than 0 or greater than Choices.Count /// </exception> private Collection <int> EmulatePromptForMultipleChoice(string caption, string message, Collection <ChoiceDescription> choices, IEnumerable <int> defaultChoices) { Dbg.Assert(_externalUI != null, "externalUI cannot be null."); if (choices == null) { throw PSTraceSource.NewArgumentNullException(nameof(choices)); } if (choices.Count == 0) { throw PSTraceSource.NewArgumentException(nameof(choices), InternalHostUserInterfaceStrings.EmptyChoicesError, "choices"); } Dictionary <int, bool> defaultChoiceKeys = new Dictionary <int, bool>(); if (defaultChoices != null) { foreach (int defaultChoice in defaultChoices) { if ((defaultChoice < 0) || (defaultChoice >= choices.Count)) { throw PSTraceSource.NewArgumentOutOfRangeException("defaultChoice", defaultChoice, InternalHostUserInterfaceStrings.InvalidDefaultChoiceForMultipleSelection, "defaultChoice", "choices", defaultChoice); } defaultChoiceKeys.TryAdd(defaultChoice, true); } } // Construct the caption + message + list of choices + default choices Text.StringBuilder choicesMessage = new Text.StringBuilder(); char newLine = '\n'; if (!string.IsNullOrEmpty(caption)) { choicesMessage.Append(caption); choicesMessage.Append(newLine); } if (!string.IsNullOrEmpty(message)) { choicesMessage.Append(message); choicesMessage.Append(newLine); } string[,] hotkeysAndPlainLabels = null; HostUIHelperMethods.BuildHotkeysAndPlainLabels(choices, out hotkeysAndPlainLabels); string choiceTemplate = "[{0}] {1} "; for (int i = 0; i < hotkeysAndPlainLabels.GetLength(1); ++i) { string choice = string.Format( Globalization.CultureInfo.InvariantCulture, choiceTemplate, hotkeysAndPlainLabels[0, i], hotkeysAndPlainLabels[1, i]); choicesMessage.Append(choice); choicesMessage.Append(newLine); } // default choices string defaultPrompt = string.Empty; if (defaultChoiceKeys.Count > 0) { string prepend = string.Empty; Text.StringBuilder defaultChoicesBuilder = new Text.StringBuilder(); foreach (int defaultChoice in defaultChoiceKeys.Keys) { string defaultStr = hotkeysAndPlainLabels[0, defaultChoice]; if (string.IsNullOrEmpty(defaultStr)) { defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture, "{0}{1}", prepend, defaultStr)); prepend = ","; } string defaultChoicesStr = defaultChoicesBuilder.ToString(); if (defaultChoiceKeys.Count == 1) { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, defaultChoicesStr); } else { defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoicesForMultipleChoices, defaultChoicesStr); } } string messageToBeDisplayed = choicesMessage.ToString() + defaultPrompt + newLine; // read choices from the user Collection <int> result = new Collection <int>(); int choicesSelected = 0; while (true) { string choiceMsg = StringUtil.Format(InternalHostUserInterfaceStrings.ChoiceMessage, choicesSelected); messageToBeDisplayed += choiceMsg; _externalUI.WriteLine(messageToBeDisplayed); string response = _externalUI.ReadLine(); // they just hit enter if (response.Length == 0) { // this may happen when // 1. user wants to go with the defaults // 2. user selected some choices and wanted those // choices to be picked. // user did not pick up any choices..choose the default if ((result.Count == 0) && (defaultChoiceKeys.Keys.Count >= 0)) { // if there's a default, pick that one. foreach (int defaultChoice in defaultChoiceKeys.Keys) { result.Add(defaultChoice); } } // allow for no choice selection. break; } int choicePicked = HostUIHelperMethods.DetermineChoicePicked(response.Trim(), choices, hotkeysAndPlainLabels); if (choicePicked >= 0) { result.Add(choicePicked); choicesSelected++; } // reset messageToBeDisplayed messageToBeDisplayed = string.Empty; } return(result); }
private void ExecuteFormatTokenList(TraversalInfo level, PSObject so, List <FormatToken> formatTokenList, List <FormatValue> formatValueList) { if (so == null) { throw PSTraceSource.NewArgumentNullException("so"); } // guard against infinite loop if (level.Level == level.MaxDepth) { return; } FormatEntry fe = new FormatEntry(); formatValueList.Add(fe); #region foreach loop foreach (FormatToken t in formatTokenList) { TextToken tt = t as TextToken; if (tt != null) { FormatTextField ftf = new FormatTextField(); ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); fe.formatValueList.Add(ftf); continue; } var newline = t as NewLineToken; if (newline != null) { for (int i = 0; i < newline.count; i++) { fe.formatValueList.Add(new FormatNewLine()); } continue; } FrameToken ft = t as FrameToken; if (ft != null) { // instantiate a new entry and attach a frame info object FormatEntry feFrame = new FormatEntry(); feFrame.frameInfo = new FrameInfo(); // add the frame info feFrame.frameInfo.firstLine = ft.frameInfoDefinition.firstLine; feFrame.frameInfo.leftIndentation = ft.frameInfoDefinition.leftIndentation; feFrame.frameInfo.rightIndentation = ft.frameInfoDefinition.rightIndentation; // execute the list inside the frame ExecuteFormatTokenList(level, so, ft.itemDefinition.formatTokenList, feFrame.formatValueList); // add the frame computation results to the current format entry fe.formatValueList.Add(feFrame); continue; } #region CompoundPropertyToken CompoundPropertyToken cpt = t as CompoundPropertyToken; if (cpt != null) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { // token not active, skip it continue; } // get the property from the object object val = null; // if no expression was specified, just use the // object itself if (cpt.expression == null || string.IsNullOrEmpty(cpt.expression.expressionValue)) { val = so; } else { PSPropertyExpression ex = _expressionFactory.CreateFromExpressionToken(cpt.expression, _loadingInfo); List <PSPropertyExpressionResult> resultList = ex.GetValues(so); if (resultList.Count > 0) { val = resultList[0].Result; if (resultList[0].Exception != null) { _errorManager.LogPSPropertyExpressionFailedResult(resultList[0], so); } } } // if the token is has a formatting string, it's a leaf node, // do the formatting and we will be done if (cpt.control == null || cpt.control is FieldControlBody) { // Since it is a leaf node we just consider it an empty string and go // on with formatting if (val == null) { val = string.Empty; } FieldFormattingDirective fieldFormattingDirective = null; StringFormatError formatErrorObject = null; if (cpt.control != null) { fieldFormattingDirective = ((FieldControlBody)cpt.control).fieldFormattingDirective; if (fieldFormattingDirective != null && _errorManager.DisplayFormatErrorString) { formatErrorObject = new StringFormatError(); } } IEnumerable e = PSObjectHelper.GetEnumerable(val); FormatPropertyField fpf = new FormatPropertyField(); if (cpt.enumerateCollection && e != null) { foreach (object x in e) { if (x == null) { // nothing to process continue; } fpf = new FormatPropertyField(); fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, x, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } } else { fpf = new FormatPropertyField(); fpf.propertyValue = PSObjectHelper.FormatField(fieldFormattingDirective, val, _enumerationLimit, formatErrorObject, _expressionFactory); fe.formatValueList.Add(fpf); } if (formatErrorObject != null && formatErrorObject.exception != null) { _errorManager.LogStringFormatError(formatErrorObject); fpf.propertyValue = _errorManager.FormatErrorString; } } else { // An empty result that is not a leaf node should not be expanded if (val == null) { continue; } IEnumerable e = PSObjectHelper.GetEnumerable(val); if (cpt.enumerateCollection && e != null) { foreach (object x in e) { if (x == null) { // nothing to process continue; } // proceed with the recursion ExecuteFormatControl(level.NextLevel, cpt.control, PSObject.AsPSObject(x), fe.formatValueList); } } else { // proceed with the recursion ExecuteFormatControl(level.NextLevel, cpt.control, PSObjectHelper.AsPSObject(val), fe.formatValueList); } } } #endregion CompoundPropertyToken } #endregion foreach loop }
/// <summary> /// Closes the content readers and writers in the content holder array /// </summary> internal void CloseContent(List <ContentHolder> contentHolders, bool disposing) { if (contentHolders == null) { throw PSTraceSource.NewArgumentNullException("contentHolders"); } foreach (ContentHolder holder in contentHolders) { try { if (holder.Writer != null) { holder.Writer.Close(); } } catch (Exception e) // Catch-all OK. 3rd party callout { // Catch all the exceptions caused by closing the writer // and write out an error. ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); if (!disposing) { WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); } } try { if (holder.Reader != null) { holder.Reader.Close(); } } catch (Exception e) // Catch-all OK. 3rd party callout { // Catch all the exceptions caused by closing the writer // and write out an error. ProviderInvocationException providerException = new ProviderInvocationException( "ProviderContentCloseError", SessionStateStrings.ProviderContentCloseError, holder.PathInfo.Provider, holder.PathInfo.Path, e); // Log a provider health event MshLog.LogProviderHealthEvent( this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); if (!disposing) { WriteError( new ErrorRecord( providerException.ErrorRecord, providerException)); } } } }
/// <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(nameof(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( nameof(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 ? Array.Empty <ValidateArgumentsAttribute>() : validationAttributes.ToArray(); this.ArgumentTransformationAttributes = argTransformationAttributes == null ? Array.Empty <ArgumentTransformationAttribute>() : argTransformationAttributes.ToArray(); this.Aliases = aliases ?? Array.Empty <string>(); }
/// <summary> /// This constructor instantiates a FSM object for the server side to control the remote connection. /// It initializes the event handling matrix with event handlers. /// It sets the initial state of the FSM to be Idle. /// </summary> /// <param name="session"> /// This is the remote session object. /// </param> /// <exception cref="ArgumentNullException"> /// If the parameter is null. /// </exception> internal ServerRemoteSessionDSHandlerStateMachine(ServerRemoteSession session) { if (session == null) { throw PSTraceSource.NewArgumentNullException("session"); } _session = session; _syncObject = new object(); _stateMachineHandle = new EventHandler <RemoteSessionStateMachineEventArgs> [(int)RemoteSessionState.MaxState, (int)RemoteSessionEvent.MaxEvent]; for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { _stateMachineHandle[i, (int)RemoteSessionEvent.FatalError] += DoFatalError; _stateMachineHandle[i, (int)RemoteSessionEvent.Close] += DoClose; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseFailed] += DoCloseFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.CloseCompleted] += DoCloseCompleted; _stateMachineHandle[i, (int)RemoteSessionEvent.NegotiationTimeout] += DoNegotiationTimeout; _stateMachineHandle[i, (int)RemoteSessionEvent.SendFailed] += DoSendFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.ReceiveFailed] += DoReceiveFailed; _stateMachineHandle[i, (int)RemoteSessionEvent.ConnectSession] += DoConnect; } _stateMachineHandle[(int)RemoteSessionState.Idle, (int)RemoteSessionEvent.CreateSession] += DoCreateSession; _stateMachineHandle[(int)RemoteSessionState.NegotiationPending, (int)RemoteSessionEvent.NegotiationReceived] += DoNegotiationReceived; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationSending] += DoNegotiationSending; _stateMachineHandle[(int)RemoteSessionState.NegotiationSending, (int)RemoteSessionEvent.NegotiationSendCompleted] += DoNegotiationCompleted; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationCompleted] += DoEstablished; _stateMachineHandle[(int)RemoteSessionState.NegotiationSent, (int)RemoteSessionEvent.NegotiationPending] += DoNegotiationPending; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.MessageReceived] += DoMessageReceived; _stateMachineHandle[(int)RemoteSessionState.NegotiationReceived, (int)RemoteSessionEvent.NegotiationFailed] += DoNegotiationFailed; _stateMachineHandle[(int)RemoteSessionState.Connecting, (int)RemoteSessionEvent.ConnectFailed] += DoConnectFailed; _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.Established, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySent] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySendFailed] += DoKeyExchange; _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyReceived, (int)RemoteSessionEvent.KeySent] += DoKeyExchange; //with connect, a new client can negotiate a key change to a server that has already negotiated key exchange with a previous client _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceived] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyRequested] += DoKeyExchange; // _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyExchanged, (int)RemoteSessionEvent.KeyReceiveFailed] += DoKeyExchange; // for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) { if (_stateMachineHandle[i, j] == null) { _stateMachineHandle[i, j] += DoClose; } } } // Initially, set state to Idle SetState(RemoteSessionState.Idle, null); }
private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs stateEventArgs) { ErrorRecord errorRecord; PSRemotingTransportException exception2; string str; if (sender == null) { throw PSTraceSource.NewArgumentNullException("sender"); } if (stateEventArgs == null) { throw PSTraceSource.NewArgumentNullException("stateEventArgs"); } RunspaceStateEventArgs baseEvent = stateEventArgs.BaseEvent as RunspaceStateEventArgs; RunspaceState state = baseEvent.RunspaceStateInfo.State; OpenRunspaceOperation operation = sender as OpenRunspaceOperation; RemoteRunspace operatedRunspace = operation.OperatedRunspace; if (operatedRunspace != null) { operatedRunspace.URIRedirectionReported -= new EventHandler <RemoteDataEventArgs <Uri> >(this.HandleURIDirectionReported); } PipelineWriter objectWriter = this.stream.ObjectWriter; Exception reason = baseEvent.RunspaceStateInfo.Reason; switch (state) { case RunspaceState.Opened: { PSSession remoteRunspaceInfo = new PSSession(operatedRunspace); base.RunspaceRepository.Add(remoteRunspaceInfo); Action <Cmdlet> action = cmdlet => cmdlet.WriteObject(remoteRunspaceInfo); if (objectWriter.IsOpen) { objectWriter.Write(action); } return; } case RunspaceState.Closed: { Uri uri = WSManConnectionInfo.ExtractPropertyAsWsManConnectionInfo <Uri>(operatedRunspace.ConnectionInfo, "ConnectionUri", null); string message = base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceClosed, new object[] { (uri != null) ? uri.AbsoluteUri : string.Empty }); Action <Cmdlet> action3 = cmdlet => cmdlet.WriteVerbose(message); if (objectWriter.IsOpen) { objectWriter.Write(action3); } if (reason != null) { ErrorRecord errorRecord2 = new ErrorRecord(reason, "PSSessionStateClosed", ErrorCategory.OpenError, operatedRunspace); Action <Cmdlet> action4 = cmdlet => cmdlet.WriteError(errorRecord2); if (objectWriter.IsOpen) { objectWriter.Write(action4); } } return; } case RunspaceState.Closing: return; case RunspaceState.Broken: exception2 = reason as PSRemotingTransportException; str = null; if (exception2 != null) { OpenRunspaceOperation operation2 = sender as OpenRunspaceOperation; if (operation2 != null) { string computerName = operation2.OperatedRunspace.ConnectionInfo.ComputerName; if (exception2.ErrorCode != -2144108135) { str = "[" + computerName + "] "; if (!string.IsNullOrEmpty(exception2.Message)) { str = str + exception2.Message; } else if (!string.IsNullOrEmpty(exception2.TransportMessage)) { str = str + exception2.TransportMessage; } break; } string str3 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" }); str = "[" + computerName + "] " + str3; } } break; default: return; } PSRemotingDataStructureException exception3 = reason as PSRemotingDataStructureException; if (exception3 != null) { OpenRunspaceOperation operation3 = sender as OpenRunspaceOperation; if (operation3 != null) { string str4 = operation3.OperatedRunspace.ConnectionInfo.ComputerName; str = "[" + str4 + "] " + exception3.Message; } } if (reason == null) { reason = new RuntimeException(base.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, new object[] { state })); } string fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError((exception2 != null) ? exception2.ErrorCode : 0, this._defaultFQEID); errorRecord = new ErrorRecord(reason, operatedRunspace, fQEIDFromTransportError, ErrorCategory.OpenError, null, null, null, null, null, str, null); Action <Cmdlet> action2 = cmdlet => cmdlet.WriteError(errorRecord); if (objectWriter.IsOpen) { objectWriter.Write(action2); } this.toDispose.Add(operatedRunspace); }
/// <summary> /// Sets the security descriptor for the item specified by <paramref name="path"/> /// </summary> /// /// <param name="path"> /// The path to the item to set the security descriptor on. /// </param> /// /// <param name="securityDescriptor"> /// The new security descriptor for the item. /// </param> public void SetSecurityDescriptor( string path, ObjectSecurity securityDescriptor) { IRegistryWrapper key = null; if (String.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException("securityDescriptor"); } path = NormalizePath(path); ObjectSecurity sd; if (TransactionAvailable()) { sd = securityDescriptor as TransactedRegistrySecurity; if (sd == null) { throw PSTraceSource.NewArgumentException("securityDescriptor"); } } else { sd = securityDescriptor as RegistrySecurity; if (sd == null) { throw PSTraceSource.NewArgumentException("securityDescriptor"); } } key = GetRegkeyForPathWriteIfError(path, true); if (key != null) { // // the caller already checks for the following exceptions: // -- UnauthorizedAccessException // -- PrivilegeNotHeldException // -- NotSupportedException // -- SystemException // try { key.SetAccessControl(sd); } catch (System.Security.SecurityException e) { WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } catch (System.UnauthorizedAccessException e) { WriteError(new ErrorRecord(e, e.GetType().FullName, ErrorCategory.PermissionDenied, path)); return; } WriteSecurityDescriptorObject(sd, path); } } // SetSecurityDescriptor
/// <summary> /// Sets the SecurityDescriptor at the specified path. /// </summary> /// <param name="path"> /// The path of the item to set the security descriptor on. /// It may be a drive or provider-qualified path and may include. /// glob characters. /// </param> /// <param name="securityDescriptor"> /// The new security descriptor for the item. /// </param> /// <exception cref="System.ArgumentException"> /// path is null or empty. /// </exception> /// <exception cref="System.ArgumentNullException"> /// securitydescriptor is null. /// </exception> public void SetSecurityDescriptor( string path, ObjectSecurity securityDescriptor) { if (string.IsNullOrEmpty(path)) { throw PSTraceSource.NewArgumentException("path"); } path = NormalizePath(path); if (securityDescriptor == null) { throw PSTraceSource.NewArgumentNullException("securityDescriptor"); } if (!File.Exists(path) && !Directory.Exists(path)) { ThrowTerminatingError(CreateErrorRecord(path, "SetSecurityDescriptor_FileNotFound")); } FileSystemSecurity sd = securityDescriptor as FileSystemSecurity; if (sd == null) { throw PSTraceSource.NewArgumentException("securityDescriptor"); } else { // This algorithm works around the following security descriptor complexities: // // - In order to copy an ACL between files, you need to use the // binary form, and transfer all sections. If you don't use the binary form, // then the FileSystem only applies changes that have happened to that specific // ACL object -- which will not be present if you are just stamping a specific // ACL on a lot of files. // - Copying a full ACL means copying its Audit section, which normal users // don't have access to. // // In order to make this cmdlet support regular users modifying their own files, // the solution is to: // // - First attempt to copy the entire security descriptor as we did in V1. // This ensures backward compatability for administrator scripts that currently // work. // - If the attempt fails due to a PrivilegeNotHeld exception, try again with // an estimate of the minimum required subset. This is an estimate, since the // ACL object doesn't tell you exactly what's changed. // - If their ACL doesn't include any audit rules, don't try to set the // audit section. If it does contain Audit rules, continue to try and // set the section, so they get an appropriate error message. // - If their ACL has the same Owner / Group as the destination file, // also don't try to set those sections. // If they added audit rules, or made changes to the Owner / Group, they will // still get an error message. // // We can't roll the two steps into one, as the second step can't handle the // situation where an admin wants to _clear_ the audit entries. It would be nice to // detect a difference in audit entries (like we do with Owner and Group,) but // retrieving the Audit entries requires SeSecurityPrivilege as well. try { // Try to set the entire security descriptor SetSecurityDescriptor(path, sd, AccessControlSections.All); } catch (PrivilegeNotHeldException) { // Get the security descriptor of the destination path ObjectSecurity existingDescriptor = new FileInfo(path).GetAccessControl(); Type ntAccountType = typeof(System.Security.Principal.NTAccount); AccessControlSections sections = AccessControlSections.All; // If they didn't modify any audit information, don't try to set // the audit section. int auditRuleCount = sd.GetAuditRules(true, true, ntAccountType).Count; if ((auditRuleCount == 0) && (sd.AreAuditRulesProtected == existingDescriptor.AreAccessRulesProtected)) { sections &= ~AccessControlSections.Audit; } // If they didn't modify the owner, don't try to set that section. if (sd.GetOwner(ntAccountType) == existingDescriptor.GetOwner(ntAccountType)) { sections &= ~AccessControlSections.Owner; } // If they didn't modify the group, don't try to set that section. if (sd.GetGroup(ntAccountType) == existingDescriptor.GetGroup(ntAccountType)) { sections &= ~AccessControlSections.Group; } // Try to set the security descriptor again, this time with a reduced set // of sections. SetSecurityDescriptor(path, sd, sections); } } }