Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes308downloads
SessionStatePublic.cs375 linesDownload Raw Back to engine
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System.Collections.Generic;5using System.Management.Automation.Runspaces;6 7using Dbg = System.Management.Automation;8 9namespace System.Management.Automation10{11    /// <summary>12    /// Exposes the APIs to manipulate the providers, Runspace data, and location to the Cmdlet base class.13    /// </summary>14    public sealed class SessionState15    {16        #region Constructors17 18        /// <summary>19        /// The internal constructor for this object. It should be the only one that gets called.20        /// </summary>21        /// <param name="sessionState">22        /// An instance of SessionState that the APIs should work against.23        /// </param>24        /// <exception cref="ArgumentNullException">25        /// If <paramref name="sessionState"/> is null.26        /// </exception>27        internal SessionState(SessionStateInternal sessionState)28        {29            if (sessionState == null)30            {31                throw PSTraceSource.NewArgumentNullException(nameof(sessionState));32            }33 34            _sessionState = sessionState;35        }36 37        /// <summary>38        /// The internal constructor for this object. It should be the only one that gets called.39        /// </summary>40        /// <param name="context">41        /// An instance of ExecutionContext whose EngineSessionState represents the parent session state.42        /// </param>43        /// <param name="createAsChild">44        /// True if the session state should be created as a child session state.45        /// </param>46        /// <param name="linkToGlobal">47        /// True if the session state should be linked to the global scope.48        /// </param>49        /// <exception cref="ArgumentNullException">50        /// If <paramref name="context"/> is null.51        /// </exception>52        internal SessionState(ExecutionContext context, bool createAsChild, bool linkToGlobal)53        {54            if (context == null)55                throw new InvalidOperationException("ExecutionContext");56 57            if (createAsChild)58            {59                _sessionState = new SessionStateInternal(context.EngineSessionState, linkToGlobal, context);60            }61            else62            {63                _sessionState = new SessionStateInternal(context);64            }65 66            _sessionState.PublicSessionState = this;67        }68 69        /// <summary>70        /// Construct a new session state object...71        /// </summary>72        public SessionState()73        {74            ExecutionContext ecFromTLS = LocalPipeline.GetExecutionContextFromTLS();75            if (ecFromTLS == null)76                throw new InvalidOperationException("ExecutionContext");77 78            _sessionState = new SessionStateInternal(ecFromTLS);79            _sessionState.PublicSessionState = this;80        }81 82        #endregion Constructors83 84        #region Public methods85 86        /// <summary>87        /// Gets the APIs to access drives.88        /// </summary>89        public DriveManagementIntrinsics Drive90        {91            get { return _drive ??= new DriveManagementIntrinsics(_sessionState); }92        }93 94        /// <summary>95        /// Gets the APIs to access providers.96        /// </summary>97        public CmdletProviderManagementIntrinsics Provider98        {99            get { return _provider ??= new CmdletProviderManagementIntrinsics(_sessionState); }100        }101 102        /// <summary>103        /// Gets the APIs to access paths and location.104        /// </summary>105        public PathIntrinsics Path106        {107            get { return _path ??= new PathIntrinsics(_sessionState); }108        }109 110        /// <summary>111        /// Gets the APIs to access variables in session state.112        /// </summary>113        public PSVariableIntrinsics PSVariable114        {115            get { return _variable ??= new PSVariableIntrinsics(_sessionState); }116        }117 118        /// <summary>119        /// Get/set constraints for this execution environment.120        /// </summary>121        public PSLanguageMode LanguageMode122        {123            get { return _sessionState.LanguageMode; }124 125            set { _sessionState.LanguageMode = value; }126        }127 128        /// <summary>129        /// If true the PowerShell debugger will use FullLanguage mode, otherwise it will use the current language mode.130        /// </summary>131        public bool UseFullLanguageModeInDebugger132        {133            get { return _sessionState.UseFullLanguageModeInDebugger; }134        }135 136        /// <summary>137        /// Public proxy for the list of scripts that are allowed to be run. If the name "*"138        /// is in the list, then all scripts can be run. (This is the default.)139        /// </summary>140        public List<string> Scripts141        {142            get { return _sessionState.Scripts; }143        }144 145        /// <summary>146        /// Public proxy for the list of applications that are allowed to be run. If the name "*"147        /// is in the list, then all applications can be run. (This is the default.)148        /// </summary>149        public List<string> Applications150        {151            get { return _sessionState.Applications; }152        }153 154        /// <summary>155        /// The module associated with this session state instance...156        /// </summary>157        public PSModuleInfo Module158        {159            get { return _sessionState.Module; }160        }161 162        /// <summary>163        /// The provider intrinsics for this session state instance.164        /// </summary>165        public ProviderIntrinsics InvokeProvider166        {167            get { return _sessionState.InvokeProvider; }168        }169 170        /// <summary>171        /// The command invocation intrinsics for this session state instance.172        /// </summary>173        public CommandInvocationIntrinsics InvokeCommand174        {175            get { return _sessionState.ExecutionContext.EngineIntrinsics.InvokeCommand; }176        }177 178        /// <summary>179        /// Utility to check the visibility of an object based on the current180        /// command origin. If the object implements IHasSessionStateEntryVisibility181        /// then the check will be made. If the check fails, then an exception will be thrown...182        /// </summary>183        /// <param name="origin">The command origin value to check against...</param>184        /// <param name="valueToCheck">The object to check.</param>185        public static void ThrowIfNotVisible(CommandOrigin origin, object valueToCheck)186        {187            SessionStateException exception;188            if (!IsVisible(origin, valueToCheck))189            {190                PSVariable sv = valueToCheck as PSVariable;191                if (sv != null)192                {193                    exception =194                       new SessionStateException(195                           sv.Name,196                           SessionStateCategory.Variable,197                           "VariableIsPrivate",198                           SessionStateStrings.VariableIsPrivate,199                           ErrorCategory.PermissionDenied);200 201                    throw exception;202                }203 204                CommandInfo cinfo = valueToCheck as CommandInfo;205                if (cinfo != null)206                {207                    string commandName = cinfo.Name;208                    if (commandName != null)209                    {210                        // If we have a name, use it in the error message211                        exception =212                            new SessionStateException(213                                commandName,214                                SessionStateCategory.Command,215                                "NamedCommandIsPrivate",216                                SessionStateStrings.NamedCommandIsPrivate,217                                ErrorCategory.PermissionDenied);218                    }219                    else220                    {221                        exception =222                            new SessionStateException(223                                string.Empty,224                                SessionStateCategory.Command,225                                "CommandIsPrivate",226                                SessionStateStrings.CommandIsPrivate,227                                ErrorCategory.PermissionDenied);228                    }229 230                    throw exception;231                }232 233                // Catch all error for other types of resources...234                exception =235                    new SessionStateException(236                        null,237                        SessionStateCategory.Resource,238                        "ResourceIsPrivate",239                        SessionStateStrings.ResourceIsPrivate,240                        ErrorCategory.PermissionDenied);241 242                throw exception;243            }244        }245 246        /// <summary>247        /// Checks the visibility of an object based on the command origin argument.248        /// </summary>249        /// <param name="origin">The origin to check against.</param>250        /// <param name="valueToCheck">The object to check.</param>251        /// <returns>Returns true if the object is visible, false otherwise.</returns>252        public static bool IsVisible(CommandOrigin origin, object valueToCheck)253        {254            if (origin == CommandOrigin.Internal)255                return true;256            IHasSessionStateEntryVisibility obj = valueToCheck as IHasSessionStateEntryVisibility;257            if (obj != null)258            {259                return (obj.Visibility == SessionStateEntryVisibility.Public);260            }261 262            return true;263        }264        /// <summary>265        /// Checks the visibility of an object based on the command origin argument.266        /// </summary>267        /// <param name="origin">The origin to check against.</param>268        /// <param name="variable">The variable to check.</param>269        /// <returns>Returns true if the object is visible, false otherwise.</returns>270        public static bool IsVisible(CommandOrigin origin, PSVariable variable)271        {272            if (origin == CommandOrigin.Internal)273                return true;274            if (variable == null)275            {276                throw PSTraceSource.NewArgumentNullException(nameof(variable));277            }278 279            return (variable.Visibility == SessionStateEntryVisibility.Public);280        }281        /// <summary>282        /// Checks the visibility of an object based on the command origin argument.283        /// </summary>284        /// <param name="origin">The origin to check against.</param>285        /// <param name="commandInfo">The command to check.</param>286        /// <returns>Returns true if the object is visible, false otherwise.</returns>287        public static bool IsVisible(CommandOrigin origin, CommandInfo commandInfo)288        {289            if (origin == CommandOrigin.Internal)290                return true;291            if (commandInfo == null)292            {293                throw PSTraceSource.NewArgumentNullException(nameof(commandInfo));294            }295 296            return (commandInfo.Visibility == SessionStateEntryVisibility.Public);297        }298 299        #endregion Public methods300 301        #region Internal methods302 303        /// <summary>304        /// Gets a reference to the "real" session state object instead of the facade.305        /// </summary>306        internal SessionStateInternal Internal307        {308            get { return _sessionState; }309        }310        #endregion Internal methods311 312        #region private data313 314        private readonly SessionStateInternal _sessionState;315        private DriveManagementIntrinsics _drive;316        private CmdletProviderManagementIntrinsics _provider;317        private PathIntrinsics _path;318        private PSVariableIntrinsics _variable;319 320        #endregion private data321    }322 323    /// <summary>324    /// This enum defines the visibility of execution environment elements...325    /// </summary>326    public enum SessionStateEntryVisibility327    {328        /// <summary>329        /// Entries are visible to requests from outside the runspace.330        /// </summary>331        Public = 0,332 333        /// <summary>334        /// Entries are not visible to requests from outside the runspace.335        /// </summary>336        Private = 1337    }338 339#nullable enable340    internal interface IHasSessionStateEntryVisibility341    {342        SessionStateEntryVisibility Visibility { get; set; }343    }344 345    /// <summary>346    /// This enum defines what subset of the PowerShell language is permitted when347    /// calling into this execution environment.348    /// </summary>349    public enum PSLanguageMode350    {351        /// <summary>352        /// All PowerShell language elements are available.353        /// </summary>354        FullLanguage = 0,355 356        /// <summary>357        /// A subset of language elements are available to external requests.358        /// </summary>359        RestrictedLanguage = 1,360 361        /// <summary>362        /// Commands containing script text to evaluate are not allowed. You can only363        /// call commands using the Runspace APIs when in this mode.364        /// </summary>365        NoLanguage = 2,366 367        /// <summary>368        /// Exposes a subset of the PowerShell language that limits itself to core PowerShell369        /// types, does not support method invocation (except on those types), and does not370        /// support property setters (except on those types).371        /// </summary>372        ConstrainedLanguage = 3373    }374}375