Example #1
0
        /// <summary>
        /// Creates a RemoteDataObject by deserializing <paramref name="data"/>.
        /// </summary>
        /// <param name="serializedDataStream"></param>
        /// <param name="defragmentor">
        /// Defragmentor used to deserialize an object.
        /// </param>
        /// <returns></returns>
        internal static RemoteDataObject <T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
        {
            Dbg.Assert(serializedDataStream != null, "cannot construct a RemoteDataObject from null data");
            Dbg.Assert(defragmentor != null, "defragmentor cannot be null.");

            if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength)
            {
                PSRemotingTransportException e =
                    new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject,
                                                     RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject,
                                                     headerLength + FragmentedRemoteObject.HeaderLength);
                throw e;
            }

            RemotingDestination destination = (RemotingDestination)DeserializeUInt(serializedDataStream);
            RemotingDataType    dataType    = (RemotingDataType)DeserializeUInt(serializedDataStream);
            Guid runspacePoolId             = DeserializeGuid(serializedDataStream);
            Guid powerShellId = DeserializeGuid(serializedDataStream);

            object actualData = null;

            if ((serializedDataStream.Length - headerLength) > 0)
            {
                actualData = defragmentor.DeserializeToPSObject(serializedDataStream);
            }

            T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T),
                                                                   System.Globalization.CultureInfo.CurrentCulture);

            return(new RemoteDataObject <T>(destination, dataType, runspacePoolId, powerShellId, deserializedObject));
        }
 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);
 }
Example #3
0
        private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg)
        {
            using (_trace.TraceEventHandlers())
            {
                switch (this._state)
                {
                case RemoteSessionState.Connecting:
                case RemoteSessionState.Connected:
                case RemoteSessionState.NegotiationSending:
                case RemoteSessionState.NegotiationSent:
                case RemoteSessionState.NegotiationReceived:
                case RemoteSessionState.Established:
                case RemoteSessionState.EstablishedAndKeySent:
                case RemoteSessionState.EstablishedAndKeyReceived:
                case RemoteSessionState.Disconnecting:
                case RemoteSessionState.Disconnected:
                case RemoteSessionState.Reconnecting:
                case RemoteSessionState.RCDisconnecting:
                    this.SetState(RemoteSessionState.ClosingConnection, arg.Reason);
                    break;

                case RemoteSessionState.ClosingConnection:
                case RemoteSessionState.Closed:
                    break;

                default:
                {
                    PSRemotingTransportException reason = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed, new object[0]);
                    this.SetState(RemoteSessionState.Closed, reason);
                    break;
                }
                }
                this.CleanAll();
            }
        }
Example #4
0
        /// <summary>
        /// Process data coming from the transport. This method analyses the data
        /// and if an object can be created, it creates one and calls the
        /// <paramref name="callback"/> with the deserialized object. This method
        /// does not assume all fragments to be available. So if not enough fragments are
        /// available it will simply return..
        /// </summary>
        /// <param name="data">
        /// Data to process.
        /// </param>
        /// <param name="priorityType">
        /// Priority stream this data belongs to.
        /// </param>
        /// <param name="callback">
        /// Callback to call once a complete deserialized object is available.
        /// </param>
        /// <returns>
        /// Defragmented Object if any, otherwise null.
        /// </returns>
        /// <exception cref="PSRemotingTransportException">
        /// 1. Fragment Ids not in sequence
        /// 2. Object Ids does not match
        /// 3. The current deserialized object size of the received data exceeded
        /// allowed maximum object size. The current deserialized object size is {0}.
        /// Allowed maximum object size is {1}.
        /// 4.The total data received from the remote machine exceeded allowed maximum.
        /// The total data received from remote machine is {0}. Allowed maximum is {1}.
        /// </exception>
        /// <remarks>
        /// Might throw other exceptions as the deserialized object is handled here.
        /// </remarks>
        internal void ProcessRawData(byte[] data,
                                     DataPriorityType priorityType,
                                     ReceiveDataCollection.OnDataAvailableCallback callback)
        {
            Dbg.Assert(data != null, "Cannot process null data");

            try
            {
                _defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length);
            }
            catch (System.Xml.XmlException)
            {
                PSRemotingTransportException e = null;

                if (_isCreateByClientTM)
                {
                    e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient,
                                                         RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient,
                                                         _defragmentor.DeserializationContext.MaximumAllowedMemory.Value);
                }
                else
                {
                    e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer,
                                                         RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer,
                                                         _defragmentor.DeserializationContext.MaximumAllowedMemory.Value);
                }

                throw e;
            }

            _recvdData[(int)priorityType].ProcessRawData(data, callback);
        }
 internal virtual void ProcessRawData(byte[] data, string stream)
 {
     try
     {
         this.ProcessRawData(data, stream, this.onDataAvailableCallback);
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         baseTracer.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);
     }
 }
Example #6
0
        /// <summary>
        /// This is the handler for Close event. It closes the connection.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="fsmEventArg">
        /// This parameter contains the FSM event.
        /// </param>
        ///
        /// <exception cref="ArgumentNullException">
        /// If the parameter <paramref name="fsmEventArg"/> is null.
        /// </exception>
        private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
        {
            using (s_trace.TraceEventHandlers())
            {
                if (fsmEventArg == null)
                {
                    throw PSTraceSource.NewArgumentNullException("fsmEventArg");
                }

                RemoteSessionState oldState = _state;

                switch (oldState)
                {
                case RemoteSessionState.ClosingConnection:
                case RemoteSessionState.Closed:
                    // do nothing
                    break;

                case RemoteSessionState.Connecting:
                case RemoteSessionState.Connected:
                case RemoteSessionState.Established:
                case RemoteSessionState.EstablishedAndKeySent:      //server session will never be in this state.. TODO- remove this
                case RemoteSessionState.EstablishedAndKeyReceived:
                case RemoteSessionState.EstablishedAndKeyExchanged:
                case RemoteSessionState.NegotiationReceived:
                case RemoteSessionState.NegotiationSent:
                case RemoteSessionState.NegotiationSending:
                    SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason);
                    _session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason);
                    break;

                case RemoteSessionState.Idle:
                case RemoteSessionState.UndefinedState:
                default:
                    Exception forcedCloseException = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed);
                    SetState(RemoteSessionState.Closed, forcedCloseException);
                    break;
                }

                CleanAll();
            }
        }
 internal void ProcessRawData(byte[] data, DataPriorityType priorityType, ReceiveDataCollection.OnDataAvailableCallback callback)
 {
     try
     {
         this.defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length);
     }
     catch (XmlException)
     {
         PSRemotingTransportException exception = null;
         if (this.isCreateByClientTM)
         {
             exception = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient, new object[] { this.defragmentor.DeserializationContext.MaximumAllowedMemory.Value });
         }
         else
         {
             exception = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer, new object[] { this.defragmentor.DeserializationContext.MaximumAllowedMemory.Value });
         }
         throw exception;
     }
     this.recvdData[(int)priorityType].ProcessRawData(data, callback);
 }
 internal void ProcessRawData(byte[] data, DataPriorityType priorityType, ReceiveDataCollection.OnDataAvailableCallback callback)
 {
     try
     {
         this.defragmentor.DeserializationContext.LogExtraMemoryUsage(data.Length);
     }
     catch (XmlException)
     {
         PSRemotingTransportException exception = null;
         if (this.isCreateByClientTM)
         {
             exception = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumClient, new object[] { this.defragmentor.DeserializationContext.MaximumAllowedMemory.Value });
         }
         else
         {
             exception = new PSRemotingTransportException(PSRemotingErrorId.ReceivedDataSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedDataSizeExceededMaximumServer, new object[] { this.defragmentor.DeserializationContext.MaximumAllowedMemory.Value });
         }
         throw exception;
     }
     this.recvdData[(int) priorityType].ProcessRawData(data, callback);
 }
Example #9
0
        /// <summary>
        /// This is the handler for Close event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="arg">
        /// This parameter contains the FSM event.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// If the parameter <paramref name="arg"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If the parameter <paramref name="arg"/> does not contain remote data.
        /// </exception>
        private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg)
        {
            using (s_trace.TraceEventHandlers())
            {
                RemoteSessionState oldState = _state;

                switch (oldState)
                {
                case RemoteSessionState.ClosingConnection:
                case RemoteSessionState.Closed:
                    // do nothing
                    break;

                case RemoteSessionState.Connecting:
                case RemoteSessionState.Connected:
                case RemoteSessionState.Established:
                case RemoteSessionState.EstablishedAndKeyReceived:      // TODO - Client session would never get into this state... to be removed
                case RemoteSessionState.EstablishedAndKeySent:
                case RemoteSessionState.NegotiationReceived:
                case RemoteSessionState.NegotiationSent:
                case RemoteSessionState.NegotiationSending:
                case RemoteSessionState.Disconnected:
                case RemoteSessionState.Disconnecting:
                case RemoteSessionState.Reconnecting:
                case RemoteSessionState.RCDisconnecting:
                    SetState(RemoteSessionState.ClosingConnection, arg.Reason);
                    break;

                case RemoteSessionState.Idle:
                case RemoteSessionState.UndefinedState:
                default:
                    PSRemotingTransportException forceClosedException = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed);
                    SetState(RemoteSessionState.Closed, forceClosedException);
                    break;
                }

                CleanAll();
            }
        }
Example #10
0
        internal static RemoteDataObject <T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
        {
            if ((serializedDataStream.Length - serializedDataStream.Position) < 40L)
            {
                PSRemotingTransportException exception = new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject, RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject, new object[] { 0x3d });
                throw exception;
            }
            RemotingDestination destination = (RemotingDestination)RemoteDataObject <T> .DeserializeUInt(serializedDataStream);

            RemotingDataType dataType = (RemotingDataType)RemoteDataObject <T> .DeserializeUInt(serializedDataStream);

            Guid runspacePoolId = RemoteDataObject <T> .DeserializeGuid(serializedDataStream);

            Guid powerShellId = RemoteDataObject <T> .DeserializeGuid(serializedDataStream);

            object valueToConvert = null;

            if ((serializedDataStream.Length - 40L) > 0L)
            {
                valueToConvert = defragmentor.DeserializeToPSObject(serializedDataStream);
            }
            return(new RemoteDataObject <T>(destination, dataType, runspacePoolId, powerShellId, (T)LanguagePrimitives.ConvertTo(valueToConvert, typeof(T), CultureInfo.CurrentCulture)));
        }
        private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
        {
            using (_trace.TraceEventHandlers())
            {
                if (fsmEventArg == null)
                {
                    throw PSTraceSource.NewArgumentNullException("fsmEventArg");
                }
                switch (this._state)
                {
                case RemoteSessionState.Connecting:
                case RemoteSessionState.Connected:
                case RemoteSessionState.NegotiationSending:
                case RemoteSessionState.NegotiationSent:
                case RemoteSessionState.NegotiationReceived:
                case RemoteSessionState.Established:
                case RemoteSessionState.EstablishedAndKeySent:
                case RemoteSessionState.EstablishedAndKeyReceived:
                case RemoteSessionState.EstablishedAndKeyExchanged:
                    this.SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason);
                    this._session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason);
                    break;

                case RemoteSessionState.ClosingConnection:
                case RemoteSessionState.Closed:
                    break;

                default:
                {
                    Exception reasion = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed, new object[0]);
                    this.SetState(RemoteSessionState.Closed, reasion);
                    break;
                }
                }
                this.CleanAll();
            }
        }
 internal TransportErrorOccuredEventArgs(PSRemotingTransportException e, TransportMethodEnum m)
 {
     this.exception = e;
     this.method = m;
 }
 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);
         }
     }
 }
 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);
         }
     }
 }
        /// <summary>
        /// This is the handler for Close event. It closes the connection.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="fsmEventArg">
        /// This parameter contains the FSM event.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If the parameter <paramref name="fsmEventArg"/> is null.
        /// </exception>
        private void DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
        {
            using (s_trace.TraceEventHandlers())
            {
                if (fsmEventArg == null)
                {
                    throw PSTraceSource.NewArgumentNullException("fsmEventArg");
                }

                RemoteSessionState oldState = _state;

                switch (oldState)
                {
                    case RemoteSessionState.ClosingConnection:
                    case RemoteSessionState.Closed:
                        // do nothing
                        break;

                    case RemoteSessionState.Connecting:
                    case RemoteSessionState.Connected:
                    case RemoteSessionState.Established:
                    case RemoteSessionState.EstablishedAndKeySent:  //server session will never be in this state.. TODO- remove this
                    case RemoteSessionState.EstablishedAndKeyReceived:
                    case RemoteSessionState.EstablishedAndKeyExchanged:
                    case RemoteSessionState.NegotiationReceived:
                    case RemoteSessionState.NegotiationSent:
                    case RemoteSessionState.NegotiationSending:
                        SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason);
                        _session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason);
                        break;

                    case RemoteSessionState.Idle:
                    case RemoteSessionState.UndefinedState:
                    default:
                        Exception forcedCloseException = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed);
                        SetState(RemoteSessionState.Closed, forcedCloseException);
                        break;
                }

                CleanAll();
            }
        }
 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));
     }
 }
Example #17
0
        /// <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);
            }
        }
        /// <summary>
        /// Handler which handles transport errors.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e)
        {
            Dbg.Assert(e != null, "HandleTransportError expects non-null eventargs");
            // handle uri redirections
            PSRemotingTransportRedirectException redirectException = e.Exception as PSRemotingTransportRedirectException;
            if ((redirectException != null) && (_maxUriRedirectionCount > 0))
            {
                Exception exception = null;

                try
                {
                    // honor max redirection count given by the user.
                    _maxUriRedirectionCount--;
                    PerformURIRedirection(redirectException.RedirectLocation);
                    return;
                }
                catch (ArgumentNullException argumentException)
                {
                    exception = argumentException;
                }
                catch (UriFormatException uriFormatException)
                {
                    exception = uriFormatException;
                }
                // if we are here, there must be an exception constructing a uri
                if (null != exception)
                {
                    PSRemotingTransportException newException =
                        new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted,
                            _session.Context.RemoteAddress.OriginalString,
                            redirectException.RedirectLocation);
                    newException.TransportMessage = e.Exception.TransportMessage;
                    e.Exception = newException;
                }
            }

            RemoteSessionEvent sessionEvent = RemoteSessionEvent.ConnectFailed;

            switch (e.ReportingTransportMethod)
            {
                case TransportMethodEnum.CreateShellEx:
                    sessionEvent = RemoteSessionEvent.ConnectFailed;
                    break;
                case TransportMethodEnum.SendShellInputEx:
                case TransportMethodEnum.CommandInputEx:
                    sessionEvent = RemoteSessionEvent.SendFailed;
                    break;
                case TransportMethodEnum.ReceiveShellOutputEx:
                case TransportMethodEnum.ReceiveCommandOutputEx:
                    sessionEvent = RemoteSessionEvent.ReceiveFailed;
                    break;
                case TransportMethodEnum.CloseShellOperationEx:
                    sessionEvent = RemoteSessionEvent.CloseFailed;
                    break;
                case TransportMethodEnum.DisconnectShellEx:
                    sessionEvent = RemoteSessionEvent.DisconnectFailed;
                    break;
                case TransportMethodEnum.ReconnectShellEx:
                    sessionEvent = RemoteSessionEvent.ReconnectFailed;
                    break;
            }

            RemoteSessionStateMachineEventArgs errorArgs =
                new RemoteSessionStateMachineEventArgs(sessionEvent, e.Exception);
            _stateMachine.RaiseEvent(errorArgs);
        }
 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));
 }
Example #20
0
        /// <summary>
        /// Process data coming from the transport. This method analyses the data
        /// and if an object can be created, it creates one and calls the
        /// <paramref name="callback"/> with the deserialized object. This method
        /// does not assume all fragments to be available. So if not enough fragments are
        /// available it will simply return..
        /// </summary>
        /// <param name="data">
        /// Data to process.
        /// </param>
        /// <param name="callback">
        /// Callback to call once a complete deserialized object is available.
        /// </param>
        /// <returns>
        /// Defragmented Object if any, otherwise null.
        /// </returns>
        /// <exception cref="PSRemotingTransportException">
        /// 1. Fragment Ids not in sequence
        /// 2. Object Ids does not match
        /// 3. The current deserialized object size of the received data exceeded
        /// allowed maximum object size. The current deserialized object size is {0}.
        /// Allowed maximum object size is {1}.
        /// </exception>
        /// <remarks>
        /// Might throw other exceptions as the deserialized object is handled here.
        /// </remarks>
        internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback)
        {
            Dbg.Assert(data != null, "Cannot process null data");
            Dbg.Assert(callback != null, "Callback cannot be null");

            lock (_syncObject)
            {
                if (_isDisposed)
                {
                    return;
                }

                _numberOfThreadsProcessing++;
                if (_numberOfThreadsProcessing > _maxNumberOfThreadsToAllowForProcessing)
                {
                    Dbg.Assert(false, "Multiple threads are not allowed in ProcessRawData.");
                }
            }

            try
            {
                _pendingDataStream.Write(data, 0, data.Length);

                // this do loop will process one deserialized object.
                // using a loop allows to process multiple objects within
                // the same packet
                while (true)
                {
                    if (_pendingDataStream.Length <= FragmentedRemoteObject.HeaderLength)
                    {
                        // there is not enough data to be processed.
                        s_baseTracer.WriteLine("Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.",
                                               _pendingDataStream.Length, FragmentedRemoteObject.HeaderLength);
                        return;
                    }

                    byte[] dataRead = _pendingDataStream.ToArray();

                    // there is enough data to process here. get the fragment header
                    long objectId = FragmentedRemoteObject.GetObjectId(dataRead, 0);
                    if (objectId <= 0)
                    {
                        throw new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdCannotBeLessThanZero);
                    }

                    long fragmentId = FragmentedRemoteObject.GetFragmentId(dataRead, 0);
                    bool sFlag      = FragmentedRemoteObject.GetIsStartFragment(dataRead, 0);
                    bool eFlag      = FragmentedRemoteObject.GetIsEndFragment(dataRead, 0);
                    int  blobLength = FragmentedRemoteObject.GetBlobLength(dataRead, 0);

                    if ((s_baseTracer.Options & PSTraceSourceOptions.WriteLine) != PSTraceSourceOptions.None)
                    {
                        s_baseTracer.WriteLine("Object Id: {0}", objectId);
                        s_baseTracer.WriteLine("Fragment Id: {0}", fragmentId);
                        s_baseTracer.WriteLine("Start Flag: {0}", sFlag);
                        s_baseTracer.WriteLine("End Flag: {0}", eFlag);
                        s_baseTracer.WriteLine("Blob Length: {0}", blobLength);
                    }

                    int totalLengthOfFragment = 0;

                    try
                    {
                        totalLengthOfFragment = checked (FragmentedRemoteObject.HeaderLength + blobLength);
                    }
                    catch (System.OverflowException)
                    {
                        s_baseTracer.WriteLine("Fragment too big.");
                        ResetReceiveData();
                        PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig);
                        throw e;
                    }

                    if (_pendingDataStream.Length < totalLengthOfFragment)
                    {
                        s_baseTracer.WriteLine("Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.",
                                               _pendingDataStream.Length, totalLengthOfFragment);
                        return;
                    }

                    // ensure object size limit is not reached
                    if (_maxReceivedObjectSize.HasValue)
                    {
                        _totalReceivedObjectSizeSoFar = unchecked (_totalReceivedObjectSizeSoFar + totalLengthOfFragment);
                        if ((_totalReceivedObjectSizeSoFar < 0) || (_totalReceivedObjectSizeSoFar > _maxReceivedObjectSize.Value))
                        {
                            s_baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}",
                                                   _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
                            PSRemotingTransportException e = null;

                            if (_isCreateByClientTM)
                            {
                                e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient,
                                                                     RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient,
                                                                     _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
                            }
                            else
                            {
                                e = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer,
                                                                     RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer,
                                                                     _totalReceivedObjectSizeSoFar, _maxReceivedObjectSize);
                            }

                            ResetReceiveData();
                            throw e;
                        }
                    }

                    // appears like stream doesn't have individual position marker for read and write
                    // since we are going to read from now...
                    _pendingDataStream.Seek(0, SeekOrigin.Begin);

                    // we have enough data to process..so read the data from the stream and process.
                    byte[] oneFragment = new byte[totalLengthOfFragment];
                    // this will change position back to totalLengthOfFragment
                    int dataCount = _pendingDataStream.Read(oneFragment, 0, totalLengthOfFragment);
                    Dbg.Assert(dataCount == totalLengthOfFragment, "Unable to read enough data from the stream. Read failed");

                    PSEtwLog.LogAnalyticVerbose(
                        PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None,
                        PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic,
                        (Int64)objectId,
                        (Int64)fragmentId,
                        sFlag ? 1 : 0,
                        eFlag ? 1 : 0,
                        (UInt32)blobLength,
                        new PSETWBinaryBlob(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength));

                    byte[] extraData = null;
                    if (totalLengthOfFragment < _pendingDataStream.Length)
                    {
                        // there is more data in the stream than fragment size..so save that data
                        extraData = new byte[_pendingDataStream.Length - totalLengthOfFragment];
                        _pendingDataStream.Read(extraData, 0, (int)(_pendingDataStream.Length - totalLengthOfFragment));
                    }

                    // reset incoming stream.
                    _pendingDataStream.Dispose();
                    _pendingDataStream = new MemoryStream();
                    if (extraData != null)
                    {
                        _pendingDataStream.Write(extraData, 0, extraData.Length);
                    }

                    if (sFlag)
                    {
                        _canIgnoreOffSyncFragments = false; // reset this upon receiving a start fragment of a fresh object
                        _currentObjectId           = objectId;
                        // Memory streams created with an unsigned byte array provide a non-resizable stream view
                        // of the data, and can only be written to. When using a byte array, you can neither append
                        // to nor shrink the stream, although you might be able to modify the existing contents
                        // depending on the parameters passed into the constructor. Empty memory streams are
                        // resizable, and can be written to and read from.
                        _dataToProcessStream = new MemoryStream();
                    }
                    else
                    {
                        // check if the data belongs to the same object as the start fragment
                        if (objectId != _currentObjectId)
                        {
                            s_baseTracer.WriteLine("ObjectId != CurrentObjectId");
                            // TODO - drop an ETW event
                            ResetReceiveData();
                            if (!_canIgnoreOffSyncFragments)
                            {
                                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching);
                                throw e;
                            }
                            else
                            {
                                s_baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId");
                                continue;
                            }
                        }

                        if (fragmentId != (_currentFrgId + 1))
                        {
                            s_baseTracer.WriteLine("Fragment Id is not in sequence.");
                            // TODO - drop an ETW event
                            ResetReceiveData();
                            if (!_canIgnoreOffSyncFragments)
                            {
                                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.FragmentIdsNotInSequence);
                                throw e;
                            }
                            else
                            {
                                s_baseTracer.WriteLine("Ignoring Fragment Id is not in sequence.");
                                continue;
                            }
                        }
                    }

                    // make fragment id from this packet as the current fragment id
                    _currentFrgId = fragmentId;
                    // store the blob in a separate stream
                    _dataToProcessStream.Write(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength);

                    if (eFlag)
                    {
                        try
                        {
                            // appears like stream doesn't individual position marker for read and write
                            // since we are going to read from now..i am resetting position to 0.
                            _dataToProcessStream.Seek(0, SeekOrigin.Begin);
                            RemoteDataObject <PSObject> remoteObject = RemoteDataObject <PSObject> .CreateFrom(_dataToProcessStream, _defragmentor);

                            s_baseTracer.WriteLine("Runspace Id: {0}", remoteObject.RunspacePoolId);
                            s_baseTracer.WriteLine("PowerShell Id: {0}", remoteObject.PowerShellId);
                            // notify the caller that a deserialized object is available.
                            callback(remoteObject);
                        }
                        finally
                        {
                            // Reset the receive data buffers and start the process again.
                            ResetReceiveData();
                        }

                        if (_isDisposed)
                        {
                            break;
                        }
                    }
                }
            }
            finally
            {
                lock (_syncObject)
                {
                    if (_isDisposed && (_numberOfThreadsProcessing == 1))
                    {
                        ReleaseResources();
                    }

                    _numberOfThreadsProcessing--;
                }
            }
        }
 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 CreateAsync()
        {
            byte[] firstArgument = base.serializedPipeline.ReadOrRegisterCallback(null);
			if (firstArgument == null) firstArgument = new byte[0];
            bool flag = true;
            if (commandCodeSendRedirect != null)
            {
                object[] objArray2 = new object[2];
                objArray2[1] = firstArgument;
                object[] objArray = objArray2;
                flag = (bool) commandCodeSendRedirect.DynamicInvoke(objArray);
                firstArgument = (byte[]) objArray[0];
            }
            if (!flag)
            {
                return;
            }
            WSManNativeApi.WSManCommandArgSet set = new WSManNativeApi.WSManCommandArgSet(firstArgument);
            this.cmdContextId = GetNextCmdTMHandleId();
            AddCmdTransportManager(this.cmdContextId, this);
            PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommand, PSOpcode.Connect, PSTask.CreateRunspace, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { base.RunspacePoolInstanceId.ToString(), this.powershellInstanceId.ToString() });
            this.createCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdCreateCallback);
            this.createCmdCompletedGCHandle = GCHandle.Alloc(this.createCmdCompleted);
            this.reconnectCmdCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.cmdContextId), cmdReconnectCallback);
            using (set)
            {
                lock (base.syncObject)
                {
                    if (!base.isClosed)
                    {
                        WSManNativeApi.WSManRunShellCommandEx(this.wsManShellOperationHandle, 0, base.PowershellInstanceId.ToString().ToUpper(CultureInfo.InvariantCulture), ((this.cmdLine == null) || (this.cmdLine.Length == 0)) ? " " : ((this.cmdLine.Length <= 0x100) ? this.cmdLine : this.cmdLine.Substring(0, 0xff)), (IntPtr) set, IntPtr.Zero, (IntPtr) this.createCmdCompleted, ref this.wsManCmdOperationHandle);
                        BaseClientTransportManager.tracer.WriteLine("Started cmd with command context : {0} Operation context: {1}", new object[] { this.cmdContextId, this.wsManCmdOperationHandle });
                    }
                }
            }
            if (this.wsManCmdOperationHandle == IntPtr.Zero)
            {
                PSRemotingTransportException e = new PSRemotingTransportException(RemotingErrorIdStrings.RunShellCommandExFailed);
                TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.RunShellCommandEx);
                this.ProcessWSManTransportError(eventArgs);
            }
        }
 internal 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 DoClose(object sender, RemoteSessionStateMachineEventArgs fsmEventArg)
        {
            using (_trace.TraceEventHandlers())
            {
                if (fsmEventArg == null)
                {
                    throw PSTraceSource.NewArgumentNullException("fsmEventArg");
                }
                switch (this._state)
                {
                    case RemoteSessionState.Connecting:
                    case RemoteSessionState.Connected:
                    case RemoteSessionState.NegotiationSending:
                    case RemoteSessionState.NegotiationSent:
                    case RemoteSessionState.NegotiationReceived:
                    case RemoteSessionState.Established:
                    case RemoteSessionState.EstablishedAndKeySent:
                    case RemoteSessionState.EstablishedAndKeyReceived:
                    case RemoteSessionState.EstablishedAndKeyExchanged:
                        this.SetState(RemoteSessionState.ClosingConnection, fsmEventArg.Reason);
                        this._session.SessionDataStructureHandler.CloseConnectionAsync(fsmEventArg.Reason);
                        break;

                    case RemoteSessionState.ClosingConnection:
                    case RemoteSessionState.Closed:
                        break;

                    default:
                    {
                        Exception reasion = new PSRemotingTransportException(fsmEventArg.Reason, RemotingErrorIdStrings.ForceClosed, new object[0]);
                        this.SetState(RemoteSessionState.Closed, reasion);
                        break;
                    }
                }
                this.CleanAll();
            }
        }
Example #25
0
        internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback)
        {
            lock (this.syncObject)
            {
                if (this.isDisposed)
                {
                    return;
                }
                this.numberOfThreadsProcessing++;
                int maxNumberOfThreadsToAllowForProcessing = this.maxNumberOfThreadsToAllowForProcessing;
                int numberOfThreadsProcessing = this.numberOfThreadsProcessing;
            }
            try
            {
                this.pendingDataStream.Write(data, 0, data.Length);
            Label_005A:
                if (this.pendingDataStream.Length <= 0x15L)
                {
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.", new object[] { this.pendingDataStream.Length, 0x15 }), new object[0]);
                }
                else
                {
                    byte[] fragmentBytes = this.pendingDataStream.GetBuffer();
                    long objectId = FragmentedRemoteObject.GetObjectId(fragmentBytes, 0);
                    if (objectId <= 0L)
                    {
                        throw new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdCannotBeLessThanZero);
                    }
                    long fragmentId = FragmentedRemoteObject.GetFragmentId(fragmentBytes, 0);
                    bool isStartFragment = FragmentedRemoteObject.GetIsStartFragment(fragmentBytes, 0);
                    bool isEndFragment = FragmentedRemoteObject.GetIsEndFragment(fragmentBytes, 0);
                    int blobLength = FragmentedRemoteObject.GetBlobLength(fragmentBytes, 0);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Object Id: {0}", new object[] { objectId }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Fragment Id: {0}", new object[] { fragmentId }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Start Flag: {0}", new object[] { isStartFragment }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "End Flag: {0}", new object[] { isEndFragment }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Blob Length: {0}", new object[] { blobLength }), new object[0]);
                    int count = 0;
                    try
                    {
                        count = 0x15 + blobLength;
                    }
                    catch (OverflowException)
                    {
                        baseTracer.WriteLine("Fragement too big.", new object[0]);
                        this.ResetRecieveData();
                        PSRemotingTransportException exception = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig);
                        throw exception;
                    }
                    if (this.pendingDataStream.Length < count)
                    {
                        baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.", new object[] { this.pendingDataStream.Length, count }), new object[0]);
                    }
                    else
                    {
                        if (this.maxReceivedObjectSize.HasValue)
                        {
                            this.totalReceivedObjectSizeSoFar += count;
                            if ((this.totalReceivedObjectSizeSoFar < 0) || (this.totalReceivedObjectSizeSoFar > this.maxReceivedObjectSize.Value))
                            {
                                baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}", new object[] { this.totalReceivedObjectSizeSoFar, this.maxReceivedObjectSize });
                                PSRemotingTransportException exception2 = null;
                                if (this.isCreateByClientTM)
                                {
                                    exception2 = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient, new object[] { this.totalReceivedObjectSizeSoFar, this.maxReceivedObjectSize });
                                }
                                else
                                {
                                    exception2 = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer, new object[] { this.totalReceivedObjectSizeSoFar, this.maxReceivedObjectSize });
                                }
                                this.ResetRecieveData();
                                throw exception2;
                            }
                        }
                        this.pendingDataStream.Seek(0L, SeekOrigin.Begin);
                        byte[] buffer = new byte[count];
                        this.pendingDataStream.Read(buffer, 0, count);
                        PSEtwLog.LogAnalyticVerbose(PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, objectId, fragmentId, isStartFragment ? 1 : 0, isEndFragment ? 1 : 0, (int) blobLength, new PSETWBinaryBlob(buffer, 0x15, blobLength));
                        byte[] buffer3 = null;
                        if (count < this.pendingDataStream.Length)
                        {
                            buffer3 = new byte[this.pendingDataStream.Length - count];
                            this.pendingDataStream.Read(buffer3, 0, ((int) this.pendingDataStream.Length) - count);
                        }
                        this.pendingDataStream.Close();
                        this.pendingDataStream = new MemoryStream();
                        if (buffer3 != null)
                        {
                            this.pendingDataStream.Write(buffer3, 0, buffer3.Length);
                        }
                        if (isStartFragment)
                        {
                            this.canIgnoreOffSyncFragments = false;
                            this.currentObjectId = objectId;
                            this.dataToProcessStream = new MemoryStream();
                        }
                        else
                        {
                            if (objectId != this.currentObjectId)
                            {
                                baseTracer.WriteLine("ObjectId != CurrentObjectId", new object[0]);
                                this.ResetRecieveData();
                                if (!this.canIgnoreOffSyncFragments)
                                {
                                    PSRemotingTransportException exception3 = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching);
                                    throw exception3;
                                }
                                baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId", new object[0]);
                                goto Label_005A;
                            }
                            if (fragmentId != (this.currentFrgId + 1L))
                            {
                                baseTracer.WriteLine("Fragment Id is not in sequence.", new object[0]);
                                this.ResetRecieveData();
                                if (!this.canIgnoreOffSyncFragments)
                                {
                                    PSRemotingTransportException exception4 = new PSRemotingTransportException(RemotingErrorIdStrings.FragmetIdsNotInSequence);
                                    throw exception4;
                                }
                                baseTracer.WriteLine("Ignoring Fragment Id is not in sequence.", new object[0]);
                                goto Label_005A;
                            }
                        }
                        this.currentFrgId = fragmentId;
                        this.dataToProcessStream.Write(buffer, 0x15, blobLength);
                        if (!isEndFragment)
                        {
                            goto Label_005A;
                        }
                        try
                        {
                            this.dataToProcessStream.Seek(0L, SeekOrigin.Begin);
                            RemoteDataObject<PSObject> obj2 = RemoteDataObject<PSObject>.CreateFrom(this.dataToProcessStream, this.defragmentor);
                            baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Runspace Id: {0}", new object[] { obj2.RunspacePoolId }), new object[0]);
                            baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "PowerShell Id: {0}", new object[] { obj2.PowerShellId }), new object[0]);
                            callback(obj2);
                        }
                        finally
                        {
                            this.ResetRecieveData();
                        }
						if (!this.isDisposed && this.pendingDataStream.Length > 0x15L)
                        {
                            goto Label_005A;
                        }
                    }
                }
            }
            finally
            {
                lock (this.syncObject)
                {
                    if (this.isDisposed && (this.numberOfThreadsProcessing == 1))
                    {
                        this.ReleaseResources();
                    }
                    this.numberOfThreadsProcessing--;
                }
            }
        }
 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));
 }
Example #27
0
        internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback)
        {
            lock (this.syncObject)
            {
                if (this.isDisposed)
                {
                    return;
                }
                this.numberOfThreadsProcessing++;
                int maxNumberOfThreadsToAllowForProcessing = this.maxNumberOfThreadsToAllowForProcessing;
                int numberOfThreadsProcessing = this.numberOfThreadsProcessing;
            }
            try
            {
                this.pendingDataStream.Write(data, 0, data.Length);
Label_005A:
                if (this.pendingDataStream.Length <= 0x15L)
                {
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not enough data to process. Data is less than header length. Data length is {0}. Header Length {1}.", new object[] { this.pendingDataStream.Length, 0x15 }), new object[0]);
                }
                else
                {
                    byte[] fragmentBytes = this.pendingDataStream.GetBuffer();
                    long   objectId      = FragmentedRemoteObject.GetObjectId(fragmentBytes, 0);
                    if (objectId <= 0L)
                    {
                        throw new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdCannotBeLessThanZero);
                    }
                    long fragmentId      = FragmentedRemoteObject.GetFragmentId(fragmentBytes, 0);
                    bool isStartFragment = FragmentedRemoteObject.GetIsStartFragment(fragmentBytes, 0);
                    bool isEndFragment   = FragmentedRemoteObject.GetIsEndFragment(fragmentBytes, 0);
                    int  blobLength      = FragmentedRemoteObject.GetBlobLength(fragmentBytes, 0);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Object Id: {0}", new object[] { objectId }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Fragment Id: {0}", new object[] { fragmentId }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Start Flag: {0}", new object[] { isStartFragment }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "End Flag: {0}", new object[] { isEndFragment }), new object[0]);
                    baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Blob Length: {0}", new object[] { blobLength }), new object[0]);
                    int count = 0;
                    try
                    {
                        count = 0x15 + blobLength;
                    }
                    catch (OverflowException)
                    {
                        baseTracer.WriteLine("Fragement too big.", new object[0]);
                        this.ResetRecieveData();
                        PSRemotingTransportException exception = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIsTooBig);
                        throw exception;
                    }
                    if (this.pendingDataStream.Length < count)
                    {
                        baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Not enough data to process packet. Data is less than expected blob length. Data length {0}. Expected Length {1}.", new object[] { this.pendingDataStream.Length, count }), new object[0]);
                    }
                    else
                    {
                        if (this.maxReceivedObjectSize.HasValue)
                        {
                            this.totalReceivedObjectSizeSoFar += count;
                            if ((this.totalReceivedObjectSizeSoFar < 0) || (this.totalReceivedObjectSizeSoFar > this.maxReceivedObjectSize.Value))
                            {
                                baseTracer.WriteLine("ObjectSize > MaxReceivedObjectSize. ObjectSize is {0}. MaxReceivedObjectSize is {1}", new object[] { this.totalReceivedObjectSizeSoFar, this.maxReceivedObjectSize });
                                PSRemotingTransportException exception2 = null;
                                if (this.isCreateByClientTM)
                                {
                                    exception2 = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumClient, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumClient, new object[] { this.totalReceivedObjectSizeSoFar, this.maxReceivedObjectSize });
                                }
                                else
                                {
                                    exception2 = new PSRemotingTransportException(PSRemotingErrorId.ReceivedObjectSizeExceededMaximumServer, RemotingErrorIdStrings.ReceivedObjectSizeExceededMaximumServer, new object[] { this.totalReceivedObjectSizeSoFar, this.maxReceivedObjectSize });
                                }
                                this.ResetRecieveData();
                                throw exception2;
                            }
                        }
                        this.pendingDataStream.Seek(0L, SeekOrigin.Begin);
                        byte[] buffer = new byte[count];
                        this.pendingDataStream.Read(buffer, 0, count);
                        PSEtwLog.LogAnalyticVerbose(PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, objectId, fragmentId, isStartFragment ? 1 : 0, isEndFragment ? 1 : 0, (int)blobLength, new PSETWBinaryBlob(buffer, 0x15, blobLength));
                        byte[] buffer3 = null;
                        if (count < this.pendingDataStream.Length)
                        {
                            buffer3 = new byte[this.pendingDataStream.Length - count];
                            this.pendingDataStream.Read(buffer3, 0, ((int)this.pendingDataStream.Length) - count);
                        }
                        this.pendingDataStream.Close();
                        this.pendingDataStream = new MemoryStream();
                        if (buffer3 != null)
                        {
                            this.pendingDataStream.Write(buffer3, 0, buffer3.Length);
                        }
                        if (isStartFragment)
                        {
                            this.canIgnoreOffSyncFragments = false;
                            this.currentObjectId           = objectId;
                            this.dataToProcessStream       = new MemoryStream();
                        }
                        else
                        {
                            if (objectId != this.currentObjectId)
                            {
                                baseTracer.WriteLine("ObjectId != CurrentObjectId", new object[0]);
                                this.ResetRecieveData();
                                if (!this.canIgnoreOffSyncFragments)
                                {
                                    PSRemotingTransportException exception3 = new PSRemotingTransportException(RemotingErrorIdStrings.ObjectIdsNotMatching);
                                    throw exception3;
                                }
                                baseTracer.WriteLine("Ignoring ObjectId != CurrentObjectId", new object[0]);
                                goto Label_005A;
                            }
                            if (fragmentId != (this.currentFrgId + 1L))
                            {
                                baseTracer.WriteLine("Fragment Id is not in sequence.", new object[0]);
                                this.ResetRecieveData();
                                if (!this.canIgnoreOffSyncFragments)
                                {
                                    PSRemotingTransportException exception4 = new PSRemotingTransportException(RemotingErrorIdStrings.FragmetIdsNotInSequence);
                                    throw exception4;
                                }
                                baseTracer.WriteLine("Ignoring Fragment Id is not in sequence.", new object[0]);
                                goto Label_005A;
                            }
                        }
                        this.currentFrgId = fragmentId;
                        this.dataToProcessStream.Write(buffer, 0x15, blobLength);
                        if (!isEndFragment)
                        {
                            goto Label_005A;
                        }
                        try
                        {
                            this.dataToProcessStream.Seek(0L, SeekOrigin.Begin);
                            RemoteDataObject <PSObject> obj2 = RemoteDataObject <PSObject> .CreateFrom(this.dataToProcessStream, this.defragmentor);

                            baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Runspace Id: {0}", new object[] { obj2.RunspacePoolId }), new object[0]);
                            baseTracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "PowerShell Id: {0}", new object[] { obj2.PowerShellId }), new object[0]);
                            callback(obj2);
                        }
                        finally
                        {
                            this.ResetRecieveData();
                        }
                        if (!this.isDisposed && this.pendingDataStream.Length > 0x15L)
                        {
                            goto Label_005A;
                        }
                    }
                }
            }
            finally
            {
                lock (this.syncObject)
                {
                    if (this.isDisposed && (this.numberOfThreadsProcessing == 1))
                    {
                        this.ReleaseResources();
                    }
                    this.numberOfThreadsProcessing--;
                }
            }
        }
Example #28
0
        internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e)
        {
            PSRemotingTransportRedirectException exception = e.Exception as PSRemotingTransportRedirectException;

            if ((exception != null) && (this.maxUriRedirectionCount > 0))
            {
                Exception exception2 = null;
                try
                {
                    this.maxUriRedirectionCount--;
                    this.PerformURIRedirection(exception.RedirectLocation);
                    return;
                }
                catch (ArgumentNullException exception3)
                {
                    exception2 = exception3;
                }
                catch (UriFormatException exception4)
                {
                    exception2 = exception4;
                }
                if (exception2 != null)
                {
                    PSRemotingTransportException exception5 = new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted, new object[] { this._session.Context.RemoteAddress.OriginalString, exception.RedirectLocation })
                    {
                        TransportMessage = e.Exception.TransportMessage
                    };
                    e.Exception = exception5;
                }
            }
            RemoteSessionEvent connectFailed = RemoteSessionEvent.ConnectFailed;

            switch (e.ReportingTransportMethod)
            {
            case TransportMethodEnum.CreateShellEx:
                connectFailed = RemoteSessionEvent.ConnectFailed;
                break;

            case TransportMethodEnum.SendShellInputEx:
            case TransportMethodEnum.CommandInputEx:
                connectFailed = RemoteSessionEvent.SendFailed;
                break;

            case TransportMethodEnum.ReceiveShellOutputEx:
            case TransportMethodEnum.ReceiveCommandOutputEx:
                connectFailed = RemoteSessionEvent.ReceiveFailed;
                break;

            case TransportMethodEnum.CloseShellOperationEx:
                connectFailed = RemoteSessionEvent.CloseFailed;
                break;

            case TransportMethodEnum.DisconnectShellEx:
                connectFailed = RemoteSessionEvent.DisconnectFailed;
                break;

            case TransportMethodEnum.ReconnectShellEx:
                connectFailed = RemoteSessionEvent.ReconnectFailed;
                break;
            }
            RemoteSessionStateMachineEventArgs arg = new RemoteSessionStateMachineEventArgs(connectFailed, e.Exception);

            this._stateMachine.RaiseEvent(arg, false);
        }
        internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e)
        {
            PSRemotingTransportRedirectException exception = e.Exception as PSRemotingTransportRedirectException;
            if ((exception != null) && (this.maxUriRedirectionCount > 0))
            {
                Exception exception2 = null;
                try
                {
                    this.maxUriRedirectionCount--;
                    this.PerformURIRedirection(exception.RedirectLocation);
                    return;
                }
                catch (ArgumentNullException exception3)
                {
                    exception2 = exception3;
                }
                catch (UriFormatException exception4)
                {
                    exception2 = exception4;
                }
                if (exception2 != null)
                {
                    PSRemotingTransportException exception5 = new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted, new object[] { this._session.Context.RemoteAddress.OriginalString, exception.RedirectLocation }) {
                        TransportMessage = e.Exception.TransportMessage
                    };
                    e.Exception = exception5;
                }
            }
            RemoteSessionEvent connectFailed = RemoteSessionEvent.ConnectFailed;
            switch (e.ReportingTransportMethod)
            {
                case TransportMethodEnum.CreateShellEx:
                    connectFailed = RemoteSessionEvent.ConnectFailed;
                    break;

                case TransportMethodEnum.SendShellInputEx:
                case TransportMethodEnum.CommandInputEx:
                    connectFailed = RemoteSessionEvent.SendFailed;
                    break;

                case TransportMethodEnum.ReceiveShellOutputEx:
                case TransportMethodEnum.ReceiveCommandOutputEx:
                    connectFailed = RemoteSessionEvent.ReceiveFailed;
                    break;

                case TransportMethodEnum.CloseShellOperationEx:
                    connectFailed = RemoteSessionEvent.CloseFailed;
                    break;

                case TransportMethodEnum.DisconnectShellEx:
                    connectFailed = RemoteSessionEvent.DisconnectFailed;
                    break;

                case TransportMethodEnum.ReconnectShellEx:
                    connectFailed = RemoteSessionEvent.ReconnectFailed;
                    break;
            }
            RemoteSessionStateMachineEventArgs arg = new RemoteSessionStateMachineEventArgs(connectFailed, e.Exception);
            this._stateMachine.RaiseEvent(arg, false);
        }
        /// <summary>
        /// This is the handler for Close event. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="arg">
        /// This parameter contains the FSM event.
        /// </param>
        /// 
        /// <exception cref="ArgumentNullException">
        /// If the parameter <paramref name="arg"/> is null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If the parameter <paramref name="arg"/> does not contain remote data.
        /// </exception>
        private void DoClose(object sender, RemoteSessionStateMachineEventArgs arg)
        {
            using (s_trace.TraceEventHandlers())
            {
                RemoteSessionState oldState = _state;

                switch (oldState)
                {
                    case RemoteSessionState.ClosingConnection:
                    case RemoteSessionState.Closed:
                        // do nothing
                        break;

                    case RemoteSessionState.Connecting:
                    case RemoteSessionState.Connected:
                    case RemoteSessionState.Established:
                    case RemoteSessionState.EstablishedAndKeyReceived:  //TODO - Client session would never get into this state... to be removed
                    case RemoteSessionState.EstablishedAndKeySent:
                    case RemoteSessionState.NegotiationReceived:
                    case RemoteSessionState.NegotiationSent:
                    case RemoteSessionState.NegotiationSending:
                    case RemoteSessionState.Disconnected:
                    case RemoteSessionState.Disconnecting:
                    case RemoteSessionState.Reconnecting:
                    case RemoteSessionState.RCDisconnecting:
                        SetState(RemoteSessionState.ClosingConnection, arg.Reason);
                        break;

                    case RemoteSessionState.Idle:
                    case RemoteSessionState.UndefinedState:
                    default:
                        PSRemotingTransportException forceClosedException = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed);
                        SetState(RemoteSessionState.Closed, forceClosedException);
                        break;
                }

                CleanAll();
            }
        }
Example #31
0
		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);
			}
		}
 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 DoClose(object sender, RemoteSessionStateMachineEventArgs arg)
 {
     using (_trace.TraceEventHandlers())
     {
         switch (this._state)
         {
             case RemoteSessionState.Connecting:
             case RemoteSessionState.Connected:
             case RemoteSessionState.NegotiationSending:
             case RemoteSessionState.NegotiationSent:
             case RemoteSessionState.NegotiationReceived:
             case RemoteSessionState.Established:
             case RemoteSessionState.EstablishedAndKeySent:
             case RemoteSessionState.EstablishedAndKeyReceived:
             case RemoteSessionState.Disconnecting:
             case RemoteSessionState.Disconnected:
             case RemoteSessionState.Reconnecting:
             case RemoteSessionState.RCDisconnecting:
                 this.SetState(RemoteSessionState.ClosingConnection, arg.Reason);
                 break;
             case RemoteSessionState.ClosingConnection:
             case RemoteSessionState.Closed:
                 break;
             default:
             {
                 PSRemotingTransportException reason = new PSRemotingTransportException(arg.Reason, RemotingErrorIdStrings.ForceClosed, new object[0]);
                 this.SetState(RemoteSessionState.Closed, reason);
                 break;
             }
         }
         this.CleanAll();
     }
 }
Example #34
0
        /// <summary>
        /// Handler which handles transport errors.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        internal void HandleTransportError(object sender, TransportErrorOccuredEventArgs e)
        {
            Dbg.Assert(e != null, "HandleTransportError expects non-null eventargs");
            // handle uri redirections
            PSRemotingTransportRedirectException redirectException = e.Exception as PSRemotingTransportRedirectException;

            if ((redirectException != null) && (_maxUriRedirectionCount > 0))
            {
                Exception exception = null;

                try
                {
                    // honor max redirection count given by the user.
                    _maxUriRedirectionCount--;
                    PerformURIRedirection(redirectException.RedirectLocation);
                    return;
                }
                catch (ArgumentNullException argumentException)
                {
                    exception = argumentException;
                }
                catch (UriFormatException uriFormatException)
                {
                    exception = uriFormatException;
                }
                // if we are here, there must be an exception constructing a uri
                if (exception != null)
                {
                    PSRemotingTransportException newException =
                        new PSRemotingTransportException(PSRemotingErrorId.RedirectedURINotWellFormatted, RemotingErrorIdStrings.RedirectedURINotWellFormatted,
                                                         _session.Context.RemoteAddress.OriginalString,
                                                         redirectException.RedirectLocation);
                    newException.TransportMessage = e.Exception.TransportMessage;
                    e.Exception = newException;
                }
            }

            RemoteSessionEvent sessionEvent = RemoteSessionEvent.ConnectFailed;

            switch (e.ReportingTransportMethod)
            {
            case TransportMethodEnum.CreateShellEx:
                sessionEvent = RemoteSessionEvent.ConnectFailed;
                break;

            case TransportMethodEnum.SendShellInputEx:
            case TransportMethodEnum.CommandInputEx:
                sessionEvent = RemoteSessionEvent.SendFailed;
                break;

            case TransportMethodEnum.ReceiveShellOutputEx:
            case TransportMethodEnum.ReceiveCommandOutputEx:
                sessionEvent = RemoteSessionEvent.ReceiveFailed;
                break;

            case TransportMethodEnum.CloseShellOperationEx:
                sessionEvent = RemoteSessionEvent.CloseFailed;
                break;

            case TransportMethodEnum.DisconnectShellEx:
                sessionEvent = RemoteSessionEvent.DisconnectFailed;
                break;

            case TransportMethodEnum.ReconnectShellEx:
                sessionEvent = RemoteSessionEvent.ReconnectFailed;
                break;
            }

            RemoteSessionStateMachineEventArgs errorArgs =
                new RemoteSessionStateMachineEventArgs(sessionEvent, e.Exception);

            _stateMachine.RaiseEvent(errorArgs);
        }
 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 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();
     }
 }
 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 = 0L;
     WSManClientSessionTransportManager sessnTransportManager = null;
     if (!TryGetSessionTransportManager(operationContext, out sessnTransportManager, out sessnTMId))
     {
         BaseClientTransportManager.tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Unable to find a transport manager for context {0}.", new object[] { sessnTMId }), new object[0]);
     }
     else
     {
         PSEtwLog.LogAnalyticInformational(PSEventId.WSManSendShellInputExCallbackReceived, PSOpcode.Connect, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, new object[] { sessnTransportManager.RunspacePoolInstanceId.ToString(), Guid.Empty.ToString() });
         if (!shellOperationHandle.Equals(sessnTransportManager.wsManShellOperationHandle))
         {
             PSRemotingTransportException e = new PSRemotingTransportException(PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.SendExFailed, new object[] { sessnTransportManager.ConnectionInfo.ComputerName }));
             TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(e, TransportMethodEnum.SendShellInputEx);
             sessnTransportManager.ProcessWSManTransportError(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 != 0x3e3))
                     {
                         BaseClientTransportManager.tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, "Got error with error code {0}. Message {1}", new object[] { errorStruct.errorCode, errorStruct.errorDetail }), new object[0]);
                         TransportErrorOccuredEventArgs args2 = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(wsManApiStaticData.WSManAPIHandle, sessnTransportManager, errorStruct, TransportMethodEnum.SendShellInputEx, RemotingErrorIdStrings.SendExCallBackError, new object[] { sessnTransportManager.ConnectionInfo.ComputerName, WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail) });
                         sessnTransportManager.ProcessWSManTransportError(args2);
                         return;
                     }
                 }
                 sessnTransportManager.SendOneItem();
             }
         }
     }
 }
Example #38
0
 internal TransportErrorOccuredEventArgs(PSRemotingTransportException e, TransportMethodEnum m)
 {
     this.exception = e;
     this.method    = m;
 }
 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);
             }
         }
     }
 }
Example #41
0
 internal virtual void ProcessRawData(byte[] data, string stream)
 {
     try
     {
         this.ProcessRawData(data, stream, this.onDataAvailableCallback);
     }
     catch (Exception exception)
     {
         CommandProcessorBase.CheckForSevereException(exception);
         baseTracer.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);
     }
 }