ftp-client.scm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2019 Ludovic Courtès <ludo@gnu.org>
  3. ;;;
  4. ;;; This file is part of GNU Guix.
  5. ;;;
  6. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  7. ;;; under the terms of the GNU General Public License as published by
  8. ;;; the Free Software Foundation; either version 3 of the License, or (at
  9. ;;; your option) any later version.
  10. ;;;
  11. ;;; GNU Guix is distributed in the hope that it will be useful, but
  12. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  13. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. ;;; GNU General Public License for more details.
  15. ;;;
  16. ;;; You should have received a copy of the GNU General Public License
  17. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  18. (define-module (guix ftp-client)
  19. #:use-module (srfi srfi-1)
  20. #:use-module (srfi srfi-9)
  21. #:use-module (srfi srfi-11)
  22. #:use-module (srfi srfi-26)
  23. #:use-module (srfi srfi-31)
  24. #:use-module (ice-9 binary-ports)
  25. #:use-module (rnrs bytevectors)
  26. #:use-module (ice-9 match)
  27. #:use-module (ice-9 regex)
  28. #:use-module (ice-9 rdelim)
  29. #:export (ftp-connection?
  30. ftp-connection-addrinfo
  31. connect*
  32. ftp-open
  33. ftp-close
  34. ftp-chdir
  35. ftp-size
  36. ftp-list
  37. ftp-retr))
  38. ;;; Commentary:
  39. ;;;
  40. ;;; Simple FTP client (RFC 959).
  41. ;;;
  42. ;;; Code:
  43. ;; TODO: Use SRFI-3{4,5} error conditions.
  44. (define-record-type <ftp-connection>
  45. (%make-ftp-connection socket addrinfo)
  46. ftp-connection?
  47. (socket ftp-connection-socket)
  48. (addrinfo ftp-connection-addrinfo))
  49. (define %ftp-ready-rx
  50. (make-regexp "^([0-9]{3}) (.+)$"))
  51. (define (%ftp-listen port)
  52. (let loop ((line (read-line port)))
  53. (cond ((eof-object? line) (values line #f))
  54. ((regexp-exec %ftp-ready-rx line)
  55. =>
  56. (lambda (match)
  57. (values (string->number (match:substring match 1))
  58. (match:substring match 2))))
  59. (else
  60. (loop (read-line port))))))
  61. (define (%ftp-command command expected-code port)
  62. (format port "~A~A~A" command (string #\return) (string #\newline))
  63. (let-values (((code message) (%ftp-listen port)))
  64. (if (eqv? code expected-code)
  65. message
  66. (throw 'ftp-error port command code message))))
  67. (define (%ftp-login user pass port)
  68. (let ((command (string-append "USER " user
  69. (string #\return) (string #\newline))))
  70. (display command port)
  71. (let-values (((code message) (%ftp-listen port)))
  72. (case code
  73. ((230) #t)
  74. ((331) (%ftp-command (string-append "PASS " pass) 230 port))
  75. (else (throw 'ftp-error port command code message))))))
  76. (define-syntax-rule (catch-EINPROGRESS body ...)
  77. (catch 'system-error
  78. (lambda ()
  79. body ...)
  80. (lambda args
  81. (unless (= (system-error-errno args) EINPROGRESS)
  82. (apply throw args)))))
  83. ;; XXX: For lack of a better place.
  84. (define* (connect* s sockaddr #:optional timeout)
  85. "When TIMEOUT is omitted or #f, this procedure is equivalent to 'connect'.
  86. When TIMEOUT is a number, it is the (possibly inexact) maximum number of
  87. seconds to wait for the connection to succeed."
  88. (define (raise-error errno)
  89. (throw 'system-error 'connect* "~A"
  90. (list (strerror errno))
  91. (list errno)))
  92. (if timeout
  93. (let ((flags (fcntl s F_GETFL)))
  94. (fcntl s F_SETFL (logior flags O_NONBLOCK))
  95. (catch-EINPROGRESS (connect s sockaddr))
  96. (match (select '() (list s) (list s) timeout)
  97. ((() () ())
  98. ;; Time is up!
  99. (raise-error ETIMEDOUT))
  100. ((() (write) ())
  101. ;; Check for ECONNREFUSED and the likes.
  102. (fcntl s F_SETFL flags)
  103. (let ((errno (getsockopt s SOL_SOCKET SO_ERROR)))
  104. (unless (zero? errno)
  105. (raise-error errno))))
  106. ((() () (except))
  107. ;; Seems like this cannot really happen, but who knows.
  108. (let ((errno (getsockopt s SOL_SOCKET SO_ERROR)))
  109. (raise-error errno)))))
  110. (connect s sockaddr)))
  111. (define* (ftp-open host #:optional (port "ftp")
  112. #:key timeout
  113. (username "anonymous")
  114. (password "guix@example.com"))
  115. "Open an FTP connection to HOST on PORT (a service-identifying string,
  116. or a TCP port number), and return it.
  117. When TIMEOUT is not #f, it must be a (possibly inexact) number denoting the
  118. maximum duration in seconds to wait for the connection to complete; passed
  119. TIMEOUT, an ETIMEDOUT error is raised."
  120. ;; Using "ftp" for PORT instead of 21 allows 'getaddrinfo' to return only
  121. ;; TCP/IP addresses (otherwise it would return SOCK_DGRAM and SOCK_RAW
  122. ;; addresses as well.) With our bootstrap Guile, which includes a
  123. ;; statically-linked NSS, resolving "ftp" works well, as long as
  124. ;; /etc/services is available.
  125. (define addresses
  126. (getaddrinfo host
  127. (if (number? port) (number->string port) port)
  128. (if (number? port)
  129. (logior AI_ADDRCONFIG AI_NUMERICSERV)
  130. AI_ADDRCONFIG)))
  131. (let loop ((addresses addresses))
  132. (match addresses
  133. ((ai rest ...)
  134. (let ((s (socket (addrinfo:fam ai)
  135. ;; TCP/IP only
  136. SOCK_STREAM IPPROTO_IP)))
  137. (catch 'system-error
  138. (lambda ()
  139. (connect* s (addrinfo:addr ai) timeout)
  140. (setvbuf s 'line)
  141. (let-values (((code message) (%ftp-listen s)))
  142. (if (eqv? code 220)
  143. (begin
  144. ;;(%ftp-command "OPTS UTF8 ON" 200 s)
  145. (%ftp-login username password s)
  146. (%make-ftp-connection s ai))
  147. (begin
  148. (close s)
  149. (throw 'ftp-error s "log-in" code message)))))
  150. (lambda args
  151. ;; Connection failed, so try one of the other addresses.
  152. (close s)
  153. (if (null? rest)
  154. (apply throw args)
  155. (loop rest)))))))))
  156. (define (ftp-close conn)
  157. (close (ftp-connection-socket conn)))
  158. (define %char-set:not-slash
  159. (char-set-complement (char-set #\/)))
  160. (define (ftp-chdir conn dir)
  161. "Change to directory DIR."
  162. ;; On ftp.gnupg.org, "PASV" right after "CWD /gcrypt/gnupg" hangs. Doing
  163. ;; CWD in two steps works, so just do this.
  164. (let ((components (string-tokenize dir %char-set:not-slash)))
  165. (fold (lambda (dir result)
  166. (%ftp-command (string-append "CWD " dir) 250
  167. (ftp-connection-socket conn)))
  168. #f
  169. (if (string-prefix? "/" dir)
  170. (cons "/" components)
  171. components))))
  172. (define (ftp-size conn file)
  173. "Return the size in bytes of FILE."
  174. ;; Ask for "binary mode", otherwise some servers, such as sourceware.org,
  175. ;; fail with 550 ("SIZE not allowed in ASCII mode").
  176. (%ftp-command "TYPE I" 200 (ftp-connection-socket conn))
  177. (let ((message (%ftp-command (string-append "SIZE " file) 213
  178. (ftp-connection-socket conn))))
  179. (string->number (string-trim-both message))))
  180. (define (ftp-pasv conn)
  181. (define %pasv-rx
  182. (make-regexp "([0-9]+),([0-9]+),([0-9]+),([0-9]+),([0-9]+),([0-9]+)"))
  183. (let ((message (%ftp-command "PASV" 227 (ftp-connection-socket conn))))
  184. (cond ((regexp-exec %pasv-rx message)
  185. =>
  186. (lambda (match)
  187. (+ (* (string->number (match:substring match 5)) 256)
  188. (string->number (match:substring match 6)))))
  189. (else
  190. (throw 'ftp-error conn "PASV" 227 message)))))
  191. (define (ftp-epsv conn)
  192. (let* ((message (%ftp-command "EPSV" 229 (ftp-connection-socket conn))))
  193. (string->number
  194. (match:substring (string-match "\\(...([0-9]+).\\)" message) 1))))
  195. (define (ftp-passive conn)
  196. "Enter passive mode using EPSV or PASV, return a data connection port on
  197. success."
  198. ;; IPv6 only works with EPSV, so try it first.
  199. (or (false-if-exception (ftp-epsv conn)) (ftp-pasv conn)))
  200. (define (address-with-port sa port)
  201. "Return a socket-address object based on SA, but with PORT."
  202. (let ((fam (sockaddr:fam sa))
  203. (addr (sockaddr:addr sa)))
  204. (cond ((= fam AF_INET)
  205. (make-socket-address fam addr port))
  206. ((= fam AF_INET6)
  207. (make-socket-address fam addr port
  208. (sockaddr:flowinfo sa)
  209. (sockaddr:scopeid sa)))
  210. (else #f))))
  211. (define* (ftp-list conn #:optional directory #:key timeout)
  212. (if directory
  213. (ftp-chdir conn directory))
  214. (let* ((port (ftp-passive conn))
  215. (ai (ftp-connection-addrinfo conn))
  216. (s (socket (addrinfo:fam ai) (addrinfo:socktype ai)
  217. (addrinfo:protocol ai))))
  218. (connect* s (address-with-port (addrinfo:addr ai) port) timeout)
  219. (setvbuf s 'line)
  220. (dynamic-wind
  221. (lambda () #t)
  222. (lambda ()
  223. (%ftp-command "LIST" 150 (ftp-connection-socket conn))
  224. (let loop ((line (read-line s))
  225. (result '()))
  226. (cond ((eof-object? line) (reverse result))
  227. ((regexp-exec %ftp-ready-rx line)
  228. =>
  229. (lambda (match)
  230. (let ((code (string->number (match:substring match 1))))
  231. (if (= 126 code)
  232. (reverse result)
  233. (throw 'ftp-error conn "LIST" code)))))
  234. (else
  235. (loop (read-line s)
  236. (match (reverse (string-tokenize line))
  237. ((file _ ... permissions)
  238. (let ((type (case (string-ref permissions 0)
  239. ((#\d) 'directory)
  240. (else 'file))))
  241. (cons (list file type) result)))
  242. ((file _ ...)
  243. (cons (cons file 'file) result))))))))
  244. (lambda ()
  245. (close s)
  246. (let-values (((code message) (%ftp-listen (ftp-connection-socket conn))))
  247. (or (eqv? code 226)
  248. (throw 'ftp-error conn "LIST" code message)))))))
  249. (define* (ftp-retr conn file #:optional directory
  250. #:key timeout)
  251. "Retrieve FILE from DIRECTORY (or, if omitted, the current directory) from
  252. FTP connection CONN. Return a binary port to that file. The returned port
  253. must be closed before CONN can be used for other purposes."
  254. (if directory
  255. (ftp-chdir conn directory))
  256. ;; Ask for "binary mode".
  257. (%ftp-command "TYPE I" 200 (ftp-connection-socket conn))
  258. (let* ((port (ftp-passive conn))
  259. (ai (ftp-connection-addrinfo conn))
  260. (s (with-fluids ((%default-port-encoding #f))
  261. (socket (addrinfo:fam ai) (addrinfo:socktype ai)
  262. (addrinfo:protocol ai)))))
  263. (define (terminate)
  264. (close s)
  265. (let-values (((code message) (%ftp-listen (ftp-connection-socket conn))))
  266. (or (eqv? code 226)
  267. (throw 'ftp-error conn "LIST" code message))))
  268. (connect* s (address-with-port (addrinfo:addr ai) port) timeout)
  269. (setvbuf s 'line)
  270. (%ftp-command (string-append "RETR " file)
  271. 150 (ftp-connection-socket conn))
  272. (make-custom-binary-input-port "FTP RETR port"
  273. (rec (read! bv start count)
  274. (match (get-bytevector-n! s bv
  275. start count)
  276. ((? eof-object?) 0)
  277. (0
  278. ;; Nothing available yet, so try
  279. ;; again. This is important because
  280. ;; the return value of `read!' makes
  281. ;; it impossible to distinguish
  282. ;; between "not yet" and "EOF".
  283. (read! bv start count))
  284. (read read)))
  285. #f #f ; no get/set position
  286. terminate)))
  287. ;;; ftp-client.scm ends here