示例#1
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="tcpClient">The tcp client channel connection from server to client.</param>
        public FileTransferConnection(TcpClient tcpClient)
        {
            try
            {
                // The tcp client to server channel.
                // Assign the network stream from the client
                // channel stream.
                this.tcpClient     = tcpClient;
                this.networkStream = tcpClient.GetStream();

                // Create a new state object.
                ServerSocketState state = new ServerSocketState();
                state.NetworkStream = this.networkStream;

                // This starts the asynchronous read thread.
                // The data will be saved into readBuffer.
                this.networkStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE,
                                             new AsyncCallback(DataReceiver), state);

                // Send a welcome message to the client.
                WriteCommand("WELC 101;Welcome to File Transfer Server - Authorized Accounts Only", networkStream);
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferConnection", "Constructor", e.Message,
                           59, WriteTo.EventLog, LogType.Error);
            }
        }
示例#2
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="tcpClient">The tcp client channel connection from server to client.</param>
        /// <param name="connection">The connection adapter used to connect to the server.</param>
        public Imap4TlsProxyConnection(TcpClient tcpClient, Imap4ConnectionAdapter connection)
        {
            try
            {
                // The tcp client to server channel.
                // Assign the network stream from the client
                // channel stream.
                _tcpClient  = tcpClient;
                _connection = connection;

                // Create a new state object.
                ServerSocketState state = new ServerSocketState();
                state.TcpClient = _tcpClient;

                // This starts the asynchronous read thread.
                // The data will be saved into readBuffer.
                _tcpClient.Client.BeginReceive(_readBuffer, 0, READ_BUFFER_SIZE,
                                               SocketFlags.None, new AsyncCallback(InitializingSSLDataReceiver), state);

                // Send a welcome message to the client.
                SendNonSSLClientCommand("* OK Welcome to Secure Imap4 Proxy Server - Authorized Accounts Only");
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("Imap4TlsProxyConnection", "Constructor", e.Message,
                           65, WriteTo.EventLog, LogType.Error);
            }
        }
示例#3
0
        private void OnReceive(IAsyncResult result)
        {
            ServerSocketState recvState = (ServerSocketState)result.AsyncState;

            try
            {
                int bytesReceived = recvState.Socket.EndReceive(result);
                if (bytesReceived == 0)
                {
                    recvState.Socket.Dispose();
                    return;
                }

                ServerSocketState sendState = new ServerSocketState(recvState, bytesReceived);

                sendState.Socket.BeginSend(sendState.TransferBuffer, 0, bytesReceived, SocketFlags.None, OnSend, sendState);
                recvState.Socket.BeginReceive(
                    recvState.TransferBuffer,
                    0,
                    recvState.TransferBuffer.Length,
                    SocketFlags.None,
                    OnReceive,
                    recvState);
            }
            catch (SocketException)
            {
                recvState.Socket.Dispose();
                return;
            }
            catch (ObjectDisposedException)
            {
                return;
            }
        }
示例#4
0
        /// <summary>
        /// End the authtication
        /// </summary>
        /// <param name="ar">The async result.</param>
        private void EndAuthenticateCallback(IAsyncResult ar)
        {
            try
            {
                SslStream sslStream = (SslStream)ar.AsyncState;
                sslStream.EndAuthenticateAsServer(ar);

                // Create a new state object.
                ServerSocketState state = new ServerSocketState();
                state.SslStream = sslStream;

                // Create a new imap client and
                // attempt to make a connection
                // get the response from the server.
                bool   ret        = GetSocket();
                byte[] welcomData = new byte[READ_BUFFER_SIZE];
                int    retBytes   = _socket.Receive(welcomData);

                // This starts the asynchronous read thread.
                // The data will be saved into readBuffer.
                sslStream.BeginRead(_readBuffer, 0, READ_BUFFER_SIZE,
                                    new AsyncCallback(DataReceiver), state);

                // If return false.
                if (!ret)
                {
                    // Write an error response back to
                    // the ftp client.
                    SendNonSSLClientCommand("BAD Could not Initialise TLS");
                }
                else
                {
                    _tlsNegComplete = true;

                    // Create a new state object.
                    ServerSocketState stateSocket = new ServerSocketState();
                    stateSocket.SslStream = sslStream;
                    stateSocket.Socket    = _socket;

                    // Start receiving data asynchrounusly.
                    _socket.BeginReceive(_receiveBuffer, 0, READ_BUFFER_SIZE,
                                         SocketFlags.None, new AsyncCallback(ReceiveCallback), stateSocket);
                }
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("SmtpTlsProxyConnection", "EndAuthenticateCallback", e.Message,
                           65, WriteTo.EventLog, LogType.Error);

                // On any error close the connection.
                Disconnect();
            }
        }
        private void OnAccept(IAsyncResult result)
        {
            Socket client = null;

            if (_disposed)
            {
                return;
            }

            try
            {
                client = _socket.EndAccept(result);
            }
            catch (SocketException e)
            {
                if (_disposed ||
                    e.SocketErrorCode == SocketError.OperationAborted ||
                    e.SocketErrorCode == SocketError.Interrupted)
                {
                    return;
                }

                throw;
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            NotifyAccepted(client);
            ServerSocketState state = new ServerSocketState(client, _receiveBufferSize);

            try
            {
                state.Socket.BeginReceive(state.TransferBuffer, 0, state.TransferBuffer.Length, SocketFlags.None, OnReceive, state);
            }
            catch (SocketException)
            {
            }

            try
            {
                _socket.BeginAccept(OnAccept, null);
            }
            catch (SocketException e)
            {
                if (_disposed ||
                    e.SocketErrorCode == SocketError.OperationAborted ||
                    e.SocketErrorCode == SocketError.Interrupted)
                {
                    return;
                }

                throw;
            }
            catch (ObjectDisposedException)
            {
            }
        }
        private void OnAccept(IAsyncResult result)
        {
            Socket client = null;

            if (disposed)
            {
                return;
            }

            try
            {
                client = socket.EndAccept(result);
            }
            catch (SocketException e)
            {
                if (disposed ||
                    e.SocketErrorCode == SocketError.OperationAborted || 
                    e.SocketErrorCode == SocketError.Interrupted)
                {
                    return;
                }

                throw;
            }
            catch (ObjectDisposedException)
            {
                return;
            }

            ServerSocketState state = new ServerSocketState(client, _receiveBufferSize);
            try
            {
                state.Socket.BeginReceive(state.TransferBuffer, 0, state.TransferBuffer.Length, SocketFlags.None, OnReceive, state);
            }
            catch (SocketException)
            {
            }

            try
            {
                socket.BeginAccept(OnAccept, null);
            }
            catch (SocketException e)
            {
                if (disposed ||
                    e.SocketErrorCode == SocketError.OperationAborted || 
                    e.SocketErrorCode == SocketError.Interrupted)
                {
                    return;
                }

                throw;
            }
            catch (ObjectDisposedException)
            {
            }
        }
示例#7
0
        /// <summary>
        /// Receive call back asynchrounus result.
        /// Handles the receiving of the email message.
        /// </summary>
        /// <param name="ar">The current asynchronus result.</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            int bytesRead = 0;

            // Get the current network stream from the
            // asynchronus result state object.
            ServerSocketState stateSocket = (ServerSocketState)ar.AsyncState;
            SslStream         sslStream   = stateSocket.SslStream;
            Socket            nStream     = stateSocket.Socket;

            try
            {
                lock (nStream)
                    // End the current asynchrounus
                    // read operation.
                    bytesRead = nStream.EndReceive(ar);

                // Look for the initial welcome from the smtp server
                // e.g. 220 [servername] ESMTP
                // Do not send this to the smtp client.
                string command = Encoding.ASCII.GetString(_receiveBuffer, 0, bytesRead);
                if ((command.ToUpper().IndexOf("220") > -1) && (command.ToUpper().IndexOf("ESMTP") > -1))
                {
                    bytesRead = 0;
                }

                if ((command.ToUpper().IndexOf("220") > -1) && (command.ToUpper().IndexOf("SMTP") > -1))
                {
                    bytesRead = 0;
                }

                if (bytesRead > 0)
                {
                    // Decode the current buffer and add the new data
                    // to the message string builder.
                    sslStream.Write(_receiveBuffer, 0, bytesRead);
                }

                // Start a new asynchronous read into readBuffer.
                // more data maybe present. This will wait for more
                // data from the client.
                lock (nStream)
                    nStream.BeginReceive(_receiveBuffer, 0, READ_BUFFER_SIZE,
                                         SocketFlags.None, new AsyncCallback(ReceiveCallback), stateSocket);
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("SmtpTlsProxyConnection", "ReceiveCallback", e.Message,
                           333, WriteTo.EventLog, LogType.Error);
            }
        }
示例#8
0
        private void OnConnectionError(Exception ex, ServerSocketState newState)
        {
            if (cancelToken.IsCancellationRequested)
            {
                return;
            }

            cancelToken.Cancel();
            ISLogger.Write("Serversocket error: " + ex.Message);
            SetState(newState);
        }
示例#9
0
        /// <summary>
        /// Disconnects the current client.
        /// </summary>
        /// <param name="state">The current state object.</param>
        public void Disconnect(ServerSocketState state)
        {
            try
            {
                if (this.tcpClient != null)
                {
                    this.tcpClient.Client.Shutdown(SocketShutdown.Both);
                    this.tcpClient.Client.Disconnect(false);
                    this.tcpClient.Close();
                    this.networkStream.Close();
                }

                tcpClient     = null;
                networkStream = null;
            }
            catch { }

            if (state != null)
            {
                try
                {
                    // Get the current network stream from the
                    // asynchronus result state object.
                    ServerSocketState stateObject = (ServerSocketState)state;

                    // Get the current file stream.
                    FileStream fileStream = stateObject.FileStream;

                    // Close the file and and dispose
                    // of the object.
                    if (fileStream != null)
                    {
                        // Close the file.
                        fileStream.Close();

                        // Delete the current upload file.
                        File.Delete(destinationFile);

                        // Release all resources
                        fileStream.Dispose();
                    }
                }
                catch { }
            }

            // Send a single to end the connection.
            if (OnDataReceived != null)
            {
                OnDataReceived(this, "ENDC");
            }
        }
示例#10
0
        /// <summary>
        /// Starts the upload process.
        /// </summary>
        public void Upload()
        {
            FileStream        fileStream = null;
            ServerSocketState state      = new ServerSocketState();

            try
            {
                // Open the upload file.
                fileStream = new FileStream(targetFile,
                                            FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                // Create a new file state object
                // assign the current network stream
                // and the upload file stream.
                state.NetworkStream = networkStream;
                state.FileStream    = fileStream;

                // Get the first set of bytes from
                // the upload file.
                int readBytes = fileStream.Read(writeBuffer, 0, WRITE_BUFFER_SIZE);

                // Begin a new asynochronus write operation
                // to send the client the requested file.
                lock (networkStream)
                    networkStream.BeginWrite(writeBuffer, 0, readBytes,
                                             new AsyncCallback(UploadFile), state);
            }
            catch (Exception e)
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }

                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferConnection", "Upload", e.Message,
                           484, WriteTo.EventLog, LogType.Error);

                // On any error close the connection.
                state.FileStream = null;
                Disconnect(state);
            }
        }
示例#11
0
文件: Program.cs 项目: aooshi/adf.cs
        static void Server()
        {
            var tcpListener = new System.Net.Sockets.TcpListener(IPAddress.Any, port);

            tcpListener.Start();

            System.Threading.ThreadPool.QueueUserWorkItem(sta =>
            {
                var socket = tcpListener.AcceptSocket();
                //
                var state    = new ServerSocketState();
                state.socket = socket;
                state.buffer = new byte[1];
                //
                socket.BeginReceive(state.buffer, 0, state.buffer.Length, System.Net.Sockets.SocketFlags.None, ServerCallback, state);
            });
        }
示例#12
0
        private void OnConnectionError(Exception ex, ServerSocketState newState)
        {
            if (cancelToken.IsCancellationRequested)
            {
                return;
            }

            foreach (var handler in receiveHandlers.ToArray())
            {
                handler.CancelTransfer();
            }

            cancelToken.Cancel();
            tcpSocket.Close();
            ISLogger.Write("Serversocket error: " + ex.Message);
            SetState(newState);
        }
示例#13
0
        private void SetState(ServerSocketState state)
        {
            State = state;

            switch (state)
            {
            case ServerSocketState.Connected:
                Connected?.Invoke(this, null);
                break;

            case ServerSocketState.ConnectionError:
                ConnectionError?.Invoke(this, null);
                break;

            case ServerSocketState.ConnectionFailed:
                ConnectionFailed?.Invoke(this, null);
                break;
            }
        }
示例#14
0
        /// <summary>
        /// Receive call back asynchrounus result.
        /// Handles the receiving of the email message.
        /// </summary>
        /// <param name="ar">The current asynchronus result.</param>
        private void ReceiveCallback(IAsyncResult ar)
        {
            int bytesRead = 0;

            // Get the current network stream from the
            // asynchronus result state object.
            ServerSocketState stateSocket = (ServerSocketState)ar.AsyncState;
            SslStream         sslStream   = stateSocket.SslStream;
            Socket            nStream     = stateSocket.Socket;

            try
            {
                lock (nStream)
                    // End the current asynchrounus
                    // read operation.
                    bytesRead = nStream.EndReceive(ar);

                if (bytesRead > 0)
                {
                    // Decode the current buffer and add the new data
                    // to the message string builder.
                    sslStream.Write(_receiveBuffer, 0, bytesRead);
                }

                // Start a new asynchronous read into readBuffer.
                // more data maybe present. This will wait for more
                // data from the client.
                lock (nStream)
                    nStream.BeginReceive(_receiveBuffer, 0, READ_BUFFER_SIZE,
                                         SocketFlags.None, new AsyncCallback(ReceiveCallback), stateSocket);
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("SmtpSslProxyConnection", "ReceiveCallback", e.Message,
                           333, WriteTo.EventLog, LogType.Error);
            }
        }
示例#15
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="tcpClient">The tcp client channel connection from server to client.</param>
        public FileTransferSslConnection(TcpClient tcpClient)
        {
            try
            {
                // The tcp client to server channel.
                // Assign the network stream from the client
                // channel stream.
                this.tcpClient = tcpClient;
                this.sslStream = new SslStream(tcpClient.GetStream());

                // Certificate file containing a public key
                // and private key for secure data transfer.
                X509Certificate2 certificate = GetServerCredentials();

                // Load the certificate into the
                // secure stream used for secure communication.
                this.sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Tls, false);

                // Create a new state object.
                ServerSocketState state = new ServerSocketState();
                state.SslStream = this.sslStream;

                // This starts the asynchronous read thread.
                // The data will be saved into readBuffer.
                this.sslStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE,
                                         new AsyncCallback(DataReceiver), state);

                // Send a welcome message to the client.
                WriteCommand("WELC 101;Welcome to Secure File Transfer Server - Authorized Accounts Only", sslStream);
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferSslConnection", "Constructor", e.Message,
                           65, WriteTo.EventLog, LogType.Error);
            }
        }
示例#16
0
        private void OnSend(IAsyncResult result)
        {
            ServerSocketState sendState = (ServerSocketState)result.AsyncState;

            try
            {
                int bytesSent = sendState.Socket.EndSend(result);
                if (bytesSent != sendState.TransferBuffer.Length)
                {
                    _log.WriteLine("{2} APM: OnSend {0}bytes - expecting {1}bytes.", bytesSent, sendState.TransferBuffer.Length, sendState.Socket.GetHashCode());
                }
            }
            catch (SocketException)
            {
                sendState.Socket.Dispose();
                return;
            }
            catch (ObjectDisposedException)
            {
                return;
            }
        }
示例#17
0
 public ServerSocketState(ServerSocketState original, int count)
 {
     __socket = original.__socket;
     _buffer  = new byte[count];
     Buffer.BlockCopy(original._buffer, 0, _buffer, 0, count);
 }
示例#18
0
        /// <summary>
        /// This method handles the download asynchronus result
        /// when the server receives a file from the client.
        /// </summary>
        /// <param name="ar">The current asynchronus result</param>
        private void DownloadFile(IAsyncResult ar)
        {
            // Get the current network stream from the
            // asynchronus result state object.
            ServerSocketState state   = (ServerSocketState)ar.AsyncState;
            NetworkStream     nStream = state.NetworkStream;

            long       totalBytesRead = 0;
            FileStream fileStream     = null;

            try
            {
                // If the file state file stream has
                // been created then get the stream
                // from the state object.
                if (state.FileStream != null)
                {
                    fileStream     = state.FileStream;
                    totalBytesRead = state.TotalBytesRead;
                }
                else
                {
                    // Create a new download file stream.
                    fileStream = new FileStream(destinationFile,
                                                FileMode.Create, FileAccess.Write, FileShare.ReadWrite);

                    // Get the network stream and file stream
                    // form the state object.
                    state.NetworkStream  = nStream;
                    state.FileStream     = fileStream;
                    state.TotalBytesRead = 0;
                }
            }
            catch (Exception e)
            {
                // Stop the download.
                downloadingFile = false;

                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferConnection", "DownloadFile", e.Message,
                           333, WriteTo.EventLog, LogType.Error);
            }

            try
            {
                int bytesRead;
                // End the current read process.

                lock (nStream)
                    bytesRead = nStream.EndRead(ar);

                if (bytesRead < 1)
                {
                    // If the connection is closed
                    // then throw a new exception.
                    if (!tcpClient.Connected)
                    {
                        throw new Exception("Connection has closed.");
                    }

                    // Start counting loops.
                    readDownLoadLoopCount++;

                    // If count greater than
                    // 10 then throw exception
                    // and close the connection.
                    if (readDownLoadLoopCount > 4)
                    {
                        throw new Exception("Connection has been disconnected, read loop detected. " +
                                            "Connection has timed out or, may occur when client calls Shutdown(SocketShutdown.Both)");
                    }
                }

                // If not the first time reading
                // data from the network stream
                // the load the data received
                // to the file.
                fileStream.Write(readBuffer, 0, bytesRead);
                totalBytesRead += (long)bytesRead;

                // Download the current data.
                totalBytesRead += DownloadFileEx(fileStream, nStream, totalBytesRead);
            }
            catch (IOException ioe)
            {
                // Handles the forced disconnection such as
                // exiting a client program without closing
                // the connection.
                string error = ioe.Message;

                // Stop the download.
                downloadingFile = false;
            }
            catch (ObjectDisposedException ode)
            {
                // Handles the exception when the client
                // closes the current network channel
                // and disposes of the current connection
                // to client class, this object.
                string error = ode.Message;

                // Stop the download.
                downloadingFile = false;
            }
            catch (Exception e)
            {
                // Stop the download.
                downloadingFile = false;

                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferConnection", "DownloadFile", e.Message,
                           286, WriteTo.EventLog, LogType.Error);
            }

            try
            {
                // If the download file is the same size
                // as the file current being written then
                // the download has completed and data has
                // been received.
                if (destinationFileSize == totalBytesRead)
                {
                    downloadingFile = false;
                }

                // If all data has been read.
                if (!downloadingFile)
                {
                    // Close the file.
                    if (fileStream != null)
                    {
                        fileStream.Close();
                    }

                    // Release the object.
                    fileStream       = null;
                    state.FileStream = null;

                    // Start a new asynchronous read into readBuffer.
                    // more data maybe present. This will wait for more
                    // data from the client.
                    System.Threading.Thread.Sleep(5);
                    lock (nStream)
                        nStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE,
                                          new AsyncCallback(DataReceiver), state);

                    // Send to the client a command indicating that
                    // all the data has been received.
                    System.Threading.Thread.Sleep(5);
                    WriteCommand("CDDN 100", nStream);
                }
                else
                {
                    // The current bytes read in this async threa.
                    state.TotalBytesRead = totalBytesRead;

                    // Start a new asynchronous read into, more
                    // of the file being download exists so read
                    // from the network stream until all data
                    // has been received.
                    lock (nStream)
                        nStream.BeginRead(readBuffer, 0, READ_BUFFER_SIZE,
                                          new AsyncCallback(DownloadFile), state);
                }
            }
            catch (IOException ioe)
            {
                // Handles the forced disconnection such as
                // exiting a client program without closing
                // the connection.
                string error = ioe.Message;

                // On any error close the connection.
                Disconnect(state);
            }
            catch (ObjectDisposedException ode)
            {
                // Handles the exception when the client
                // closes the current network channel
                // and disposes of the current connection
                // to client class, this object.
                string error = ode.Message;

                // On any error close the connection.
                Disconnect(state);
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferConnection", "DownloadFile", e.Message,
                           368, WriteTo.EventLog, LogType.Error);

                // On any error close the connection.
                Disconnect(state);
            }
        }
示例#19
0
        /// <summary>
        /// This method handles the upload asynchronus result
        /// when the server sends a file to the client.
        /// </summary>
        /// <param name="ar">The current asynchronus result</param>
        private void UploadFile(IAsyncResult ar)
        {
            // Get the current network stream from the
            // asynchronus result state object.
            ServerSocketState state      = (ServerSocketState)ar.AsyncState;
            NetworkStream     nStream    = state.NetworkStream;
            FileStream        fileStream = state.FileStream;

            // End the current asynchronus write
            // operation.
            lock (nStream)
                nStream.EndWrite(ar);

            try
            {
                int       readBytes    = 0;
                const int bufferLength = WRITE_BUFFER_SIZE;
                byte[]    buffer       = new byte[bufferLength];

                // Read all the data in the upload file and
                // send the data from the file to the client
                // through the current network stream.
                do
                {
                    readBytes = fileStream.Read(buffer, 0, bufferLength);
                    nStream.Write(buffer, 0, readBytes);

                    // If the time out control has been created
                    // then reset the timer.
                    if (_timeOut != null)
                    {
                        _timeOut.Change(
                            new TimeSpan(0, _timeOutInterval, 0),
                            new TimeSpan(0, _timeOutInterval, 0));
                    }
                }while (readBytes != 0);

                // Close the current upload file.
                fileStream.Close();
            }
            catch (IOException ioe)
            {
                // Handles the forced disconnection such as
                // exiting a client program without closing
                // the connection.
                string error = ioe.Message;

                // On any error close the connection.
                state.FileStream = null;
                Disconnect(state);
            }
            catch (ObjectDisposedException ode)
            {
                // Handles the exception when the client
                // closes the current network channel
                // and disposes of the current connection
                // to client class, this object.
                string error = ode.Message;

                // On any error close the connection.
                state.FileStream = null;
                Disconnect(state);
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("FileTransferConnection", "UploadFile", e.Message,
                           484, WriteTo.EventLog, LogType.Error);

                // On any error close the connection.
                state.FileStream = null;
                Disconnect(state);
            }
            finally
            {
                if (fileStream != null)
                {
                    fileStream.Close();
                }
            }
        }
        private void OnReceive(IAsyncResult result)
        {
            ServerSocketState recvState = (ServerSocketState)result.AsyncState;

            try
            {
                int bytesReceived = recvState.Socket.EndReceive(result);
                if (bytesReceived == 0)
                {
                    recvState.Socket.Dispose();
                    return;
                }

                ServerSocketState sendState = new ServerSocketState(recvState, bytesReceived);

                sendState.Socket.BeginSend(sendState.TransferBuffer, 0, bytesReceived, SocketFlags.None, OnSend, sendState);
                recvState.Socket.BeginReceive(
                    recvState.TransferBuffer, 
                    0, 
                    recvState.TransferBuffer.Length, 
                    SocketFlags.None, 
                    OnReceive, 
                    recvState);
            }
            catch (SocketException)
            {
                recvState.Socket.Dispose();
                return;
            }
            catch (ObjectDisposedException)
            {
                return;
            }
        }
 public ServerSocketState(ServerSocketState original, int count)
 {
     _socket = original._socket;
     _buffer = new byte[count];
     Buffer.BlockCopy(original._buffer, 0, _buffer, 0, count);
 }
示例#22
0
        /// <summary>
        /// Default constructor.
        /// </summary>
        /// <param name="tcpClient">The tcp client channel connection from server to client.</param>
        /// <param name="connection">The connection adapter used to connect to the server.</param>
        public SmtpSslProxyConnection(TcpClient tcpClient, SmtpConnectionAdapter connection)
        {
            try
            {
                // The tcp client to server channel.
                // Assign the network stream from the client
                // channel stream.
                _tcpClient  = tcpClient;
                _connection = connection;
                _sslStream  = new SslStream(tcpClient.GetStream());

                // Certificate file containing a public key
                // and private key for secure data transfer.
                X509Certificate2 certificate = GetServerCredentials();

                // Load the certificate into the
                // secure stream used for secure communication.
                _sslStream.AuthenticateAsServer(certificate, false, SslProtocols.Ssl3, false);

                // Create a new state object.
                ServerSocketState state = new ServerSocketState();
                state.SslStream = _sslStream;

                // This starts the asynchronous read thread.
                // The data will be saved into readBuffer.
                _sslStream.BeginRead(_readBuffer, 0, READ_BUFFER_SIZE,
                                     new AsyncCallback(DataReceiver), state);

                // Create a new smtp client and
                // attempt to make a connection
                // get the response from the server.
                bool ret = GetSocket();

                // If return false.
                if (!ret)
                {
                    // Write an error response back to
                    // the smtp client.
                    _sslStream.Write(Encoding.ASCII.GetBytes("-ERR" + "\r\n"));
                }
                else
                {
                    // Create a new state object.
                    ServerSocketState stateSocket = new ServerSocketState();
                    stateSocket.EmailMessage = new StringBuilder();
                    stateSocket.SslStream    = _sslStream;
                    stateSocket.Socket       = _socket;

                    // Start receiving data asynchrounusly.
                    _socket.BeginReceive(_receiveBuffer, 0, READ_BUFFER_SIZE,
                                         SocketFlags.None, new AsyncCallback(ReceiveCallback), stateSocket);
                }
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("SmtpSslProxyConnection", "Constructor", e.Message,
                           65, WriteTo.EventLog, LogType.Error);
            }
        }
示例#23
0
        /// <summary>
        /// Data received asynchronus result method, all client commands
        /// are processed through this asynchronus result method.
        /// </summary>
        /// <param name="ar">The current asynchronus result.</param>
        private void DataReceiver(IAsyncResult ar)
        {
            int bytesRead = 0;

            // Get the current network stream from the
            // asynchronus result state object.
            ServerSocketState state   = (ServerSocketState)ar.AsyncState;
            SslStream         nStream = state.SslStream;

            try
            {
                // Finish asynchronous read into readBuffer
                // and get number of bytes read.
                lock (nStream)
                    bytesRead = nStream.EndRead(ar);

                if (bytesRead > 0)
                {
                    // Convert the byte array the message command.
                    // Trigger the data receiver delegate and send
                    // the command and data to the host.
                    try
                    {
                        string command = Encoding.ASCII.GetString(_readBuffer, 0, bytesRead);
                        OnDataReceived(this, command);

                        // If the time out control has been created
                        // then reset the timer.
                        if (_timeOut != null)
                        {
                            _timeOut.Change(
                                new TimeSpan(0, _timeOutInterval, 0),
                                new TimeSpan(0, _timeOutInterval, 0));
                        }
                    }
                    catch { }
                }
                else
                {
                    // If the connection is closed
                    // then throw a new exception.
                    if (!_tcpClient.Connected)
                    {
                        throw new Exception("Connection has closed.");
                    }

                    // Start counting loops.
                    _readLoopCount++;

                    // If count greater than
                    // 10 then throw exception
                    // and close the connection.
                    if (_readLoopCount > 4)
                    {
                        throw new Exception("Connection has been disconnected, read loop detected. " +
                                            "Connection has timed out or, may occur when client calls Shutdown(SocketShutdown.Both)");
                    }
                }

                // Start a new asynchronous read into readBuffer.
                // more data maybe present. This will wait for more
                // data from the client.
                lock (nStream)
                    nStream.BeginRead(_readBuffer, 0, READ_BUFFER_SIZE,
                                      new AsyncCallback(DataReceiver), state);
            }
            catch (IOException ioe)
            {
                // Handles the forced disconnection such as
                // exiting a client program without closing
                // the connection.
                string error = "IOException\r\n" + ioe.Message;

                // On any error close the connection.
                Disconnect();
            }
            catch (ObjectDisposedException ode)
            {
                // Handles the exception when the client
                // closes the current network channel
                // and disposes of the current connection
                // to client class, this object.
                string error = "ObjectDisposedException\r\n" + ode.Message;

                // On any error close the connection.
                //Disconnect();
            }
            catch (Exception e)
            {
                // Detect a thread abort exception.
                if (e is ThreadAbortException)
                {
                    Thread.ResetAbort();
                }

                base.Write("SmtpSslProxyConnection", "DataReceiver", e.Message,
                           243, WriteTo.EventLog, LogType.Error);

                // On any error close the connection.
                Disconnect();
            }
        }