download.scm 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. ;;; GNU Guix --- Functional package management for GNU
  2. ;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
  3. ;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
  4. ;;; Copyright © 2017 Tobias Geerinckx-Rice <me@tobias.gr>
  5. ;;;
  6. ;;; This file is part of GNU Guix.
  7. ;;;
  8. ;;; GNU Guix is free software; you can redistribute it and/or modify it
  9. ;;; under the terms of the GNU General Public License as published by
  10. ;;; the Free Software Foundation; either version 3 of the License, or (at
  11. ;;; your option) any later version.
  12. ;;;
  13. ;;; GNU Guix is distributed in the hope that it will be useful, but
  14. ;;; WITHOUT ANY WARRANTY; without even the implied warranty of
  15. ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. ;;; GNU General Public License for more details.
  17. ;;;
  18. ;;; You should have received a copy of the GNU General Public License
  19. ;;; along with GNU Guix. If not, see <http://www.gnu.org/licenses/>.
  20. (define-module (guix build download)
  21. #:use-module (web uri)
  22. #:use-module (web http)
  23. #:use-module ((web client) #:hide (open-socket-for-uri))
  24. #:use-module (web response)
  25. #:use-module (guix base64)
  26. #:use-module (guix ftp-client)
  27. #:use-module (guix build utils)
  28. #:use-module (guix progress)
  29. #:use-module (rnrs io ports)
  30. #:use-module (rnrs bytevectors)
  31. #:use-module (srfi srfi-1)
  32. #:use-module (srfi srfi-11)
  33. #:use-module (srfi srfi-19)
  34. #:use-module (srfi srfi-26)
  35. #:autoload (ice-9 ftw) (scandir)
  36. #:use-module (ice-9 match)
  37. #:use-module (ice-9 format)
  38. #:export (open-socket-for-uri
  39. open-connection-for-uri
  40. http-fetch
  41. %x509-certificate-directory
  42. close-connection
  43. resolve-uri-reference
  44. maybe-expand-mirrors
  45. url-fetch
  46. byte-count->string
  47. uri-abbreviation
  48. nar-uri-abbreviation
  49. store-path-abbreviation))
  50. ;;; Commentary:
  51. ;;;
  52. ;;; Fetch data such as tarballs over HTTP or FTP (builder-side code).
  53. ;;;
  54. ;;; Code:
  55. (define %http-receive-buffer-size
  56. ;; Size of the HTTP receive buffer.
  57. 65536)
  58. (define* (ellipsis #:optional (port (current-output-port)))
  59. "Make a rough guess at whether Unicode's HORIZONTAL ELLIPSIS can be written
  60. in PORT's encoding, and return either that or ASCII dots."
  61. (if (equal? (port-encoding port) "UTF-8")
  62. "…"
  63. "..."))
  64. (define* (store-path-abbreviation store-path #:optional (prefix-length 6))
  65. "If STORE-PATH is the file name of a store entry, return an abbreviation of
  66. STORE-PATH for display, showing PREFIX-LENGTH characters of the hash.
  67. Otherwise return STORE-PATH."
  68. (if (string-prefix? (%store-directory) store-path)
  69. (let ((base (basename store-path)))
  70. (string-append (string-take base prefix-length)
  71. (ellipsis)
  72. (string-drop base 32)))
  73. store-path))
  74. (define* (uri-abbreviation uri #:optional (max-length 42))
  75. "If URI's string representation is larger than MAX-LENGTH, return an
  76. abbreviation of URI showing the scheme, host, and basename of the file."
  77. (define uri-as-string
  78. (uri->string uri))
  79. (define (elide-path)
  80. (let* ((path (uri-path uri))
  81. (base (basename path))
  82. (prefix (string-append (symbol->string (uri-scheme uri)) "://"
  83. ;; `file' URIs have no host part.
  84. (or (uri-host uri) "")
  85. (string-append "/" (ellipsis) "/"))))
  86. (if (> (+ (string-length prefix) (string-length base)) max-length)
  87. (string-append prefix (ellipsis)
  88. (string-drop base (quotient (string-length base) 2)))
  89. (string-append prefix base))))
  90. (if (> (string-length uri-as-string) max-length)
  91. (let ((short (elide-path)))
  92. (if (< (string-length short) (string-length uri-as-string))
  93. short
  94. uri-as-string))
  95. uri-as-string))
  96. (define (nar-uri-abbreviation uri)
  97. "Abbreviate URI, which is assumed to be the URI of a nar as served by Hydra
  98. and 'guix publish', something like
  99. \"http://example.org/nar/1ldrllwbna0aw5z8kpci4fsvbd2w8cw4-texlive-bin-2015\"."
  100. (let* ((uri (if (string? uri) (string->uri uri) uri))
  101. (path (basename (uri-path uri))))
  102. (if (and (> (string-length path) 33)
  103. (char=? (string-ref path 32) #\-))
  104. (string-drop path 33)
  105. path)))
  106. (define* (ftp-fetch uri file #:key timeout print-build-trace?)
  107. "Fetch data from URI and write it to FILE. Return FILE on success. Bail
  108. out if the connection could not be established in less than TIMEOUT seconds."
  109. (let* ((conn (match (and=> (uri-userinfo uri)
  110. (cut string-split <> #\:))
  111. (((? string? user))
  112. (ftp-open (uri-host uri) #:timeout timeout
  113. #:username user))
  114. (((? string? user) (? string? pass))
  115. (ftp-open (uri-host uri) #:timeout timeout
  116. #:username user
  117. #:password pass))
  118. (_ (ftp-open (uri-host uri) #:timeout timeout))))
  119. (size (false-if-exception (ftp-size conn (uri-path uri))))
  120. (in (ftp-retr conn (basename (uri-path uri))
  121. (dirname (uri-path uri))
  122. #:timeout timeout)))
  123. (call-with-output-file file
  124. (lambda (out)
  125. (dump-port* in out
  126. #:buffer-size %http-receive-buffer-size
  127. #:reporter
  128. (if print-build-trace?
  129. (progress-reporter/trace
  130. file (uri->string uri) size)
  131. (progress-reporter/file
  132. (uri-abbreviation uri) size)))))
  133. (ftp-close conn)
  134. (unless print-build-trace?
  135. (newline))
  136. file))
  137. ;; Autoload GnuTLS so that this module can be used even when GnuTLS is
  138. ;; not available. At compile time, this yields "possibly unbound
  139. ;; variable" warnings, but these are OK: we know that the variables will
  140. ;; be bound if we need them, because (guix download) adds GnuTLS as an
  141. ;; input in that case.
  142. (define (load-gnutls)
  143. ;; XXX: Use this hack instead of #:autoload to avoid compilation errors.
  144. ;; See <http://bugs.gnu.org/12202>.
  145. (module-use! (resolve-module '(guix build download))
  146. (resolve-interface '(gnutls)))
  147. (set! load-gnutls (const #t)))
  148. (define %x509-certificate-directory
  149. ;; The directory where X.509 authority PEM certificates are stored.
  150. (make-parameter (or (getenv "GUIX_TLS_CERTIFICATE_DIRECTORY")
  151. (getenv "SSL_CERT_DIR") ;like OpenSSL
  152. "/etc/ssl/certs")))
  153. (define (set-certificate-credentials-x509-trust-file!* cred file format)
  154. "Like 'set-certificate-credentials-x509-trust-file!', but without the file
  155. name decoding bug described at
  156. <https://debbugs.gnu.org/cgi/bugreport.cgi?bug=26948#17>."
  157. (let ((data (call-with-input-file file get-bytevector-all)))
  158. (set-certificate-credentials-x509-trust-data! cred data format)))
  159. (define (make-credendials-with-ca-trust-files directory)
  160. "Return certificate credentials with X.509 authority certificates read from
  161. DIRECTORY. Those authority certificates are checked when
  162. 'peer-certificate-status' is later called."
  163. (let ((cred (make-certificate-credentials))
  164. (files (match (scandir directory (cut string-suffix? ".pem" <>))
  165. ((or #f ())
  166. ;; Some distros provide nothing but bundles (*.crt) under
  167. ;; /etc/ssl/certs, so look for them.
  168. (or (scandir directory (cut string-suffix? ".crt" <>))
  169. '()))
  170. (pem pem))))
  171. (for-each (lambda (file)
  172. (let ((file (string-append directory "/" file)))
  173. ;; Protect against dangling symlinks.
  174. (when (file-exists? file)
  175. (set-certificate-credentials-x509-trust-file!*
  176. cred file
  177. x509-certificate-format/pem))))
  178. files)
  179. cred))
  180. (define (peer-certificate session)
  181. "Return the certificate of the remote peer in SESSION."
  182. (match (session-peer-certificate-chain session)
  183. ((first _ ...)
  184. (import-x509-certificate first x509-certificate-format/der))))
  185. (define (assert-valid-server-certificate session server)
  186. "Return #t if the certificate of the remote peer for SESSION is a valid
  187. certificate for SERVER, where SERVER is the expected host name of peer."
  188. (define cert
  189. (peer-certificate session))
  190. ;; First check whether the server's certificate matches SERVER.
  191. (unless (x509-certificate-matches-hostname? cert server)
  192. (throw 'tls-certificate-error 'host-mismatch cert server))
  193. ;; Second check its validity and reachability from the set of authority
  194. ;; certificates loaded via 'set-certificate-credentials-x509-trust-file!'.
  195. (match (peer-certificate-status session)
  196. (() ;certificate is valid
  197. #t)
  198. ((statuses ...)
  199. (throw 'tls-certificate-error 'invalid-certificate cert server
  200. statuses))))
  201. (define (print-tls-certificate-error port key args default-printer)
  202. "Print the TLS certificate error represented by ARGS in an intelligible
  203. way."
  204. (match args
  205. (('host-mismatch cert server)
  206. (format port
  207. "X.509 server certificate for '~a' does not match: ~a~%"
  208. server (x509-certificate-dn cert)))
  209. (('invalid-certificate cert server statuses)
  210. (format port
  211. "X.509 certificate of '~a' could not be verified:~%~{ ~a~%~}"
  212. server
  213. (map certificate-status->string statuses)))))
  214. (set-exception-printer! 'tls-certificate-error
  215. print-tls-certificate-error)
  216. (define* (tls-wrap port server #:key (verify-certificate? #t))
  217. "Return PORT wrapped in a TLS connection to SERVER. SERVER must be a DNS
  218. host name without trailing dot."
  219. (define (log level str)
  220. (format (current-error-port)
  221. "gnutls: [~a|~a] ~a" (getpid) level str))
  222. (load-gnutls)
  223. (let ((session (make-session connection-end/client))
  224. (ca-certs (%x509-certificate-directory)))
  225. ;; Some servers such as 'cloud.github.com' require the client to support
  226. ;; the 'SERVER NAME' extension. However, 'set-session-server-name!' is
  227. ;; not available in older GnuTLS releases. See
  228. ;; <http://bugs.gnu.org/18526> for details.
  229. (if (module-defined? (resolve-interface '(gnutls))
  230. 'set-session-server-name!)
  231. (set-session-server-name! session server-name-type/dns server)
  232. (format (current-error-port)
  233. "warning: TLS 'SERVER NAME' extension not supported~%"))
  234. (set-session-transport-fd! session (fileno port))
  235. (set-session-default-priority! session)
  236. ;; The "%COMPAT" bit allows us to work around firewall issues (info
  237. ;; "(gnutls) Priority Strings"); see <http://bugs.gnu.org/23311>.
  238. ;; Explicitly disable SSLv3, which is insecure:
  239. ;; <https://tools.ietf.org/html/rfc7568>.
  240. (set-session-priorities! session "NORMAL:%COMPAT:-VERS-SSL3.0")
  241. (set-session-credentials! session
  242. (if (and verify-certificate? ca-certs)
  243. (make-credendials-with-ca-trust-files
  244. ca-certs)
  245. (make-certificate-credentials)))
  246. ;; Uncomment the following lines in case of debugging emergency.
  247. ;;(set-log-level! 10)
  248. ;;(set-log-procedure! log)
  249. (catch 'gnutls-error
  250. (lambda ()
  251. (handshake session))
  252. (lambda (key err proc . rest)
  253. (cond ((eq? err error/warning-alert-received)
  254. ;; Like Wget, do no stop upon non-fatal alerts such as
  255. ;; 'alert-description/unrecognized-name'.
  256. (format (current-error-port)
  257. "warning: TLS warning alert received: ~a~%"
  258. (alert-description->string (alert-get session)))
  259. (handshake session))
  260. (else
  261. ;; XXX: We'd use 'gnutls_error_is_fatal' but (gnutls) doesn't
  262. ;; provide a binding for this.
  263. (apply throw key err proc rest)))))
  264. ;; Verify the server's certificate if needed.
  265. (when verify-certificate?
  266. (catch 'tls-certificate-error
  267. (lambda ()
  268. (assert-valid-server-certificate session server))
  269. (lambda args
  270. (close-port port)
  271. (apply throw args))))
  272. (let ((record (session-record-port session)))
  273. (define (read! bv start count)
  274. (define read
  275. (catch 'gnutls-error
  276. (lambda ()
  277. (get-bytevector-n! record bv start count))
  278. (lambda (key err proc . rest)
  279. ;; When responding to "Connection: close" requests, some
  280. ;; servers close the connection abruptly after sending the
  281. ;; response body, without doing a proper TLS connection
  282. ;; termination. Treat it as EOF.
  283. (if (eq? err error/premature-termination)
  284. the-eof-object
  285. (apply throw key err proc rest)))))
  286. (if (eof-object? read)
  287. 0
  288. read))
  289. (define (write! bv start count)
  290. (put-bytevector record bv start count)
  291. (force-output record)
  292. count)
  293. (define (get-position)
  294. (port-position record))
  295. (define (set-position! new-position)
  296. (set-port-position! record new-position))
  297. (define (close)
  298. (unless (port-closed? port)
  299. (close-port port))
  300. (unless (port-closed? record)
  301. (close-port record)))
  302. (define (unbuffered port)
  303. (setvbuf port 'none)
  304. port)
  305. (setvbuf record 'block)
  306. ;; Return a port that wraps RECORD to ensure that closing it also
  307. ;; closes PORT, the actual socket port, and its file descriptor.
  308. ;; Make sure it does not introduce extra buffering (custom ports
  309. ;; are buffered by default as of Guile 3.0.5).
  310. ;; XXX: This wrapper would be unnecessary if GnuTLS could
  311. ;; automatically close SESSION's file descriptor when RECORD is
  312. ;; closed, but that doesn't seem to be possible currently (as of
  313. ;; 3.6.9).
  314. (unbuffered
  315. (make-custom-binary-input/output-port "gnutls wrapped port" read! write!
  316. get-position set-position!
  317. close)))))
  318. (define (ensure-uri uri-or-string) ;XXX: copied from (web http)
  319. (cond
  320. ((string? uri-or-string) (string->uri uri-or-string))
  321. ((uri? uri-or-string) uri-or-string)
  322. (else (error "Invalid URI" uri-or-string))))
  323. (define* (open-socket-for-uri uri-or-string #:key timeout)
  324. "Return an open input/output port for a connection to URI. When TIMEOUT is
  325. not #f, it must be a (possibly inexact) number denoting the maximum duration
  326. in seconds to wait for the connection to complete; passed TIMEOUT, an
  327. ETIMEDOUT error is raised."
  328. ;; Includes a fix for <http://bugs.gnu.org/15368> which affects Guile's
  329. ;; 'open-socket-for-uri' up to 2.0.11 included, uses 'connect*' instead
  330. ;; of 'connect', and uses AI_ADDRCONFIG.
  331. (define http-proxy (current-http-proxy))
  332. (define uri (ensure-uri (or http-proxy uri-or-string)))
  333. (define addresses
  334. (let ((port (uri-port uri)))
  335. (delete-duplicates
  336. (getaddrinfo (uri-host uri)
  337. (cond (port => number->string)
  338. (else (symbol->string (uri-scheme uri))))
  339. (if (number? port)
  340. (logior AI_ADDRCONFIG AI_NUMERICSERV)
  341. AI_ADDRCONFIG))
  342. (lambda (ai1 ai2)
  343. (equal? (addrinfo:addr ai1) (addrinfo:addr ai2))))))
  344. (let loop ((addresses addresses))
  345. (let* ((ai (car addresses))
  346. (s (with-fluids ((%default-port-encoding #f))
  347. ;; Restrict ourselves to TCP.
  348. (socket (addrinfo:fam ai) SOCK_STREAM IPPROTO_IP))))
  349. (catch 'system-error
  350. (lambda ()
  351. (connect* s (addrinfo:addr ai) timeout)
  352. ;; Buffer input and output on this port.
  353. (setvbuf s 'block)
  354. ;; If we're using a proxy, make a note of that.
  355. (when http-proxy (set-http-proxy-port?! s #t))
  356. s)
  357. (lambda args
  358. ;; Connection failed, so try one of the other addresses.
  359. (close s)
  360. (if (null? (cdr addresses))
  361. (apply throw args)
  362. (loop (cdr addresses))))))))
  363. (define (setup-http-tunnel port uri)
  364. "Establish over PORT an HTTP tunnel to the destination server of URI."
  365. (define target
  366. (string-append (uri-host uri) ":"
  367. (number->string
  368. (or (uri-port uri)
  369. (match (uri-scheme uri)
  370. ('http 80)
  371. ('https 443))))))
  372. (format port "CONNECT ~a HTTP/1.1\r\n" target)
  373. (format port "Host: ~a\r\n\r\n" target)
  374. (force-output port)
  375. (read-response port))
  376. (define* (open-connection-for-uri uri
  377. #:key
  378. timeout
  379. (verify-certificate? #t))
  380. "Like 'open-socket-for-uri', but also handle HTTPS connections. The
  381. resulting port must be closed with 'close-connection'. When
  382. VERIFY-CERTIFICATE? is true, verify HTTPS server certificates."
  383. ;; Note: Guile 2.2.0's (web client) has a same-named export that's actually
  384. ;; undefined. See Guile commit 011669af3b428e5626f7bbf66b11d57d9768c047.
  385. (define https?
  386. (eq? 'https (uri-scheme uri)))
  387. (define https-proxy (let ((proxy (getenv "https_proxy")))
  388. (and (not (equal? proxy ""))
  389. proxy)))
  390. (let-syntax ((with-https-proxy
  391. (syntax-rules ()
  392. ((_ exp)
  393. ;; For HTTPS URIs, honor 'https_proxy', not 'http_proxy'.
  394. (let ((thunk (lambda () exp)))
  395. (if (and https?
  396. (module-variable
  397. (resolve-interface '(web client))
  398. 'current-http-proxy))
  399. (parameterize ((current-http-proxy https-proxy))
  400. (thunk))
  401. (thunk)))))))
  402. (with-https-proxy
  403. (let ((s (open-socket-for-uri uri #:timeout timeout)))
  404. ;; Buffer input and output on this port.
  405. (setvbuf s 'block %http-receive-buffer-size)
  406. (when (and https? https-proxy)
  407. (setup-http-tunnel s uri))
  408. (if https?
  409. (tls-wrap s (uri-host uri)
  410. #:verify-certificate? verify-certificate?)
  411. s)))))
  412. (define (close-connection port) ;deprecated
  413. (unless (port-closed? port)
  414. (close-port port)))
  415. ;; XXX: This is an awful hack to make sure the (set-port-encoding! p
  416. ;; "ISO-8859-1") call in `read-response' passes, even during bootstrap
  417. ;; where iconv is not available.
  418. (module-define! (resolve-module '(web response))
  419. 'set-port-encoding!
  420. (lambda (p e) #f))
  421. (define (resolve-uri-reference ref base)
  422. "Resolve the URI reference REF, interpreted relative to the BASE URI, into a
  423. target URI, according to the algorithm specified in RFC 3986 section 5.2.2.
  424. Return the resulting target URI."
  425. (define (merge-paths base-path rel-path)
  426. (let* ((base-components (string-split base-path #\/))
  427. (base-directory-components (match base-components
  428. ((components ... last) components)
  429. (() '())))
  430. (base-directory (string-join base-directory-components "/")))
  431. (string-append base-directory "/" rel-path)))
  432. (define (remove-dot-segments path)
  433. (let loop ((in
  434. ;; Drop leading "." and ".." components from a relative path.
  435. ;; (absolute paths will start with a "" component)
  436. (drop-while (match-lambda
  437. ((or "." "..") #t)
  438. (_ #f))
  439. (string-split path #\/)))
  440. (out '()))
  441. (match in
  442. (("." . rest)
  443. (loop rest out))
  444. ((".." . rest)
  445. (match out
  446. ((or () (""))
  447. (error "remove-dot-segments: too many '..' components" path))
  448. (_
  449. (loop rest (cdr out)))))
  450. ((component . rest)
  451. (loop rest (cons component out)))
  452. (()
  453. (string-join (reverse out) "/")))))
  454. (cond ((or (uri-scheme ref)
  455. (uri-host ref))
  456. (build-uri (or (uri-scheme ref)
  457. (uri-scheme base))
  458. #:userinfo (uri-userinfo ref)
  459. #:host (uri-host ref)
  460. #:port (uri-port ref)
  461. #:path (remove-dot-segments (uri-path ref))
  462. #:query (uri-query ref)
  463. #:fragment (uri-fragment ref)))
  464. ((string-null? (uri-path ref))
  465. (build-uri (uri-scheme base)
  466. #:userinfo (uri-userinfo base)
  467. #:host (uri-host base)
  468. #:port (uri-port base)
  469. #:path (remove-dot-segments (uri-path base))
  470. #:query (or (uri-query ref)
  471. (uri-query base))
  472. #:fragment (uri-fragment ref)))
  473. (else
  474. (build-uri (uri-scheme base)
  475. #:userinfo (uri-userinfo base)
  476. #:host (uri-host base)
  477. #:port (uri-port base)
  478. #:path (remove-dot-segments
  479. (if (string-prefix? "/" (uri-path ref))
  480. (uri-path ref)
  481. (merge-paths (uri-path base)
  482. (uri-path ref))))
  483. #:query (uri-query ref)
  484. #:fragment (uri-fragment ref)))))
  485. (define* (http-fetch uri #:key timeout (verify-certificate? #t))
  486. "Return an input port containing the data at URI, and the expected number of
  487. bytes available or #f. When TIMEOUT is true, bail out if the connection could
  488. not be established in less than TIMEOUT seconds. When VERIFY-CERTIFICATE? is
  489. true, verify HTTPS certificates; otherwise simply ignore them."
  490. (define headers
  491. `(;; Some web sites, such as http://dist.schmorp.de, would block you if
  492. ;; there's no 'User-Agent' header, presumably on the assumption that
  493. ;; you're a spammer. So work around that.
  494. (User-Agent . "GNU Guile")
  495. ;; Some servers, such as https://alioth.debian.org, return "406 Not
  496. ;; Acceptable" when not explicitly told that everything is accepted.
  497. (Accept . "*/*")
  498. ;; Basic authentication, if needed.
  499. ,@(match (uri-userinfo uri)
  500. ((? string? str)
  501. `((Authorization . ,(string-append "Basic "
  502. (base64-encode
  503. (string->utf8 str))))))
  504. (_ '()))))
  505. (let*-values (((connection)
  506. (open-connection-for-uri uri
  507. #:timeout timeout
  508. #:verify-certificate?
  509. verify-certificate?))
  510. ((resp port)
  511. (http-get uri #:port connection #:decode-body? #f
  512. #:streaming? #t
  513. #:headers headers))
  514. ((code)
  515. (response-code resp)))
  516. (case code
  517. ((200) ; OK
  518. (values port (response-content-length resp)))
  519. ((301 ; moved permanently
  520. 302 ; found (redirection)
  521. 303 ; see other
  522. 307 ; temporary redirection
  523. 308) ; permanent redirection
  524. (let ((uri (resolve-uri-reference (response-location resp) uri)))
  525. (format #t "following redirection to `~a'...~%"
  526. (uri->string uri))
  527. (close connection)
  528. (http-fetch uri
  529. #:timeout timeout
  530. #:verify-certificate? verify-certificate?)))
  531. (else
  532. (error "download failed" (uri->string uri)
  533. code (response-reason-phrase resp))))))
  534. (define-syntax-rule (false-if-exception* body ...)
  535. "Like `false-if-exception', but print the exception on the error port."
  536. (catch #t
  537. (lambda ()
  538. body ...)
  539. (lambda (key . args)
  540. #f)
  541. (lambda (key . args)
  542. (print-exception (current-error-port) #f key args))))
  543. (define (uri-vicinity dir file)
  544. "Concatenate DIR, slash, and FILE, keeping only one slash in between.
  545. This is required by some HTTP servers."
  546. (string-append (string-trim-right dir #\/) "/"
  547. (string-trim file #\/)))
  548. (define (maybe-expand-mirrors uri mirrors)
  549. "If URI uses the 'mirror' scheme, expand it according to the MIRRORS alist.
  550. Return a list of URIs."
  551. (case (uri-scheme uri)
  552. ((mirror)
  553. (let ((kind (string->symbol (uri-host uri)))
  554. (path (uri-path uri)))
  555. (match (assoc-ref mirrors kind)
  556. ((mirrors ..1)
  557. (map (compose string->uri (cut uri-vicinity <> path))
  558. mirrors))
  559. (_
  560. (error "unsupported URL mirror kind" kind uri)))))
  561. (else
  562. (list uri))))
  563. (define* (url-fetch url file
  564. #:key
  565. (timeout 10) (verify-certificate? #t)
  566. (mirrors '()) (content-addressed-mirrors '())
  567. (hashes '())
  568. print-build-trace?)
  569. "Fetch FILE from URL; URL may be either a single string, or a list of
  570. string denoting alternate URLs for FILE. Return #f on failure, and FILE
  571. on success.
  572. When MIRRORS is defined, it must be an alist of mirrors; it is used to resolve
  573. 'mirror://' URIs.
  574. HASHES must be a list of algorithm/hash pairs, where each algorithm is a
  575. symbol such as 'sha256 and each hash is a bytevector.
  576. CONTENT-ADDRESSED-MIRRORS must be a list of procedures that, given a hash
  577. algorithm and a hash, return a URL where the specified data can be retrieved
  578. or #f.
  579. When VERIFY-CERTIFICATE? is true, validate HTTPS server certificates;
  580. otherwise simply ignore them."
  581. (define uri
  582. (append-map (cut maybe-expand-mirrors <> mirrors)
  583. (match url
  584. ((_ ...) (map string->uri url))
  585. (_ (list (string->uri url))))))
  586. (define (fetch uri file)
  587. (format #t "~%Starting download of ~a~%From ~a...~%"
  588. file (uri->string uri))
  589. (case (uri-scheme uri)
  590. ((http https)
  591. (false-if-exception*
  592. (let-values (((port size)
  593. (http-fetch uri
  594. #:verify-certificate? verify-certificate?
  595. #:timeout timeout)))
  596. (call-with-output-file file
  597. (lambda (output)
  598. (dump-port* port output
  599. #:buffer-size %http-receive-buffer-size
  600. #:reporter (if print-build-trace?
  601. (progress-reporter/trace
  602. file (uri->string uri) size)
  603. (progress-reporter/file
  604. (uri-abbreviation uri) size)))
  605. (newline)))
  606. file)))
  607. ((ftp)
  608. (false-if-exception* (ftp-fetch uri file
  609. #:timeout timeout
  610. #:print-build-trace?
  611. print-build-trace?)))
  612. (else
  613. (format #t "skipping URI with unsupported scheme: ~s~%"
  614. uri)
  615. #f)))
  616. (define content-addressed-uris
  617. (append-map (lambda (make-url)
  618. (filter-map (match-lambda
  619. ((hash-algo . hash)
  620. (let ((file (strip-store-file-name file)))
  621. (string->uri (make-url file hash-algo hash)))))
  622. hashes))
  623. content-addressed-mirrors))
  624. ;; Make this unbuffered so 'progress-report/file' works as expected. 'line
  625. ;; means '\n', not '\r', so it's not appropriate here.
  626. (setvbuf (current-output-port) 'none)
  627. (setvbuf (current-error-port) 'line)
  628. (let try ((uri (append uri content-addressed-uris)))
  629. (match uri
  630. ((uri tail ...)
  631. (or (fetch uri file)
  632. (try tail)))
  633. (()
  634. (format (current-error-port) "failed to download ~s from ~s~%"
  635. file url)
  636. ;; Remove FILE in case we made an incomplete download, for example due
  637. ;; to ENOSPC.
  638. (catch 'system-error
  639. (lambda ()
  640. (delete-file file))
  641. (const #f))
  642. #f))))
  643. ;;; download.scm ends here