internal void ConstructUri(string scheme, string computerName, int?port, string appName) { this._scheme = scheme; if (string.IsNullOrEmpty(this._scheme)) { this._scheme = "http"; } if ((!this._scheme.Equals("http", StringComparison.OrdinalIgnoreCase) && !this._scheme.Equals("https", StringComparison.OrdinalIgnoreCase)) && !this._scheme.Equals("http", StringComparison.OrdinalIgnoreCase)) { ArgumentException exception = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidSchemeValue, new object[] { this._scheme })); throw exception; } if (string.IsNullOrEmpty(computerName) || string.Equals(computerName, ".", StringComparison.OrdinalIgnoreCase)) { this._computerName = "localhost"; } else { this._computerName = computerName.Trim(); IPAddress address = null; if ((IPAddress.TryParse(this._computerName, out address) && (address.AddressFamily == AddressFamily.InterNetworkV6)) && ((this._computerName.Length == 0) || (this._computerName[0] != '['))) { this._computerName = "[" + this._computerName + "]"; } } PSEtwLog.LogAnalyticVerbose(PSEventId.ComputerName, PSOpcode.Method, PSTask.CreateRunspace, PSKeyword.Runspace | PSKeyword.UseAlwaysAnalytic, new object[] { this._computerName }); if (port.HasValue) { if (port.Value == 0) { this._port = -1; this.UseDefaultWSManPort = true; } else if ((port.Value == 80) || (port.Value == 0x1bb)) { this._port = port.Value; this.UseDefaultWSManPort = false; } else { if ((port.Value < 0) || (port.Value > 0xffff)) { ArgumentException exception2 = new ArgumentException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.PortIsOutOfRange, new object[] { port })); throw exception2; } this._port = port.Value; this.UseDefaultWSManPort = false; } } this._appName = appName; if (string.IsNullOrEmpty(this._appName)) { this._appName = DefaultAppName; } UriBuilder builder = new UriBuilder(this._scheme, this._computerName, this._port, this._appName); this._connectionUri = builder.Uri; }
/// <summary> /// Logs a command message. /// </summary> /// <param name="message">Message to log.</param> internal void LogMessage(string message) { List <string> details = new List <string>() { message }; PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details); }
/// <summary> /// Logs a command message /// </summary> /// <param name="message">Message to log.</param> internal void LogMessage(string message) { List <string> details = new List <string>(); details.Add(message); #if !CORECLR // TODO:CORECLR Uncomment when we add PSEtwLog support PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details); #endif }
internal void OnRemoteCmdSignalCompleted() { PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignalCallbackReceived, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString() }); this.StopSignalTimerAndDecrementOperations(); if (!base.isClosed) { base.EnqueueAndStartProcessingThread(null, null, true); } }
private static void OnRemoteCmdDataReceived(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { BaseClientTransportManager.tracer.WriteLine("Remote Command DataReceived callback.", new object[0]); long cmdTMId = 0L; WSManClientCommandTransportManager cmdTransportManager = null; if (!TryGetCmdTransportManager(operationContext, out cmdTransportManager, out cmdTMId)) { BaseClientTransportManager.tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", new object[] { cmdTMId }); } else if (!shellOperationHandle.Equals(cmdTransportManager.wsManShellOperationHandle) || !commandOperationHandle.Equals(cmdTransportManager.wsManCmdOperationHandle)) { BaseClientTransportManager.tracer.WriteLine("CmdReceive callback: ShellOperationHandles are not the same as the Receive is initiated with", new object[0]); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandReceiveExFailed); TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveCommandOutputEx); cmdTransportManager.ProcessWSManTransportError(eventArgs); } else { cmdTransportManager.ClearReceiveOrSendResources(flags, false); if (cmdTransportManager.isClosed) { BaseClientTransportManager.tracer.WriteLine("Client Command TM: Transport manager is closed. So returning", new object[0]); } else { if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { BaseClientTransportManager.tracer.WriteLine("CmdReceive callback: WSMan reported an error: {0}", new object[] { errorStruct.errorDetail }); TransportErrorOccuredEventArgs args2 = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.ReceiveCommandOutputEx, RemotingErrorIdStrings.CommandReceiveExCallBackError, new object[] { errorStruct.errorDetail }); cmdTransportManager.ProcessWSManTransportError(args2); return; } } if (flags == 0x2000) { cmdTransportManager.isDisconnectedOnInvoke = true; cmdTransportManager.RaiseDelayStreamProcessedEvent(); } else { WSManNativeApi.WSManReceiveDataResult result = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data); if (result.data != null) { BaseClientTransportManager.tracer.WriteLine("Cmd Received Data : {0}", new object[] { result.data.Length }); object[] args = new object[] { cmdTransportManager.RunspacePoolInstanceId.ToString(), cmdTransportManager.powershellInstanceId.ToString(), result.data.Length.ToString(CultureInfo.InvariantCulture) }; PSEtwLog.LogAnalyticInformational(PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, args); cmdTransportManager.ProcessRawData(result.data, result.stream); } } } } }
private void WriteCurrentFragmentAndReset() { PSEtwLog.LogAnalyticVerbose(PSEventId.SentRemotingFragment, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, this.currentFragment.ObjectId, this.currentFragment.FragmentId, this.currentFragment.IsStartFragment ? 1 : 0, this.currentFragment.IsEndFragment ? 1 : 0, (int)this.currentFragment.BlobLength, new PSETWBinaryBlob(this.currentFragment.Blob, 0, this.currentFragment.BlobLength)); byte[] bytes = this.currentFragment.GetBytes(); int length = bytes.Length; if (fragmentSize == 0) { fragmentSize = length; } int offset = 0; if (!this.notifyOnWriteFragmentImmediately) { lock (this.syncObject) { if (this.isDisposed) { return; } if (this.writeStream == null) { this.writeStream = new MemoryStream(this.fragmentSize); _trace.WriteLine("Created write stream: {0}", new object[] { this.writeStream.GetHashCode() }); this.writeOffset = 0; } while (length > 0) { int num3 = this.writeStream.Capacity - this.writeOffset; if (num3 == 0) { this.EnqueueWriteStream(); num3 = this.writeStream.Capacity - this.writeOffset; } int count = (length > num3) ? num3 : length; length -= count; this.writeStream.Position = this.writeOffset; this.writeStream.Write(bytes, offset, count); offset += count; this.writeOffset += count; this.length += count; } } } if (this.onDataAvailableCallback != null) { this.onDataAvailableCallback(bytes, this.currentFragment.IsEndFragment); } this.currentFragment.FragmentId = this.fragmentId += 1L; this.currentFragment.IsStartFragment = false; this.currentFragment.IsEndFragment = false; this.currentFragment.BlobLength = 0; this.currentFragment.Blob = new byte[this.fragmentSize]; }
private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { BaseClientTransportManager.tracer.WriteLine("Signal Completed callback received.", new object[0]); long cmdTMId = 0L; WSManClientCommandTransportManager cmdTransportManager = null; if (!TryGetCmdTransportManager(operationContext, out cmdTransportManager, out cmdTMId)) { BaseClientTransportManager.tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", new object[] { cmdTMId }); } else { PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignalCallbackReceived, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { cmdTransportManager.RunspacePoolInstanceId.ToString(), cmdTransportManager.powershellInstanceId.ToString() }); if (!shellOperationHandle.Equals(cmdTransportManager.wsManShellOperationHandle) || !commandOperationHandle.Equals(cmdTransportManager.wsManCmdOperationHandle)) { BaseClientTransportManager.tracer.WriteLine("Cmd Signal callback: ShellOperationHandles are not the same as the signal is initiated with", new object[0]); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandSendExFailed); TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CommandInputEx); cmdTransportManager.ProcessWSManTransportError(eventArgs); } else { if (IntPtr.Zero != cmdTransportManager.cmdSignalOperationHandle) { WSManNativeApi.WSManCloseOperation(cmdTransportManager.cmdSignalOperationHandle, 0); cmdTransportManager.cmdSignalOperationHandle = IntPtr.Zero; } if (cmdTransportManager.signalCmdCompleted != null) { cmdTransportManager.signalCmdCompleted.Dispose(); cmdTransportManager.signalCmdCompleted = null; } if (cmdTransportManager.isClosed) { BaseClientTransportManager.tracer.WriteLine("Client Command TM: Transport manager is closed. So returning", new object[0]); } else { if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { BaseClientTransportManager.tracer.WriteLine("Cmd Signal callback: WSMan reported an error: {0}", new object[] { errorStruct.errorDetail }); TransportErrorOccuredEventArgs args2 = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.CommandInputEx, RemotingErrorIdStrings.CommandSendExCallBackError, new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); cmdTransportManager.ProcessWSManTransportError(args2); return; } } cmdTransportManager.EnqueueAndStartProcessingThread(null, null, true); } } } }
private void SendData(byte[] data, DataPriorityType priorityType) { object[] args = new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString(), data.Length.ToString(CultureInfo.InvariantCulture) }; PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputEx, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, args); lock (base.syncObject) { if (!base.isClosed) { this.stdInWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, priorityType, base.powershellInstanceId)); } } }
internal void ServicePendingCallbacks(object objectToProcess) { tracer.WriteLine("ServicePendingCallbacks thread is starting", new object[0]); PSEtwLog.ReplaceActivityIdForCurrentThread(this.runspacePoolInstanceId, PSEventId.OperationalTransferEventRunspacePool, PSEventId.AnalyticTransferEventRunspacePool, PSKeyword.Transport, PSTask.None); try { while (!this.isClosed) { CallbackNotificationInformation information = null; lock (this.callbackNotificationQueue) { if ((this.callbackNotificationQueue.Count <= 0) || this.suspendQueueServicing) { return; } information = this.callbackNotificationQueue.Dequeue(); } if (information != null) { if (information.transportError != null) { this.RaiseErrorHandler(information.transportError); return; } if (information.privateData != null) { this.ProcessPrivateData(information.privateData); } else { base.OnDataAvailableCallback(information.remoteObject); } } } } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Exception processing data. {0}", new object[] { exception.Message }), new object[0]); PSRemotingTransportException e = new PSRemotingTransportException(exception.Message, exception); TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx); this.RaiseErrorHandler(eventArgs); } finally { lock (this.callbackNotificationQueue) { tracer.WriteLine("ServicePendingCallbacks thread is exiting", new object[0]); this.isServicingCallbacks = false; this.EnqueueAndStartProcessingThread(null, null, null); } } }
internal void OnRemoteCmdSendCompleted() { PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString() }); lock (base.syncObject) { if (base.isClosed) { BaseClientTransportManager.tracer.WriteLine("Client Command TM: Transport manager is closed. So returning", new object[0]); return; } } this.SendOneItem(); }
internal void OnRemoteCmdDataReceived(byte[] rawData, string stream) { object[] args = new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString(), rawData.Length.ToString(CultureInfo.InvariantCulture) }; PSEtwLog.LogAnalyticInformational(PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, args); if (base.isClosed) { BaseClientTransportManager.tracer.WriteLine("Client Command TM: Transport manager is closed. So returning", new object[0]); } else { this.ProcessRawData(rawData, stream); } }
private static Type LoadAndAnalyzeAssembly(string shellId, string applicationBase, string assemblyName, string typeToLoad) { if ((string.IsNullOrEmpty(assemblyName) && !string.IsNullOrEmpty(typeToLoad)) || (!string.IsNullOrEmpty(assemblyName) && string.IsNullOrEmpty(typeToLoad))) { throw PSTraceSource.NewInvalidOperationException("remotingerroridstrings", "TypeNeedsAssembly", new object[] { "assemblyname", "pssessionconfigurationtypename", "InitializationParameters" }); } Assembly assembly = null; if (!string.IsNullOrEmpty(assemblyName)) { PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellAssembly, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { assemblyName, shellId }); assembly = LoadSsnStateProviderAssembly(applicationBase, assemblyName); if (null == assembly) { throw PSTraceSource.NewArgumentException("assemblyName", "remotingerroridstrings", "UnableToLoadAssembly", new object[] { assemblyName, "InitializationParameters" }); } } if (null == assembly) { return(typeof(DefaultRemotePowerShellConfiguration)); } try { PSEtwLog.LogAnalyticVerbose(PSEventId.LoadingPSCustomShellType, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { typeToLoad, shellId }); Type type = assembly.GetType(typeToLoad, true, true); if (null == type) { throw PSTraceSource.NewArgumentException("typeToLoad", "remotingerroridstrings", "UnableToLoadType", new object[] { typeToLoad, "InitializationParameters" }); } return(type); } catch (ReflectionTypeLoadException) { } catch (TypeLoadException) { } catch (ArgumentException) { } catch (MissingMethodException) { } catch (InvalidCastException) { } catch (TargetInvocationException) { } throw PSTraceSource.NewArgumentException("typeToLoad", "remotingerroridstrings", "UnableToLoadType", new object[] { typeToLoad, "InitializationParameters" }); }
public static RemoteRunspace FromPSObjectForRemoting(PSObject obj) { int id = RemotingDecoder.GetPropertyValue <int> (obj, "Id"); string name = RemotingDecoder.GetPropertyValue <string> (obj, "Name"); PSPrimitiveDictionary appArgs = RemotingDecoder.GetPropertyValue <PSPrimitiveDictionary> (obj, "ApplicationArguments"); string connectionInfoType = RemotingDecoder.GetPropertyValue <string> (obj, "ConnectionInfoType"); PSObject connectionObj = RemotingDecoder.GetPropertyValue <PSObject> (obj, "ConnectionInfo"); RunspaceConnectionInfo connectionInfo = null; if (connectionInfoType == "WSManConnectionInfo") { connectionInfo = WSManConnectionInfo.FromPSObjectForRemoting(connectionObj); } else { var securePassord = new System.Security.SecureString(); securePassord.AppendChar('z'); connectionInfo = new NewProcessConnectionInfo(new PSCredential("Anonymous", securePassord)); } var runspace = new RemoteRunspace(new TypeTable(), connectionInfo, null, appArgs, name, id); runspace._version = RemotingDecoder.GetPropertyValue <Version>(obj, "Version"); runspace.ApartmentState = RemotingDecoder.GetPropertyValue <ApartmentState>(obj, "ApartmentState"); runspace.InstanceId = RemotingDecoder.GetPropertyValue <Guid>(obj, "InstanceId"); runspace._shouldCloseOnPop = RemotingDecoder.GetPropertyValue <bool>(obj, "ShouldCloseOnPop"); runspace._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RemotingDecoder.GetPropertyValue <RunspaceState>(obj, "RunspaceStateInfo")); runspace._runspaceAvailability = RemotingDecoder.GetPropertyValue <RunspaceAvailability>(obj, "RunspaceAvailability"); runspace.ThreadOptions = RemotingDecoder.GetPropertyValue <PSThreadOptions>(obj, "ThreadOptions"); runspace.EngineActivityId = RemotingDecoder.GetPropertyValue <Guid>(obj, "EngineActivityId"); runspace._bSessionStateProxyCallInProgress = RemotingDecoder.GetPropertyValue <bool>(obj, "SessionStateProxyCallInProgress"); runspace._bypassRunspaceStateCheck = RemotingDecoder.GetPropertyValue <bool>(obj, "ByPassRunspaceStateCheck"); PSEtwLog.SetActivityIdForCurrentThread(runspace.InstanceId); string originalConnectionInfoType = RemotingDecoder.GetPropertyValue <string> (obj, "OriginalConnectionInfoType"); PSObject originalConnectionObj = RemotingDecoder.GetPropertyValue <PSObject> (obj, "OriginalConnectionInfo"); RunspaceConnectionInfo originalConnectionInfo = null; if (originalConnectionInfoType == "WSManConnectionInfo") { originalConnectionInfo = WSManConnectionInfo.FromPSObjectForRemoting(originalConnectionObj); } else { var securePassord = new System.Security.SecureString(); securePassord.AppendChar('z'); originalConnectionInfo = new NewProcessConnectionInfo(new PSCredential("Anonymous", securePassord)); } runspace._originalConnectionInfo = originalConnectionInfo; runspace.RunspacePool.RemoteRunspacePoolInternal.SetStateInfo(new RunspacePoolStateInfo(RunspacePoolState.Opened, null)); return(runspace); }
private void SetRunspaceState(RunspaceState state, Exception reason) { lock (this._syncRoot) { if (state != this._runspaceStateInfo.State) { this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(state, reason); System.Management.Automation.Runspaces.RunspaceAvailability currentAvailability = this._runspaceAvailability; base.UpdateRunspaceAvailability(this._runspaceStateInfo.State, false); this._runspaceEventQueue.Enqueue(new RunspaceEventQueueItem(this._runspaceStateInfo.Clone(), currentAvailability, this._runspaceAvailability)); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceStateChange, PSOpcode.Open, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { state.ToString() }); } } }
protected override IAsyncResult CoreOpen(bool isAsync, AsyncCallback callback, object asyncState) { PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspacePoolOpen, PSOpcode.Open, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[0]); lock (base.syncObject) { base.AssertIfStateIsBeforeOpen(); base.stateInfo = new RunspacePoolStateInfo(RunspacePoolState.Opening, null); } base.RaiseStateChangeEvent(base.stateInfo); RunspacePoolAsyncResult result = new RunspacePoolAsyncResult(base.instanceId, callback, asyncState, true); this.openAsyncResult = result; this.dataStructureHandler.CreateRunspacePoolAndOpenAsync(); return(result); }
private void ProcessingThreadStart(object state) { try { string data = state as string; OutOfProcessUtils.ProcessData(data, this.callbacks); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); PSEtwLog.LogOperationalError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, new object[] { Guid.Empty.ToString(), Guid.Empty.ToString(), 0xfa0, exception.Message, exception.StackTrace }); PSEtwLog.LogAnalyticError(PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { Guid.Empty.ToString(), Guid.Empty.ToString(), 0xfa0, exception.Message, exception.StackTrace }); this.originalStdErr.WriteLine(exception.Message + exception.StackTrace); Environment.Exit(0xfa0); } }
/// <summary> /// Set the desired execution policy. /// </summary> protected override void ProcessRecord() { string shellId = base.Context.ShellID; string executionPolicy = SecuritySupport.GetExecutionPolicy(ExecutionPolicy); if (ShouldProcessPolicyChange(executionPolicy)) { try { SecuritySupport.SetExecutionPolicy(_executionPolicyScope, ExecutionPolicy, shellId); } catch (UnauthorizedAccessException exception) { OnAccessDeniedError(exception); } catch (System.Security.SecurityException exception) { OnAccessDeniedError(exception); } // Ensure it is now the effective execution policy if (ExecutionPolicy != ExecutionPolicy.Undefined) { string effectiveExecutionPolicy = SecuritySupport.GetExecutionPolicy(shellId).ToString(); if (!string.Equals(effectiveExecutionPolicy, executionPolicy, StringComparison.OrdinalIgnoreCase)) { string message = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, effectiveExecutionPolicy); string recommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction; ErrorRecord errorRecord = new ErrorRecord( new System.Security.SecurityException(), "ExecutionPolicyOverride", ErrorCategory.PermissionDenied, null); errorRecord.ErrorDetails = new ErrorDetails(message); errorRecord.ErrorDetails.RecommendedAction = recommendedAction; ThrowTerminatingError(errorRecord); } } #if !CORECLR PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(Context, MyInvocation), EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null); #endif } }//End ProcessRecord()
protected void ProcessingThreadStart(object state) { try { #if !CORECLR // CurrentUICulture is not available in Thread Class in CSS // WinBlue: 621775. Thread culture is not properly set // for local background jobs causing experience differences // between local console and local background jobs. Thread.CurrentThread.CurrentUICulture = Microsoft.PowerShell.NativeCultureResolver.UICulture; Thread.CurrentThread.CurrentCulture = Microsoft.PowerShell.NativeCultureResolver.Culture; #endif string data = state as string; OutOfProcessUtils.ProcessData(data, callbacks); } catch (Exception e) { PSEtwLog.LogOperationalError( PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, Guid.Empty.ToString(), Guid.Empty.ToString(), OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION, e.Message, e.StackTrace); PSEtwLog.LogAnalyticError( PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, Guid.Empty.ToString(), Guid.Empty.ToString(), OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION, e.Message, e.StackTrace); // notify the remote client of any errors and fail gracefully if (_exitProcessOnError) { originalStdErr.WriteLine(e.Message + e.StackTrace); Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION); } } }
internal override void CreateAsync() { byte[] firstArgument = base.serializedPipeline.ReadOrRegisterCallback(null); if (firstArgument == null) { firstArgument = new byte[0]; } bool flag = true; if (commandCodeSendRedirect != null) { object[] objArray2 = new object[2]; objArray2[1] = firstArgument; object[] objArray = objArray2; flag = (bool)commandCodeSendRedirect.DynamicInvoke(objArray); firstArgument = (byte[])objArray[0]; } if (!flag) { return; } WSManNativeApi.WSManCommandArgSet set = new WSManNativeApi.WSManCommandArgSet(firstArgument); this.cmdContextId = GetNextCmdTMHandleId(); AddCmdTransportManager(this.cmdContextId, this); PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommand, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString() }); this.createCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdCreateCallback); this.createCmdCompletedGCHandle = GCHandle.Alloc(this.createCmdCompleted); this.reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdReconnectCallback); using (set) { lock (base.syncObject) { if (!base.isClosed) { WSManNativeApi.WSManRunShellCommandEx(this.wsManShellOperationHandle, 0, base.PowershellInstanceId.ToString().ToUpper(CultureInfo.InvariantCulture), ((this.cmdLine == null) || (this.cmdLine.Length == 0)) ? " " : ((this.cmdLine.Length <= 0x100) ? this.cmdLine : this.cmdLine.Substring(0, 0xff)), (IntPtr)set, IntPtr.Zero, (IntPtr)this.createCmdCompleted, ref this.wsManCmdOperationHandle); BaseClientTransportManager.tracer.WriteLine("Started cmd with command context : {0} Operation context: {1}", new object[] { this.cmdContextId, this.wsManCmdOperationHandle }); } } } if (this.wsManCmdOperationHandle == IntPtr.Zero) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed); TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.RunShellCommandEx); this.ProcessWSManTransportError(eventArgs); } }
internal override void CloseAsync() { lock (base.syncObject) { if (base.isClosed) { return; } base.isClosed = true; } base.CloseAsync(); PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommand, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString() }); if (this.stdInWriter != null) { this.stdInWriter.WriteLine(OutOfProcessUtils.CreateClosePacket(base.powershellInstanceId)); } }
internal static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs args) { // args can never be null. Exception exception = (Exception)args.ExceptionObject; // log the exception to crimson event logs PSEtwLog.LogOperationalError(PSEventId.AppDomainUnhandledException, PSOpcode.Close, PSTask.None, PSKeyword.UseAlwaysOperational, exception.GetType().ToString(), exception.Message, exception.StackTrace); PSEtwLog.LogAnalyticError(PSEventId.AppDomainUnhandledException_Analytic, PSOpcode.Close, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, exception.GetType().ToString(), exception.Message, exception.StackTrace); }
protected override void EndProcessing() { foreach (UpdatableHelpExceptionContext context in this.exceptions.Values) { UpdatableHelpExceptionContext context2 = context; if ((context.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") && (((context.Cultures != null) && (context.Cultures.Count > 1)) || ((context.Modules != null) && (context.Modules.Count > 1)))) { context2 = new UpdatableHelpExceptionContext(new UpdatableHelpSystemException("HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.CannotMatchUICulturePattern, string.Join(", ", context.Cultures)), ErrorCategory.InvalidArgument, context.Cultures, null)) { Modules = context.Modules, Cultures = context.Cultures }; } base.WriteError(context2.CreateErrorRecord(this._commandType)); LogContext logContext = MshLog.GetLogContext(base.Context, base.MyInvocation); logContext.Severity = "Error"; PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline, logContext, context2.GetExceptionMessage(this._commandType)); } }
internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) { string stackTrace; if (!string.IsNullOrEmpty(eventArgs.Exception.StackTrace)) { stackTrace = eventArgs.Exception.StackTrace; } else if ((eventArgs.Exception.InnerException != null) && !string.IsNullOrEmpty(eventArgs.Exception.InnerException.StackTrace)) { stackTrace = eventArgs.Exception.InnerException.StackTrace; } else { stackTrace = string.Empty; } PSEtwLog.LogOperationalError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString(), eventArgs.Exception.ErrorCode.ToString(CultureInfo.InvariantCulture), eventArgs.Exception.Message, stackTrace }); PSEtwLog.LogAnalyticError(PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString(), eventArgs.Exception.ErrorCode.ToString(CultureInfo.InvariantCulture), eventArgs.Exception.Message, stackTrace }); base.RaiseErrorHandler(eventArgs); }
internal void OnDataAvailableCallback(RemoteDataObject <PSObject> remoteObject) { PSEtwLog.LogAnalyticInformational(PSEventId.TransportReceivedObject, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { remoteObject.RunspacePoolId.ToString(), remoteObject.PowerShellId.ToString(), (int)remoteObject.Destination, (int)remoteObject.DataType, (int)remoteObject.TargetInterface }); this.PowerShellGuidObserver.SafeInvoke(remoteObject.PowerShellId, EventArgs.Empty); RemoteDataEventArgs eventArgs = new RemoteDataEventArgs(remoteObject); if (remoteObject.DataType == RemotingDataType.RunspacePoolStateInfo) { System.Diagnostics.Debug.WriteLine("RunspacePool State Opened Received"); Thread.Sleep(800); //HACK: Delay reception in local mode... TODO: Find why!!! cannot have a Wait somewhere _slowed = true; } this.DataReceived.SafeInvoke <RemoteDataEventArgs>(this, eventArgs); }
private static void OnCloseCmdCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { BaseClientTransportManager.tracer.WriteLine("OnCloseCmdCompleted callback received for operation context {0}", new object[] { commandOperationHandle }); long cmdTMId = 0L; WSManClientCommandTransportManager cmdTransportManager = null; if (!TryGetCmdTransportManager(operationContext, out cmdTransportManager, out cmdTMId)) { BaseClientTransportManager.tracer.WriteLine("OnCloseCmdCompleted: Unable to find a transport manager for the command context {0}.", new object[] { cmdTMId }); } else { BaseClientTransportManager.tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Close completed callback received for command: {0}", new object[] { cmdTransportManager.cmdContextId }), new object[0]); PSEtwLog.LogAnalyticInformational(PSEventId.WSManCloseCommandCallbackReceived, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { cmdTransportManager.RunspacePoolInstanceId.ToString(), cmdTransportManager.powershellInstanceId.ToString() }); if (cmdTransportManager.isDisconnectPending) { cmdTransportManager.RaiseReadyForDisconnect(); } cmdTransportManager.RaiseCloseCompleted(); } }
internal override void SendStopSignal() { lock (base.syncObject) { if (!base.isClosed) { if (!this.isCreateCallbackReceived) { this.isStopSignalPending = true; } else { this.isStopSignalPending = false; BaseClientTransportManager.tracer.WriteLine("Sending stop signal with command context: {0} Operation Context {1}", new object[] { this.cmdContextId, this.wsManCmdOperationHandle }); PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignal, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString(), StopSignal }); this.signalCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdSignalCallback); WSManNativeApi.WSManSignalShellEx(this.wsManShellOperationHandle, this.wsManCmdOperationHandle, 0, StopSignal, (IntPtr)this.signalCmdCompleted, ref this.cmdSignalOperationHandle); } } } }
internal static void AddNoteProperty <T>(PSObject pso, string propertyName, ValueGetterDelegate <T> valueGetter) { T local = default(T); try { local = valueGetter(); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); PSEtwLog.LogAnalyticWarning(PSEventId.Serializer_PropertyGetterFailed, PSOpcode.Exception, PSTask.Serialization, PSKeyword.Serializer | PSKeyword.UseAlwaysAnalytic, new object[] { propertyName, (valueGetter.Target == null) ? string.Empty : valueGetter.Target.GetType().FullName, exception.ToString(), (exception.InnerException == null) ? string.Empty : exception.InnerException.ToString() }); } try { pso.Properties.Add(new PSNoteProperty(propertyName, local)); } catch (ExtendedTypeSystemException) { object obj1 = pso.Properties[propertyName].Value; } }
protected void ProcessingThreadStart(object state) { try { string data = state as string; OutOfProcessUtils.ProcessData(data, callbacks); } catch (Exception e) { PSEtwLog.LogOperationalError( PSEventId.TransportError, PSOpcode.Open, PSTask.None, PSKeyword.UseAlwaysOperational, Guid.Empty.ToString(), Guid.Empty.ToString(), OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION, e.Message, e.StackTrace); PSEtwLog.LogAnalyticError( PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, Guid.Empty.ToString(), Guid.Empty.ToString(), OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION, e.Message, e.StackTrace); // notify the remote client of any errors and fail gracefully if (_exitProcessOnError) { originalStdErr.WriteLine(e.Message + e.StackTrace); Environment.Exit(OutOfProcessUtils.EXITCODE_UNHANDLED_EXCEPTION); } } }
internal override void StartReceivingData() { PSEtwLog.LogAnalyticInformational(PSEventId.WSManReceiveShellOutputEx, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString() }); this.shouldStartReceivingData = false; lock (base.syncObject) { if (base.isClosed) { BaseClientTransportManager.tracer.WriteLine("Client Session TM: Transport manager is closed. So returning", new object[0]); } else if (base.receiveDataInitiated) { BaseClientTransportManager.tracer.WriteLine("Client Session TM: Command ReceiveData has already been called.", new object[0]); } else { base.receiveDataInitiated = true; this.receivedFromRemote = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdReceiveCallback); WSManNativeApi.WSManReceiveShellOutputEx(this.wsManShellOperationHandle, this.wsManCmdOperationHandle, base.startInDisconnectedMode ? 0x10 : 0, (IntPtr)WSManClientSessionTransportManager.wsManApiStaticData.OutputStreamSet, (IntPtr)this.receivedFromRemote, ref this.wsManRecieveOperationHandle); } } }
internal RemoteRunspace(System.Management.Automation.Runspaces.RunspacePool runspacePool) { this._runningPipelines = new ArrayList(); this._syncRoot = new object(); this._runspaceStateInfo = new System.Management.Automation.Runspaces.RunspaceStateInfo(RunspaceState.BeforeOpen); this._version = PSVersionInfo.PSVersion; this._runspaceEventQueue = new Queue <RunspaceEventQueueItem>(); this.id = -1; if ((runspacePool.RunspacePoolStateInfo.State != RunspacePoolState.Disconnected) || !(runspacePool.ConnectionInfo is WSManConnectionInfo)) { throw PSTraceSource.NewInvalidOperationException("RunspaceStrings", "InvalidRunspacePool", new object[0]); } this._runspacePool = runspacePool; this._runspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1); this._runspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1); this._connectionInfo = ((WSManConnectionInfo)runspacePool.ConnectionInfo).Copy(); this.SetRunspaceState(RunspaceState.Disconnected, null); this._runspaceAvailability = this._runspacePool.RemoteRunspacePoolInternal.AvailableForConnection ? System.Management.Automation.Runspaces.RunspaceAvailability.None : System.Management.Automation.Runspaces.RunspaceAvailability.Busy; this.SetEventHandlers(); PSEtwLog.SetActivityIdForCurrentThread(base.InstanceId); PSEtwLog.LogOperationalVerbose(PSEventId.RunspaceConstructor, PSOpcode.Constructor, PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, new object[] { base.InstanceId.ToString() }); }