ftp-client.scm 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 (address-with-port sa port)
  192. "Return a socket-address object based on SA, but with PORT."
  193. (let ((fam (sockaddr:fam sa))
  194. (addr (sockaddr:addr sa)))
  195. (cond ((= fam AF_INET)
  196. (make-socket-address fam addr port))
  197. ((= fam AF_INET6)
  198. (make-socket-address fam addr port
  199. (sockaddr:flowinfo sa)
  200. (sockaddr:scopeid sa)))
  201. (else #f))))
  202. (define* (ftp-list conn #:optional directory #:key timeout)
  203. (if directory
  204. (ftp-chdir conn directory))
  205. (let* ((port (ftp-pasv conn))
  206. (ai (ftp-connection-addrinfo conn))
  207. (s (socket (addrinfo:fam ai) (addrinfo:socktype ai)
  208. (addrinfo:protocol ai))))
  209. (connect* s (address-with-port (addrinfo:addr ai) port) timeout)
  210. (setvbuf s 'line)
  211. (dynamic-wind
  212. (lambda () #t)
  213. (lambda ()
  214. (%ftp-command "LIST" 150 (ftp-connection-socket conn))
  215. (let loop ((line (read-line s))
  216. (result '()))
  217. (cond ((eof-object? line) (reverse result))
  218. ((regexp-exec %ftp-ready-rx line)
  219. =>
  220. (lambda (match)
  221. (let ((code (string->number (match:substring match 1))))
  222. (if (= 126 code)
  223. (reverse result)
  224. (throw 'ftp-error conn "LIST" code)))))
  225. (else
  226. (loop (read-line s)
  227. (match (reverse (string-tokenize line))
  228. ((file _ ... permissions)
  229. (let ((type (case (string-ref permissions 0)
  230. ((#\d) 'directory)
  231. (else 'file))))
  232. (cons (list file type) result)))
  233. ((file _ ...)
  234. (cons (cons file 'file) result))))))))
  235. (lambda ()
  236. (close s)
  237. (let-values (((code message) (%ftp-listen (ftp-connection-socket conn))))
  238. (or (eqv? code 226)
  239. (throw 'ftp-error conn "LIST" code message)))))))
  240. (define* (ftp-retr conn file #:optional directory
  241. #:key timeout)
  242. "Retrieve FILE from DIRECTORY (or, if omitted, the current directory) from
  243. FTP connection CONN. Return a binary port to that file. The returned port
  244. must be closed before CONN can be used for other purposes."
  245. (if directory
  246. (ftp-chdir conn directory))
  247. ;; Ask for "binary mode".
  248. (%ftp-command "TYPE I" 200 (ftp-connection-socket conn))
  249. (let* ((port (ftp-pasv conn))
  250. (ai (ftp-connection-addrinfo conn))
  251. (s (with-fluids ((%default-port-encoding #f))
  252. (socket (addrinfo:fam ai) (addrinfo:socktype ai)
  253. (addrinfo:protocol ai)))))
  254. (define (terminate)
  255. (close s)
  256. (let-values (((code message) (%ftp-listen (ftp-connection-socket conn))))
  257. (or (eqv? code 226)
  258. (throw 'ftp-error conn "LIST" code message))))
  259. (connect* s (address-with-port (addrinfo:addr ai) port) timeout)
  260. (setvbuf s 'line)
  261. (%ftp-command (string-append "RETR " file)
  262. 150 (ftp-connection-socket conn))
  263. (make-custom-binary-input-port "FTP RETR port"
  264. (rec (read! bv start count)
  265. (match (get-bytevector-n! s bv
  266. start count)
  267. ((? eof-object?) 0)
  268. (0
  269. ;; Nothing available yet, so try
  270. ;; again. This is important because
  271. ;; the return value of `read!' makes
  272. ;; it impossible to distinguish
  273. ;; between "not yet" and "EOF".
  274. (read! bv start count))
  275. (read read)))
  276. #f #f ; no get/set position
  277. terminate)))
  278. ;;; ftp-client.scm ends here