2 # = net/ftp.rb - FTP Client Library
4 # Written by Shugo Maeda <shugo@ruby-lang.org>.
6 # Documentation by Gavin Sinclair, sourced from "Programming Ruby" (Hunt/Thomas)
7 # and "Ruby In a Nutshell" (Matsumoto), used with permission.
9 # This library is distributed under the terms of the Ruby license.
10 # You can freely distribute/modify this library.
12 # It is included in the Ruby standard library.
14 # See the Net::FTP class for an overview.
23 class FTPError < StandardError; end
24 class FTPReplyError < FTPError; end
25 class FTPTempError < FTPError; end
26 class FTPPermError < FTPError; end
27 class FTPProtoError < FTPError; end
31 # This class implements the File Transfer Protocol. If you have used a
32 # command-line FTP program, and are familiar with the commands, you will be
33 # able to use this class easily. Some extra features are included to take
34 # advantage of Ruby's style and strengths.
42 # ftp = Net::FTP.new('ftp.netlab.co.jp')
44 # files = ftp.chdir('pub/lang/ruby/contrib')
45 # files = ftp.list('n*')
46 # ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
51 # Net::FTP.open('ftp.netlab.co.jp') do |ftp|
53 # files = ftp.chdir('pub/lang/ruby/contrib')
54 # files = ftp.list('n*')
55 # ftp.getbinaryfile('nif.rb-0.91.gz', 'nif.gz', 1024)
60 # The following are the methods most likely to be useful to users:
78 DEFAULT_BLOCKSIZE = 4096
81 # When +true+, transfers are performed in binary mode. Default: +true+.
84 # When +true+, the connection is in passive mode. Default: +false+.
85 attr_accessor :passive
87 # When +true+, all traffic to and from the server is written
88 # to +$stdout+. Default: +false+.
89 attr_accessor :debug_mode
91 # Sets or retrieves the +resume+ status, which decides whether incomplete
92 # transfers are resumed or restarted. Default: +false+.
95 # The server's welcome message.
98 # The server's last response code.
99 attr_reader :last_response_code
100 alias lastresp last_response_code
102 # The server's last response.
103 attr_reader :last_response
106 # A synonym for <tt>FTP.new</tt>, but with a mandatory host parameter.
108 # If a block is given, it is passed the +FTP+ object, which will be closed
109 # when the block finishes, or when an exception is raised.
111 def FTP.open(host, user = nil, passwd = nil, acct = nil)
113 ftp = new(host, user, passwd, acct)
120 new(host, user, passwd, acct)
125 # Creates and returns a new +FTP+ object. If a +host+ is given, a connection
126 # is made. Additionally, if the +user+ is given, the given user name,
127 # password, and (optionally) account are used to log in. See #login.
129 def initialize(host = nil, user = nil, passwd = nil, acct = nil)
138 login(user, passwd, acct)
144 if newmode != @binary
146 @binary ? voidcmd("TYPE I") : voidcmd("TYPE A")
150 def with_binary(newmode)
152 self.binary = newmode
156 self.binary = oldmode
163 $stderr.puts("warning: Net::FTP#return_code is obsolete and do nothing")
169 $stderr.puts("warning: Net::FTP#return_code= is obsolete and do nothing")
172 def open_socket(host, port)
173 if defined? SOCKSsocket and ENV["SOCKS_SERVER"]
175 return SOCKSsocket.open(host, port)
177 return TCPSocket.open(host, port)
183 # Establishes an FTP connection to host, optionally overriding the default
184 # port. If the environment variable +SOCKS_SERVER+ is set, sets up the
185 # connection through a SOCKS proxy. Raises an exception (typically
186 # <tt>Errno::ECONNREFUSED</tt>) if the connection cannot be established.
188 def connect(host, port = FTP_PORT)
190 print "connect: ", host, ", ", port, "\n"
193 @sock = open_socket(host, port)
199 # WRITEME or make private
201 def set_socket(sock, get_greeting = true)
212 return s[0, 5] + "*" * (s.length - 5)
221 print "put: ", sanitize(line), "\n"
229 line = @sock.readline # if get EOF, raise EOFError
230 line.sub!(/(\r\n|\n|\r)\z/n, "")
232 print "get: ", sanitize(line), "\n"
246 end until line[0, 3] == code and line[3] != ?-
250 private :getmultiline
253 @last_response = getmultiline
254 @last_response_code = @last_response[0, 3]
255 case @last_response_code
257 return @last_response
259 raise FTPTempError, @last_response
261 raise FTPPermError, @last_response
263 raise FTPProtoError, @last_response
271 raise FTPReplyError, resp
277 # Sends a command and returns the response.
287 # Sends a command and expect a response beginning with '2'.
296 def sendport(host, port)
297 af = (@sock.peeraddr)[0]
299 cmd = "PORT " + (host.split(".") + port.divmod(256)).join(",")
300 elsif af == "AF_INET6"
301 cmd = sprintf("EPRT |2|%s|%d|", host, port)
303 raise FTPProtoError, host
310 sock = TCPServer.open(@sock.addr[3], 0)
313 resp = sendport(host, port)
319 if @sock.peeraddr[0] == "AF_INET"
320 host, port = parse227(sendcmd("PASV"))
322 host, port = parse229(sendcmd("EPSV"))
323 # host, port = parse228(sendcmd("LPSV"))
329 def transfercmd(cmd, rest_offset = nil)
331 host, port = makepasv
332 conn = open_socket(host, port)
333 if @resume and rest_offset
334 resp = sendcmd("REST " + rest_offset.to_s)
336 raise FTPReplyError, resp
340 # skip 2XX for some ftp servers
341 resp = getresp if resp[0] == ?2
343 raise FTPReplyError, resp
347 if @resume and rest_offset
348 resp = sendcmd("REST " + rest_offset.to_s)
350 raise FTPReplyError, resp
354 # skip 2XX for some ftp servers
355 resp = getresp if resp[0] == ?2
357 raise FTPReplyError, resp
367 thishost = Socket.gethostname
368 if not thishost.index(".")
369 thishost = Socket.gethostbyname(thishost)[0]
371 if ENV.has_key?("LOGNAME")
372 realuser = ENV["LOGNAME"]
373 elsif ENV.has_key?("USER")
374 realuser = ENV["USER"]
376 realuser = "anonymous"
378 return realuser + "@" + thishost
383 # Logs in to the remote host. The session must have been previously
384 # connected. If +user+ is the string "anonymous" and the +password+ is
385 # +nil+, a password of <tt>user@host</tt> is synthesized. If the +acct+
386 # parameter is not +nil+, an FTP ACCT command is sent following the
387 # successful login. Raises an exception on error (typically
388 # <tt>Net::FTPPermError</tt>).
390 def login(user = "anonymous", passwd = nil, acct = nil)
391 if user == "anonymous" and passwd == nil
397 resp = sendcmd('USER ' + user)
399 raise FTPReplyError, resp if passwd.nil?
400 resp = sendcmd('PASS ' + passwd)
403 raise FTPReplyError, resp if acct.nil?
404 resp = sendcmd('ACCT ' + acct)
408 raise FTPReplyError, resp
415 # Puts the connection into binary (image) mode, issues the given command,
416 # and fetches the data returned, passing it to the associated block in
417 # chunks of +blocksize+ characters. Note that +cmd+ is a server command
418 # (such as "RETR myfile").
420 def retrbinary(cmd, blocksize, rest_offset = nil) # :yield: data
423 conn = transfercmd(cmd, rest_offset)
425 data = conn.read(blocksize)
436 # Puts the connection into ASCII (text) mode, issues the given command, and
437 # passes the resulting data, one line at a time, to the associated block. If
438 # no block is given, prints the lines. Note that +cmd+ is a server command
439 # (such as "RETR myfile").
441 def retrlines(cmd) # :yield: line
443 with_binary(false) do
444 conn = transfercmd(cmd)
448 if line[-2, 2] == CRLF
450 elsif line[-1] == ?\n
462 # Puts the connection into binary (image) mode, issues the given server-side
463 # command (such as "STOR myfile"), and sends the contents of the file named
464 # +file+ to the server. If the optional block is given, it also passes it
465 # the data, in chunks of +blocksize+ characters.
467 def storbinary(cmd, file, blocksize, rest_offset = nil, &block) # :yield: data
469 file.seek(rest_offset, IO::SEEK_SET)
473 conn = transfercmd(cmd, rest_offset)
475 buf = file.read(blocksize)
485 # EPIPE, in this case, means that the data connection was unexpectedly
486 # terminated. Rather than just raising EPIPE to the caller, check the
487 # response on the control connection. If getresp doesn't raise a more
488 # appropriate exception, re-raise the original exception.
494 # Puts the connection into ASCII (text) mode, issues the given server-side
495 # command (such as "STOR myfile"), and sends the contents of the file
496 # named +file+ to the server, one line at a time. If the optional block is
497 # given, it also passes it the lines.
499 def storlines(cmd, file, &block) # :yield: line
501 with_binary(false) do
502 conn = transfercmd(cmd)
506 if buf[-2, 2] != CRLF
507 buf = buf.chomp + CRLF
517 # EPIPE, in this case, means that the data connection was unexpectedly
518 # terminated. Rather than just raising EPIPE to the caller, check the
519 # response on the control connection. If getresp doesn't raise a more
520 # appropriate exception, re-raise the original exception.
526 # Retrieves +remotefile+ in binary mode, storing the result in +localfile+.
527 # If +localfile+ is nil, returns retrieved data.
528 # If a block is supplied, it is passed the retrieved data in +blocksize+
531 def getbinaryfile(remotefile, localfile = File.basename(remotefile),
532 blocksize = DEFAULT_BLOCKSIZE) # :yield: data
536 rest_offset = File.size?(localfile)
537 f = open(localfile, "a")
540 f = open(localfile, "w")
546 f.binmode if localfile
547 retrbinary("RETR " + remotefile, blocksize, rest_offset) do |data|
548 f.write(data) if localfile
549 yield(data) if block_given?
550 result.concat(data) if result
559 # Retrieves +remotefile+ in ASCII (text) mode, storing the result in
561 # If +localfile+ is nil, returns retrieved data.
562 # If a block is supplied, it is passed the retrieved data one
565 def gettextfile(remotefile, localfile = File.basename(remotefile)) # :yield: line
568 f = open(localfile, "w")
573 retrlines("RETR " + remotefile) do |line|
574 f.puts(line) if localfile
575 yield(line) if block_given?
576 result.concat(line + "\n") if result
585 # Retrieves +remotefile+ in whatever mode the session is set (text or
586 # binary). See #gettextfile and #getbinaryfile.
588 def get(remotefile, localfile = File.basename(remotefile),
589 blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
591 getbinaryfile(remotefile, localfile, blocksize, &block)
593 gettextfile(remotefile, localfile, &block)
598 # Transfers +localfile+ to the server in binary mode, storing the result in
599 # +remotefile+. If a block is supplied, calls it, passing in the transmitted
600 # data in +blocksize+ chunks.
602 def putbinaryfile(localfile, remotefile = File.basename(localfile),
603 blocksize = DEFAULT_BLOCKSIZE, &block) # :yield: data
606 rest_offset = size(remotefile)
607 rescue Net::FTPPermError
616 storbinary("STOR " + remotefile, f, blocksize, rest_offset, &block)
623 # Transfers +localfile+ to the server in ASCII (text) mode, storing the result
624 # in +remotefile+. If callback or an associated block is supplied, calls it,
625 # passing in the transmitted data one line at a time.
627 def puttextfile(localfile, remotefile = File.basename(localfile), &block) # :yield: line
630 storlines("STOR " + remotefile, f, &block)
637 # Transfers +localfile+ to the server in whatever mode the session is set
638 # (text or binary). See #puttextfile and #putbinaryfile.
640 def put(localfile, remotefile = File.basename(localfile),
641 blocksize = DEFAULT_BLOCKSIZE, &block)
643 putbinaryfile(localfile, remotefile, blocksize, &block)
645 puttextfile(localfile, remotefile, &block)
650 # Sends the ACCT command. TODO: more info.
653 cmd = "ACCT " + account
658 # Returns an array of filenames in the remote directory.
663 cmd = cmd + " " + dir
666 retrlines(cmd) do |line|
673 # Returns an array of file information in the directory (the output is like
674 # `ls -l`). If a block is given, it iterates through the listing.
676 def list(*args, &block) # :yield: line
679 cmd = cmd + " " + arg
682 retrlines(cmd, &block)
685 retrlines(cmd) do |line|
695 # Renames a file on the server.
697 def rename(fromname, toname)
698 resp = sendcmd("RNFR " + fromname)
700 raise FTPReplyError, resp
702 voidcmd("RNTO " + toname)
706 # Deletes a file on the server.
709 resp = sendcmd("DELE " + filename)
710 if resp[0, 3] == "250"
713 raise FTPPermError, resp
715 raise FTPReplyError, resp
720 # Changes the (remote) directory.
727 rescue FTPPermError => e
728 if e.message[0, 3] != "500"
733 cmd = "CWD " + dirname
738 # Returns the size of the given (remote) filename.
742 resp = sendcmd("SIZE " + filename)
743 if resp[0, 3] != "213"
744 raise FTPReplyError, resp
746 return resp[3..-1].strip.to_i
750 MDTM_REGEXP = /^(\d\d\d\d)(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)/ # :nodoc:
753 # Returns the last modification time of the (remote) file. If +local+ is
754 # +true+, it is returned as a local time, otherwise it's a UTC time.
756 def mtime(filename, local = false)
758 ary = str.scan(MDTM_REGEXP)[0].collect {|i| i.to_i}
759 return local ? Time.local(*ary) : Time.gm(*ary)
763 # Creates a remote directory.
766 resp = sendcmd("MKD " + dirname)
767 return parse257(resp)
771 # Removes a remote directory.
774 voidcmd("RMD " + dirname)
778 # Returns the current remote directory.
781 resp = sendcmd("PWD")
782 return parse257(resp)
787 # Returns system information.
790 resp = sendcmd("SYST")
791 if resp[0, 3] != "215"
792 raise FTPReplyError, resp
798 # Aborts the previous command (ABOR command).
802 print "put: ABOR\n" if @debug_mode
803 @sock.send(line, Socket::MSG_OOB)
805 unless ["426", "226", "225"].include?(resp[0, 3])
806 raise FTPProtoError, resp
812 # Returns the status (STAT command).
816 print "put: STAT\n" if @debug_mode
817 @sock.send(line, Socket::MSG_OOB)
822 # Issues the MDTM command. TODO: more info.
825 resp = sendcmd("MDTM " + filename)
826 if resp[0, 3] == "213"
827 return resp[3 .. -1].strip
832 # Issues the HELP command.
837 cmd = cmd + " " + arg
843 # Exits the FTP session.
850 # Issues a NOOP command.
857 # Issues a SITE command.
865 # Closes the connection. Further operations are impossible until you open
866 # a new connection with #connect.
869 @sock.close if @sock and not @sock.closed?
873 # Returns +true+ iff the connection is closed.
876 @sock == nil or @sock.closed?
880 if resp[0, 3] != "227"
881 raise FTPReplyError, resp
883 left = resp.index("(")
884 right = resp.index(")")
885 if left == nil or right == nil
886 raise FTPProtoError, resp
888 numbers = resp[left + 1 .. right - 1].split(",")
889 if numbers.length != 6
890 raise FTPProtoError, resp
892 host = numbers[0, 4].join(".")
893 port = (numbers[4].to_i << 8) + numbers[5].to_i
899 if resp[0, 3] != "228"
900 raise FTPReplyError, resp
902 left = resp.index("(")
903 right = resp.index(")")
904 if left == nil or right == nil
905 raise FTPProtoError, resp
907 numbers = resp[left + 1 .. right - 1].split(",")
909 if numbers.length != 9 || numbers[1] != "4" || numbers[2 + 4] != "2"
910 raise FTPProtoError, resp
912 host = numbers[2, 4].join(".")
913 port = (numbers[7].to_i << 8) + numbers[8].to_i
914 elsif numbers[0] == "6"
915 if numbers.length != 21 || numbers[1] != "16" || numbers[2 + 16] != "2"
916 raise FTPProtoError, resp
918 v6 = ["", "", "", "", "", "", "", ""]
920 v6[i] = sprintf("%02x%02x", numbers[(i * 2) + 2].to_i,
921 numbers[(i * 2) + 3].to_i)
923 host = v6[0, 8].join(":")
924 port = (numbers[19].to_i << 8) + numbers[20].to_i
931 if resp[0, 3] != "229"
932 raise FTPReplyError, resp
934 left = resp.index("(")
935 right = resp.index(")")
936 if left == nil or right == nil
937 raise FTPProtoError, resp
939 numbers = resp[left + 1 .. right - 1].split(resp[left + 1, 1])
940 if numbers.length != 4
941 raise FTPProtoError, resp
943 port = numbers[3].to_i
944 host = (@sock.peeraddr())[3]
950 if resp[0, 3] != "257"
951 raise FTPReplyError, resp
953 if resp[3, 2] != ' "'
963 if i > n or resp[i, 1] != '"'
968 dirname = dirname + c
978 # Documentation comments:
979 # - sourced from pickaxe and nutshell, with improvements (hopefully)
980 # - three methods should be private (search WRITEME)
981 # - two methods need more information (search TODO)