Team Ai
Datasetpublic

MegaBites-AI/Windows-powershell

sourceHugging Facemitupdated 6mo agoView on Hugging Face
0likes372downloads
remotingexceptions.cs649 linesDownload Raw Back to common
1// Copyright (c) Microsoft Corporation.2// Licensed under the MIT License.3 4using System.Management.Automation.Internal;5using System.Runtime.Serialization;6using System.Security.Permissions;7 8namespace System.Management.Automation.Remoting9{10    /// <summary>11    /// This enum defines the error message ids used by the resource manager to get12    /// localized messages.13    ///14    /// Related error ids are organized in a pre-defined range of values.15    /// </summary>16    internal enum PSRemotingErrorId : uint17    {18        // OS related 1-919        DefaultRemotingExceptionMessage = 0,20        OutOfMemory = 1,21        UnsupportedOSForRemoteEnumeration = 2,22 23        // Pipeline related range: 10-9924        PipelineIdsDoNotMatch = 10,25        PipelineNotFoundOnServer = 11,26        PipelineStopped = 12,27 28        // Runspace, Host, UI and RawUI related range: 200-29929        RunspaceAlreadyExists = 200,30        RunspaceIdsDoNotMatch = 201,31        RemoteRunspaceOpenFailed = 202,32        RunspaceCannotBeFound = 203,33        ResponsePromptIdCannotBeFound = 204,34        RemoteHostCallFailed = 205,35        RemoteHostMethodNotImplemented = 206,36        RemoteHostDataEncodingNotSupported = 207,37        RemoteHostDataDecodingNotSupported = 208,38        NestedPipelineNotSupported = 209,39        RelativeUriForRunspacePathNotSupported = 210,40        RemoteHostDecodingFailed = 211,41        MustBeAdminToOverrideThreadOptions = 212,42        RemoteHostPromptForCredentialModifiedCaption = 213,43        RemoteHostPromptForCredentialModifiedMessage = 214,44        RemoteHostReadLineAsSecureStringPrompt = 215,45        RemoteHostGetBufferContents = 216,46        RemoteHostPromptSecureStringPrompt = 217,47        WinPERemotingNotSupported = 218,48 49        // reserved range: 300-39950 51        // Encoding/Decoding and fragmentation related range: 400-49952        ReceivedUnsupportedRemoteHostCall = 400,53        ReceivedUnsupportedAction = 401,54        ReceivedUnsupportedDataType = 402,55        MissingDestination = 403,56        MissingTarget = 404,57        MissingRunspaceId = 405,58        MissingDataType = 406,59        MissingCallId = 407,60        MissingMethodName = 408,61        MissingIsStartFragment = 409,62        MissingProperty = 410,63        ObjectIdsNotMatching = 411,64        FragmentIdsNotInSequence = 412,65        ObjectIsTooBig = 413,66        MissingIsEndFragment = 414,67        DeserializedObjectIsNull = 415,68        BlobLengthNotInRange = 416,69        DecodingErrorForErrorRecord = 417,70        DecodingErrorForPipelineStateInfo = 418,71        DecodingErrorForRunspaceStateInfo = 419,72        ReceivedUnsupportedRemotingTargetInterfaceType = 420,73        UnknownTargetClass = 421,74        MissingTargetClass = 422,75        DecodingErrorForRunspacePoolStateInfo = 423,76        DecodingErrorForMinRunspaces = 424,77        DecodingErrorForMaxRunspaces = 425,78        DecodingErrorForPowerShellStateInfo = 426,79        DecodingErrorForThreadOptions = 427,80        CantCastPropertyToExpectedType = 428,81        CantCastRemotingDataToPSObject = 429,82        CantCastCommandToPSObject = 430,83        CantCastParameterToPSObject = 431,84        ObjectIdCannotBeLessThanZero = 432,85        NotEnoughHeaderForRemoteDataObject = 433,86 87        // reserved range: 500-59988 89        // Remote Session related range: 600-69990        RemotingDestinationNotForMe = 600,91        ClientNegotiationTimeout = 601,92        ClientNegotiationFailed = 602,93        ServerRequestedToCloseSession = 603,94        ServerNegotiationFailed = 604,95        ServerNegotiationTimeout = 605,96        ClientRequestedToCloseSession = 606,97        FatalErrorCausingClose = 607,98        ClientKeyExchangeFailed = 608,99        ServerKeyExchangeFailed = 609,100        ClientNotFoundCapabilityProperties = 610,101        ServerNotFoundCapabilityProperties = 611,102 103        // reserved range: 700-799104 105        // Transport related range: 800-899106 107        ConnectFailed = 801,108        CloseIsCalled = 802,109        ForceClosed = 803,110        CloseFailed = 804,111        CloseCompleted = 805,112        UnsupportedWaitHandleType = 806,113        ReceivedDataStreamIsNotStdout = 807,114        StdInIsNotOpen = 808,115        NativeWriteFileFailed = 809,116        NativeReadFileFailed = 810,117        InvalidSchemeValue = 811,118        ClientReceiveFailed = 812,119        ClientSendFailed = 813,120        CommandHandleIsNull = 814,121        StdInCannotBeSetToNoWait = 815,122        PortIsOutOfRange = 816,123        ServerProcessExited = 817,124        CannotGetStdInHandle = 818,125        CannotGetStdOutHandle = 819,126        CannotGetStdErrHandle = 820,127        CannotSetStdInHandle = 821,128        CannotSetStdOutHandle = 822,129        CannotSetStdErrHandle = 823,130        InvalidConfigurationName = 824,131        ConnectSkipCheckFailed = 825,132        // Error codes added to support new WSMan Fan-In Model API133        CreateSessionFailed = 851,134        CreateExFailed = 853,135        ConnectExCallBackError = 854,136        SendExFailed = 855,137        SendExCallBackError = 856,138        ReceiveExFailed = 857,139        ReceiveExCallBackError = 858,140        RunShellCommandExFailed = 859,141        RunShellCommandExCallBackError = 860,142        CommandSendExFailed = 861,143        CommandSendExCallBackError = 862,144        CommandReceiveExFailed = 863,145        CommandReceiveExCallBackError = 864,146        CloseExCallBackError = 866,147        // END: Error codes added to support new WSMan Fan-In Model API148        // BEGIN: Error IDs introduced for URI redirection149        RedirectedURINotWellFormatted = 867,150        URIEndPointNotResolved = 868,151        // END: Error IDs introduced for URI redirection152        // BEGIN: Error IDs introduced for Quota Management153        ReceivedObjectSizeExceededMaximumClient = 869,154        ReceivedDataSizeExceededMaximumClient = 870,155        ReceivedObjectSizeExceededMaximumServer = 871,156        ReceivedDataSizeExceededMaximumServer = 872,157        // END: Error IDs introduced for Quota Management158        // BEGIN: Error IDs introduced for startup script159        StartupScriptThrewTerminatingError = 873,160        // END: Error IDs introduced for startup script161        TroubleShootingHelpTopic = 874,162        // BEGIN: Error IDs introduced for disconnect/reconnect163        DisconnectShellExFailed = 875,164        DisconnectShellExCallBackErrr = 876,165        ReconnectShellExFailed = 877,166        ReconnectShellExCallBackErrr = 878,167        // END: Error IDs introduced for disconnect/reconnect168        // Cmdlets related range: 900-999169        RemoteRunspaceInfoHasDuplicates = 900,170        RemoteRunspaceInfoLimitExceeded = 901,171        RemoteRunspaceOpenUnknownState = 902,172        UriSpecifiedNotValid = 903,173        RemoteRunspaceClosed = 904,174        RemoteRunspaceNotAvailableForSpecifiedComputer = 905,175        RemoteRunspaceNotAvailableForSpecifiedRunspaceId = 906,176        StopPSJobWhatIfTarget = 907,177        InvalidJobStateGeneral = 909,178        JobWithSpecifiedNameNotFound = 910,179        JobWithSpecifiedInstanceIdNotFound = 911,180        JobWithSpecifiedSessionIdNotFound = 912,181        JobWithSpecifiedNameNotCompleted = 913,182        JobWithSpecifiedSessionIdNotCompleted = 914,183        JobWithSpecifiedInstanceIdNotCompleted = 915,184        RemovePSJobWhatIfTarget = 916,185        ComputerNameParamNotSupported = 917,186        RunspaceParamNotSupported = 918,187        RemoteRunspaceNotAvailableForSpecifiedName = 919,188        RemoteRunspaceNotAvailableForSpecifiedSessionId = 920,189        ItemNotFoundInRepository = 921,190        CannotRemoveJob = 922,191        NewRunspaceAmbiguousAuthentication = 923,192        WildCardErrorFilePathParameter = 924,193        FilePathNotFromFileSystemProvider = 925,194        FilePathShouldPS1Extension = 926,195        PSSessionConfigurationName = 927,196        PSSessionAppName = 928,197        // Custom Shell commands198        CSCDoubleParameterOutOfRange = 929,199        URIRedirectionReported = 930,200        NoMoreInputWrites = 931,201        InvalidComputerName = 932,202        ProxyAmbiguousAuthentication = 933,203        ProxyCredentialWithoutAccess = 934,204 205        // Start-PSSession related error codes.206        PushedRunspaceMustBeOpen = 951,207        HostDoesNotSupportPushRunspace = 952,208        RemoteRunspaceHasMultipleMatchesForSpecifiedRunspaceId = 953,209        RemoteRunspaceHasMultipleMatchesForSpecifiedSessionId = 954,210        RemoteRunspaceHasMultipleMatchesForSpecifiedName = 955,211        RemoteRunspaceDoesNotSupportPushRunspace = 956,212        HostInNestedPrompt = 957,213        InvalidVMId = 959,214        InvalidVMNameNoVM = 960,215        InvalidVMNameMultipleVM = 961,216        HyperVModuleNotAvailable = 962,217        InvalidUsername = 963,218        InvalidCredential = 964,219        VMSessionConnectFailed = 965,220        InvalidContainerId = 966,221        CannotCreateProcessInContainer = 967,222        CannotTerminateProcessInContainer = 968,223        ContainersFeatureNotEnabled = 969,224        RemoteSessionHyperVSocketServerConstructorFailure = 970,225        ContainerSessionConnectFailed = 973,226        RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure = 974,227        InvalidVMState = 975,228 229        // Invoke-Command related error codes.230        InvalidVMIdNotSingle = 981,231        InvalidVMNameNotSingle = 982,232 233        // SessionState Description related messages234        WsmanMaxRedirectionCountVariableDescription = 1001,235        PSDefaultSessionOptionDescription = 1002,236        PSSenderInfoDescription = 1004,237 238        // IPC for Background jobs related errors: 2000239        IPCUnknownNodeType = 2001,240        IPCInsufficientDataforElement = 2002,241        IPCWrongAttributeCountForDataElement = 2003,242        IPCOnlyTextExpectedInDataElement = 2004,243        IPCWrongAttributeCountForElement = 2005,244        IPCUnknownElementReceived = 2006,245        IPCSupportsOnlyDefaultAuth = 2007,246        IPCWowComponentNotPresent = 2008,247        IPCServerProcessReportedError = 2100,248        IPCServerProcessExited = 2101,249        IPCErrorProcessingServerData = 2102,250        IPCUnknownCommandGuid = 2103,251        IPCNoSignalForSession = 2104,252        IPCSignalTimedOut = 2105,253        IPCCloseTimedOut = 2106,254        IPCExceptionLaunchingProcess = 2107,255    }256 257    /// <summary>258    /// This static class defines the resource base name used by remoting errors.259    /// It also provides a convenience method to get the localized strings.260    /// </summary>261    internal static class PSRemotingErrorInvariants262    {263        /// <summary>264        /// This method is a convenience method to retrieve the localized string.265        /// </summary>266        /// <param name="resourceString">267        /// This parameter holds the string in the resource file.268        /// </param>269        /// <param name="args">270        /// Optional parameters required by the resource string formatting information.271        /// </param>272        /// <returns>273        /// The formatted localized string.274        /// </returns>275        internal static string FormatResourceString(string resourceString, params object[] args)276        {277            string resourceFormatedString = StringUtil.Format(resourceString, args);278 279            return resourceFormatedString;280        }281    }282 283    /// <summary>284    /// This exception is used by remoting code to indicated a data structure handler related error.285    /// </summary>286    public class PSRemotingDataStructureException : RuntimeException287    {288        #region Constructors289 290        /// <summary>291        /// Default constructor.292        /// </summary>293        public PSRemotingDataStructureException()294            : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingDataStructureException).FullName))295        {296            SetDefaultErrorRecord();297        }298 299        /// <summary>300        /// This constructor takes a localized string as the error message.301        /// </summary>302        /// <param name="message">303        /// A localized string as an error message.304        /// </param>305        public PSRemotingDataStructureException(string message)306            : base(message)307        {308            SetDefaultErrorRecord();309        }310 311        /// <summary>312        /// This constructor takes a localized string as the error message, and an inner exception.313        /// </summary>314        /// <param name="message">315        /// A localized string as an error message.316        /// </param>317        /// <param name="innerException">318        /// Inner exception.319        /// </param>320        public PSRemotingDataStructureException(string message, Exception innerException)321            : base(message, innerException)322        {323            SetDefaultErrorRecord();324        }325 326        /// <summary>327        /// This constructor takes an error id and optional parameters.328        /// </summary>329        /// <param name="resourceString">330        /// The resource string in the base resource file.331        /// </param>332        /// <param name="args">333        /// Optional parameters required to format the resource string.334        /// </param>335        internal PSRemotingDataStructureException(string resourceString, params object[] args)336            : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args))337        {338            SetDefaultErrorRecord();339        }340 341        /// <summary>342        /// This constructor takes an inner exception and an error id.343        /// </summary>344        /// <param name="innerException">345        /// Inner exception.346        /// </param>347        /// <param name="resourceString">348        /// The resource string in the base resource file.349        /// </param>350        /// <param name="args">351        /// Optional parameters required to format the resource string.352        /// </param>353        internal PSRemotingDataStructureException(Exception innerException, string resourceString, params object[] args)354            : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException)355        {356            SetDefaultErrorRecord();357        }358 359        /// <summary>360        /// This constructor is required by serialization.361        /// </summary>362        /// <param name="info"></param>363        /// <param name="context"></param>364        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]365        protected PSRemotingDataStructureException(SerializationInfo info, StreamingContext context)366        {367            throw new NotSupportedException();368        }369 370        #endregion Constructors371 372        /// <summary>373        /// Set the default ErrorRecord.374        /// </summary>375        private void SetDefaultErrorRecord()376        {377            SetErrorCategory(ErrorCategory.ResourceUnavailable);378            SetErrorId(typeof(PSRemotingDataStructureException).FullName);379        }380    }381 382    /// <summary>383    /// This exception is used by remoting code to indicate an error condition in network operations.384    /// </summary>385    public class PSRemotingTransportException : RuntimeException386    {387        private int _errorCode;388        private string _transportMessage;389 390        #region Constructors391 392        /// <summary>393        /// This is the default constructor.394        /// </summary>395        public PSRemotingTransportException()396            : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage, typeof(PSRemotingTransportException).FullName))397        {398            SetDefaultErrorRecord();399        }400 401        /// <summary>402        /// This constructor takes a localized error message.403        /// </summary>404        /// <param name="message">405        /// A localized error message.406        /// </param>407        public PSRemotingTransportException(string message)408            : base(message)409        {410            SetDefaultErrorRecord();411        }412 413        /// <summary>414        /// This constructor takes a localized message and an inner exception.415        /// </summary>416        /// <param name="message">417        /// Localized error message.418        /// </param>419        /// <param name="innerException">420        /// Inner exception.421        /// </param>422        public PSRemotingTransportException(string message, Exception innerException)423            : base(message, innerException)424        {425            SetDefaultErrorRecord();426        }427 428        /// <summary>429        /// This constructor takes an error id and optional parameters.430        /// </summary>431        /// <param name="errorId">432        /// The error id in the base resource file.433        /// </param>434        /// <param name="resourceString">435        /// The resource string in the base resource file.436        /// </param>437        /// <param name="args">438        /// Optional parameters required to format the resource string.439        /// </param>440        internal PSRemotingTransportException(PSRemotingErrorId errorId, string resourceString, params object[] args)441            : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args))442        {443            SetDefaultErrorRecord();444            _errorCode = (int)errorId;445        }446 447        /// <summary>448        /// This constructor takes an inner exception and an error id.449        /// </summary>450        /// <param name="innerException">451        /// Inner exception.452        /// </param>453        /// <param name="resourceString">454        /// The resource string in the base resource file.455        /// </param>456        /// <param name="args">457        /// Optional parameters required to format the resource string.458        /// </param>459        internal PSRemotingTransportException(Exception innerException, string resourceString, params object[] args)460            : base(PSRemotingErrorInvariants.FormatResourceString(resourceString, args), innerException)461        {462            SetDefaultErrorRecord();463        }464 465        /// <summary>466        /// This constructor is required by serialization.467        /// </summary>468        /// <param name="info"></param>469        /// <param name="context"></param>470        /// <exception cref="ArgumentNullException">471        /// 1. info is null.472        /// </exception>473        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]474        protected PSRemotingTransportException(SerializationInfo info, StreamingContext context)475        {476            throw new NotSupportedException();477        }478 479        #endregion Constructors480 481        /// <summary>482        /// Set the default ErrorRecord.483        /// </summary>484        protected void SetDefaultErrorRecord()485        {486            SetErrorCategory(ErrorCategory.ResourceUnavailable);487            SetErrorId(typeof(PSRemotingDataStructureException).FullName);488        }489 490        /// <summary>491        /// The error code from native library API call.492        /// </summary>493        public int ErrorCode494        {495            get496            {497                return _errorCode;498            }499 500            set501            {502                _errorCode = value;503            }504        }505 506        /// <summary>507        /// This the message from the native transport layer.508        /// </summary>509        public string TransportMessage510        {511            get512            {513                return _transportMessage;514            }515 516            set517            {518                _transportMessage = value;519            }520        }521    }522 523    /// <summary>524    /// This exception is used by PowerShell's remoting infrastructure to notify a URI redirection525    /// exception.526    /// </summary>527    public class PSRemotingTransportRedirectException : PSRemotingTransportException528    {529        #region Constructor530        /// <summary>531        /// This is the default constructor.532        /// </summary>533        public PSRemotingTransportRedirectException()534            : base(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.DefaultRemotingExceptionMessage,535             typeof(PSRemotingTransportRedirectException).FullName))536        {537            SetDefaultErrorRecord();538        }539 540        /// <summary>541        /// This constructor takes a localized error message.542        /// </summary>543        /// <param name="message">544        /// A localized error message.545        /// </param>546        public PSRemotingTransportRedirectException(string message)547            : base(message)548        {549        }550 551        /// <summary>552        /// This constructor takes a localized message and an inner exception.553        /// </summary>554        /// <param name="message">555        /// Localized error message.556        /// </param>557        /// <param name="innerException">558        /// Inner exception.559        /// </param>560        public PSRemotingTransportRedirectException(string message, Exception innerException)561            : base(message, innerException)562        {563        }564 565        /// <summary>566        /// This constructor takes an inner exception and an error id.567        /// </summary>568        /// <param name="innerException">569        /// Inner exception.570        /// </param>571        /// <param name="resourceString">572        /// The resource string in the base resource file.573        /// </param>574        /// <param name="args">575        /// Optional parameters required to format the resource string.576        /// </param>577        internal PSRemotingTransportRedirectException(Exception innerException, string resourceString, params object[] args)578            : base(innerException, resourceString, args)579        {580        }581 582        /// <summary>583        /// This constructor is required by serialization.584        /// </summary>585        /// <param name="info"></param>586        /// <param name="context"></param>587        /// <exception cref="ArgumentNullException">588        /// 1. info is null.589        /// </exception>590        [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")]591        protected PSRemotingTransportRedirectException(SerializationInfo info, StreamingContext context)592        {593            throw new NotSupportedException();594        }595 596        /// <summary>597        /// This constructor takes an redirect URI, error id and optional parameters.598        /// </summary>599        /// <param name="redirectLocation">600        /// String specifying a redirect location.601        /// </param>602        /// <param name="errorId">603        /// The error id in the base resource file.604        /// </param>605        /// <param name="resourceString">606        /// The resource string in the base resource file.607        /// </param>608        /// <param name="args">609        /// Optional parameters required to format the resource string.610        /// </param>611        internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotingErrorId errorId, string resourceString, params object[] args)612            : base(errorId, resourceString, args)613        {614            RedirectLocation = redirectLocation;615        }616 617        #endregion618 619        #region Properties620        /// <summary>621        /// String specifying a redirect location.622        /// </summary>623        public string RedirectLocation { get; }624 625        #endregion626    }627 628    /// <summary>629    /// This exception is used by PowerShell Direct errors.630    /// </summary>631    public class PSDirectException : RuntimeException632    {633        #region Constructor634 635        /// <summary>636        /// This constructor takes a localized string as the error message.637        /// </summary>638        /// <param name="message">639        /// A localized string as an error message.640        /// </param>641        public PSDirectException(string message)642            : base(message)643        {644        }645 646        #endregion Constructor647    }648}649