private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager)
        {
            // Use the identity for impersonation etc.
            NegotiateStream negoServer = null;

            try
            {
                negoServer = new NegotiateStream(netStream);
                // Block for authentication request
                TokenImpersonationLevel impLevel = TokenImpersonationLevel.Identification;
                if (_impersonate)
                {
                    impLevel = TokenImpersonationLevel.Impersonation;
                }
                negoServer.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, _protectionLevel, impLevel);
                netStream = negoServer;
                return((WindowsIdentity)negoServer.RemoteIdentity);
            }
            catch
            {
                streamManager.SendErrorResponse(
                    String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed")), false);
                if (negoServer != null)
                {
                    negoServer.Close();
                }
                throw;
            }
        }
        private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager)
        {
            NegotiateStream stream = null;
            WindowsIdentity remoteIdentity;

            try
            {
                stream = new NegotiateStream(netStream);
                TokenImpersonationLevel identification = TokenImpersonationLevel.Identification;
                if (this._impersonate)
                {
                    identification = TokenImpersonationLevel.Impersonation;
                }
                stream.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, this._protectionLevel, identification);
                netStream      = stream;
                remoteIdentity = (WindowsIdentity)stream.RemoteIdentity;
            }
            catch
            {
                streamManager.SendErrorResponse(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed"), new object[0]), false);
                if (stream != null)
                {
                    stream.Close();
                }
                throw;
            }
            return(remoteIdentity);
        }
        public void AsyncProcessResponse(IServerResponseChannelSinkStack sinkStack, object state, IMessage msg, ITransportHeaders headers, Stream stream)
        {
            TcpServerSocketHandler handler = null;

            handler = (TcpServerSocketHandler)state;
            handler.SendResponse(headers, stream);
            if (handler.CanServiceAnotherRequest())
            {
                handler.BeginReadMessage();
            }
            else
            {
                handler.Close();
            }
        }
Ejemplo n.º 4
0
        } // StopListening

        //
        // end of IChannelReceiver implementation
        //


        //
        // Server helpers
        //

        // Thread for listening
        void Listen()
        {
            bool bOkToListen = false;
        
            try
            {
                _tcpListener.Start();
                bOkToListen = true;
            }
            catch (Exception e)
            {
                _startListeningException = e;
            }   

            _waitForStartListening.Set(); // allow main thread to continue now that we have tried to start the socket

            InternalRemotingServices.RemotingTrace( "Waiting to Accept the Socket on Port: " + _port);

            //
            // Wait for an incoming socket
            //
            Socket socket;

            while (bOkToListen)
            {
                InternalRemotingServices.RemotingTrace("TCPChannel::Listen - tcpListen.Pending() == true");

                try
                {
                    socket = _tcpListener.AcceptSocket();

                    if (socket == null)
                    {
                        throw new RemotingException(
                            String.Format(
                                CoreChannel.GetResourceString("Remoting_Socket_Accept"),
                                Marshal.GetLastWin32Error().ToString()));
                    }                
                
                    // disable nagle delay
                    socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                    // set linger option
                    LingerOption lingerOption = new LingerOption(true, 3);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
                
                    TcpServerSocketHandler streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue);
                    streamManager.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                    streamManager.BeginReadMessage();
                }
                catch (Exception e)
                {
                    if (!_bListening)
                    {
                        // We called Stop() on the tcp listener, so gracefully exit.
                        bOkToListen = false;                        
                    }
                    else
                    {
                        // we want the exception to show up as unhandled since this
                        //   is an unexpected failure.
                        if (!(e is SocketException))
                        {
                            //throw;                      
                        }
                    }
                }
            }
        }
        } // TcpServerTransportSink

        internal void ServiceRequest(Object state)
        {
            TcpServerSocketHandler streamManager = (TcpServerSocketHandler)state;

            ITransportHeaders headers       = streamManager.ReadHeaders();
            Stream            requestStream = streamManager.GetRequestStream();

            headers["__CustomErrorsEnabled"] = streamManager.CustomErrorsEnabled();

            // process request
            ServerChannelSinkStack sinkStack = new ServerChannelSinkStack();

            sinkStack.Push(this, streamManager);

            IMessage          responseMessage;
            ITransportHeaders responseHeaders;
            Stream            responseStream;

#if !FEATURE_PAL
            // If Impersonation was requested impersonate the client identity
            WindowsIdentity             identity = streamManager.ImpersonationIdentity;
            WindowsImpersonationContext context  = null;
            IPrincipal oldPrincipal     = null;
            bool       principalChanged = false;
            if (identity != null)
            {
                oldPrincipal     = Thread.CurrentPrincipal;
                principalChanged = true;
                if (_impersonate)
                {
                    Thread.CurrentPrincipal = new WindowsPrincipal(identity);
                    context = identity.Impersonate();
                }
                else
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(identity, null);
                }
            }
#endif // !FEATURE_PAL
            ServerProcessing processing;
            // wrap Undo in an outer try block
            try{
                try{
                    processing =
                        _nextSink.ProcessMessage(sinkStack, null, headers, requestStream,
                                                 out responseMessage,
                                                 out responseHeaders, out responseStream);
                }
                finally{
    #if !FEATURE_PAL
                    // Revert the principal if we had changed the principal
                    if (principalChanged)
                    {
                        Thread.CurrentPrincipal = oldPrincipal;
                    }
                    // Revert the impersonation if we had impersonated
                    if (_impersonate)
                    {
                        context.Undo();
                    }
    #endif // !FEATURE_PAL
                }
            }
            catch { throw; }

            // handle response
            switch (processing)
            {
            case ServerProcessing.Complete:
            {
                // Send the response. Call completed synchronously.
                sinkStack.Pop(this);
                streamManager.SendResponse(responseHeaders, responseStream);
                break;
            } // case ServerProcessing.Complete

            case ServerProcessing.OneWay:
            {
                // No response needed, but the following method will make sure that
                //   we send at least a skeleton reply if the incoming request was
                //   not marked OneWayRequest (client/server metadata could be out of
                //   [....]).
                streamManager.SendResponse(responseHeaders, responseStream);
                break;
            } // case ServerProcessing.OneWay

            case ServerProcessing.Async:
            {
                sinkStack.StoreAndDispatch(this, streamManager);
                break;
            } // case ServerProcessing.Async
            } // switch (processing)


            // async processing will take care if handling this later
            if (processing != ServerProcessing.Async)
            {
                if (streamManager.CanServiceAnotherRequest())
                {
                    streamManager.BeginReadMessage();
                }
                else
                {
                    streamManager.Close();
                }
            }
        } // ServiceRequest
        // AcceptSocket method which will invoke the
        // authorization callbacks
        void AcceptSocketCallback(IAsyncResult ar)
        {
            Socket socket = null;

            InternalRemotingServices.RemotingTrace("TCPChannel::Listen - tcpListen.Pending() == true");
            TcpServerSocketHandler streamManager = null;
            bool closeImmediately = true;

            try
            {
                //
                // Wait for an incoming socket
                // if the listener is still active
                if (_tcpListener.IsListening)
                {
                    _tcpListener.BeginAcceptSocket(_acceptSocketCallback, null);
                }

                socket = _tcpListener.EndAcceptSocket(ar);

                if (socket == null)
                {
                    throw new RemotingException(
                              String.Format(
                                  CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Socket_Accept"),
                                  Marshal.GetLastWin32Error().ToString(CultureInfo.CurrentCulture)));
                }

                if (_authorizeRemotingConnection != null)
                {
                    bool authorized = _authorizeRemotingConnection.IsConnectingEndPointAuthorized(socket.RemoteEndPoint);
                    if (!authorized)
                    {
                        throw new RemotingException(CoreChannel.GetResourceString(
                                                        "Remoting_Tcp_ServerAuthorizationEndpointFailed"));
                    }
                }

                // disable nagle delay
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
                // Set keepalive flag, so that inactive sockets can be cleaned up
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

                // set linger option
                LingerOption lingerOption = new LingerOption(true, 3);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                Stream netStream = new SocketStream(socket);
                streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, netStream);

#if !FEATURE_PAL
                WindowsIdentity identity = null;
#endif // !FEATURE_PAL
                // If authentication is requested wait for auth request.
                closeImmediately = false;
                if (_secure)
                {
#if !FEATURE_PAL
                    identity = Authenticate(ref netStream, streamManager);
                    // Create a new SocketHandler to wrap the new netStream
                    streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, netStream);
                    if (_authorizeRemotingConnection != null)
                    {
                        bool authorized = _authorizeRemotingConnection.IsConnectingIdentityAuthorized(identity);
                        if (!authorized)
                        {
                            throw new RemotingException(CoreChannel.GetResourceString(
                                                            "Remoting_Tcp_ServerAuthorizationIdentityFailed"));
                        }
                    }
#else
                    throw new NotSupportedException();
#endif // !FEATURE_PAL
                }

#if !FEATURE_PAL
                // Cache the identity for impersonation
                streamManager.ImpersonationIdentity = identity;
#endif // !FEATURE_PAL


                streamManager.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                streamManager.BeginReadMessage();
            }
            catch (Exception e)
            {
                // Close the socket pre-emptively. We also close the socket if
                // We need to catch all exceptions if we hit ObjectDisposedException
                try{
                    if (streamManager != null)
                    {
                        streamManager.SendErrorResponse(e, false);
                    }
                    if (socket != null)
                    {
                        if (closeImmediately)
                        {
                            socket.Close(0);
                        }
                        else
                        {
                            socket.Close();
                        }
                    }
                }catch (Exception) {}
                if (!_bListening)
                {
                    // We called Stop() on the tcp listener, so gracefully exit.
                    //bOkToListen = false;
                }
                else
                {
                    // we want the exception to show up as unhandled since this
                    //   is an unexpected failure.
                    if (!(e is SocketException))
                    {
                        // <
                    }
                }
            }
        }
        internal void ServiceRequest(object state)
        {
            ITransportHeaders      headers2;
            Stream                 stream2;
            ServerProcessing       processing;
            TcpServerSocketHandler handler        = (TcpServerSocketHandler)state;
            ITransportHeaders      requestHeaders = handler.ReadHeaders();
            Stream                 requestStream  = handler.GetRequestStream();

            requestHeaders["__CustomErrorsEnabled"] = handler.CustomErrorsEnabled();
            ServerChannelSinkStack sinkStack = new ServerChannelSinkStack();

            sinkStack.Push(this, handler);
            WindowsIdentity             impersonationIdentity = handler.ImpersonationIdentity;
            WindowsImpersonationContext context = null;
            IPrincipal currentPrincipal         = null;
            bool       flag = false;

            if (impersonationIdentity != null)
            {
                currentPrincipal = Thread.CurrentPrincipal;
                flag             = true;
                if (this._impersonate)
                {
                    Thread.CurrentPrincipal = new WindowsPrincipal(impersonationIdentity);
                    context = impersonationIdentity.Impersonate();
                }
                else
                {
                    Thread.CurrentPrincipal = new GenericPrincipal(impersonationIdentity, null);
                }
            }
            try
            {
                try
                {
                    IMessage message;
                    processing = this._nextSink.ProcessMessage(sinkStack, null, requestHeaders, requestStream, out message, out headers2, out stream2);
                }
                finally
                {
                    if (flag)
                    {
                        Thread.CurrentPrincipal = currentPrincipal;
                    }
                    if (this._impersonate)
                    {
                        context.Undo();
                    }
                }
            }
            catch
            {
                throw;
            }
            switch (processing)
            {
            case ServerProcessing.Complete:
                sinkStack.Pop(this);
                handler.SendResponse(headers2, stream2);
                break;

            case ServerProcessing.OneWay:
                handler.SendResponse(headers2, stream2);
                break;

            case ServerProcessing.Async:
                sinkStack.StoreAndDispatch(this, handler);
                break;
            }
            if (processing != ServerProcessing.Async)
            {
                if (handler.CanServiceAnotherRequest())
                {
                    handler.BeginReadMessage();
                }
                else
                {
                    handler.Close();
                }
            }
        }
 private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager)
 { 
     // Use the identity for impersonation etc. 
     NegotiateStream negoServer = null;
     try 
     {
         negoServer = new NegotiateStream(netStream);
         // Block for authentication request
         TokenImpersonationLevel impLevel = TokenImpersonationLevel.Identification; 
         if (_impersonate)
             impLevel = TokenImpersonationLevel.Impersonation; 
         negoServer.AuthenticateAsServer((NetworkCredential)CredentialCache.DefaultCredentials, _protectionLevel, impLevel); 
         netStream = negoServer;
         return (WindowsIdentity)negoServer.RemoteIdentity; 
     }
     catch
     {
         streamManager.SendErrorResponse( 
             String.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed")), false);
         if (negoServer != null) 
             negoServer.Close(); 
         throw;
     } 
 }
        // AcceptSocket method which will invoke the 
        // authorization callbacks
        void AcceptSocketCallback(IAsyncResult ar) 
        {
            Socket socket = null;
            InternalRemotingServices.RemotingTrace("TCPChannel::Listen - tcpListen.Pending() == true");
            TcpServerSocketHandler streamManager = null; 
            bool closeImmediately = true;
            try 
            { 
                //
                // Wait for an incoming socket 
                // if the listener is still active
                if (_tcpListener.IsListening)
                    _tcpListener.BeginAcceptSocket(_acceptSocketCallback, null);
 
                socket = _tcpListener.EndAcceptSocket(ar);
 
                if (socket == null) 
                {
                    throw new RemotingException( 
                        String.Format(
                            CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Socket_Accept"),
                            Marshal.GetLastWin32Error().ToString(CultureInfo.CurrentCulture)));
                } 

                if (_authorizeRemotingConnection != null) 
                { 
                        bool authorized = _authorizeRemotingConnection.IsConnectingEndPointAuthorized(socket.RemoteEndPoint);
                        if (!authorized) 
                            throw new RemotingException(CoreChannel.GetResourceString(
                                                                "Remoting_Tcp_ServerAuthorizationEndpointFailed"));
                }
 
                // disable nagle delay
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); 
                // Set keepalive flag, so that inactive sockets can be cleaned up 
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
 
                // set linger option
                LingerOption lingerOption = new LingerOption(true, 3);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
 
                Stream netStream = new SocketStream(socket);
                streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, netStream); 
 
#if !FEATURE_PAL
                WindowsIdentity identity = null; 
#endif // !FEATURE_PAL
                // If authentication is requested wait for auth request.
                closeImmediately = false;
                if (_secure) 
                {
#if !FEATURE_PAL 
                    identity = Authenticate(ref netStream, streamManager); 
                    // Create a new SocketHandler to wrap the new netStream
                    streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, netStream); 
                    if (_authorizeRemotingConnection != null)
                    {
                        bool authorized = _authorizeRemotingConnection.IsConnectingIdentityAuthorized(identity);
                        if (!authorized) 
                            throw new RemotingException(CoreChannel.GetResourceString(
                                                                "Remoting_Tcp_ServerAuthorizationIdentityFailed")); 
                    } 
#else
                    throw new NotSupportedException(); 
#endif // !FEATURE_PAL
                }

#if !FEATURE_PAL 
                // Cache the identity for impersonation
                streamManager.ImpersonationIdentity = identity; 
#endif // !FEATURE_PAL 

 
                streamManager.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                streamManager.BeginReadMessage();
            }
            catch (Exception e) 
            {
                // Close the socket pre-emptively. We also close the socket if 
                // We need to catch all exceptions if we hit ObjectDisposedException 
                try{
                    if (streamManager != null){ 
                        streamManager.SendErrorResponse(e, false);
                    }
                    if (socket != null){
                        if (closeImmediately) 
                             socket.Close(0);
                        else 
                            socket.Close(); 
                    }
                }catch(Exception){} 
                if (!_bListening)
                {
                    // We called Stop() on the tcp listener, so gracefully exit.
                    //bOkToListen = false; 
                }
                else 
                { 
                    // we want the exception to show up as unhandled since this
                    //   is an unexpected failure. 
                    if (!(e is SocketException))
                    {
                        // <
 

 
                    } 
                }
            } 
        }
        } // TcpServerTransportSink

        internal void ServiceRequest(Object state)
        {
            TcpServerSocketHandler streamManager = (TcpServerSocketHandler)state;

            ITransportHeaders headers       = streamManager.ReadHeaders();
            Stream            requestStream = streamManager.GetRequestStream();

            headers["__CustomErrorsEnabled"] = streamManager.CustomErrorsEnabled();

            // process request
            ServerChannelSinkStack sinkStack = new ServerChannelSinkStack();

            sinkStack.Push(this, streamManager);

            IMessage          responseMessage;
            ITransportHeaders responseHeaders;
            Stream            responseStream;

            ServerProcessing processing;

            // wrap Undo in an outer try block
            try{
                try{
                    processing =
                        _nextSink.ProcessMessage(sinkStack, null, headers, requestStream,
                                                 out responseMessage,
                                                 out responseHeaders, out responseStream);
                }
                finally{
                }
            }
            catch { throw; }

            // handle response
            switch (processing)
            {
            case ServerProcessing.Complete:
            {
                // Send the response. Call completed synchronously.
                sinkStack.Pop(this);
                streamManager.SendResponse(responseHeaders, responseStream);
                break;
            } // case ServerProcessing.Complete

            case ServerProcessing.OneWay:
            {
                // No response needed, but the following method will make sure that
                //   we send at least a skeleton reply if the incoming request was
                //   not marked OneWayRequest (client/server metadata could be out of
                //   sync).
                streamManager.SendResponse(responseHeaders, responseStream);
                break;
            } // case ServerProcessing.OneWay

            case ServerProcessing.Async:
            {
                sinkStack.StoreAndDispatch(this, streamManager);
                break;
            } // case ServerProcessing.Async
            } // switch (processing)


            // async processing will take care if handling this later
            if (processing != ServerProcessing.Async)
            {
                if (streamManager.CanServiceAnotherRequest())
                {
                    streamManager.BeginReadMessage();
                }
                else
                {
                    streamManager.Close();
                }
            }
        } // ServiceRequest
        private void AcceptSocketCallback(IAsyncResult ar)
        {
            Socket socket = null;
            TcpServerSocketHandler streamManager = null;
            bool flag = true;

            try
            {
                if (this._tcpListener.IsListening)
                {
                    this._tcpListener.BeginAcceptSocket(this._acceptSocketCallback, null);
                }
                socket = this._tcpListener.EndAcceptSocket(ar);
                if (socket == null)
                {
                    throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Socket_Accept"), new object[] { Marshal.GetLastWin32Error().ToString(CultureInfo.CurrentCulture) }));
                }
                if ((this._authorizeRemotingConnection != null) && !this._authorizeRemotingConnection.IsConnectingEndPointAuthorized(socket.RemoteEndPoint))
                {
                    throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthorizationEndpointFailed"));
                }
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, 1);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
                LingerOption optionValue = new LingerOption(true, 3);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, optionValue);
                Stream stream = new SocketStream(socket);
                streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, stream);
                WindowsIdentity identity = null;
                flag = false;
                if (this._secure)
                {
                    identity      = this.Authenticate(ref stream, streamManager);
                    streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, stream);
                    if ((this._authorizeRemotingConnection != null) && !this._authorizeRemotingConnection.IsConnectingIdentityAuthorized(identity))
                    {
                        throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthorizationIdentityFailed"));
                    }
                }
                streamManager.ImpersonationIdentity = identity;
                streamManager.DataArrivedCallback   = new WaitCallback(this._transportSink.ServiceRequest);
                streamManager.BeginReadMessage();
            }
            catch (Exception exception)
            {
                try
                {
                    if (streamManager != null)
                    {
                        streamManager.SendErrorResponse(exception, false);
                    }
                    if (socket != null)
                    {
                        if (flag)
                        {
                            socket.Close(0);
                        }
                        else
                        {
                            socket.Close();
                        }
                    }
                }
                catch (Exception)
                {
                }
                if (this._bListening)
                {
                    SocketException exception3 = exception as SocketException;
                }
            }
        }
Ejemplo n.º 12
0
        } // StopListening

        //
        // end of IChannelReceiver implementation
        //


        //
        // Server helpers
        //

        // Thread for listening
        void Listen()
        {
            bool bOkToListen = false;

            try
            {
                _tcpListener.Start();
                bOkToListen = true;
            }
            catch (Exception e)
            {
                _startListeningException = e;
            }

            _waitForStartListening.Set(); // allow main thread to continue now that we have tried to start the socket

            InternalRemotingServices.RemotingTrace("Waiting to Accept the Socket on Port: " + _port);

            //
            // Wait for an incoming socket
            //
            Socket socket;

            while (bOkToListen)
            {
                InternalRemotingServices.RemotingTrace("TCPChannel::Listen - tcpListen.Pending() == true");

                try
                {
                    socket = _tcpListener.AcceptSocket();

                    if (socket == null)
                    {
                        throw new RemotingException(
                                  String.Format(
                                      CoreChannel.GetResourceString("Remoting_Socket_Accept"),
                                      Marshal.GetLastWin32Error().ToString()));
                    }

                    // disable nagle delay
                    socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);

                    // set linger option
                    LingerOption lingerOption = new LingerOption(true, 3);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);

                    TcpServerSocketHandler streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue);
                    streamManager.DataArrivedCallback = new WaitCallback(_transportSink.ServiceRequest);
                    streamManager.BeginReadMessage();
                }
                catch (Exception e)
                {
                    if (!_bListening)
                    {
                        // We called Stop() on the tcp listener, so gracefully exit.
                        bOkToListen = false;
                    }
                    else
                    {
                        // we want the exception to show up as unhandled since this
                        //   is an unexpected failure.
                        if (!(e is SocketException))
                        {
                            //throw;
                        }
                    }
                }
            }
        }
 private WindowsIdentity Authenticate(ref Stream netStream, TcpServerSocketHandler streamManager)
 {
     NegotiateStream stream = null;
     WindowsIdentity remoteIdentity;
     try
     {
         stream = new NegotiateStream(netStream);
         TokenImpersonationLevel identification = TokenImpersonationLevel.Identification;
         if (this._impersonate)
         {
             identification = TokenImpersonationLevel.Impersonation;
         }
         stream.AuthenticateAsServer((NetworkCredential) CredentialCache.DefaultCredentials, this._protectionLevel, identification);
         netStream = stream;
         remoteIdentity = (WindowsIdentity) stream.RemoteIdentity;
     }
     catch
     {
         streamManager.SendErrorResponse(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthenticationFailed"), new object[0]), false);
         if (stream != null)
         {
             stream.Close();
         }
         throw;
     }
     return remoteIdentity;
 }
 private void AcceptSocketCallback(IAsyncResult ar)
 {
     Socket socket = null;
     TcpServerSocketHandler streamManager = null;
     bool flag = true;
     try
     {
         if (this._tcpListener.IsListening)
         {
             this._tcpListener.BeginAcceptSocket(this._acceptSocketCallback, null);
         }
         socket = this._tcpListener.EndAcceptSocket(ar);
         if (socket == null)
         {
             throw new RemotingException(string.Format(CultureInfo.CurrentCulture, CoreChannel.GetResourceString("Remoting_Socket_Accept"), new object[] { Marshal.GetLastWin32Error().ToString(CultureInfo.CurrentCulture) }));
         }
         if ((this._authorizeRemotingConnection != null) && !this._authorizeRemotingConnection.IsConnectingEndPointAuthorized(socket.RemoteEndPoint))
         {
             throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthorizationEndpointFailed"));
         }
         socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, 1);
         socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);
         LingerOption optionValue = new LingerOption(true, 3);
         socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, optionValue);
         Stream stream = new SocketStream(socket);
         streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, stream);
         WindowsIdentity identity = null;
         flag = false;
         if (this._secure)
         {
             identity = this.Authenticate(ref stream, streamManager);
             streamManager = new TcpServerSocketHandler(socket, CoreChannel.RequestQueue, stream);
             if ((this._authorizeRemotingConnection != null) && !this._authorizeRemotingConnection.IsConnectingIdentityAuthorized(identity))
             {
                 throw new RemotingException(CoreChannel.GetResourceString("Remoting_Tcp_ServerAuthorizationIdentityFailed"));
             }
         }
         streamManager.ImpersonationIdentity = identity;
         streamManager.DataArrivedCallback = new WaitCallback(this._transportSink.ServiceRequest);
         streamManager.BeginReadMessage();
     }
     catch (Exception exception)
     {
         try
         {
             if (streamManager != null)
             {
                 streamManager.SendErrorResponse(exception, false);
             }
             if (socket != null)
             {
                 if (flag)
                 {
                     socket.Close(0);
                 }
                 else
                 {
                     socket.Close();
                 }
             }
         }
         catch (Exception)
         {
         }
         if (this._bListening)
         {
             SocketException exception3 = exception as SocketException;
         }
     }
 }