Example #1
0
        private static void OnRemoteCmdSendCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("SendComplete 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 command context {0}.", new object[] { cmdTMId });
            }
            else
            {
                cmdTransportManager.isSendingInput = false;
                PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, 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("SendShellInputEx callback: ShellOperationHandles are not the same as the Send is initiated with", new object[0]);
                    PSRemotingTransportException   e         = new PSRemotingTransportException(RemotingErrorIdStrings.CommandSendExFailed);
                    TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CommandInputEx);
                    cmdTransportManager.ProcessWSManTransportError(eventArgs);
                }
                else
                {
                    cmdTransportManager.ClearReceiveOrSendResources(flags, true);
                    if (cmdTransportManager.isClosed)
                    {
                        BaseClientTransportManager.tracer.WriteLine("Client Command TM: Transport manager is closed. So returning", new object[0]);
                        if (cmdTransportManager.isDisconnectPending)
                        {
                            cmdTransportManager.RaiseReadyForDisconnect();
                        }
                    }
                    else
                    {
                        if (IntPtr.Zero != error)
                        {
                            WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                            if ((errorStruct.errorCode != 0) && (errorStruct.errorCode != 0x3e3))
                            {
                                BaseClientTransportManager.tracer.WriteLine("CmdSend 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.shouldStartReceivingData = true;
                        cmdTransportManager.SendOneItem();
                    }
                }
            }
        }
        private static void OnRemoteCmdSendCompleted(
            IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("SendComplete callback received", new object[0]);
            long cmdTMId = 0;
            WSManClientCommandTransportManager cmdTransportManager = (WSManClientCommandTransportManager)null;

            if (!WSManClientCommandTransportManager.TryGetCmdTransportManager(operationContext, out cmdTransportManager, out cmdTMId))
            {
                BaseClientTransportManager.tracer.WriteLine("Unable to find a transport manager for the command context {0}.", (object)cmdTMId);
            }
            else
            {
                BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, (object)cmdTransportManager.RunspacePoolInstanceId, (object)cmdTransportManager.powershellInstanceId);
                if (!shellOperationHandle.Equals((object)cmdTransportManager.wsManShellOperationHandle) || !commandOperationHandle.Equals((object)cmdTransportManager.wsManCmdOperationHandle))
                {
                    BaseClientTransportManager.tracer.WriteLine("SendShellInputEx callback: ShellOperationHandles are not the same as the Send is initiated with", new object[0]);
                    TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.CommandSendExFailed, new object[0]), TransportMethodEnum.CommandInputEx);
                    cmdTransportManager.RaiseErrorHandler(eventArgs);
                }
                else
                {
                    cmdTransportManager.ClearReceiveOrSendResources(flags, true);
                    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 && errorStruct.errorCode != 995)
                            {
                                BaseClientTransportManager.tracer.WriteLine("CmdSend callback: WSMan reported an error: {0}", (object)errorStruct.errorDetail);
                                TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, IntPtr.Zero, errorStruct, TransportMethodEnum.CommandInputEx, PSRemotingErrorId.CommandSendExCallBackError, (object)WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail));
                                cmdTransportManager.RaiseErrorHandler(eventArgs);
                                return;
                            }
                        }
                        cmdTransportManager.SendOneItem();
                    }
                }
            }
        }
        private static void OnRemoteSessionSendCompleted(
            IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("Client Session TM: SendComplete callback received", new object[0]);
            long sessnTMId = 0;
            WSManClientSessionTransportManager sessnTransportManager = (WSManClientSessionTransportManager)null;

            if (!WSManClientSessionTransportManager.TryGetSessionTransportManager(operationContext, out sessnTransportManager, out sessnTMId))
            {
                BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to find a transport manager for context {0}.", (object)sessnTMId), new object[0]);
            }
            else
            {
                BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId, (object)Guid.Empty);
                if (!shellOperationHandle.Equals((object)sessnTransportManager.wsManShellOperationHandle))
                {
                    TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.SendExFailed, new object[0]), TransportMethodEnum.SendShellInputEx);
                    sessnTransportManager.RaiseErrorHandler(eventArgs);
                }
                else
                {
                    sessnTransportManager.ClearReceiveOrSendResources(flags, true);
                    if (sessnTransportManager.isClosed)
                    {
                        BaseClientTransportManager.tracer.WriteLine("Client Session 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 && errorStruct.errorCode != 995)
                            {
                                BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Got error with error code {0}. Message {1}", (object)errorStruct.errorCode, (object)errorStruct.errorDetail), new object[0]);
                                TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, sessnTransportManager.wsManSessionHandle, errorStruct, TransportMethodEnum.SendShellInputEx, PSRemotingErrorId.SendExCallBackError, (object)WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail));
                                sessnTransportManager.RaiseErrorHandler(eventArgs);
                                return;
                            }
                        }
                        sessnTransportManager.SendOneItem();
                    }
                }
            }
        }
        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);
            });
        }
Example #5
0
        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);
            }
        }
Example #6
0
        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);
        }
Example #7
0
 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);
     }
 }
 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);
         }
     }
 }
        /// <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;
            }
        }
        // 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);
            }
        }
        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();
        }
        /// <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 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);
            }
        }
        /// <summary>
        /// Log the error message in the Crimson logger and raise error handler.
        /// </summary>
        /// <param name="eventArgs"></param>
        internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs)
        {
            // Look for a valid stack trace.
            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,
                RunspacePoolInstanceId.ToString(),
                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,
                RunspacePoolInstanceId.ToString(),
                powershellInstanceId.ToString(),
                eventArgs.Exception.ErrorCode.ToString(CultureInfo.InvariantCulture),
                eventArgs.Exception.Message,
                stackTrace);

            base.RaiseErrorHandler(eventArgs);
        }
        private static void OnCreateSessionCompleted(
            IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("Client Session TM: CreateShell callback received", new object[0]);
            long sessnTMId = 0;
            WSManClientSessionTransportManager sessnTransportManager = (WSManClientSessionTransportManager)null;

            if (!WSManClientSessionTransportManager.TryGetSessionTransportManager(operationContext, out sessnTransportManager, out sessnTMId))
            {
                BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to find a transport manager for context {0}.", (object)sessnTMId), new object[0]);
            }
            else
            {
                BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCreateShellCallbackReceived, PSOpcode.Connect, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId);
                if (sessnTransportManager.createSessionCompleted != null)
                {
                    sessnTransportManager.createSessionCompletedGCHandle.Free();
                    sessnTransportManager.createSessionCompleted.Dispose();
                    sessnTransportManager.createSessionCompleted = (WSManNativeApi.WSManShellAsync)null;
                }
                sessnTransportManager.wsManShellOperationHandle = shellOperationHandle;
                bool flag = false;
                lock (sessnTransportManager.syncObject)
                {
                    sessnTransportManager.isCreateCallbackReceived = true;
                    if (sessnTransportManager.isClosePending)
                    {
                        flag = true;
                    }
                }
                if (flag)
                {
                    sessnTransportManager.CloseAsync();
                }
                else
                {
                    if (IntPtr.Zero != error)
                    {
                        WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                        if (errorStruct.errorCode != 0)
                        {
                            BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Got error with error code {0}. Message {1}", (object)errorStruct.errorCode, (object)errorStruct.errorDetail), new object[0]);
                            TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, sessnTransportManager.wsManSessionHandle, errorStruct, TransportMethodEnum.CreateShellEx, PSRemotingErrorId.ConnectExCallBackError, (object)WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail));
                            sessnTransportManager.RaiseErrorHandler(eventArgs);
                            return;
                        }
                    }
                    if (sessnTransportManager.openContent != null)
                    {
                        sessnTransportManager.openContent.Dispose();
                        sessnTransportManager.openContent = (WSManNativeApi.WSManData)null;
                    }
                    lock (sessnTransportManager.syncObject)
                    {
                        if (sessnTransportManager.isClosed)
                        {
                            BaseClientTransportManager.tracer.WriteLine("Client Session TM: Transport manager is closed. So returning", new object[0]);
                            return;
                        }
                        sessnTransportManager.RaiseConnectCompleted();
                        BaseClientTransportManager.tracer.WriteLine("Client Session TM: Placing Receive request using WSManReceiveShellOutputEx", new object[0]);
                        BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManReceiveShellOutputEx, PSOpcode.Receive, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId, (object)Guid.Empty);
                        sessnTransportManager.receivedFromRemote = new WSManNativeApi.WSManShellAsync(operationContext, WSManClientSessionTransportManager.sessionReceiveCallback);
                        WSManNativeApi.WSManReceiveShellOutputEx(sessnTransportManager.wsManShellOperationHandle, IntPtr.Zero, 0, (IntPtr)WSManClientSessionTransportManager.wsManApiStaticData.OutputStreamSet, (IntPtr)sessnTransportManager.receivedFromRemote, ref sessnTransportManager.wsManRecieveOperationHandle);
                    }
                    sessnTransportManager.SendOneItem();
                }
            }
        }
 internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs)
 {
     BaseTransportManager.ETWTracer.OperationalChannel.WriteError(PSEventId.TransportError, PSOpcode.Open, PSTask.None, (object)this.RunspacePoolInstanceId, (object)Guid.Empty, (object)eventArgs.Exception.ErrorCode.ToString((IFormatProvider)CultureInfo.InvariantCulture), (object)eventArgs.Exception.Message, (object)eventArgs.Exception.StackTrace);
     BaseTransportManager.ETWTracer.AnalyticChannel.WriteError(PSEventId.TransportError_Analytic, PSOpcode.Open, PSTask.None, (object)this.RunspacePoolInstanceId, (object)Guid.Empty, (object)eventArgs.Exception.ErrorCode.ToString((IFormatProvider)CultureInfo.InvariantCulture), (object)eventArgs.Exception.Message, (object)eventArgs.Exception.StackTrace);
     base.RaiseErrorHandler(eventArgs);
 }
 internal void EnqueueAndStartProcessingThread(RemoteDataObject <PSObject> remoteObject, TransportErrorOccuredEventArgs transportErrorArgs, object privateData)
 {
     if (!this.isClosed)
     {
         lock (this.callbackNotificationQueue)
         {
             if (((remoteObject != null) || (transportErrorArgs != null)) || (privateData != null))
             {
                 CallbackNotificationInformation item = new CallbackNotificationInformation {
                     remoteObject   = remoteObject,
                     transportError = transportErrorArgs,
                     privateData    = privateData
                 };
                 if ((remoteObject != null) && (((remoteObject.DataType == RemotingDataType.PublicKey) || (remoteObject.DataType == RemotingDataType.EncryptedSessionKey)) || (remoteObject.DataType == RemotingDataType.PublicKeyRequest)))
                 {
                     base.CryptoHelper.Session.BaseSessionDataStructureHandler.RaiseKeyExchangeMessageReceived(remoteObject);
                 }
                 else
                 {
                     this.callbackNotificationQueue.Enqueue(item);
                 }
             }
             if ((!this.isServicingCallbacks && !this.suspendQueueServicing) && (this.callbackNotificationQueue.Count > 0))
             {
                 this.isServicingCallbacks = true;
                 ThreadPool.QueueUserWorkItem(new WaitCallback(this.ServicePendingCallbacks));
             }
         }
     }
 }
Example #18
0
 internal void ProcessWSManTransportError(TransportErrorOccuredEventArgs eventArgs)
 {
     base.EnqueueAndStartProcessingThread(null, eventArgs, null);
 }
        /// <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>
 /// Handle transport error - calls EnqueueAndStartProcessingThread to process transport exception
 /// in a different thread
 /// Logic in transport callbacks should always use this to process a transport error
 /// </summary>
 internal void ProcessWSManTransportError(TransportErrorOccuredEventArgs eventArgs)
 {
     EnqueueAndStartProcessingThread(null, eventArgs, null);
 }
        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 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();
        }
        internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e)
        {
            PSInvocationStateInfo data = new PSInvocationStateInfo(PSInvocationState.Failed, e.Exception);

            this.InvocationStateInfoReceived.SafeInvoke <RemoteDataEventArgs <PSInvocationStateInfo> >(this, new RemoteDataEventArgs <PSInvocationStateInfo>(data));
        }
        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();
        }
Example #25
0
        private static void OnCreateCmdCompleted(IntPtr operationContext, int flags, IntPtr error, IntPtr shellOperationHandle, IntPtr commandOperationHandle, IntPtr operationHandle, IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("OnCreateCmdCompleted callback received", new object[0]);
            long cmdTMId = 0L;
            WSManClientCommandTransportManager cmdTransportManager = null;

            if (!TryGetCmdTransportManager(operationContext, out cmdTransportManager, out cmdTMId))
            {
                BaseClientTransportManager.tracer.WriteLine("OnCreateCmdCompleted: Unable to find a transport manager for the command context {0}.", new object[] { cmdTMId });
            }
            else
            {
                PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommandCallbackReceived, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { cmdTransportManager.RunspacePoolInstanceId.ToString(), cmdTransportManager.powershellInstanceId.ToString() });
                if (cmdTransportManager.createCmdCompleted != null)
                {
                    cmdTransportManager.createCmdCompletedGCHandle.Free();
                    cmdTransportManager.createCmdCompleted.Dispose();
                    cmdTransportManager.createCmdCompleted = null;
                }
                cmdTransportManager.wsManCmdOperationHandle = commandOperationHandle;
                if (IntPtr.Zero != error)
                {
                    WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                    if (errorStruct.errorCode != 0)
                    {
                        BaseClientTransportManager.tracer.WriteLine("OnCreateCmdCompleted callback: WSMan reported an error: {0}", new object[] { errorStruct.errorDetail });
                        TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, null, errorStruct, TransportMethodEnum.RunShellCommandEx, RemotingErrorIdStrings.RunShellCommandExCallBackError, new object[] { WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                        cmdTransportManager.ProcessWSManTransportError(eventArgs);
                        return;
                    }
                }
                lock (cmdTransportManager.syncObject)
                {
                    cmdTransportManager.isCreateCallbackReceived = true;
                    if (cmdTransportManager.isClosed)
                    {
                        BaseClientTransportManager.tracer.WriteLine("Client Session TM: Transport manager is closed. So returning", new object[0]);
                        if (cmdTransportManager.isDisconnectPending)
                        {
                            cmdTransportManager.RaiseReadyForDisconnect();
                        }
                    }
                    else if (cmdTransportManager.isDisconnectPending)
                    {
                        cmdTransportManager.RaiseReadyForDisconnect();
                    }
                    else
                    {
                        if (cmdTransportManager.serializedPipeline.Length == 0L)
                        {
                            cmdTransportManager.shouldStartReceivingData = true;
                        }
                        cmdTransportManager.SendOneItem();
                        if (cmdTransportManager.isStopSignalPending)
                        {
                            cmdTransportManager.SendStopSignal();
                        }
                    }
                }
            }
        }
 internal override void CreateAsync()
 {
     if (this.connectionInfo != null)
     {
         this._processInstance = this.connectionInfo.Process ?? new PowerShellProcessInstance(this.connectionInfo.PSVersion, this.connectionInfo.Credential, this.connectionInfo.InitializationScript, this.connectionInfo.RunAs32);
         if (this.connectionInfo.Process != null)
         {
             this._processCreated = false;
         }
     }
     PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString() });
     try
     {
         lock (base.syncObject)
         {
             if (base.isClosed)
             {
                 return;
             }
             this.serverProcess = this._processInstance.Process;
             if (this._processInstance.RunspacePool != null)
             {
                 this._processInstance.RunspacePool.Close();
                 this._processInstance.RunspacePool.Dispose();
             }
             this.stdInWriter = this._processInstance.StdInWriter;
             this.serverProcess.OutputDataReceived += new DataReceivedEventHandler(this.OnOutputDataReceived);
             this.serverProcess.ErrorDataReceived  += new DataReceivedEventHandler(this.OnErrorDataReceived);
             this.serverProcess.Exited             += new EventHandler(this.OnExited);
             this._processInstance.Start();
             if (this.stdInWriter != null)
             {
                 this.serverProcess.CancelErrorRead();
                 this.serverProcess.CancelOutputRead();
             }
             this.serverProcess.BeginOutputReadLine();
             this.serverProcess.BeginErrorReadLine();
             this.stdInWriter = new OutOfProcessTextWriter(this.serverProcess.StandardInput);
             this._processInstance.StdInWriter = this.stdInWriter;
         }
     }
     catch (Win32Exception exception)
     {
         PSRemotingTransportException e = new PSRemotingTransportException(exception, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, new object[] { exception.Message })
         {
             ErrorCode = exception.ErrorCode
         };
         TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.CreateShellEx);
         this.RaiseErrorHandler(eventArgs);
         return;
     }
     catch (Exception exception3)
     {
         CommandProcessorBase.CheckForSevereException(exception3);
         PSRemotingTransportException   exception4 = new PSRemotingTransportException(PSRemotingErrorId.IPCExceptionLaunchingProcess, RemotingErrorIdStrings.IPCExceptionLaunchingProcess, new object[] { exception3.Message });
         TransportErrorOccuredEventArgs args2      = new TransportErrorOccuredEventArgs(exception4, TransportMethodEnum.CreateShellEx);
         this.RaiseErrorHandler(args2);
         return;
     }
     this.SendOneItem();
 }
 private void HandleWSManTransportError(object sender, TransportErrorOccuredEventArgs e)
 {
     _stdErrWriter.WriteLine(StringUtil.Format(RemotingErrorIdStrings.RemoteTransportError, e.Exception.TransportMessage));
 }
 internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e) => this.InvocationStateInfoReceived((object)this, new RemoteDataEventArgs <PSInvocationStateInfo>((object)new PSInvocationStateInfo(PSInvocationState.Failed, (Exception)e.Exception)));
        /// <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();
        }