ftp-client.scm 12 KB

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