Exemple #1
0
        public void Process(Byte[] abData)
        {
            string sMessage = this.Encoding.GetString(abData);

            sMessage = sMessage.Substring(0, sMessage.IndexOf('\r'));

            FtpServerMessageHandler.SendMessage(Id, sMessage);

            string sCommand;
            string sValue;

            int nSpaceIndex = sMessage.IndexOf(' ');

            if (nSpaceIndex < 0)
            {
                sCommand = sMessage.ToUpper();
                sValue   = "";
            }
            else
            {
                sCommand = sMessage.Substring(0, nSpaceIndex).ToUpper();
                sValue   = sMessage.Substring(sCommand.Length + 1);
            }

            // check whether the client has logged in
            if (!isLogged)
            {
                if (!((sCommand == "USER") || (sCommand == "PASS") || (sCommand == "HELP") || (sCommand == "FEAT") || (sCommand == "QUIT")))
                {
                    SocketHelpers.Send(Socket, "530 Not logged in\r\n", this.Encoding);
                    return;
                }
            }

            // check if data connection will be used
            if ((sCommand == "APPE") || (sCommand == "MLSD") || (sCommand == "LIST") || (sCommand == "RETR") || (sCommand == "STOR"))
            {
                m_useDataSocket = true;
            }

            var handler = m_theCommandHashTable[sCommand] as FtpCommandHandler;

            if (handler == null)
            {
                FtpServerMessageHandler.SendMessage(Id, string.Format("\"{0}\" : Unknown command", sCommand));
                SocketHelpers.Send(Socket, "550 Unknown command\r\n", this.Encoding);
            }
            else
            {
                handler.Process(sValue);
            }

            // reset
            m_useDataSocket = false;
        }
Exemple #2
0
        private void ThreadRun()
        {
            m_socketListen = SocketHelpers.CreateTcpListener(RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["FTP"].IPEndpoint);

            if (m_socketListen != null)
            {
                m_socketListen.Start();

                FtpServerMessageHandler.SendMessage(0, "FTP Server Started");

                bool fContinue = true;

                while (fContinue)
                {
                    TcpClient socket = null;

                    try
                    {
                        socket = m_socketListen.AcceptTcpClient();
                    }
                    catch (SocketException)
                    {
                        fContinue = false;
                    }
                    finally
                    {
                        if (socket == null)
                        {
                            fContinue = false;
                        }
                        else
                        {
                            socket.NoDelay = false;

                            m_nId++;

                            FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                            SendAcceptMessage(socket);
                            InitialiseSocketHandler(socket);
                        }
                    }
                }
            }
            else
            {
                FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
            }
        }
Exemple #3
0
        private static TcpClient OpenSocket(FtpConnectionObject connectionObject)
        {
            switch (connectionObject.DataConnectionType)
            {
            case DataConnectionType.Active:
                return(SocketHelpers.CreateTcpClient(connectionObject.PortCommandSocketAddress,
                                                     connectionObject.PortCommandSocketPort));

            case DataConnectionType.Passive:
                return(connectionObject.PassiveSocket);

            default:
                FtpServerMessageHandler.SendMessage(connectionObject.Id, "Invalid connection type!");
                return(null);
            }
        }
        private void ThreadRun()
        {
            var abData = new Byte[m_nBufferSize];

            try
            {
                int nReceived = m_theSocket.GetStream().Read(abData, 0, m_nBufferSize);

                while (nReceived > 0)
                {
                    m_theCommands.Process(abData, nReceived);

                    // the Read method will block
                    nReceived = m_theSocket.GetStream().Read(abData, 0, m_nBufferSize);

                    m_lastActiveTime = DateTime.Now;
                }
            }
            catch (SocketException)
            {
            }
            catch (IOException)
            {
            }

            FtpServerMessageHandler.SendMessage(m_nId, "Connection closed");

            if (Closed != null)
            {
                Closed(this);
            }


            m_theCommands.LogOut();

            m_theSocket.Close();
        }
Exemple #5
0
        public void Process(Byte[] abData)
        {
            string sMessage = Encoding.ASCII.GetString(abData);

            sMessage = sMessage.Substring(0, sMessage.IndexOf('\r'));

            FtpServerMessageHandler.SendMessage(Id, sMessage);

            string sCommand;
            string sValue;

            int nSpaceIndex = sMessage.IndexOf(' ');

            if (nSpaceIndex < 0)
            {
                sCommand = sMessage.ToUpper();
                sValue   = "";
            }
            else
            {
                sCommand = sMessage.Substring(0, nSpaceIndex).ToUpper();
                sValue   = sMessage.Substring(sCommand.Length + 1);
            }

            var handler = m_theCommandHashTable[sCommand] as FtpCommandHandler;

            if (handler == null)
            {
                FtpServerMessageHandler.SendMessage(Id, string.Format("\"{0}\" : Unknown command", sCommand));
                SocketHelpers.Send(Socket, "550 Unknown command\r\n");
            }
            else
            {
                handler.Process(sValue);
            }
        }
Exemple #6
0
        private void ThreadMonitor()
        {
            while (m_theThread.IsAlive)
            {
                DateTime currentTime = DateTime.Now;
                TimeSpan timeSpan    = currentTime - m_lastActiveTime;
                // has been idle for a long time
                if ((timeSpan.TotalSeconds > m_maxIdleSeconds) && !m_theCommands.DataSocketOpen)
                {
                    SocketHelpers.Send(m_theSocket, string.Format("426 No operations for {0}+ seconds. Bye!", m_maxIdleSeconds), m_theCommands.Encoding);
                    FtpServerMessageHandler.SendMessage(m_nId, "Connection closed for too long idle time.");
                    if (Closed != null)
                    {
                        Closed(this);
                    }
                    m_theSocket.Close();
                    this.Stop();
                    return;
                }
                Thread.Sleep(1000 * m_maxIdleSeconds);
            }

            return; // only monitor the work thread
        }
        public void Process(byte[] abData)
        {
            string sMessage = this.Encoding.GetString(abData);
            // 2015-11-26 cljung : BUG .IndexOf returns -1 if search item isn't found. Substring throws exception with -1
            int pos = sMessage.IndexOf('\r');

            if (pos >= 0)
            {
                sMessage = sMessage.Substring(0, pos);
            }

            FtpServerMessageHandler.SendMessage(Id, sMessage);

            string sCommand;
            string sValue;

            int nSpaceIndex = sMessage.IndexOf(' ');

            if (nSpaceIndex < 0)
            {
                sCommand = sMessage.ToUpper();
                sValue   = "";
            }
            else
            {
                sCommand = sMessage.Substring(0, nSpaceIndex).ToUpper();
                sValue   = sMessage.Substring(sCommand.Length + 1);
            }

            // check whether the client has logged in
            if (!isLogged)
            {
                if (!((sCommand == "USER") || (sCommand == "PASS") || (sCommand == "HELP") || (sCommand == "FEAT") || (sCommand == "QUIT")))
                {
                    SocketHelpers.Send(Socket, "530 Not logged in\r\n", this.Encoding);
                    return;
                }
            }

            // check if data connection will be used
            if ((sCommand == "APPE") || (sCommand == "MLSD") || (sCommand == "LIST") || (sCommand == "RETR") || (sCommand == "STOR"))
            {
                m_useDataSocket = true;
            }

            var handler = m_theCommandHashTable[sCommand] as FtpCommandHandler;

            if (handler == null)
            {
                FtpServerMessageHandler.SendMessage(Id, $"\"{sCommand}\" : Unknown command");
                FtpServer.LogWrite($"{Socket.Client.RemoteEndPoint.ToString()} Unknown/unsupported command: {sCommand}");
                SocketHelpers.Send(Socket, "550 Unknown command\r\n", this.Encoding);
            }
            else
            {
                handler.Process(sValue);
            }

            // reset
            m_useDataSocket = false;
        }
Exemple #8
0
        public void Process(Byte[] abData, int bufferLength)
        {
            string sMessage = this.Encoding.GetString(abData, 0, bufferLength);
            int    indexOfCarriageReturn = sMessage.IndexOf('\r');

            if (indexOfCarriageReturn == -1)
            {
                // the full message line has not yet been sent, append the current buffer and return
                // so that the rest of the message can be read
                currentMessage.Append(sMessage);
                return;
            }
            else
            {
                // current payload contains carriage return, read up to that point and
                // append to the current message
                sMessage = sMessage.Substring(0, indexOfCarriageReturn);
                currentMessage.Append(sMessage);
                // don't return; time to process the message
            }

            sMessage       = currentMessage.ToString();
            currentMessage = new StringBuilder();
            FtpServerMessageHandler.SendMessage(Id, sMessage);

            string sCommand;
            string sValue;

            int nSpaceIndex = sMessage.IndexOf(' ');

            if (nSpaceIndex < 0)
            {
                sCommand = sMessage.ToUpper();
                sValue   = "";
            }
            else
            {
                sCommand = sMessage.Substring(0, nSpaceIndex).ToUpper();
                sValue   = sMessage.Substring(sCommand.Length + 1);
            }

            // check whether the client has logged in
            if (!isLogged)
            {
                if (!((sCommand == "USER") || (sCommand == "PASS") || (sCommand == "HELP") || (sCommand == "FEAT") || (sCommand == "QUIT")))
                {
                    SocketHelpers.Send(Socket, "530 Not logged in\r\n", this.Encoding);
                    return;
                }
            }

            // check if data connection will be used
            if ((sCommand == "APPE") || (sCommand == "MLSD") || (sCommand == "LIST") || (sCommand == "RETR") || (sCommand == "STOR"))
            {
                m_useDataSocket = true;
            }

            var handler = m_theCommandHashTable[sCommand] as FtpCommandHandler;

            if (handler == null)
            {
                FtpServerMessageHandler.SendMessage(Id, string.Format("\"{0}\" : Unknown command", sCommand));
                SocketHelpers.Send(Socket, "550 Unknown command\r\n", this.Encoding);
            }
            else
            {
                handler.Process(sValue);
            }

            // reset
            m_useDataSocket = false;
        }
Exemple #9
0
        /// The main thread of the ftp server
        /// Listen and acception clients, create handler threads for each client
        private void ThreadRun()
        {
            try
            {
                FtpServerMessageHandler.Message += TraceMessage;

                // listen at the port by the "FTP" endpoint setting
                IPEndPoint ipEndPoint;

                ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["FTP2Azure.Command"].IPEndpoint;

                m_socketListen = SocketHelpers.CreateTcpListener(ipEndPoint);

                if (m_socketListen != null)
                {
                    Trace.TraceInformation("FTP Server listened at: " + ipEndPoint);

                    m_socketListen.Start();

                    Trace.TraceInformation("FTP Server Started");

                    bool fContinue = true;

                    while (fContinue)
                    {
                        TcpClient socket = null;

                        try
                        {
                            socket = m_socketListen.AcceptTcpClient();
                        }
                        catch (SocketException e)
                        {
                            fContinue = false;
                            if (errorHandler != null)
                            {
                                errorHandler(e);
                            }
                        }
                        finally
                        {
                            if (socket == null)
                            {
                                fContinue = false;
                            }
                            else if (m_apConnections.Count >= m_maxClients)
                            {
                                Trace.WriteLine("Too many clients, won't handle this connection", "Warnning");
                                SendRejectMessage(socket);
                                socket.Close();
                            }
                            else
                            {
                                socket.NoDelay = false;

                                m_nId++;

                                FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                                SendAcceptMessage(socket);
                                InitialiseSocketHandler(socket);
                            }
                        }
                    }
                }
                else
                {
                    FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
                }
            }
            catch (Exception e)
            {
                if (errorHandler != null)
                {
                    errorHandler(e);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// The main thread of the ftp server
        /// Listen and acception clients, create handler threads for each client
        /// </summary>
        private void ThreadRun()
        {
            FtpServerMessageHandler.Message += TraceMessage;

            // listen at the port by the "FTP" endpoint setting
            int port = int.Parse(ConfigurationManager.AppSettings["FTP"]);

            System.Net.IPAddress  ipaddr     = SocketHelpers.GetLocalAddress();
            System.Net.IPEndPoint ipEndPoint = new System.Net.IPEndPoint(ipaddr.Address, port);
            FtpServer.m_ftpIpAddr = ipaddr.ToString();
            m_socketListen        = SocketHelpers.CreateTcpListener(ipEndPoint);

            if (m_socketListen != null)
            {
                string msg = string.Format("FTP Server started.Listening to: {0}", ipEndPoint);
                FtpServer.LogWrite(msg);
                Trace.TraceInformation(msg);

                m_socketListen.Start();

                bool fContinue = true;

                while (fContinue)
                {
                    TcpClient socket = null;

                    try
                    {
                        socket = m_socketListen.AcceptTcpClient();
                    }
                    catch (SocketException)
                    {
                        fContinue = false;
                    }
                    finally
                    {
                        if (socket == null)
                        {
                            fContinue = false;
                        }
                        else if (m_apConnections.Count >= m_maxClients)
                        {
                            Trace.WriteLine("Too many clients, won't handle this connection", "Warnning");
                            SendRejectMessage(socket);
                            socket.Close();
                        }
                        else
                        {
                            socket.NoDelay = false;

                            m_nId++;

                            FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                            SendAcceptMessage(socket);
                            // 2015-11-25 cljung : under stress testing, this happens. Don't know why yet, but let's keep it from crashing
                            try
                            {
                                InitialiseSocketHandler(socket);
                            }
                            catch (System.ObjectDisposedException ode)
                            {
                                Trace.TraceError(string.Format("ObjectDisposedException initializing client socket:\r\n{0}", ode));
                                m_nId--;
                                // can't fail
                                try {
                                    socket.Close();
                                } catch { }
                            }
                        }
                    }
                }
            }
            else
            {
                FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
            }
        }
Exemple #11
0
        /// The main thread of the ftp server
        /// Listen and acception clients, create handler threads for each client
        private void ThreadRun()
        {
            try
            {
                FtpServerMessageHandler.Message += TraceMessage;

                // listen at the port by the "FTP" endpoint setting
                IPEndPoint ipEndPoint;

                ipEndPoint = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["FTP2Azure.Command"].IPEndpoint;

                m_socketListen = SocketHelpers.CreateTcpListener(ipEndPoint);

                if (m_socketListen != null)
                {
                    Trace.TraceInformation($"FTP Server listened at: {ipEndPoint}");

                    m_socketListen.Start();

                    Trace.TraceInformation("FTP Server Started");

                    bool fContinue = true;

                    while (fContinue)
                    {
                        TcpClient socket = null;

                        try
                        {
                            socket = m_socketListen.AcceptTcpClient();
                        }
                        catch (SocketException e)
                        {
                            fContinue = false;
                            ErrorHandler?.Invoke(e);
                        }
                        finally
                        {
                            if (socket == null)
                            {
                                fContinue = false;
                            }
                            else if (m_apConnections.Count >= m_maxClients)
                            {
                                Trace.WriteLine("Too many clients, won't handle this connection", "Warnning");
                                SendRejectMessage(socket);
                                socket.Close();
                            }
                            else
                            {
                                socket.NoDelay = false;

                                m_nId++;

                                FtpServerMessageHandler.SendMessage(m_nId, "New connection");

                                SendAcceptMessage(socket);

                                //under stress testing, this happens. Don't know why yet, but let's keep it from crashing
                                try
                                {
                                    InitialiseSocketHandler(socket);
                                }
                                catch (ObjectDisposedException ode)
                                {
                                    Trace.TraceError($"ObjectDisposedException initializing client socket:\r\n{ode}");

                                    m_nId--;
                                    socket.Close();
                                }
                            }
                        }
                    }
                }
                else
                {
                    FtpServerMessageHandler.SendMessage(0, "Error in starting FTP server");
                }
            }
            catch (Exception e)
            {
                ErrorHandler?.Invoke(e);
            }
        }