internal void EnqueueAndStartProcessingThread( RemoteDataObject <PSObject> remoteObject, PSRemotingTransportException transportException, object privateData) { if (this.isClosed) { return; } lock (this.callbackNotificationQueue) { if (remoteObject != null || transportException != null || privateData != null) { BaseClientTransportManager.ReceivedDataInformation receivedDataInformation = new BaseClientTransportManager.ReceivedDataInformation(); receivedDataInformation.remoteObject = remoteObject; receivedDataInformation.transportException = transportException; receivedDataInformation.privateData = privateData; if (remoteObject != null && (remoteObject.DataType == RemotingDataType.PublicKey || remoteObject.DataType == RemotingDataType.EncryptedSessionKey || remoteObject.DataType == RemotingDataType.PublicKeyRequest)) { this.CryptoHelper.Session.BaseSessionDataStructureHandler.RaiseKeyExchangeMessageReceived(remoteObject); } else { this.callbackNotificationQueue.Enqueue(receivedDataInformation); } } if (this.isServicingCallbacks || this.callbackNotificationQueue.Count <= 0) { return; } this.isServicingCallbacks = true; ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServicePendingCallbacks)); } }
internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle, WSManClientSessionTransportManager wsmanSessionTM, WSManNativeApi.WSManError errorStruct, TransportMethodEnum transportMethodReportingError, string resourceString, params object[] resourceArgs) { PSRemotingTransportException exception; if ((errorStruct.errorCode == -2144108135) && (wsmanSessionTM != null)) { string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionTM.SessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION); string str2 = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim(); exception = new PSRemotingTransportRedirectException(redirectLocation, PSRemotingErrorId.URIEndPointNotResolved, RemotingErrorIdStrings.URIEndPointNotResolved, new object[] { str2, redirectLocation }); } else if ((errorStruct.errorCode == -2144108485) && (wsmanSessionTM != null)) { string str3 = wsmanSessionTM.ConnectionInfo.ShellUri.Replace("http://schemas.microsoft.com/powershell/", string.Empty); string str4 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName, new object[] { str3, wsmanSessionTM.ConnectionInfo.ComputerName }); exception = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName, RemotingErrorIdStrings.ConnectExCallBackError, new object[] { wsmanSessionTM.ConnectionInfo.ComputerName, str4 }) { TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)) }; } else { string str5 = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs); exception = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, RemotingErrorIdStrings.TroubleShootingHelpTopic, new object[] { str5 }) { TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)) }; } exception.ErrorCode = errorStruct.errorCode; return(new TransportErrorOccuredEventArgs(exception, transportMethodReportingError)); }
private void WriteConnectFailed(Exception e, PSSession session) { Exception runtimeException; if (this._writeStream.ObjectWriter.IsOpen) { string fQEIDFromTransportError = "PSSessionConnectFailed"; if (e == null || string.IsNullOrEmpty(e.Message)) { runtimeException = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name, session.Runspace.RunspaceStateInfo.State.ToString()), null); } else { PSRemotingTransportException pSRemotingTransportException = e as PSRemotingTransportException; if (pSRemotingTransportException != null) { fQEIDFromTransportError = WSManTransportManagerUtils.GetFQEIDFromTransportError(pSRemotingTransportException.ErrorCode, fQEIDFromTransportError); } runtimeException = new RuntimeException(StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message), e); } ErrorRecord errorRecord = new ErrorRecord(runtimeException, fQEIDFromTransportError, ErrorCategory.InvalidOperation, null); Action <Cmdlet> action = (Cmdlet cmdlet) => cmdlet.WriteError(errorRecord); this._writeStream.ObjectWriter.Write(action); } }
private static void OnReconnectCmdCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { 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("Cmd Signal callback: ShellOperationHandles are not the same as the signal is initiated with", new object[0]); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ReconnectShellCommandExCallBackError); TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReconnectShellCommandEx); cmdTransportManager.ProcessWSManTransportError(eventArgs); } else { if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { BaseClientTransportManager.tracer.WriteLine("OnReconnectCmdCompleted callback: WSMan reported an error: {0}", new object[] { errorStruct.errorDetail }); TransportErrorOccuredEventArgs args2 = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.ReconnectShellCommandEx, RemotingErrorIdStrings.ReconnectShellCommandExCallBackError, new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); cmdTransportManager.ProcessWSManTransportError(args2); return; } } cmdTransportManager.shouldStartReceivingData = true; cmdTransportManager.SendOneItem(); cmdTransportManager.RaiseReconnectCompleted(); } }
internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs( IntPtr wsmanAPIHandle, IntPtr wsmanSessionHandle, WSManNativeApi.WSManError errorStruct, TransportMethodEnum transportMethodReportingError, PSRemotingErrorId errorResourceID, params object[] resourceArgs) { PSRemotingTransportException e; if (errorStruct.errorCode == -2144108135) { string sessionOptionAsString = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION); string str = WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim(); e = (PSRemotingTransportException) new PSRemotingTransportRedirectException(sessionOptionAsString, PSRemotingErrorId.URIEndPointNotResolved, new object[2] { (object)str, (object)sessionOptionAsString }); } else { e = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, new object[1] { (object)PSRemotingErrorInvariants.FormatResourceString(errorResourceID, resourceArgs) }); e.TransportMessage = WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)); } e.ErrorCode = errorStruct.errorCode; return(new TransportErrorOccuredEventArgs(e, transportMethodReportingError)); }
private void WriteConnectFailed( Exception e, PSSession session) { if (_writeStream.ObjectWriter.IsOpen) { string FQEID = "PSSessionConnectFailed"; Exception reason; if (e != null && !string.IsNullOrEmpty(e.Message)) { // Update fully qualified error Id if we have a transport error. PSRemotingTransportException transportException = e as PSRemotingTransportException; if (transportException != null) { FQEID = WSManTransportManagerUtils.GetFQEIDFromTransportError(transportException.ErrorCode, FQEID); } reason = new RuntimeException( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailedWithMessage, session.Name, e.Message), e); } else { reason = new RuntimeException( StringUtil.Format(RemotingErrorIdStrings.RunspaceConnectFailed, session.Name, session.Runspace.RunspaceStateInfo.State.ToString()), null); } ErrorRecord errorRecord = new ErrorRecord(reason, FQEID, ErrorCategory.InvalidOperation, null); Action <Cmdlet> errorWriter = delegate(Cmdlet cmdlet) { cmdlet.WriteError(errorRecord); }; _writeStream.ObjectWriter.Write(errorWriter); } }
internal void OnCloseTimeOutTimerElapsed(object source, ElapsedEventArgs e) { this.closeTimeOutTimer.Stop(); PSRemotingTransportException exception = new PSRemotingTransportException(PSRemotingErrorId.IPCCloseTimedOut, RemotingErrorIdStrings.IPCCloseTimedOut, new object[0]); this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(exception, TransportMethodEnum.CloseShellOperationEx)); }
internal void OnSignalTimeOutTimerElapsed(object source, ElapsedEventArgs e) { this.StopSignalTimerAndDecrementOperations(); if (!base.isClosed) { PSRemotingTransportException exception = new PSRemotingTransportException(RemotingErrorIdStrings.IPCSignalTimedOut); this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(exception, TransportMethodEnum.ReceiveShellOutputEx)); } }
private void HandleSSHError(PSRemotingTransportException ex) { RaiseErrorHandler( new TransportErrorOccuredEventArgs( ex, TransportMethodEnum.CloseShellOperationEx)); CloseConnection(); }
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 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); } } } }
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); } } }
private void HandleTransportError(PSRemotingTransportException transportException, bool onSetup) { this._tracer.TraceException(transportException); if (this.ProcessCrashed != null) { ActivityHostCrashedEventArgs activityHostCrashedEventArg = new ActivityHostCrashedEventArgs(); activityHostCrashedEventArg.FailureOnSetup = onSetup; activityHostCrashedEventArg.Invoker = this._currentInvoker; ActivityHostCrashedEventArgs activityHostCrashedEventArg1 = activityHostCrashedEventArg; this.ProcessCrashed(this, activityHostCrashedEventArg1); } }
private void WriteErrorCreateRemoteRunspaceFailed(Exception exception, object argument) { PSRemotingTransportException exception2 = exception as PSRemotingTransportException; string str = null; if ((exception2 != null) && (exception2.ErrorCode == -2144108135)) { str = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.URIRedirectionReported, new object[] { exception2.Message, "MaximumConnectionRedirectionCount", "PSSessionOption", "AllowRedirection" }); } ErrorRecord errorRecord = new ErrorRecord(exception, argument, "CreateRemoteRunspaceFailed", ErrorCategory.InvalidArgument, null, null, null, null, null, str, null); base.WriteError(errorRecord); }
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e) { lock (base.syncObject) { if (base.isClosed) { return; } } PSRemotingTransportException exception = new PSRemotingTransportException(PSRemotingErrorId.IPCServerProcessReportedError, RemotingErrorIdStrings.IPCServerProcessReportedError, new object[] { e.Data }); this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(exception, TransportMethodEnum.Unknown)); }
private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { try { OutOfProcessUtils.ProcessData(e.Data, this.dataProcessingCallbacks); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); PSRemotingTransportException exception2 = new PSRemotingTransportException(PSRemotingErrorId.IPCErrorProcessingServerData, RemotingErrorIdStrings.IPCErrorProcessingServerData, new object[] { exception.Message }); this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(exception2, TransportMethodEnum.ReceiveShellOutputEx)); } }
internal void ReportError(int errorCode, string methodName) { string generalError = RemotingErrorIdStrings.GeneralError; string message = string.Format(CultureInfo.InvariantCulture, generalError, new object[] { errorCode, methodName }); PSRemotingTransportException e = new PSRemotingTransportException(message) { ErrorCode = errorCode }; ThreadPool.QueueUserWorkItem(delegate(object state) { TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.Unknown); this.RaiseErrorHandler(eventArgs); }); }
/// <summary> /// Handles a transport error since it is most likely that /// the process crash /// </summary> /// <param name="transportException">the transport exception /// that was raised</param> /// <param name="onSetup">true indicates that the crash was /// encountered when setting up the process and not when the /// command was run</param> private void HandleTransportError(PSRemotingTransportException transportException, bool onSetup) { _tracer.TraceException(transportException); if (ProcessCrashed != null) { ActivityHostCrashedEventArgs eventArgs = new ActivityHostCrashedEventArgs { FailureOnSetup = onSetup, Invoker = _currentInvoker }; ProcessCrashed(this, eventArgs); } }
private void WriteException(Exception exception) { string str; PSRemotingTransportException pSRemotingTransportException = exception as PSRemotingTransportException; if (pSRemotingTransportException == null || pSRemotingTransportException.InnerException as TargetInvocationException == null || pSRemotingTransportException.InnerException.InnerException == null) { IContainsErrorRecord containsErrorRecord = exception as IContainsErrorRecord; if (containsErrorRecord != null) { ErrorRecord errorRecord = containsErrorRecord.ErrorRecord; if (errorRecord.InvocationInfo == null || errorRecord.InvocationInfo.PositionMessage == null) { str = errorRecord.ToString(); } else { str = errorRecord.InvocationInfo.PositionMessage; } string str1 = str; char[] chrArray = new char[2]; chrArray[0] = '\n'; chrArray[1] = '\r'; str1 = str1.TrimEnd(chrArray); this.WriteErrorLine(str1); object[] categoryInfo = new object[1]; categoryInfo[0] = errorRecord.CategoryInfo; this.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, " + CategoryInfo : {0} ", categoryInfo)); object[] fullyQualifiedErrorId = new object[1]; fullyQualifiedErrorId[0] = errorRecord.FullyQualifiedErrorId; this.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, " + FullyQualifiedErrorId : {0} ", fullyQualifiedErrorId)); this.WriteErrorLine(""); return; } } else { exception = pSRemotingTransportException.InnerException; } if (exception as TargetInvocationException == null) { this.host.UI.WriteErrorLine(exception.Message); return; } else { this.host.UI.WriteErrorLine(exception.InnerException.Message); return; } }
public void WhenComputerNameDoestNotExistsItThrows() { // Prepare InvokeCompatibilityCheckCmdlet cmdlet = new InvokeCompatibilityCheckCmdlet() { ComputerName = "non_existent_computer_name" }; // Exercise IEnumerator results = cmdlet.Invoke().GetEnumerator(); PSRemotingTransportException thrownException = Assert.Throws <PSRemotingTransportException>(() => results.MoveNext()); // Verify Assert.Contains("Cannot find the computer", thrownException.Message); }
private void OnExited(object sender, EventArgs e) { TransportMethodEnum unknown = TransportMethodEnum.Unknown; lock (base.syncObject) { if (base.isClosed) { unknown = TransportMethodEnum.CloseShellOperationEx; } this.stdInWriter.StopWriting(); } PSRemotingTransportException exception = new PSRemotingTransportException(PSRemotingErrorId.IPCServerProcessExited, RemotingErrorIdStrings.IPCServerProcessExited, new object[0]); this.RaiseErrorHandler(new TransportErrorOccuredEventArgs(exception, unknown)); }
public void WhenCredentialsAreIncorrectItThrows() { SecureString secureInvalidPassword = CreateSecureStringFrom("invalid_password"); InvokeCompatibilityCheckCmdlet cmdlet = new InvokeCompatibilityCheckCmdlet { ComputerName = _computerName, Credential = new PSCredential("invalid_username", secureInvalidPassword) }; IEnumerator results = cmdlet.Invoke().GetEnumerator(); PSRemotingTransportException thrownException = Assert.Throws <PSRemotingTransportException>(() => results.MoveNext()); // Verify Assert.Contains("The user name or password is incorrect.", thrownException.Message); }
private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { if (eArgs.RunspaceStateInfo.State == RunspaceState.Connecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { return; } Dbg.Assert(eArgs.RunspaceStateInfo.State != RunspaceState.BeforeOpen, "Can't reconnect a session that hasn't been previously Opened"); Dbg.Assert(eArgs.RunspaceStateInfo.State != RunspaceState.Opening, "Can't reconnect a session that hasn't been previously Opened"); if (eArgs.RunspaceStateInfo.State == RunspaceState.Opened) { // Connect operation succeeded, write the PSSession object. WriteConnectedPSSession(); } else { // Check to see if failure is due to stale PSSession error and // add to retry list if this is the case. bool writeError = true; if (_queryRunspaces == null) { PSRemotingTransportException transportException = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; if (transportException != null && transportException.ErrorCode == WSManNativeApi.ERROR_WSMAN_INUSE_CANNOT_RECONNECT) { lock (s_LockObject) { _retryList.Add(_session); } writeError = false; } } if (writeError) { // Connect operation failed, write error. WriteConnectFailed(eArgs.RunspaceStateInfo.Reason, _session); } } _session.Runspace.StateChanged -= StateCallBackHandler; SendStartComplete(); }
private void OpenRunspace(Runspace runspace) { try { Guid instanceId = this._runspace.InstanceId; this._tracer.WriteMessage("Opening runspace ", instanceId.ToString()); runspace.Open(); Guid guid = this._runspace.InstanceId; this._tracer.WriteMessage("Runspace opened successfully ", guid.ToString()); PSLanguageMode?nullable = this._languageMode; if (nullable.HasValue) { PSLanguageMode?nullable1 = this._languageMode; if (nullable1.HasValue) { PowerShell powerShell = PowerShell.Create(); using (powerShell) { powerShell.Runspace = runspace; PSLanguageMode?nullable2 = this._languageMode; string str = string.Concat("$ExecutionContext.SessionState.LanguageMode = '", nullable2.Value.ToString(), "'"); powerShell.AddScript(str); powerShell.Invoke(); } } } } catch (PSRemotingTransportRedirectException pSRemotingTransportRedirectException) { Guid instanceId1 = this._runspace.InstanceId; this._tracer.WriteMessage("Opening runspace threw PSRemotingTransportRedirectException", instanceId1.ToString()); } catch (PSRemotingTransportException pSRemotingTransportException1) { PSRemotingTransportException pSRemotingTransportException = pSRemotingTransportException1; Guid guid1 = this._runspace.InstanceId; this._tracer.WriteMessage("Opening runspace threw PSRemotingTransportException", guid1.ToString()); this._tracer.TraceException(pSRemotingTransportException); throw; } catch (PSRemotingDataStructureException pSRemotingDataStructureException) { Guid instanceId2 = this._runspace.InstanceId; this._tracer.WriteMessage("Opening runspace threw PSRemotingDataStructureException", instanceId2.ToString()); } }
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); } }
/// <summary> /// Helper method to check any error condition after a stop call /// and close the remote runspace/pool if the stop call failed due /// to network outage problems. /// </summary> /// <param name="ex">Exception.</param> private void CheckAndCloseRunspaceAfterStop(Exception ex) { PSRemotingTransportException transportException = ex as PSRemotingTransportException; if (transportException != null && (transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_CONNECT || transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_SENDDATA_CANNOT_COMPLETE || transportException.ErrorCode == System.Management.Automation.Remoting.Client.WSManNativeApi.ERROR_WSMAN_TARGETSESSION_DOESNOTEXIST)) { object rsObject = shell.GetRunspaceConnection(); if (rsObject is Runspace) { Runspace runspace = (Runspace)rsObject; if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { try { runspace.Close(); } catch (PSRemotingTransportException) { } } } else if (rsObject is RunspacePool) { RunspacePool runspacePool = (RunspacePool)rsObject; if (runspacePool.RunspacePoolStateInfo.State == RunspacePoolState.Opened) { try { runspacePool.Close(); } catch (PSRemotingTransportException) { } } } } }
internal override void ConnectAsync() { base.ReceivedDataCollection.PrepareForStreamConnect(); base.serializedPipeline.Read(); this.cmdContextId = GetNextCmdTMHandleId(); AddCmdTransportManager(this.cmdContextId, this); this.connectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdConnectCallback); this.reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdReconnectCallback); lock (base.syncObject) { if (base.isClosed) { return; } WSManNativeApi.WSManConnectShellCommandEx(this.wsManShellOperationHandle, 0, base.PowershellInstanceId.ToString().ToUpper(CultureInfo.InvariantCulture), IntPtr.Zero, IntPtr.Zero, (IntPtr)this.connectCmdCompleted, ref this.wsManCmdOperationHandle); } if (this.wsManCmdOperationHandle == IntPtr.Zero) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed); TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ConnectShellCommandEx); this.ProcessWSManTransportError(eventArgs); } }
private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { if (eArgs.RunspaceStateInfo.State == RunspaceState.Connecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { return; } else { if (eArgs.RunspaceStateInfo.State != RunspaceState.Opened) { bool flag = true; if (this._queryRunspaces == null) { PSRemotingTransportException reason = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; if (reason != null && reason.ErrorCode == -2144108083) { lock (ConnectPSSessionCommand.ConnectRunspaceOperation.s_LockObject) { this._retryList.Add(this._session); } flag = false; } } if (flag) { this.WriteConnectFailed(eArgs.RunspaceStateInfo.Reason, this._session); } } else { this.WriteConnectedPSSession(); } this._session.Runspace.StateChanged -= new EventHandler <RunspaceStateEventArgs>(this.StateCallBackHandler); this.SendStartComplete(); return; } }
private void CheckAndCloseRunspaceAfterStop(Exception ex) { PSRemotingTransportException exception = ex as PSRemotingTransportException; if ((exception != null) && ((exception.ErrorCode == -2144108526) || (exception.ErrorCode == -2144108250))) { object runspaceConnection = this.shell.GetRunspaceConnection(); if (runspaceConnection is Runspace) { Runspace runspace = (Runspace)runspaceConnection; if (runspace.RunspaceStateInfo.State == RunspaceState.Opened) { try { runspace.Close(); } catch (PSRemotingTransportException) { } } } else if (runspaceConnection is RunspacePool) { RunspacePool pool = (RunspacePool)runspaceConnection; if (pool.RunspacePoolStateInfo.State == RunspacePoolState.Opened) { try { pool.Close(); } catch (PSRemotingTransportException) { } } } } }
internal override void ProcessRawData(byte[] data, string stream) { if (!this.isClosed) { try { base.ProcessRawData(data, stream, this.onDataAvailableCallback); } catch (PSRemotingTransportException exception) { tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Exception processing data. {0}", new object[] { exception.Message }), new object[0]); TransportErrorOccuredEventArgs transportErrorArgs = new TransportErrorOccuredEventArgs(exception, TransportMethodEnum.ReceiveShellOutputEx); this.EnqueueAndStartProcessingThread(null, transportErrorArgs, null); } catch (Exception exception2) { CommandProcessorBase.CheckForSevereException(exception2); tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Exception processing data. {0}", new object[] { exception2.Message }), new object[0]); PSRemotingTransportException e = new PSRemotingTransportException(exception2.Message); TransportErrorOccuredEventArgs args2 = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx); this.EnqueueAndStartProcessingThread(null, args2, null); } } }
private static void OnRemoteSessionSendCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { tracer.WriteLine("Client Session TM: SendComplete callback received"); long sessionTMHandle = 0; WSManClientSessionTransportManager sessionTM = null; if (!TryGetSessionTransportManager(operationContext, out sessionTM, out sessionTMHandle)) { // We dont have the session TM handle..just return. tracer.WriteLine("Unable to find a transport manager for context {0}.", sessionTMHandle); return; } // do the logging for this send PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, sessionTM.RunspacePoolInstanceId.ToString(), Guid.Empty.ToString()); if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle)) { // WSMan returned data from a wrong shell..notify the caller // about the same. PSRemotingTransportException e = new PSRemotingTransportException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.SendExFailed, sessionTM.ConnectionInfo.ComputerName)); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.SendShellInputEx); sessionTM.ProcessWSManTransportError(eventargs); return; } sessionTM.ClearReceiveOrSendResources(flags, true); // if the session is already closed ignore the errors and return. if (sessionTM.isClosed) { tracer.WriteLine("Client Session TM: Transport manager is closed. So returning"); return; } if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); // Ignore operation aborted error. operation aborted is raised by WSMan to // notify operation complete. PowerShell protocol has its own // way of notifying the same using state change events. if ((errorStruct.errorCode != 0) && (errorStruct.errorCode != 995)) { tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( sessionTM.WSManAPIData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.SendShellInputEx, RemotingErrorIdStrings.SendExCallBackError, new object[] { sessionTM.ConnectionInfo.ComputerName, WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); sessionTM.ProcessWSManTransportError(eventargs); return; } } // Send the next item, if available sessionTM.SendOneItem(); }
private static void OnRemoteCmdSignalCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { tracer.WriteLine("Signal Completed callback received."); long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) { // We dont have the command TM handle..just return. tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", cmdContextId); return; } // log the callback received event. PSEtwLog.LogAnalyticInformational(PSEventId.WSManSignalCallbackReceived, PSOpcode.Disconnect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { // WSMan returned data from a wrong shell..notify the caller // about the same. tracer.WriteLine("Cmd Signal callback: ShellOperationHandles are not the same as the signal is initiated with"); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandSendExFailed); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CommandInputEx); cmdTM.ProcessWSManTransportError(eventargs); return; } // release the resources related to signal if (IntPtr.Zero != cmdTM._cmdSignalOperationHandle) { WSManNativeApi.WSManCloseOperation(cmdTM._cmdSignalOperationHandle, 0); cmdTM._cmdSignalOperationHandle = IntPtr.Zero; } if (null != cmdTM._signalCmdCompleted) { cmdTM._signalCmdCompleted.Dispose(); cmdTM._signalCmdCompleted = null; } // if the transport manager is already closed..ignore the errors and return if (cmdTM.isClosed) { tracer.WriteLine("Client Command TM: Transport manager is closed. So returning"); return; } if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { tracer.WriteLine("Cmd Signal callback: WSMan reported an error: {0}", errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( cmdTM._sessnTm.WSManAPIData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.CommandInputEx, RemotingErrorIdStrings.CommandSendExCallBackError, new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); cmdTM.ProcessWSManTransportError(eventargs); return; } } cmdTM.EnqueueAndStartProcessingThread(null, null, true); }
private void ProcessReaderThread(object state) { try { StreamReader reader = state as StreamReader; Dbg.Assert(reader != null, "Reader cannot be null."); // Send one fragment. SendOneItem(); // Start reader loop. while (true) { string data = reader.ReadLine(); if (data == null) { // End of stream indicates the target process was lost. // Raise transport exception to invalidate the client remote runspace. PSRemotingTransportException psrte = new PSRemotingTransportException( PSRemotingErrorId.IPCServerProcessReportedError, RemotingErrorIdStrings.IPCServerProcessReportedError, RemotingErrorIdStrings.NamedPipeTransportProcessEnded); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.ReceiveShellOutputEx)); break; } if (data.StartsWith(System.Management.Automation.Remoting.Server.NamedPipeErrorTextWriter.ErrorPrepend, StringComparison.OrdinalIgnoreCase)) { // Error message from the server. string errorData = data.Substring(System.Management.Automation.Remoting.Server.NamedPipeErrorTextWriter.ErrorPrepend.Length); HandleErrorDataReceived(errorData); } else { // Normal output data. HandleOutputDataReceived(data); } } } catch (ObjectDisposedException) { // Normal reader thread end. } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); if (e is ArgumentOutOfRangeException) { Dbg.Assert(false, "Need to adjust transport fragmentor to accomodate read buffer size."); } string errorMsg = (e.Message != null) ? e.Message : string.Empty; _tracer.WriteMessage("NamedPipeClientSessionTransportManager", "StartReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); } }
private void ProcessErrorThread(object state) { try { StreamReader reader = state as StreamReader; Dbg.Assert(reader != null, "Reader cannot be null."); while (true) { string error = reader.ReadLine(); if (!string.IsNullOrEmpty(error) && (error.IndexOf("WARNING:", StringComparison.OrdinalIgnoreCase) < 0)) { // Any SSH client error results in a broken session. PSRemotingTransportException psrte = new PSRemotingTransportException( PSRemotingErrorId.IPCServerProcessReportedError, RemotingErrorIdStrings.IPCServerProcessReportedError, error); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.CloseShellOperationEx)); CloseConnection(); } } } catch (ObjectDisposedException) { } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); string errorMsg = (e.Message != null) ? e.Message : string.Empty; _tracer.WriteMessage("SSHClientSessionTransportManager", "ProcessErrorThread", Guid.Empty, "Transport manager error thread ended with error: {0}", errorMsg); } }
protected void HandleOutputDataReceived(string data) { try { OutOfProcessUtils.ProcessData(data, _dataProcessingCallbacks); } catch (Exception exception) { CommandProcessorBase.CheckForSevereException(exception); PSRemotingTransportException psrte = new PSRemotingTransportException(PSRemotingErrorId.IPCErrorProcessingServerData, RemotingErrorIdStrings.IPCErrorProcessingServerData, exception.Message); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.ReceiveShellOutputEx)); } }
internal void OnSignalTimeOutTimerElapsed(object source) { //Signal timer is triggered only once if (isClosed) { return; } PSRemotingTransportException psrte = new PSRemotingTransportException(RemotingErrorIdStrings.IPCSignalTimedOut); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.ReceiveShellOutputEx)); }
protected void OnExited(object sender, EventArgs e) { TransportMethodEnum transportMethod = TransportMethodEnum.Unknown; lock (syncObject) { // There is no need to return when IsClosed==true here as in a legitimate case process exits // after Close is called..In that legitimate case, Exit handler is removed before // calling Exit..So, this Exit must have been called abnormally. if (isClosed) { transportMethod = TransportMethodEnum.CloseShellOperationEx; } // dont let the writer write new data as the process is exited. // Not assigning null to stdInWriter to fix the race condition between OnExited() and CloseAsync() methods. // stdInWriter.StopWriting(); } PSRemotingTransportException psrte = new PSRemotingTransportException(PSRemotingErrorId.IPCServerProcessExited, RemotingErrorIdStrings.IPCServerProcessExited); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, transportMethod)); }
protected void HandleErrorDataReceived(string data) { lock (syncObject) { if (isClosed) { return; } } PSRemotingTransportException psrte = new PSRemotingTransportException(PSRemotingErrorId.IPCServerProcessReportedError, RemotingErrorIdStrings.IPCServerProcessReportedError, data); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.Unknown)); }
// WSMan will make sure this callback is synchronously called ie., if 1 callback // is active, the callback will not be called from a different thread. private static void OnRemoteSessionDataReceived(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { tracer.WriteLine("Client Session TM: OnRemoteDataReceived callback."); long sessionTMHandle = 0; WSManClientSessionTransportManager sessionTM = null; if (!TryGetSessionTransportManager(operationContext, out sessionTM, out sessionTMHandle)) { // We dont have the session TM handle..just return. tracer.WriteLine("Unable to find a transport manager for context {0}.", sessionTMHandle); return; } sessionTM.ClearReceiveOrSendResources(flags, false); if (sessionTM.isClosed) { tracer.WriteLine("Client Session TM: Transport manager is closed. So returning"); return; } if (!shellOperationHandle.Equals(sessionTM._wsManShellOperationHandle)) { // WSMan returned data from a wrong shell..notify the caller // about the same. PSRemotingTransportException e = new PSRemotingTransportException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.ReceiveExFailed, sessionTM.ConnectionInfo.ComputerName)); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveShellOutputEx); sessionTM.ProcessWSManTransportError(eventargs); return; } if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { tracer.WriteLine("Got error with error code {0}. Message {1}", errorStruct.errorCode, errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( sessionTM.WSManAPIData.WSManAPIHandle, sessionTM, errorStruct, TransportMethodEnum.ReceiveShellOutputEx, RemotingErrorIdStrings.ReceiveExCallBackError, new object[] { sessionTM.ConnectionInfo.ComputerName, WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); sessionTM.ProcessWSManTransportError(eventargs); return; } } WSManNativeApi.WSManReceiveDataResult dataReceived = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data); if (null != dataReceived.data) { tracer.WriteLine("Session Received Data : {0}", dataReceived.data.Length); PSEtwLog.LogAnalyticInformational( PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, sessionTM.RunspacePoolInstanceId.ToString(), Guid.Empty.ToString(), dataReceived.data.Length.ToString(CultureInfo.InvariantCulture)); sessionTM.ProcessRawData(dataReceived.data, dataReceived.stream); } }
/// <summary> /// Constructs a WSManTransportErrorOccuredEventArgs instance from the supplied data /// </summary> /// <param name="wsmanAPIHandle"> /// WSMan API handle to use to get error messages from WSMan error id(s) /// </param> /// <param name="wsmanSessionTM"> /// Session Transportmanager to use to get error messages (for redirect) /// </param> /// <param name="errorStruct"> /// Error structure supplied by callbacks from WSMan API /// </param> /// <param name="transportMethodReportingError"> /// The transport method call that reported this error. /// </param> /// <param name="resourceString"> /// resource string that holds the message. /// </param> /// <param name="resourceArgs"> /// Arguments to pass to the resource /// </param> /// <returns> /// An instance of WSManTransportErrorOccuredEventArgs /// </returns> internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle, WSManClientSessionTransportManager wsmanSessionTM, WSManNativeApi.WSManError errorStruct, TransportMethodEnum transportMethodReportingError, string resourceString, params object[] resourceArgs) { PSRemotingTransportException e; //For the first two special error conditions, it is remotely possible that the wsmanSessionTM is null when the failures are returned //as part of command TM operations (could be returned because of RC retries under the hood) //Not worth to handle these cases separately as there are very corner scenarios, but need to make sure wsmanSessionTM is not referenced // Destination server is reporting that URI redirect is required for this user. if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) && (wsmanSessionTM != null)) { IntPtr wsmanSessionHandle = wsmanSessionTM.SessionHandle; // populate the transport message with the redirection uri..this will // allow caller to make a new connection. string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION); string winrmMessage = ParseEscapeWSManErrorMessage( WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim(); e = new PSRemotingTransportRedirectException(redirectLocation, PSRemotingErrorId.URIEndPointNotResolved, RemotingErrorIdStrings.URIEndPointNotResolved, winrmMessage, redirectLocation); } else if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI) && (wsmanSessionTM != null)) { string configurationName = wsmanSessionTM.ConnectionInfo.ShellUri.Replace(Remoting.Client.WSManNativeApi.ResourceURIPrefix, string.Empty); string errorMessage = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName, configurationName, wsmanSessionTM.ConnectionInfo.ComputerName); e = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName, RemotingErrorIdStrings.ConnectExCallBackError, wsmanSessionTM.ConnectionInfo.ComputerName, errorMessage); e.TransportMessage = ParseEscapeWSManErrorMessage( WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)); } else { // Construct specific error message and then append this message pointing to our own // help topic. PowerShell's about help topic "about_Remote_Troubleshooting" should // contain all the trouble shooting information. string wsManErrorMessage = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs); e = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, RemotingErrorIdStrings.TroubleShootingHelpTopic, wsManErrorMessage); e.TransportMessage = ParseEscapeWSManErrorMessage( WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)); } e.ErrorCode = errorStruct.errorCode; TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, transportMethodReportingError); return eventargs; }
private static void OnReconnectCmdCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) { // We dont have the command TM handle..just return. tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", cmdContextId); return; } if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { // WSMan returned data from a wrong shell..notify the caller // about the same. tracer.WriteLine("Cmd Signal callback: ShellOperationHandles are not the same as the signal is initiated with"); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ReconnectShellCommandExCallBackError); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReconnectShellCommandEx); cmdTM.ProcessWSManTransportError(eventargs); return; } if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { tracer.WriteLine("OnReconnectCmdCompleted callback: WSMan reported an error: {0}", errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( cmdTM._sessnTm.WSManAPIData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.ReconnectShellCommandEx, RemotingErrorIdStrings.ReconnectShellCommandExCallBackError, new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); cmdTM.ProcessWSManTransportError(eventargs); return; } } // The command may have been disconnected before all input was read or // the returned command data started to be received. cmdTM._shouldStartReceivingData = true; cmdTM.SendOneItem(); cmdTM.RaiseReconnectCompleted(); }
private static void OnRemoteCmdDataReceived(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { tracer.WriteLine("Remote Command DataReceived callback."); long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) { // We dont have the command TM handle..just return. tracer.WriteLine("Unable to find a transport manager for the given command context {0}.", cmdContextId); return; } if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { // WSMan returned data from a wrong shell..notify the caller // about the same. tracer.WriteLine("CmdReceive callback: ShellOperationHandles are not the same as the Receive is initiated with"); PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandReceiveExFailed); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ReceiveCommandOutputEx); cmdTM.ProcessWSManTransportError(eventargs); return; } // release the resources related to receive cmdTM.ClearReceiveOrSendResources(flags, false); // if the transport manager is already closed..ignore the errors and return if (cmdTM.isClosed) { tracer.WriteLine("Client Command TM: Transport manager is closed. So returning"); return; } if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); if (errorStruct.errorCode != 0) { tracer.WriteLine("CmdReceive callback: WSMan reported an error: {0}", errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( cmdTM._sessnTm.WSManAPIData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.ReceiveCommandOutputEx, RemotingErrorIdStrings.CommandReceiveExCallBackError, new object[] { errorStruct.errorDetail }); cmdTM.ProcessWSManTransportError(eventargs); return; } } if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_RECEIVE_DELAY_STREAM_REQUEST_PROCESSED) { cmdTM._isDisconnectedOnInvoke = true; cmdTM.RaiseDelayStreamProcessedEvent(); return; } WSManNativeApi.WSManReceiveDataResult dataReceived = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data); if (null != dataReceived.data) { tracer.WriteLine("Cmd Received Data : {0}", dataReceived.data.Length); PSEtwLog.LogAnalyticInformational( PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString(), dataReceived.data.Length.ToString(CultureInfo.InvariantCulture)); cmdTM.ProcessRawData(dataReceived.data, dataReceived.stream); } }
private static void OnRemoteCmdSendCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data) { tracer.WriteLine("SendComplete callback received"); long cmdContextId = 0; WSManClientCommandTransportManager cmdTM = null; if (!TryGetCmdTransportManager(operationContext, out cmdTM, out cmdContextId)) { // We dont have the command TM handle..just return. tracer.WriteLine("Unable to find a transport manager for the command context {0}.", cmdContextId); return; } cmdTM._isSendingInput = false; // do the logging for this send PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, cmdTM.RunspacePoolInstanceId.ToString(), cmdTM.powershellInstanceId.ToString()); if ((!shellOperationHandle.Equals(cmdTM._wsManShellOperationHandle)) || (!commandOperationHandle.Equals(cmdTM._wsManCmdOperationHandle))) { tracer.WriteLine("SendShellInputEx callback: ShellOperationHandles are not the same as the Send is initiated with"); // WSMan returned data from a wrong shell..notify the caller // about the same. PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.CommandSendExFailed); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CommandInputEx); cmdTM.ProcessWSManTransportError(eventargs); return; } // release the resources related to send cmdTM.ClearReceiveOrSendResources(flags, true); // if the transport manager is already closed..ignore the errors and return if (cmdTM.isClosed) { tracer.WriteLine("Client Command TM: Transport manager is closed. So returning"); if (cmdTM._isDisconnectPending) { cmdTM.RaiseReadyForDisconnect(); } return; } if (IntPtr.Zero != error) { WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error); // Ignore Command aborted error. Command aborted is raised by WSMan to // notify command operation complete. PowerShell protocol has its own // way of notifying the same using state change events. if ((errorStruct.errorCode != 0) && (errorStruct.errorCode != 995)) { tracer.WriteLine("CmdSend callback: WSMan reported an error: {0}", errorStruct.errorDetail); TransportErrorOccuredEventArgs eventargs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs( cmdTM._sessnTm.WSManAPIData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.CommandInputEx, RemotingErrorIdStrings.CommandSendExCallBackError, new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) }); cmdTM.ProcessWSManTransportError(eventargs); return; } } // Send the next item, if available cmdTM.SendOneItem(); }
/// <summary> /// /// </summary> /// <exception cref="PSRemotingTransportException"> /// WSManRunShellCommandEx failed. /// </exception> internal override void CreateAsync() { byte[] cmdPart1 = serializedPipeline.ReadOrRegisterCallback(null); if (null != cmdPart1) { #region SHIM: Redirection code for command code send. bool sendContinue = true; if (s_commandCodeSendRedirect != null) { object[] arguments = new object[2] { null, cmdPart1 }; sendContinue = (bool)s_commandCodeSendRedirect.DynamicInvoke(arguments); cmdPart1 = (byte[])arguments[0]; } if (!sendContinue) return; #endregion WSManNativeApi.WSManCommandArgSet argSet = new WSManNativeApi.WSManCommandArgSet(cmdPart1); // create cmdContextId _cmdContextId = GetNextCmdTMHandleId(); AddCmdTransportManager(_cmdContextId, this); PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommand, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString(), powershellInstanceId.ToString()); _createCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdCreateCallback); _createCmdCompletedGCHandle = GCHandle.Alloc(_createCmdCompleted); _reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdReconnectCallback); using (argSet) { lock (syncObject) { if (!isClosed) { WSManNativeApi.WSManRunShellCommandEx(_wsManShellOperationHandle, 0, PowershellInstanceId.ToString().ToUpperInvariant(), // WSManRunsShellCommand doesn't accept empty string "". (_cmdLine == null || _cmdLine.Length == 0) ? " " : (_cmdLine.Length <= 256 ? _cmdLine : _cmdLine.Substring(0, 255)), argSet, IntPtr.Zero, _createCmdCompleted, ref _wsManCmdOperationHandle); tracer.WriteLine("Started cmd with command context : {0} Operation context: {1}", _cmdContextId, _wsManCmdOperationHandle); } } } } if (_wsManCmdOperationHandle == IntPtr.Zero) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.RunShellCommandEx); ProcessWSManTransportError(eventargs); return; } }
/// <summary> /// </summary> /// <exception cref="PSRemotingTransportException"> /// WSManConnectShellCommandEx failed. /// </exception> internal override void ConnectAsync() { Dbg.Assert(!isClosed, "object already disposed"); ReceivedDataCollection.PrepareForStreamConnect(); // Empty the serializedPipeline data that contains PowerShell command information created in the // constructor. We are connecting to an existing command on the server and don't want to send // information on a new command. serializedPipeline.Read(); // create cmdContextId _cmdContextId = GetNextCmdTMHandleId(); AddCmdTransportManager(_cmdContextId, this); // Create Callback _connectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdConnectCallback); _reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(_cmdContextId), s_cmdReconnectCallback); lock (syncObject) { if (isClosed) { // the transport is already closed..so no need to create a connection // anymore. return; } WSManNativeApi.WSManConnectShellCommandEx(_wsManShellOperationHandle, 0, PowershellInstanceId.ToString().ToUpperInvariant(), IntPtr.Zero, IntPtr.Zero, _connectCmdCompleted, ref _wsManCmdOperationHandle); } if (_wsManCmdOperationHandle == IntPtr.Zero) { PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.ConnectShellCommandEx); ProcessWSManTransportError(eventargs); return; } }
internal void OnCloseTimeOutTimerElapsed(object source) { PSRemotingTransportException psrte = new PSRemotingTransportException(PSRemotingErrorId.IPCCloseTimedOut, RemotingErrorIdStrings.IPCCloseTimedOut); RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.CloseShellOperationEx)); }
/// <summary> /// Launch a new Process (PowerShell.exe -s) to perform remoting. This is used by *-Job cmdlets /// to support background jobs without depending on WinRM (WinRM has complex requirements like /// elevation to support local machine remoting) /// </summary> /// <exception cref="System.InvalidOperationException"> /// </exception> /// <exception cref="System.ComponentModel.Win32Exception"> /// 1. There was an error in opening the associated file. /// </exception> internal override void CreateAsync() { if (null != _connectionInfo) { _processInstance = _connectionInfo.Process ?? new PowerShellProcessInstance(_connectionInfo.PSVersion, _connectionInfo.Credential, _connectionInfo.InitializationScript, _connectionInfo.RunAs32); if (_connectionInfo.Process != null) { _processCreated = false; } // _processInstance.Start(); } PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, RunspacePoolInstanceId.ToString()); try { lock (syncObject) { if (isClosed) { return; } // Attach handlers and start the process _serverProcess = _processInstance.Process; if (_processInstance.RunspacePool != null) { _processInstance.RunspacePool.Close(); _processInstance.RunspacePool.Dispose(); } stdInWriter = _processInstance.StdInWriter; //if (stdInWriter == null) { _serverProcess.OutputDataReceived += new DataReceivedEventHandler(OnOutputDataReceived); _serverProcess.ErrorDataReceived += new DataReceivedEventHandler(OnErrorDataReceived); } _serverProcess.Exited += new EventHandler(OnExited); //serverProcess.Start(); _processInstance.Start(); if (stdInWriter != null) { _serverProcess.CancelErrorRead(); _serverProcess.CancelOutputRead(); } // Start asynchronous reading of output/errors _serverProcess.BeginOutputReadLine(); _serverProcess.BeginErrorReadLine(); stdInWriter = new OutOfProcessTextWriter(_serverProcess.StandardInput); _processInstance.StdInWriter = stdInWriter; } } catch (System.ComponentModel.Win32Exception w32e) { PSRemotingTransportException psrte = new PSRemotingTransportException(w32e, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, w32e.Message); psrte.ErrorCode = w32e.HResult; TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.CreateShellEx); RaiseErrorHandler(eventargs); return; } catch (Exception e) { CommandProcessorBase.CheckForSevereException(e); PSRemotingTransportException psrte = new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, e.Message); TransportErrorOccuredEventArgs eventargs = new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.CreateShellEx); RaiseErrorHandler(eventargs); return; } // Send one fragment SendOneItem(); }