public ICommand CreateCommand(IFtpMessage ftpMessage, IExecutorState executorState)
        {
            switch (ftpMessage.CommandName)
            {
            case ProcessingClientCommand.Prot:
                return(new ProtCommand(executorState, ftpMessage));

            case ProcessingClientCommand.Pbsz:
                return(new PbszCommand(executorState, ftpMessage));

            case ProcessingClientCommand.Rein:     // Блок недоступных команд
                return(new UnavailableCommand(executorState, ftpMessage));

            case ProcessingClientCommand.Port:
            case ProcessingClientCommand.Eprt:
                return(new ActiveDataConnectionCommand(executorState, ftpMessage, _connectionFactory,
                                                       _commandExecutorHelper));

            case ProcessingClientCommand.Pasv:
            case ProcessingClientCommand.Epsv:
                return(new PassiveDataConnectionCommand(executorState, ftpMessage, _connectionFactory,
                                                        _commandExecutorHelper));
            }
            return(new OtherCommand(executorState, ftpMessage, _dataOperationExecutor));
        }
Exemplo n.º 2
0
 private void SendMessage(IConnection connection, IFtpMessage message)
 {
     if (connection != null && message != null)
     {
         connection.SendMessage(message);
     }
 }
Exemplo n.º 3
0
        public override void Execute()
        {
            IFtpMessage serverResponce = ExecutorState.ServerConnection.SendWithResponce(FtpMessage);
            IFtpMessage commandResult  = null;

            if (FtpMessage.Args.StartsWith("P"))
            {
                ExecutorState.ClientConnection.SetDataEncryptionStatus(true);
                if (serverResponce.CommandType == ServerCommandType.Success)
                {
                    ExecutorState.ServerConnection.SetDataEncryptionStatus(true);
                }
                commandResult = new FtpMessage(ServerMessageCode.Success, "Data protection enabled",
                                               ExecutorState.ClientConnection.Encoding);
            }
            if (FtpMessage.Args.StartsWith("C"))
            {
                ExecutorState.ClientConnection.SetDataEncryptionStatus(false);
                ExecutorState.ServerConnection.SetDataEncryptionStatus(false);
                commandResult = new FtpMessage(ServerMessageCode.Success, "Data protection not enabled",
                                               ExecutorState.ClientConnection.Encoding);
            }
            commandResult = commandResult ??
                            new FtpMessage(ServerMessageCode.UnknownCommand, "Unknown command",
                                           ExecutorState.ClientConnection.Encoding);
            ExecutorState.ClientConnection.SendMessage(commandResult);
        }
Exemplo n.º 4
0
 public UserCommand(IExecutorState executorState,
                    IFtpMessage ftpMessage,
                    ICommandArgsResolver commandArgsResolver)
     : base(executorState, ftpMessage)
 {
     _commandArgsResolver = commandArgsResolver;
 }
Exemplo n.º 5
0
 public PassCommand(IExecutorState executorState, IFtpMessage ftpMessage, IUserChecker userChecker, ICommandArgsResolver commandArgsResolver, IServerConnectionBuilder serverConnectionBuilder, ICommandFactory remoteCommandFactory) : base(executorState, ftpMessage)
 {
     _userChecker             = userChecker;
     _commandArgsResolver     = commandArgsResolver;
     _serverConnectionBuilder = serverConnectionBuilder;
     _remoteCommandFactory    = remoteCommandFactory;
 }
Exemplo n.º 6
0
        protected Command(IExecutorState executorState, IFtpMessage ftpMessage)
        {
            ExecutorState = executorState;
            FtpMessage    = ftpMessage;

            _errors = new List <string>();
        }
Exemplo n.º 7
0
        public ICommand CreateCommand(IFtpMessage ftpMessage, IExecutorState executorState)
        {
            if (ftpMessage == null)
            {
                return(new WelcomeCommand(executorState));
            }

            switch (ftpMessage.CommandName)
            {
            case ProcessingClientCommand.Auth:
                return(new AuthCommand(executorState, ftpMessage));

            case ProcessingClientCommand.User:
                return(new UserCommand(executorState, ftpMessage, _commandArgsResolver));

            case ProcessingClientCommand.Pass:
                return(new PassCommand(executorState,
                                       ftpMessage,
                                       _userChecker,
                                       _commandArgsResolver,
                                       _serverConnectionBuilder,
                                       _remoteCommandFactory));

            default:
                return(new UnauthorizedCommand(executorState, ftpMessage));
            }
        }
Exemplo n.º 8
0
        public virtual ICommand GetNextCommand(IExecutorState executorState)
        {
            IFtpMessage ftpMessage = executorState.ClientConnection.GetMessage();

            return(ftpMessage != null
                ? executorState.CommandFactory.CreateCommand(ftpMessage, executorState)
                : null);
        }
        public void DoDataConnectionOperation(IAsyncResult result)
        {
            DataConnectionExecutorState state = result.AsyncState as DataConnectionExecutorState;

            if (state == null)
            {
                return;
            }

            _clientDataConnection = state.ClientDataConnection.Connection;
            _serverDataConnection = state.ServerDataConnection.Connection;

            lock (state.ClientConnection.ConnectionOperationLocker)
            {
                try
                {
                    PrepareDataConnections(result, state);
                }
                catch (Exception ex)
                {
                    Logger.Log.Error("Error starting data connection operation", ex);
                    return;
                }

                try
                {
                    // Бесконечный цикл, работает до появления в одном из каналов данных для считывания
                    // таким образом проверяется направление передачи
                    while (true)
                    {
                        if (_serverDataConnection.DataAvailable)
                        {
                            _serverDataConnection.CopyDataTo(_clientDataConnection);
                            break;
                        }
                        if (_clientDataConnection.DataAvailable)
                        {
                            _clientDataConnection.CopyDataTo(_serverDataConnection);
                            break;
                        }
                        Thread.Sleep(150);
                    }
                }
                catch (Exception ex)
                {
                    Logger.Log.Error("Data connection closed when copy operation was running", ex);
                }

                _serverDataConnection.CloseConnection();
                IFtpMessage command = state.ServerConnection.GetMessage();
                if (command != null)
                {
                    state.ClientConnection.SendMessage(command);
                }
                _clientDataConnection.CloseConnection();
            }
        }
Exemplo n.º 10
0
        public override void Execute()
        {
            if (FtpMessage.Args != "0")
            {
                SendToClient(new FtpMessage("501 Server cannot accept argument", ClientConnection.Encoding));
                return;
            }
            IFtpMessage serverResponce = SendWithResponceServer(FtpMessage);

            SendToClient(serverResponce);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Возвращает готовое к устанволению связи соединение для активного режима передачи.
        /// Тип активного режима PORT или EPRT выбирается по переданной команде клиента
        /// </summary>
        /// <param name="clientCommand"></param>
        /// <returns></returns>
        public Connection GetActiveDataConnection(IFtpMessage clientCommand)
        {
            switch (clientCommand.CommandName)
            {
            case ProcessingClientCommand.Port:
                return(GetPortDataConnetion(clientCommand));

            case ProcessingClientCommand.Eprt:
                return(GetEprtDataConnection(clientCommand));
            }

            throw new ArgumentException("Invalid connection type");
        }
Exemplo n.º 12
0
        private Connection GetEprtDataConnection(IFtpMessage clientCommand)
        {
            string hostPort = clientCommand.Args;

            char delimiter = hostPort[0];

            string[] rawSplit = hostPort.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);

            string ipAddress = rawSplit[1];
            string port      = rawSplit[2];

            return(new Connection(IPAddress.Parse(ipAddress), int.Parse(port)));
        }
        public IServerConnectionBuilder BuildPass(string pass)
        {
            _connection.SendMessage(new FtpMessage(String.Format("PASS {0}", pass),
                                                   _connection.Encoding));
            IFtpMessage recivedCommand = _connection.GetMessage();

            // Если сервер вернул не код подтверждения корректности пароля - данные неверны
            if (recivedCommand.CommandName != "230")
            {
                throw new AuthenticationException("Incorrect password for remote server");
            }

            return(this);
        }
        public IServerConnectionBuilder BuildUser(string user)
        {
            _connection.SendMessage(new FtpMessage(String.Format("USER {0}", user),
                                                   _connection.Encoding));
            IFtpMessage recivedCommand = _connection.GetMessage();

            // Если сервер вернул не код ожидания ввода пароля - данные неверны
            if (recivedCommand.CommandName != "331")
            {
                throw new AuthenticationException("Incorrect user login for remote server");
            }

            return(this);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Соединение данных для пассивного режима работы (EPSV)
        /// </summary>
        /// <param name="serverResponce">Ответ сервера на команду EPSV</param>
        /// <param name="serverIpAddress">IpAddress соединения с сервером</param>
        /// <returns></returns>
        public Connection GetEpsvDataConnection(IFtpMessage serverResponce, IPAddress serverIpAddress)
        {
            Match epsvInfo = Regex.Match(serverResponce.Args,
                                         @"\(\|\|\|(?<port>\d+)\|\)");

            if (!epsvInfo.Success)
            {
                Logger.Log.Error(String.Format("Malformed EPSV response: {0}", serverResponce));
                return(null);
            }

            int port = Int32.Parse(epsvInfo.Groups["port"].Value);

            return(new Connection(serverIpAddress, port));
        }
        public IServerConnectionBuilder BuildRemoteConnection(string url, int port)
        {
            _connection = _connectionFactory.CreateConnection(url, port);
            _connection.Connect();

            IFtpMessage recivedCommand = _connection.GetMessage();

            // Если сервер вернул не код подтверждения подключения
            if (recivedCommand.CommandName != "220")
            {
                throw new AuthenticationException("Remote server is not available");
            }

            return(this);
        }
        public IServerConnectionBuilder BuildConnectionSecurity()
        {
            _connection.SendCommand("AUTH TLS");

            IFtpMessage recivedCommand = _connection.GetMessage();

            // Если сервер вернул не код подтверждения установки соединения - соединение не установлено
            if (recivedCommand.CommandName != "234")
            {
                throw new AuthenticationException("Server not support connection secutity");
            }

            _connection.SetUpSecureConnectionAsClient();

            return(this);
        }
Exemplo n.º 18
0
        private Connection GetPortDataConnetion(IFtpMessage clientCommand)
        {
            Match portInfo = Regex.Match(clientCommand.Args,
                                         @"(?<quad1>\d+),(?<quad2>\d+),(?<quad3>\d+),(?<quad4>\d+),(?<port1>\d+),(?<port2>\d+)");

            byte[] host =
            {
                Convert.ToByte(portInfo.Groups["quad1"].Value),
                Convert.ToByte(portInfo.Groups["quad2"].Value),
                Convert.ToByte(portInfo.Groups["quad3"].Value),
                Convert.ToByte(portInfo.Groups["quad4"].Value)
            };

            int port = (Convert.ToInt32(portInfo.Groups["port1"].Value) << 8) +
                       Convert.ToInt32(portInfo.Groups["port2"].Value);

            return(new Connection(new IPAddress(host), port));
        }
Exemplo n.º 19
0
 public void SendMessage(IFtpMessage command)
 {
     try
     {
         int    position = 0;
         byte[] bytes    = command.Bytes;
         while (position < bytes.Length)
         {
             int length = Math.Min(bytes.Length - position, CommandBufferSize);
             AciveStream.Write(bytes, position, length);
             position += length;
         }
     }
     catch (Exception ex)
     {
         Logger.Log.Error(ex.Message, ex);
         throw;
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// Соединение данных для пассивного режима работы (PASV)
        /// </summary>
        /// <param name="serverResponce">Ответ сервера на команда PASV</param>
        /// <returns>Соединение</returns>
        public Connection GetPasvDataConnection(IFtpMessage serverResponce)
        {
            Match pasvInfo = Regex.Match(serverResponce.Args,
                                         @"(?<quad1>\d+),(?<quad2>\d+),(?<quad3>\d+),(?<quad4>\d+),(?<port1>\d+),(?<port2>\d+)");

            if (!pasvInfo.Success || pasvInfo.Groups.Count != 7)
            {
                Logger.Log.Error(String.Format("Malformed PASV response: {0}", serverResponce));
                return(null);
            }
            byte[] host =
            {
                Convert.ToByte(pasvInfo.Groups["quad1"].Value),
                Convert.ToByte(pasvInfo.Groups["quad2"].Value),
                Convert.ToByte(pasvInfo.Groups["quad3"].Value),
                Convert.ToByte(pasvInfo.Groups["quad4"].Value)
            };

            int port = (Convert.ToInt32(pasvInfo.Groups["port1"].Value) << 8) +
                       Convert.ToInt32(pasvInfo.Groups["port2"].Value);

            return(new Connection(new IPAddress(host), port));
        }
Exemplo n.º 21
0
        public override void Execute()
        {
            IFtpMessage serverResponce = SendWithResponceServer(FtpMessage);

            if (serverResponce == null)
            {
                return;
            }
            switch (serverResponce.CommandType)
            {
            case ServerCommandType.Waiting:
                if (ExecutorState.ClientDataConnection != null)
                {
                    StartDataConnectionOperation();
                }
                else
                {
                    SendToClient(serverResponce);
                    serverResponce = GetServerResponce();
                }
                break;
            }
            SendToClient(serverResponce);
        }
Exemplo n.º 22
0
 public OtherCommand(IExecutorState executorState, IFtpMessage clientFtpMessage, IDataOperationExecutor dataOperationExecutor)
     : base(executorState, clientFtpMessage)
 {
     _dataOperationExecutor = dataOperationExecutor;
 }
Exemplo n.º 23
0
 protected IFtpMessage SendWithResponceClient(IFtpMessage ftpMessage)
 {
     SendToClient(ftpMessage);
     return(GetClientResponce());
 }
Exemplo n.º 24
0
 protected IFtpMessage SendWithResponceServer(IFtpMessage ftpMessage)
 {
     SendToServer(ftpMessage);
     return(GetServerResponce());
 }
Exemplo n.º 25
0
 protected void SendToClient(IFtpMessage ftpMessage)
 {
     SendMessage(ExecutorState.ClientConnection, ftpMessage);
 }
Exemplo n.º 26
0
 protected void SendToServer(IFtpMessage ftpMessage)
 {
     SendMessage(ExecutorState.ServerConnection, ftpMessage);
 }
Exemplo n.º 27
0
        public override void Execute()
        {
            IFtpMessage welcomeMessage = GetWelcomeFtpMessage();

            ExecutorState.ClientConnection.SendMessage(welcomeMessage);
        }
Exemplo n.º 28
0
 public UnauthorizedCommand(IExecutorState executorState, IFtpMessage ftpMessage)
     : base(executorState, ftpMessage)
 {
 }
Exemplo n.º 29
0
 public IFtpMessage SendWithResponce(IFtpMessage ftpMessage)
 {
     SendMessage(ftpMessage);
     return(GetMessage());
 }
Exemplo n.º 30
0
 public UnavailableCommand(IExecutorState executorState, IFtpMessage ftpMessage) : base(executorState, ftpMessage)
 {
 }