lib/fake_ftp/server.rb in fake_ftp-0.0.2 vs lib/fake_ftp/server.rb in fake_ftp-0.0.3

- old
+ new

@@ -3,10 +3,11 @@ module FakeFtp class Server attr_accessor :port, :passive_port + attr_reader :mode CMDS = %w[acct cwd cdup pass pasv port pwd quit stor type user] LNBK = "\r\n" def initialize(control_port = 21, data_port = nil, options = {}) @@ -15,18 +16,19 @@ raise(Errno::EADDRINUSE, "#{port}") if is_running? raise(Errno::EADDRINUSE, "#{passive_port}") if passive_port && is_running?(passive_port) @connection = nil @options = options @files = [] + @mode = :active end def files @files.map(&:name) end def file(name) - @files.detect { |file| file.name == name} + @files.detect { |file| file.name == name } end def start @started = true @server = ::TCPServer.new('127.0.0.1', port) @@ -98,29 +100,29 @@ '230 logged in' end def _pasv(*args) if passive_port + @mode = :passive p1 = (passive_port / 256).to_i p2 = passive_port % 256 "227 Entering Passive Mode (127,0,0,1,#{p1},#{p2})" else '502 Aww hell no, use Active' end end def _port(remote) - # remote = remote.split(',') - # remote_port = remote[4].to_i * 256 + remote[5].to_i - # unless @data_connection.nil? - # @data_connection.close - # @data_connection = nil - # end - # puts remote_port - # @data_connection = ::TCPSocket.open('127.0.0.1', remote_port) - # '200 Okay' - '500 Not implemented yet' + remote = remote.first.split(',') + remote_port = remote[4].to_i * 256 + remote[5].to_i + unless @active_connection.nil? + @active_connection.close + @active_connection = nil + end + @mode = :active + @active_connection = ::TCPSocket.open('127.0.0.1', remote_port) + '200 Okay' end def _pwd(*args) "257 \"/pub\" is current directory" end @@ -130,18 +132,25 @@ @client.close if @client @client = nil end def _stor(filename) - respond_with('125 Do it!') + if @mode == :passive + respond_with('125 Do it!') + data_client = @data_server.accept + else + respond_with('425 Ain\'t no data port!') && return if @active_connection.nil? + respond_with('125 Do it!') - data_client = @data_server.accept - data = data_client.recv(1024) + data_client = @active_connection + end + data = data_client.recv(1024) file = FakeFtp::File.new(::File.basename(filename.to_s), data.length) @files << file data_client.close + @active_connection = nil '226 Did it!' end def _type(type = 'A') case type.to_s \ No newline at end of file