Example #1
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            session.Send(session.AppServer.FeaturesResponse);
        }
Example #2
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (session.AppServer.Certificate == null)
            {
                session.Send(FtpCoreResource.AuthError_504);
                return;
            }

            string ssl = requestInfo.Body;

            switch (ssl)
            {
                case ("SSL"):
                    session.SecureProtocol = SslProtocols.Ssl3;
                    break;
                case ("SSL2"):
                    session.SecureProtocol = SslProtocols.Ssl2;
                    break;
                case ("TLS"):
                    session.SecureProtocol = SslProtocols.Tls;
                    break;
                default:
                    session.Send(FtpCoreResource.AuthError_504);
                    return;
            }

            session.Send(FtpCoreResource.AuthOk_234, ssl);

            session.AppServer.ResetSessionSecurity(session, session.SecureProtocol);
        }
Example #3
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            DataConnection dataConnection;

            if (DataConnection.TryOpenDataConnection(session, out dataConnection))
            {
                var port = dataConnection.Port;

                var localAddress = session.AppServer.ExternalLocalAddress;

                if(string.IsNullOrEmpty(localAddress))
                    localAddress = ((IPEndPoint)session.LocalEndPoint).Address.ToString();

                string address = localAddress.Replace('.', ',') + "," + (port >> 8) + "," + (port & 0xFF);
                session.DataConnection = dataConnection;
                session.Send(FtpCoreResource.PassiveEnter_227, address);
            }
            else
            {
                session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
            }
        }
Example #4
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (session.AppServer.Certificate == null)
            {
                session.Send(FtpCoreResource.AuthError_504);
                return;
            }

            string ssl = requestInfo.Body;

            switch (ssl)
            {
            case ("SSL"):
                session.SecureProtocol = SslProtocols.Ssl3;
                break;

            case ("SSL2"):
                session.SecureProtocol = SslProtocols.Ssl2;
                break;

            case ("TLS"):
                session.SecureProtocol = SslProtocols.Tls;
                break;

            default:
                session.Send(FtpCoreResource.AuthError_504);
                return;
            }

            session.Send(FtpCoreResource.AuthOk_234, ssl);

            session.AppServer.ResetSessionSecurity(session, session.SecureProtocol);
        }
Example #5
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            string foldername = requestInfo.Body;

            if (string.IsNullOrEmpty(foldername))
            {
                session.SendParameterError();
                return;
            }

            if (session.AppServer.FtpServiceProvider.CreateFolder(session.Context, foldername))
            {
                session.Send(FtpCoreResource.MakeDirOk_250, session.Context.CurrentPath + "/" + foldername);
            }
            else
            {
                session.Send(session.Context.Message);
            }
        }
Example #6
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (session.Logged)
            {
                session.Send(FtpCoreResource.AlreadyLoggedIn_230);
                return;
            }

            string username = requestInfo.Body;

            if (string.IsNullOrEmpty(username))
            {
                session.SendParameterError();
                return;
            }
            else if (string.Compare(username, "anonymous", StringComparison.OrdinalIgnoreCase) == 0)
            {
                session.Send(FtpCoreResource.RequirePasswor_331, username);
                session.Context.UserName = username;
                return;
            }
            else
            {
                session.Send(FtpCoreResource.RequirePasswor_331, username);
                session.Context.UserName = username;
                return;
            }
        }
Example #7
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string filepath = requestInfo.Body;

            if (string.IsNullOrEmpty(filepath))
            {
                session.SendParameterError();
                return;
            }

            if (session.AppServer.FtpServiceProvider.IsExistFile(session.Context, filepath))
            {
                session.Context.RenameFor = filepath;
                session.Context.RenameItemType = ItemType.File;
                session.Send(FtpCoreResource.RenameForOk_350);
            }
            else if (session.AppServer.FtpServiceProvider.IsExistFolder(session.Context, filepath))
            {
                session.Context.RenameFor = filepath;
                session.Context.RenameItemType = ItemType.Folder;
                session.Send(FtpCoreResource.RenameForOk_350);
            }
            else
            {
                session.Send(session.Context.Message);
            }
        }
Example #8
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                return;
            }

            DataConnection dataConnection;

            if (DataConnection.TryOpenDataConnection(session, out dataConnection))
            {
                var port = dataConnection.Port;

                var localAddress = session.AppServer.ExternalLocalAddress;

                if (string.IsNullOrEmpty(localAddress))
                {
                    localAddress = ((IPEndPoint)session.LocalEndPoint).Address.ToString();
                }

                string address = localAddress.Replace('.', ',') + "," + (port >> 8) + "," + (port & 0xFF);
                session.DataConnection = dataConnection;
                session.Send(FtpCoreResource.PassiveEnter_227, address);
            }
            else
            {
                session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
            }
        }
Example #9
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string newfileName = requestInfo.Body;

            if (string.IsNullOrEmpty(newfileName))
            {
                session.SendParameterError();
                return;
            }

            if (session.Context.RenameItemType == ItemType.File)
            {
                if (!session.AppServer.FtpServiceProvider.RenameFile(session.Context, session.Context.RenameFor, newfileName))
                {
                    session.Send(session.Context.Message);
                    return;
                }
            }
            else
            {
                if (!session.AppServer.FtpServiceProvider.RenameFolder(session.Context, session.Context.RenameFor, newfileName))
                {
                    session.Send(session.Context.Message);
                    return;
                }
            }

            session.Send(FtpCoreResource.RenameToOk_250);
        }
Example #10
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            if (string.IsNullOrEmpty(session.Context.CurrentPath) || session.Context.CurrentPath == "/")
            {
                session.Send(FtpCoreResource.NotFound_550);
                return;
            }

            string path = StringUtil.GetParentDirectory(session.Context.CurrentPath, '/');

            //No parent path, so it's root
            if (string.IsNullOrEmpty(path))
                path = "/";

            if (session.AppServer.FtpServiceProvider.IsExistFolder(session.Context, path))
            {
                session.Context.CurrentPath = path;
                session.Send(string.Format(FtpCoreResource.ChangeDirectoryUp_250, path));
            }
            else
            {
                if (session.Context.Status == FtpStatus.Error)
                    session.Send(session.Context.Message);
                else
                    session.Send(FtpCoreResource.NotFound_550);
            }
        }
Example #11
0
        /// <summary>
        /// Releases the instance (deferences it from the session locks).
        /// </summary>
        /// <param name="expectEndReply">if set to <c>true</c> [expect end reply].</param>
        private void Release(bool expectEndReply)
        {
            var session = Session;

            if (session != null)
            {
                Session = null;
                try
                {
                    if (expectEndReply)
                    {
                        Process(() => session.Expect(
                                    226, // default ack
                                    150  // if the stream was opened but nothing was sent, then we still shall exit gracefully
                                    ));
                    }
                }
                // on long transfers, the command socket may be closed
                // however we need to signal it to client
                finally
                {
                    session.Connection.Release();
                }
            }
        }
Example #12
0
 public override void ExecuteCommand(FtpSession session, StringRequestInfo reuquestInfo)
 {
     session.Context.ResetState();
     //Close current data connection?
     session.CloseDataConnection();
     session.Send(FtpCoreResource.AbortOk_226);
 }
Example #13
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            long size = session.AppServer.FtpServiceProvider.GetFileSize(session.Context, filename);

            if (session.Context.Status == FtpStatus.Error)
            {
                session.Send(session.Context.Message);
            }
            else
            {
                session.Send(FtpCoreResource.SizeOk_213, size);
            }
        }
Example #14
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                return;
            }

            string newfileName = requestInfo.Body;

            if (string.IsNullOrEmpty(newfileName))
            {
                session.SendParameterError();
                return;
            }

            if (session.Context.RenameItemType == ItemType.File)
            {
                if (!session.AppServer.FtpServiceProvider.RenameFile(session.Context, session.Context.RenameFor, newfileName))
                {
                    session.Send(session.Context.Message);
                    return;
                }
            }
            else
            {
                if (!session.AppServer.FtpServiceProvider.RenameFolder(session.Context, session.Context.RenameFor, newfileName))
                {
                    session.Send(session.Context.Message);
                    return;
                }
            }

            session.Send(FtpCoreResource.RenameToOk_250);
        }
Example #15
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            session.Send(Environment.OSVersion.ToString());
        }
Example #16
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                return;
            }

            string filepath = requestInfo.Body;

            if (string.IsNullOrEmpty(filepath))
            {
                session.SendParameterError();
                return;
            }

            if (session.AppServer.FtpServiceProvider.IsExistFile(session.Context, filepath))
            {
                session.Context.RenameFor      = filepath;
                session.Context.RenameItemType = ItemType.File;
                session.Send(FtpCoreResource.RenameForOk_350);
            }
            else if (session.AppServer.FtpServiceProvider.IsExistFolder(session.Context, filepath))
            {
                session.Context.RenameFor      = filepath;
                session.Context.RenameItemType = ItemType.Folder;
                session.Send(FtpCoreResource.RenameForOk_350);
            }
            else
            {
                session.Send(session.Context.Message);
            }
        }
Example #17
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            char typeCode = ' ';

            string newType = requestInfo.GetFirstParam();

            if (!string.IsNullOrEmpty(newType) && newType.Length > 0)
            {
                typeCode = newType[0];
            }

            switch (typeCode)
            {
                case ('A'):
                    session.Context.TransferType = TransferType.A;
                    break;
                case ('E'):
                    session.Context.TransferType = TransferType.E;
                    break;
                case ('I'):
                    session.Context.TransferType = TransferType.I;
                    break;
                case ('L'):
                    session.Context.TransferType = TransferType.L;
                    break;
                default:
                    session.SendParameterError();
                    return;
            }

            session.Send(FtpCoreResource.TypeOk_220, typeCode);
        }
Example #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FtpPassiveStream" /> class.
 /// </summary>
 /// <param name="socket">The socket.</param>
 /// <param name="session">The session.</param>
 /// <param name="mode">The mode.</param>
 /// <param name="lazy">if set to <c>true</c> [lazy].</param>
 /// <exception cref="IOException">The <paramref name="socket" /> parameter is not connected.-or- The <see cref="P:System.Net.Sockets.Socket.SocketType" /> property of the <paramref name="socket" /> parameter is not <see cref="F:System.Net.Sockets.SocketType.Stream" />.-or- The <paramref name="socket" /> parameter is in a nonblocking state.</exception>
 /// <exception cref="SocketException">An error occurred when attempting to access the socket.</exception>
 internal FtpPassiveStream(Socket socket, FtpSession session, FtpStreamMode?mode, bool lazy)
 {
     _mode   = mode;
     Session = session;
     Session.Connection.AddReference();
     SetSocket(socket, lazy);
 }
Example #19
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            string param = requestInfo.Body;
            if (string.IsNullOrEmpty(requestInfo.Body))
                param = Guid.NewGuid().ToString();

            base.ExecuteCommand(session, new StringRequestInfo(requestInfo.Key, param, new string[]{ }));
        }
 public DataConnection(FtpSession session, Socket listenSocket, int port)
 {
     m_Session = session;
     m_Address = session.Config.Ip;
     SecureProtocol = session.Context.DataSecureProtocol;
     m_Listener = listenSocket;
     m_Port = port;
 }
Example #21
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                return;
            }

            session.Send(Environment.OSVersion.ToString());
        }
Example #22
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            if (!string.IsNullOrEmpty(requestInfo.Body))
            {
                if (requestInfo.Body.StartsWith(FtpPath.Root))
                {
                    session.Context.CurrentPath = requestInfo.Body;
                }
                else
                {
                    session.Context.CurrentPath = FtpPath.Combine(session.Context.CurrentPath, requestInfo.Body);
                }
            }

            List <ListItem> list = session.AppServer.FtpServiceProvider.GetList(session.Context);

            if (session.Context.Status == FtpStatus.Error)
            {
                session.Send(session.Context.Message);
                return;
            }

            DataConnection dataConn = session.DataConnection;

            if (dataConn != null && dataConn.RunDataConnection().Wait(60 * 1000))
            {
                session.Send(FtpCoreResource.DataConnectionAccepted_150);

                try
                {
                    dataConn.SendResponse(session.Context, list);
                }
                catch (Exception e)
                {
                    session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
                    session.Logger.Error(e);
                    return;
                }
                finally
                {
                    session.CloseDataConnection();
                }

                session.Send(FtpCoreResource.DataTransferComplete_226);
            }
            else
            {
                session.CloseDataConnection();
                session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
            }
        }
Example #23
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                return;
            }

            session.Send(session.AppServer.FeaturesResponse);
        }
Example #24
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            session.Send(session.AppServer.FeaturesResponse);
        }
Example #25
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            session.Send(Environment.OSVersion.ToString());
        }
Example #26
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            DataConnection dataConn = session.DataConnection;

            if (dataConn.RunDataConnection().Wait(60 * 1000))
            {
                Stream stream = dataConn.GetStream(session.Context);

                try
                {
                    session.Send(FtpCoreResource.DataConnectionAccepted_150);

                    if (session.AppServer.FtpServiceProvider.StoreFile(session.Context, filename, stream))
                    {
                        session.Send(FtpCoreResource.DataTransferComplete_226);
                    }
                    else
                    {
                        session.Send(session.Context.Message);
                    }
                }
                catch (SocketException)
                {
                    session.Send(FtpCoreResource.DataConnectionError_426);
                }
                catch (Exception e)
                {
                    session.Logger.Error(e);
                    session.Send(FtpCoreResource.OuputFileError_551);
                }
                finally
                {
                    session.CloseDataConnection();
                }
            }
            else
            {
                session.CloseDataConnection();
                session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
            }
        }
Example #27
0
        public void Execute(FtpRequest request, FtpSession session) {

            if (request.Arguments == null || request.Arguments.Trim() == "") {
                session.Send("501 Missing User Name Argument");
                return;
            }

            //record user name input
            session.SetData(UserDataKey, request.Arguments);
            session.Send("331 Send Password Command");
        }
Example #28
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            long offset = requestInfo.Body.ToLong();

            session.Context.Offset = offset;

            session.Send(FtpCoreResource.RestartOk_350, offset);
        }
Example #29
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            string param = requestInfo.Body;

            if (string.IsNullOrEmpty(requestInfo.Body))
            {
                param = Guid.NewGuid().ToString();
            }

            base.ExecuteCommand(session, new StringRequestInfo(requestInfo.Key, param, new string[] { }));
        }
Example #30
0
        public void Execute(FtpRequest request, FtpSession session) {
            var inputUser = session.GetData(User.UserDataKey);
            var inputPass = request.Arguments;

            if (inputUser == null) {
                session.Send(SendUserFirst);
                return;    
            }


            session.Authenticate(inputUser, inputPass);
        }
Example #31
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (session.Logged)
            {
                session.Send(FtpCoreResource.AlreadyLoggedIn_230);
                return;
            }

            string password = requestInfo.Body;

            if (string.IsNullOrEmpty(password))
            {
                session.SendParameterError();
                return;
            }

            FtpUser user = null;

            AuthenticationResult result = AuthenticationResult.Success;

            //if (session.Context.IsAnonymous)
            //    user = new Anonymous();
            //else

            result = session.AppServer.FtpServiceProvider.Authenticate(session.Context.UserName, password, out user);

            if (result == AuthenticationResult.Success)
            {
                session.FailedLogInTimes = 0;

                if (session.AppServer.Logon(session.Context, user))
                {
                    session.Send(FtpCoreResource.LoggedIn_230);
                    session.Logged = true;
                }
                else
                {
                    session.Send(FtpCoreResource.ReachedLoginLimit_421);
                    session.Close();
                }
            }
            else
            {
                session.FailedLogInTimes++;
                session.Send(FtpCoreResource.AuthenticationFailed_530);

                //Exceed max allowed failed login times, close the connection
                if (session.FailedLogInTimes >= session.AppServer.MaxFailedLogInTimes)
                {
                    session.Close();
                }
            }
        }
Example #32
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                return;
            }

            long offset = requestInfo.Body.ToLong();

            session.Context.Offset = offset;

            session.Send(FtpCoreResource.RestartOk_350, offset);
        }
Example #33
0
        public void Setup()
        {
            channelCounter = 0;
            mainChannel    = MockRepository.GenerateStub <IFtpChannel>();
            dataChannel    = MockRepository.GenerateMock <IFtpChannel>();

            channelFactory = MockRepository.GenerateStub <IFtpChannelFactory>();
            channelFactory.Stub(x => x.CreateChannel()).Do(new Func <IFtpChannel>(CreateChannel));

            communicator = MockRepository.GenerateMock <IFtpCommunicator>();
            fileSystem   = MockRepository.GenerateMock <IFileSystem>();
            session      = new FtpSession(channelFactory, communicator, fileSystem);
        }
Example #34
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (session.Logged)
            {
                session.Send(FtpCoreResource.AlreadyLoggedIn_230);
                return;
            }

            string password = requestInfo.Body;

            if (string.IsNullOrEmpty(password))
            {
                session.SendParameterError();
                return;
            }

            FtpUser user = null;

            AuthenticationResult result = AuthenticationResult.Success;

            //if (session.Context.IsAnonymous)
            //    user = new Anonymous();
            //else

            result = session.AppServer.FtpServiceProvider.Authenticate(session.Context.UserName, password, out user);

            if (result == AuthenticationResult.Success)
            {
                session.FailedLogInTimes = 0;

                if (session.AppServer.Logon(session.Context, user))
                {
                    session.Send(FtpCoreResource.LoggedIn_230);
                    session.Logged = true;
                }
                else
                {
                    session.Send(FtpCoreResource.ReachedLoginLimit_421);
                    session.Close();
                }
            }
            else
            {
                session.FailedLogInTimes++;
                session.Send(FtpCoreResource.AuthenticationFailed_530);

                //Exceed max allowed failed login times, close the connection
                if(session.FailedLogInTimes >= session.AppServer.MaxFailedLogInTimes)
                    session.Close();
            }
        }
Example #35
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            if (!string.IsNullOrEmpty(requestInfo.Body))
            {
                if (requestInfo.Body.StartsWith(FtpPath.Root))
                    session.Context.CurrentPath = requestInfo.Body;
                else
                    session.Context.CurrentPath = FtpPath.Combine(session.Context.CurrentPath, requestInfo.Body);
            }

            List<ListItem> list = session.AppServer.FtpServiceProvider.GetList(session.Context);

            if (session.Context.Status == FtpStatus.Error)
            {
                session.Send(session.Context.Message);
                return;
            }

            DataConnection dataConn = session.DataConnection;

            if (dataConn != null && dataConn.RunDataConnection().Wait(60 * 1000))
            {
                session.Send(FtpCoreResource.DataConnectionAccepted_150);

                try
                {
                    dataConn.SendResponse(session.Context, list);
                }
                catch (Exception e)
                {
                    session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
                    session.Logger.Error(e);
                    return;
                }
                finally
                {
                    session.CloseDataConnection();
                }
                
                session.Send(FtpCoreResource.DataTransferComplete_226);
            }
            else
            {
                session.CloseDataConnection();
                session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
            }
        }
Example #36
0
        public void InvalidPassword()
        {
            FtpConnectionData connectionData = new FtpConnectionData();

            connectionData.Credentials = new NetworkCredential(Username, Password + "xxx");
            connectionData.Host        = Host;

            using (IFtpSession session
                       = new FtpSession(new FtpChannelFactoryUsingSockets(), new FtpCommunicator(), new WindowsFileSystem()))
            {
                var ex = Assert.Throws <FtpException>(delegate { session.BeginSession(connectionData); });
                Assert.AreEqual("Could not log in to the FTP server: 530 User cannot log in.", ex.Message);
            }
        }
            internal PendingFileTransfer(NetworkHost dataSessionClient, ushort?dataSessionClientPort, NetworkHost dataSessionServer, ushort dataSessionServerPort, bool dataSessionIsPassive, FtpSession ftpControlSession)
            {
                this.dataSessionClient     = dataSessionClient;
                this.dataSessionClientPort = dataSessionClientPort;
                this.dataSessionServer     = dataSessionServer;
                this.dataSessionServerPort = dataSessionServerPort;

                this.dataSessionIsPassive = dataSessionIsPassive;
                this.fileDirectionIsDataSessionServerToDataSessionClient = null;
                this.fileTransferSessionEstablished = false;

                this.ftpControlSession = ftpControlSession;
                this.filename          = null;
                this.details           = "";
            }
Example #38
0
        private static void FtpAction(Action <IFtpSession> action)
        {
            FtpConnectionData connectionData = new FtpConnectionData();

            connectionData.Credentials = new NetworkCredential(Username, Password);
            connectionData.Host        = Host;
            connectionData.Port        = Port;

            using (IFtpSession session
                       = new FtpSession(new FtpChannelFactoryUsingSockets(), new FtpCommunicator(), new WindowsFileSystem()))
            {
                session.BeginSession(connectionData);
                action(session);
            }
        }
        protected override async Task <Action <NativeActivityContext> > ExecuteAsync(NativeActivityContext context, CancellationToken cancellationToken)
        {
            IFtpSession      ftpSession       = null;
            FtpConfiguration ftpConfiguration = new FtpConfiguration(Host.Get(context));

            ftpConfiguration.Port = Port.Expression == null ? null : (int?)Port.Get(context);
            ftpConfiguration.UseAnonymousLogin         = UseAnonymousLogin;
            ftpConfiguration.SslProtocols              = SslProtocols;
            ftpConfiguration.ClientCertificatePath     = ClientCertificatePath.Get(context);
            ftpConfiguration.ClientCertificatePassword = ClientCertificatePassword.Get(context);
            ftpConfiguration.AcceptAllCertificates     = AcceptAllCertificates;

            if (ftpConfiguration.UseAnonymousLogin == false)
            {
                ftpConfiguration.Username = Username.Get(context);
                ftpConfiguration.Password = Password.Get(context);

                if (string.IsNullOrWhiteSpace(ftpConfiguration.Username))
                {
                    throw new ArgumentNullException(Resources.EmptyUsernameException);
                }

                if (string.IsNullOrWhiteSpace(ftpConfiguration.Password) && string.IsNullOrWhiteSpace(ftpConfiguration.ClientCertificatePath))
                {
                    throw new ArgumentNullException(Resources.NoValidAuthenticationMethod);
                }
            }

            if (UseSftp)
            {
                ftpSession = new SftpSession(ftpConfiguration);
            }
            else
            {
                ftpSession = new FtpSession(ftpConfiguration, FtpsMode);
            }

            await ftpSession.OpenAsync(cancellationToken);

            return((nativeActivityContext) =>
            {
                if (Body != null)
                {
                    _ftpSession = ftpSession;
                    nativeActivityContext.ScheduleAction(Body, ftpSession, OnCompleted, OnFaulted);
                }
            });
        }
Example #40
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            string path = requestInfo.Body;

            if (string.IsNullOrEmpty(path))
            {
                session.SendParameterError();
                return;
            }

            if (!path.StartsWith("/"))
            {
                var context     = session.Context;
                var currentPath = context.CurrentPath;

                if (currentPath == "/")
                {
                    path = currentPath + path;
                }
                else
                {
                    path = currentPath + "/" + path;
                }
            }

            if (session.AppServer.FtpServiceProvider.IsExistFolder(session.Context, path))
            {
                session.Context.CurrentPath = path;
                session.Send(FtpCoreResource.ChangeWorkDirOk_250, path);
            }
            else
            {
                if (session.Context.Status == FtpStatus.Error)
                {
                    session.Send(session.Context.Message);
                }
                else
                {
                    session.Send(FtpCoreResource.NotFound_550);
                }
            }
        }
Example #41
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            DataConnection dataConn = session.DataConnection;

            if (dataConn.RunDataConnection().Wait(60 * 1000))
            {
                Stream stream = dataConn.GetStream(session.Context);

                try
                {
                    session.Send(FtpCoreResource.DataConnectionAccepted_150);

                    if (session.AppServer.FtpServiceProvider.StoreFile(session.Context, filename, stream))
                        session.Send(FtpCoreResource.DataTransferComplete_226);
                    else
                        session.Send(session.Context.Message);
                }
                catch (SocketException)
                {
                    session.Send(FtpCoreResource.DataConnectionError_426);
                }
                catch (Exception e)
                {
                    session.Logger.Error(e);
                    session.Send(FtpCoreResource.OuputFileError_551);
                }
                finally
                {
                    session.CloseDataConnection();
                }
            }
            else
            {
                session.CloseDataConnection();
                session.Send(FtpCoreResource.DataConnectionCannotOpen_420);
            }
        }
Example #42
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            if (session.SecureProtocol == SslProtocols.None)
            {
                session.Send(FtpCoreResource.ProtDisabled_431);
                return;
            }

            string level = requestInfo.Body;

            if (string.IsNullOrEmpty(level) || level.Length > 1)
            {
                session.SendParameterError();
                return;
            }

            switch (level[0])
            {
            case ('C'):
            case ('c'):
                session.Context.DataSecureProtocol = SslProtocols.None;
                break;

            case ('P'):
            case ('p'):
                session.Context.DataSecureProtocol = session.SecureProtocol;
                break;

            default:
                session.Send(FtpCoreResource.ProtectionLevelUnknow_504);
                return;
            }

            session.Context.ResetState();
            session.Send(FtpCoreResource.ProtOk_200);
        }
Example #43
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            long size = session.AppServer.FtpServiceProvider.GetFileSize(session.Context, filename);

            if (session.Context.Status == FtpStatus.Error)
                session.Send(session.Context.Message);
            else
                session.Send(FtpCoreResource.SizeOk_213, size);
        }
Example #44
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string path = requestInfo.Body;

            if (string.IsNullOrEmpty(path))
            {
                session.SendParameterError();
                return;
            }

            if (!path.StartsWith("/"))
            {
                var context = session.Context;
                var currentPath = context.CurrentPath;

                if (currentPath == "/")
                {
                    path = currentPath + path;
                }
                else
                {
                    path = currentPath + "/" + path;
                }
            }

            if (session.AppServer.FtpServiceProvider.IsExistFolder(session.Context, path))
            {
                session.Context.CurrentPath = path;
                session.Send(FtpCoreResource.ChangeWorkDirOk_250, path);
            }
            else
            {
                if (session.Context.Status == FtpStatus.Error)
                    session.Send(session.Context.Message);
                else
                    session.Send(FtpCoreResource.NotFound_550);
            }
        }
Example #45
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            DateTime mdfTime = session.AppServer.FtpServiceProvider.GetModifyTime(session.Context, filename);

            if (session.Context.Status == FtpStatus.Error)
            {
                session.Send(session.Context.Message);
            }
            else
            {
                session.Send(string.Format(FtpCoreResource.FileOk_213, mdfTime.ToString("yyyyMMddhhmmss")));
            }
        }
Example #46
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            DateTime mdfTime = session.AppServer.FtpServiceProvider.GetModifyTime(session.Context, filename);

            if (session.Context.Status == FtpStatus.Error)
            {
                session.Send(session.Context.Message);
            }
            else
            {
                session.Send(string.Format(FtpCoreResource.FileOk_213, mdfTime.ToString("yyyyMMddhhmmss")));
            }
        }
Example #47
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            string address = requestInfo.GetFirstParam();

            string[] arrAddress = new string[0];

            if (!string.IsNullOrEmpty(address))
            {
                arrAddress = address.Split(',');
            }

            if (arrAddress == null || arrAddress.Length != 6)
            {
                session.SendParameterError();
                return;
            }

            string ip   = arrAddress[0] + "." + arrAddress[1] + "." + arrAddress[2] + "." + arrAddress[3];
            int    port = (Convert.ToInt32(arrAddress[4]) << 8) | Convert.ToInt32(arrAddress[5]);

            DataConnection dataConnection;

            if (DataConnection.TryOpenDataConnection(session, port, out dataConnection))
            {
                session.DataConnection = dataConnection;
                session.Send(FtpCoreResource.PortOk_220);
                return;
            }
            else
            {
                session.Send(FtpCoreResource.PortInvalid_552);
                return;
            }
        }
Example #48
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
            {
                session.Send(FtpCoreResource.AuthenticationFailed_530);
                return;
            }

            if (string.IsNullOrEmpty(session.Context.CurrentPath) || session.Context.CurrentPath == "/")
            {
                session.Send(FtpCoreResource.NotFound_550);
                return;
            }

            string path = StringUtil.GetParentDirectory(session.Context.CurrentPath, '/');

            //No parent path, so it's root
            if (string.IsNullOrEmpty(path))
            {
                path = "/";
            }

            if (session.AppServer.FtpServiceProvider.IsExistFolder(session.Context, path))
            {
                session.Context.CurrentPath = path;
                session.Send(string.Format(FtpCoreResource.ChangeDirectoryUp_250, path));
            }
            else
            {
                if (session.Context.Status == FtpStatus.Error)
                {
                    session.Send(session.Context.Message);
                }
                else
                {
                    session.Send(FtpCoreResource.NotFound_550);
                }
            }
        }
Example #49
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string foldername = requestInfo.Body;

            if (string.IsNullOrEmpty(foldername))
            {
                session.SendParameterError();
                return;
            }

            if (session.AppServer.FtpServiceProvider.RemoveFolder(session.Context, foldername))
            {
                session.Send(FtpCoreResource.RemoveOk_250, CombinePath(session.Context.CurrentPath, foldername));
            }
            else
            {
                session.Send(session.Context.Message);
            }
        }
Example #50
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string filename = requestInfo.Body;

            if (string.IsNullOrEmpty(filename))
            {
                session.SendParameterError();
                return;
            }

            if (session.AppServer.FtpServiceProvider.DeleteFile(session.Context, filename))
            {
                session.Send(FtpCoreResource.DeleteOk_250);
            }
            else
            {
                session.Send(session.Context.Message);
            }
        }
Example #51
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            if (session.SecureProtocol == SslProtocols.None)
            {
                session.Send(FtpCoreResource.ProtDisabled_431);
                return;
            }

            string level = requestInfo.Body;

            if (string.IsNullOrEmpty(level) || level.Length > 1)
            {
                session.SendParameterError();
                return;
            }

            switch (level[0])
            {
                case ('C'):
                case ('c'):
                    session.Context.DataSecureProtocol = SslProtocols.None;
                    break;
                case ('P'):
                case ('p'):
                    session.Context.DataSecureProtocol = session.SecureProtocol;
                    break;
                default:
                    session.Send(FtpCoreResource.ProtectionLevelUnknow_504);
                    return;
            }

            session.Context.ResetState();
            session.Send(FtpCoreResource.ProtOk_200);
        }
Example #52
0
        public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
        {
            if (!session.Logged)
                return;

            string address = requestInfo.GetFirstParam();

            string[] arrAddress = new string[0];

            if (!string.IsNullOrEmpty(address))
            {
                arrAddress = address.Split(',');
            }

            if (arrAddress == null || arrAddress.Length != 6)
            {
                session.SendParameterError();
                return;
            }

            //string ip = arrAddress[0] + "." + arrAddress[1] + "." + arrAddress[2] + "." + arrAddress[3];
            int port = (Convert.ToInt32(arrAddress[4]) << 8) | Convert.ToInt32(arrAddress[5]);

            DataConnection dataConnection;
            if (DataConnection.TryOpenDataConnection(session, port, out dataConnection))
            {
                session.DataConnection = dataConnection;
                session.Send(FtpCoreResource.PortOk_220);
                return;
            }
            else
            {
                session.Send(FtpCoreResource.PortInvalid_552);
                return;
            }
        }
        public virtual void Close()
        {
            StopListener();

            if (Client != null && !m_IsClosed)
            {
                try
                {
                    Client.Shutdown(SocketShutdown.Both);
                }
                catch (Exception e)
                {
                    m_Session.Logger.Error(e);
                }

                try
                {
                    Client.Close();
                }
                catch (Exception e)
                {
                    m_Session.Logger.Error(e);
                }
                finally
                {
                    Client = null;
                    m_Session = null;
                    m_IsClosed = true;
                    OnClose();
                }
            }
        }
        internal static bool TryOpenDataConnection(FtpSession session, out DataConnection dataConnection)
        {
            dataConnection = null;

            int tryPort = session.AppServer.FtpServiceProvider.GetRandomPort();
            int previousPort = tryPort;
            int tryTimes = 0;

            IPAddress ipAddress = session.LocalEndPoint.Address;

            while (true)
            {
                var listenSocket = TryListenSocketPort(ipAddress, tryPort);

                if (listenSocket != null)
                {
                    dataConnection = new DataConnection(session, listenSocket, tryPort);
                    return true;
                }

                tryTimes++;

                if (tryTimes > 5)
                {
                    return false;
                }

                tryPort = session.AppServer.FtpServiceProvider.GetRandomPort();

                if (previousPort == tryPort)
                {
                    return false;
                }
            }
        }
        internal static bool TryOpenDataConnection(FtpSession session, int port, out DataConnection dataConnection)
        {
            IPAddress ipAddress = session.LocalEndPoint.Address;
            var listenSocket = TryListenSocketPort(ipAddress, port);

            if (listenSocket != null)
            {
                dataConnection = new DataConnection(session, listenSocket, port);
                return true;
            }

            dataConnection = null;
            return false;
        }
Example #56
0
 /// <summary>
 ///   Initializes a new instance of the <see cref="FtpSessionState" /> class.
 /// </summary>
 /// <param name="ftpSession"> The FTP session. </param>
 internal FtpSessionState(FtpSession ftpSession)
 {
     _ftpSession = ftpSession;
 }
Example #57
0
 public override void ExecuteCommand(FtpSession session, StringRequestInfo requestInfo)
 {
     session.Send(FtpCoreResource.NoopOk_200);
 }