Esempio n. 1
0
        protected override string OnProcess(string sMessage)
        {
            string sFilePath = GetPath(sMessage);

            if (!ConnectionObject.FileSystemObject.FileExists(sFilePath))
            {
                return(GetMessage(550, "File doesn't exist"));
            }

            var replySocket = new FtpReplySocket(ConnectionObject);

            if (!replySocket.Loaded)
            {
                return(GetMessage(550, "Unable to establish data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, "150 Starting data transfer, please wait...\r\n");

            const int m_nBufferSize = 65536;

            IFile file = ConnectionObject.FileSystemObject.OpenFile(sFilePath, false);

            if (file == null)
            {
                return(GetMessage(550, "Couldn't open file"));
            }

            var abBuffer = new byte[m_nBufferSize];

            int nRead = file.Read(abBuffer, m_nBufferSize);

            while (nRead > 0 && replySocket.Send(abBuffer, nRead))
            {
                nRead = file.Read(abBuffer, m_nBufferSize);
            }

            file.Close();
            replySocket.Close();

            return(GetMessage(226, "File download succeeded."));
        }
Esempio n. 2
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            Stopwatch sw = new Stopwatch();

            sw.Start();
            if (!FileNameHelpers.IsValid(sFile))
            {
                FtpServer.LogWrite(this, sMessage, 553, sw.ElapsedMilliseconds);
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            if (!ConnectionObject.FileSystemObject.AppendFile(sFile, socketData.Socket.GetStream()))
            {
                FtpServer.LogWrite(this, sMessage, 553, sw.ElapsedMilliseconds);
                return(GetMessage(553, string.Format("{0} error", Command)));
            }

            // remove the orginal blob ContentMD5
            ConnectionObject.FileSystemObject.SetFileMd5(sFile, string.Empty);

            sw.Stop();
            FtpServer.LogWrite(this, sMessage, 250, sw.ElapsedMilliseconds);
            return(GetMessage(250, string.Format("{0} successful", Command)));
        }
Esempio n. 3
0
        /// <summary>
        /// Resumes asynchronous TCP receiving from the server.
        /// </summary>
        private void ResumeReceive()
        {
            if (this._tcpSock != null && this._tcpSock.Connected)
            {
                SocketAsyncEventArgs socketArgs = SocketHelpers.AcquireSocketArg();
                int offset = this._offset + this._remainingLength;

                socketArgs.SetBuffer(
                    this._bufferSegment.Buffer.Array,
                    this._bufferSegment.Offset + offset,
                    BufferSize - offset);
                socketArgs.UserToken  = this;
                socketArgs.Completed += this.ReceiveAsyncComplete;

                bool willRaiseEvent = this._tcpSock.ReceiveAsync(socketArgs);
                if (!willRaiseEvent)
                {
                    this.ProcessRecieve(socketArgs);
                }
            }
        }
Esempio n. 4
0
        private string GetPassiveAddressInfo()
        {
            // get local ipv4 ip
            IPAddress ipAddress = SocketHelpers.GetLocalAddress();

            if (ipAddress == null)
            {
                throw new Exception("The ftp server do not have a ipv4 address");
            }
            string retIpPort = ipAddress.ToString();

            retIpPort = retIpPort.Replace('.', ',');

            // append the port
            retIpPort += ',';
            retIpPort += (m_nPort / 256).ToString();
            retIpPort += ',';
            retIpPort += (m_nPort % 256).ToString();

            return(retIpPort);
        }
Esempio n. 5
0
        private string GetPassiveAddressInfo()
        {
            // get routable ipv4 address of load balanced service
            IPAddress ipAddress = SocketHelpers.GetLocalAddress(StorageProviderConfiguration.FtpServerHostPublic);

            if (ipAddress == null)
            {
                throw new Exception("The ftp server do not have a ipv4 address");
            }
            string retIpPort = ipAddress.ToString();

            retIpPort = retIpPort.Replace('.', ',');

            // append the port
            retIpPort += ',';
            retIpPort += (m_nPort / 256).ToString();
            retIpPort += ',';
            retIpPort += (m_nPort % 256).ToString();

            return(retIpPort);
        }
        protected override string OnProcess(string sMessage)
        {
            if (ConnectionObject.PassiveSocket != null)
            {
                ConnectionObject.PassiveSocket.Close();
                ConnectionObject.PassiveSocket = null;
            }

            ConnectionObject.DataConnectionType = DataConnectionType.Passive;

            string pasvListenAddress = GetPassiveAddressInfo();

            TcpListener listener;

            if (StorageProviderConfiguration.Mode == Modes.Live)
            {
                listener = SocketHelpers.CreateTcpListener(
                    RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["FTP2Azure.Passive"].IPEndpoint);
            }
            else
            {
                listener = SocketHelpers.CreateTcpListener(new IPEndPoint(
                                                               IPAddress.Parse("127.0.0.1"), RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["FTP2Azure.Passive"].IPEndpoint.Port));
            }
            if (listener == null)
            {
                return(GetMessage(550, $"Couldn't start listener on port {m_nPort}"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(227, $"Entering Passive Mode ({pasvListenAddress})"), ConnectionObject.Encoding);

            listener.Start();

            ConnectionObject.PassiveSocket = listener.AcceptTcpClient();

            listener.Stop();

            return(string.Empty);
        }
Esempio n. 7
0
        protected override string OnProcess(string message)
        {
            string filePath = this.GetPath(message);

            if (!this.ConnectionObject.FileSystemObject.FileExists(filePath))
            {
                return(this.GetMessage(550, "File doesn't exist"));
            }

            var replySocket = new FtpReplySocket(this.ConnectionObject);

            if (!replySocket.Loaded)
            {
                return(this.GetMessage(550, "Unable to establish data connection"));
            }

            SocketHelpers.Send(this.ConnectionObject.Socket, "150 Starting data transfer, please wait...\r\n");

            var file = this.ConnectionObject.FileSystemObject.OpenFile(filePath, false);

            if (file == null)
            {
                return(this.GetMessage(550, "Couldn't open file"));
            }

            const int BufferSize = 65536;
            var       buffer     = new byte[BufferSize];
            int       read       = file.Read(buffer, BufferSize);

            while (read > 0 && replySocket.Send(buffer, read))
            {
                read = file.Read(buffer, BufferSize);
            }

            file.Close();
            replySocket.Close();

            return(this.GetMessage(226, "File download succeeded."));
        }
        protected override string OnProcess(string sMessage)
        {
            if (sMessage.Length != 0)
            {
                return(GetMessage(501, "Invalid syntax for FEAT command"));
            }

            string response = "211-Extensions supported:\r\n";

            response += " XCUP\r\n";
            response += " XCWD\r\n";
            response += " XMKD\r\n";
            response += " XPWD\r\n";
            response += " XRMD\r\n";
            response += " MDTM\r\n";
            response += " MLSD\r\n";
            response += " MLST\r\n";
            response += " SIZE\r\n";
            response += "211 END\r\n";
            SocketHelpers.Send(ConnectionObject.Socket, response, ConnectionObject.Encoding);
            return("");
        }
Esempio n. 9
0
        protected override string OnProcess(string sMessage)
        {
            ConnectionObject.DataConnectionType = DataConnectionType.Passive;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            string pasvListenAddress = GetPassiveAddressInfo();

            //return GetMessage(227, string.Format("Entering Passive Mode ({0})", pasvListenAddress));

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

            System.Net.IPAddress  ipaddr     = SocketHelpers.GetLocalAddress();
            System.Net.IPEndPoint ipEndPoint = new System.Net.IPEndPoint(ipaddr.Address, port);

            TcpListener listener = SocketHelpers.CreateTcpListener(ipEndPoint);

            if (listener == null)
            {
                FtpServer.LogWrite(this, sMessage, 550, 0);
                return(GetMessage(550, string.Format("Couldn't start listener on port {0}", m_nPort)));
            }
            Trace.TraceInformation(string.Format("Entering Passive Mode on {0}", pasvListenAddress));
            SocketHelpers.Send(ConnectionObject.Socket, string.Format("227 Entering Passive Mode ({0})\r\n", pasvListenAddress), ConnectionObject.Encoding);

            listener.Start();

            ConnectionObject.PassiveSocket = listener.AcceptTcpClient();

            listener.Stop();

            sw.Stop();
            FtpServer.LogWrite(this, sMessage, 0, sw.ElapsedMilliseconds);

            return("");
        }
Esempio n. 10
0
        protected override string OnProcess(string message)
        {
            if (this.ConnectionObject.PasvSocket == null)
            {
                var listener = SocketHelpers.CreateTcpListener(Port);
                if (listener == null)
                {
                    return(this.GetMessage(550, string.Format("Couldn't start listener on port {0}", Port)));
                }

                this.SendPasvReply();

                listener.Start();

                this.ConnectionObject.PasvSocket = listener.AcceptTcpClient();

                listener.Stop();
                return(string.Empty);
            }

            this.SendPasvReply();
            return(string.Empty);
        }
Esempio n. 11
0
        protected override string OnProcess(string message)
        {
            SocketHelpers.Send(ConnectionObject.Socket, "150 Opening data connection for LIST\r\n");

            string[] asFiles       = null;
            string[] asDirectories = null;

            message = message.Trim();

            var path = GetPath(string.Empty);

            if (message.Length == 0 || message[0] == '-')
            {
                asFiles       = ConnectionObject.FileSystemObject.GetFiles(path);
                asDirectories = ConnectionObject.FileSystemObject.GetDirectories(path);
            }
            else
            {
                asFiles       = ConnectionObject.FileSystemObject.GetFiles(path, message);
                asDirectories = ConnectionObject.FileSystemObject.GetDirectories(path, message);
            }

            var asAll    = ArrayHelpers.Add(asDirectories, asFiles) as string[];
            var fileList = BuildReply(message, asAll);

            var socketReply = new FtpReplySocket(ConnectionObject);

            if (!socketReply.Loaded)
            {
                return(GetMessage(550, "LIST unable to establish return connection."));
            }

            socketReply.Send(fileList);
            socketReply.Close();

            return(GetMessage(226, "LIST successful."));
        }
Esempio n. 12
0
        public void Process(byte[] data)
        {
            var message = Encoding.ASCII.GetString(data);

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

            FtpServerMessageHandler.SendMessage(this.Id, message);

            string command;
            string value;

            int spaceIndex = message.IndexOf(' ');

            if (spaceIndex < 0)
            {
                command = message.ToUpper();
                value   = string.Empty;
            }
            else
            {
                command = message.Substring(0, spaceIndex).ToUpper();
                value   = message.Substring(command.Length + 1);
            }

            var handler = this.commandHashTable[command] as FtpCommandHandler;

            if (handler == null)
            {
                FtpServerMessageHandler.SendMessage(this.Id, string.Format("\"{0}\" : Unknown command", command));
                SocketHelpers.Send(this.Socket, "550 Unknown command\r\n");
            }
            else
            {
                handler.Process(value);
            }
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
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
        }
Esempio n. 15
0
 private static void SendAcceptMessage(TcpClient socket)
 {
     SocketHelpers.Send(socket, System.Text.Encoding.ASCII.GetBytes("220 WheelMUD FTP Server Ready\r\n"));
 }
Esempio n. 16
0
        public void RandomSendAndReceiveTest()
        {
            var random = new Random();

            var caseList = new List <int>();

            caseList.AddRange(Enumerable.Range(1, 32));
            caseList.AddRange(new int[] { 100, 1000, 10000, 1024 * 1024, 1024 * 1024 * 32 });

            var(socket1, socket2) = SocketHelpers.GetSockets();

            var options = new OmniNonblockingConnectionOptions()
            {
                MaxReceiveByteCount = 1024 * 1024 * 256,
                MaxSendByteCount    = 1024 * 1024 * 256,
                BufferPool          = BufferPool.Shared,
            };

            using (var baseConnection1 = new OmniNonblockingConnection(new SocketCap(socket1, false), options))
                using (var baseConnection2 = new OmniNonblockingConnection(new SocketCap(socket2, false), options))
                    using (var connection1 = new OmniSecureConnection(baseConnection1, new OmniSecureConnectionOptions()
                    {
                        Type = OmniSecureConnectionType.Connect
                    }))
                        using (var connection2 = new OmniSecureConnection(baseConnection2, new OmniSecureConnectionOptions()
                        {
                            Type = OmniSecureConnectionType.Accept
                        }))
                        {
                            // ハンドシェイクを行う
                            {
                                var valueTask1 = connection1.Handshake();
                                var valueTask2 = connection2.Handshake();

                                var stopwatch = Stopwatch.StartNew();

                                while (!valueTask1.IsCompleted || !valueTask2.IsCompleted)
                                {
                                    if (stopwatch.Elapsed.TotalSeconds > 60)
                                    {
                                        throw new TimeoutException("Handshake");
                                    }

                                    Thread.Sleep(100);

                                    connection1.DoEvents();
                                    connection2.DoEvents();
                                }
                            }

                            foreach (var bufferSize in caseList)
                            {
                                var buffer1 = new byte[bufferSize];
                                var buffer2 = new byte[bufferSize];

                                random.NextBytes(buffer1);

                                var valueTask1 = connection1.EnqueueAsync((bufferWriter) =>
                                {
                                    bufferWriter.Write(buffer1);
                                });

                                var valueTask2 = connection2.DequeueAsync((sequence) =>
                                {
                                    sequence.CopyTo(buffer2);
                                });

                                var stopwatch = Stopwatch.StartNew();

                                while (!valueTask1.IsCompleted || !valueTask2.IsCompleted)
                                {
                                    if (stopwatch.Elapsed.TotalSeconds > 60)
                                    {
                                        throw new TimeoutException("SendAndReceive");
                                    }

                                    Thread.Sleep(100);

                                    connection1.DoEvents();
                                    connection2.DoEvents();
                                }

                                Assert.True(BytesOperations.SequenceEqual(buffer1, buffer2));
                            }
                        }
        }
Esempio n. 17
0
 public bool Send(byte[] abData, int nSize)
 {
     return(SocketHelpers.Send(m_theSocket, abData, 0, nSize));
 }
Esempio n. 18
0
 public void Stop()
 {
     SocketHelpers.Close(this.clientSocket);
     ////_mainThread.Join();
 }
Esempio n. 19
0
 /// <summary>
 /// </summary>
 /// <param name="sender">
 /// </param>
 /// <param name="args">
 /// </param>
 private static void SendAsyncComplete(object sender, SocketAsyncEventArgs args)
 {
     args.Completed -= SendAsyncComplete;
     SocketHelpers.ReleaseSocketArg(args);
 }
Esempio n. 20
0
 private void SendAcceptMessage(TcpClient socket)
 {
     SocketHelpers.Send(socket, m_encoding.GetBytes(
                            "220 FTP to Windows Azure Blob Storage Bridge Ready\r\n"));
 }
Esempio n. 21
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();

            // Get the dir to list
            string targetToList = GetPath(sMessage);

            // checks the dir name
            if (!FileNameHelpers.IsValid(targetToList))
            {
                return(GetMessage(501, $"\"{sMessage}\" is not a valid directory name"));
            }

            // specify the directory tag
            targetToList = FileNameHelpers.AppendDirTag(targetToList);

            bool targetIsDir = ConnectionObject.FileSystemObject.DirectoryExists(targetToList);

            if (!targetIsDir)
            {
                return(GetMessage(550, $"Directory \"{targetToList}\" not exists"));
            }

            #region Generate response

            StringBuilder response = new StringBuilder();

            string[] files       = ConnectionObject.FileSystemObject.GetFiles(targetToList);
            string[] directories = ConnectionObject.FileSystemObject.GetDirectories(targetToList);

            if (files != null && files.Any())
            {
                foreach (var file in files)
                {
                    var fileInfo = ConnectionObject.FileSystemObject.GetFileInfo(file);

                    response.Append(GenerateEntry(fileInfo));

                    response.Append("\r\n");
                }
            }

            if (directories != null && directories.Any())
            {
                foreach (var dir in directories)
                {
                    var dirInfo = ConnectionObject.FileSystemObject.GetDirectoryInfo(dir);

                    response.Append(GenerateEntry(dirInfo));

                    response.Append("\r\n");
                }
            }

            #endregion

            #region Write response

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, $"150 {ConnectionObject.DataType} Opening data connection for MLSD {targetToList}\r\n", ConnectionObject.Encoding);

            try
            {
                // ToDo, send response according to ConnectionObject.DataType, i.e., Ascii or Binary
                socketData.Send(response.ToString(), ConnectionObject.Encoding);
            }
            finally
            {
                socketData.Close();
            }

            #endregion

            return(GetMessage(226, "MLSD successful"));
        }
Esempio n. 22
0
 public bool Send(char[] chars, int size)
 {
     return(SocketHelpers.Send(socket, System.Text.Encoding.ASCII.GetBytes(chars), 0, size));
 }
Esempio n. 23
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFile = GetPath(sMessage);

            if (!FileNameHelpers.IsValid(sFile) || sFile.EndsWith(@"/"))
            {
                return(GetMessage(553, string.Format("\"{0}\" is not a valid file name", sMessage)));
            }

            if (ConnectionObject.FileSystemObject.FileExists(sFile))
            {
                // 2015-11-24 cljung : RFC959 says STOR commands overwrite files, so delete if exists
                if (!StorageProviderConfiguration.FtpOverwriteFileOnSTOR)
                {
                    return(GetMessage(553, string.Format("File \"{0}\" already exists.", sMessage)));
                }
                Trace.TraceInformation(string.Format("STOR {0} - Deleting existing file", sFile));
                if (!ConnectionObject.FileSystemObject.DeleteFile(sFile))
                {
                    return(GetMessage(550, string.Format("Delete file \"{0}\" failed.", sFile)));
                }
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            Trace.TraceInformation(string.Format("STOR {0} - BEGIN", sFile));

            IFile file = ConnectionObject.FileSystemObject.OpenFile(sFile, true);

            if (file == null)
            {
                socketData.Close();// close data socket
                return(GetMessage(550, "Couldn't open file"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, GetMessage(150, "Opening connection for data transfer."), ConnectionObject.Encoding);

            string md5Value = string.Empty;

            Stopwatch sw = new Stopwatch();

            sw.Start();

            // TYPE I, default
            if (ConnectionObject.DataType == DataType.Image)
            {
                // md5 hash function
                MD5 md5Hash = MD5.Create();

                var abData = new byte[m_nBufferSize];

                int nReceived = socketData.Receive(abData);

                while (nReceived > 0)
                {
                    int writeSize = file.Write(abData, nReceived);
                    // maybe error
                    if (writeSize != nReceived)
                    {
                        file.Close();
                        socketData.Close();
                        FtpServer.LogWrite(this, sMessage, 451, sw.ElapsedMilliseconds);
                        return(GetMessage(451, "Write data to Azure error!"));
                    }
                    md5Hash.TransformBlock(abData, 0, nReceived, null, 0);
                    nReceived = socketData.Receive(abData);
                }
                md5Hash.TransformFinalBlock(new byte[1], 0, 0);
                md5Value = BytesToStr(md5Hash.Hash);
            }
            // TYPE A
            // won't compute md5, because read characters from client stream
            else if (ConnectionObject.DataType == DataType.Ascii)
            {
                int readSize = SocketHelpers.CopyStreamAscii(socketData.Socket.GetStream(), file.BlobStream, m_nBufferSize);
                FtpServerMessageHandler.SendMessage(ConnectionObject.Id, string.Format("Use ascii type success, read {0} chars!", readSize));
            }
            else   // mustn't reach
            {
                file.Close();
                socketData.Close();
                FtpServer.LogWrite(this, sMessage, 451, sw.ElapsedMilliseconds);
                return(GetMessage(451, "Error in transfer data: invalid data type."));
            }

            sw.Stop();
            Trace.TraceInformation(string.Format("STOR {0} - END, Time {1} ms", sFile, sw.ElapsedMilliseconds));

            // upload notification
            ConnectionObject.FileSystemObject.Log4Upload(sFile);

            file.Close();
            socketData.Close();

            // record md5
            ConnectionObject.FileSystemObject.SetFileMd5(sFile, md5Value);

            FtpServer.LogWrite(this, sMessage, 226, sw.ElapsedMilliseconds);
            return(GetMessage(226, string.Format("{0} successful. Time {1} ms", Command, sw.ElapsedMilliseconds)));
        }
Esempio n. 24
0
 public bool Send(byte[] data, int size)
 {
     return(SocketHelpers.Send(socket, data, 0, size));
 }
Esempio n. 25
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
            var ipEndPoint = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 21);

            m_socketListen = SocketHelpers.CreateTcpListener(ipEndPoint);

            if (m_socketListen != null)
            {
                Console.WriteLine("Information: FTP Server listened at: " + ipEndPoint);

                m_socketListen.Start();

                Console.WriteLine("Information: 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 if (m_apConnections.Count >= m_maxClients)
                        {
                            Console.WriteLine(
                                "Warning: Too many clients, won't handle this connection");
                            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");
            }
        }
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();
            if (sMessage == "")
            {
                return(GetMessage(501, string.Format("{0} needs a parameter", Command)));
            }

            string sFilePath = GetPath(sMessage);

            if (!ConnectionObject.FileSystemObject.FileExists(sFilePath))
            {
                return(GetMessage(550, string.Format("File \"{0}\" doesn't exist", sMessage)));
            }

            var socketData = new FtpDataSocket(ConnectionObject);

            if (!socketData.Loaded)
            {
                return(GetMessage(425, "Unable to establish the data connection"));
            }

            SocketHelpers.Send(ConnectionObject.Socket, "150 Starting data transfer, please wait...\r\n", ConnectionObject.Encoding);

            IFile file = ConnectionObject.FileSystemObject.OpenFile(sFilePath, false);

            if (file == null)
            {
                return(GetMessage(550, "Couldn't open file"));
            }

            // TYPE I, default
            if (ConnectionObject.DataType == DataType.Image)
            {
                var abBuffer = new byte[m_nBufferSize];

                int nRead = file.Read(abBuffer, m_nBufferSize);

                while (nRead > 0 && socketData.Send(abBuffer, nRead))
                {
                    nRead = file.Read(abBuffer, m_nBufferSize);
                }
            }
            // TYPE A
            else if (ConnectionObject.DataType == DataType.Ascii)
            {
                int writeSize = SocketHelpers.CopyStreamAscii(file.BlobStream, socketData.Socket.GetStream(), m_nBufferSize);
                FtpServerMessageHandler.SendMessage(ConnectionObject.Id, string.Format("Use ascii type success, write {0} chars!", writeSize));
            }
            else // mustn't reach
            {
                file.Close();
                socketData.Close();
                return(GetMessage(451, "Error in transfer data: invalid data type."));
            }

            file.Close();
            socketData.Close();

            return(GetMessage(226, "File download succeeded."));
        }
Esempio n. 27
0
        protected override string OnProcess(string sMessage)
        {
            sMessage = sMessage.Trim();

            if (sMessage == "")
            {
                return(GetMessage(211, "Server status: OK"));
            }

            // if no parameter is given, STAT works as LIST
            // but won't use data connection
            string[] asFiles       = null;
            string[] asDirectories = null;

            // Get the file/dir to list
            string targetToList = GetPath(sMessage);

            // checks the file/dir name
            if (!FileNameHelpers.IsValid(targetToList))
            {
                return(GetMessage(501, string.Format("\"{0}\" is not a valid file/directory name", sMessage)));
            }

            // two vars indicating different list results
            bool targetIsFile = false;
            bool targetIsDir  = false;

            // targetToList ends with '/', must be a directory
            if (targetToList.EndsWith(@"/"))
            {
                targetIsFile = false;
                if (ConnectionObject.FileSystemObject.DirectoryExists(targetToList))
                {
                    targetIsDir = true;
                }
            }
            else
            {
                // check whether the target to list is a directory
                if (ConnectionObject.FileSystemObject.DirectoryExists(FileNameHelpers.AppendDirTag(targetToList)))
                {
                    targetIsDir = true;
                }
                // check whether the target to list is a file
                if (ConnectionObject.FileSystemObject.FileExists(targetToList))
                {
                    targetIsFile = true;
                }
            }

            if (targetIsFile)
            {
                asFiles = new string[1] {
                    targetToList
                };
                if (targetIsDir)
                {
                    asDirectories = new string[1] {
                        FileNameHelpers.AppendDirTag(targetToList)
                    }
                }
                ;
            }
            // list a directory
            else if (targetIsDir)
            {
                targetToList  = FileNameHelpers.AppendDirTag(targetToList);
                asFiles       = ConnectionObject.FileSystemObject.GetFiles(targetToList);
                asDirectories = ConnectionObject.FileSystemObject.GetDirectories(targetToList);
            }
            else
            {
                return(GetMessage(550, string.Format("\"{0}\" not exists", sMessage)));
            }

            // generate the response
            string sFileList = BuildReply(asFiles, asDirectories);

            SocketHelpers.Send(ConnectionObject.Socket, string.Format("213-Begin STAT \"{0}\":\r\n", sMessage), ConnectionObject.Encoding);

            SocketHelpers.Send(ConnectionObject.Socket, sFileList, ConnectionObject.Encoding);

            return(GetMessage(213, string.Format("{0} successful.", Command)));
        }
Esempio n. 28
0
 public void Stop()
 {
     SocketHelpers.Close(m_theSocket);
     m_theThread.Join();
     m_theMonitorThread.Join();
 }
Esempio n. 29
0
 public void Close()
 {
     SocketHelpers.Close(socket);
     this.socket = null;
 }
Esempio n. 30
0
 private void SendRejectMessage(TcpClient socket)
 {
     SocketHelpers.Send(socket, m_encoding.GetBytes("421 Too many users now\r\n"));
 }