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