;;; GNU Guix --- Functional package management for GNU
  Copyright © 2012 , 2013 , 2014 , 2015 , 2016   <  >
  Copyright © 2013 , 2014 , 2015   <  >
  Copyright © 2015   <  >
  Copyright © 2016   <  >
  Copyright © 2016   <  >
  Copyright © 2017     <  >
;;;
;;; This file is part of GNU Guix.
;;;
  GNU  is free software ; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by
  the Free Software Foundation ; either version 3 of the License , or ( at
;;; your option) any later version.
;;;
;;; GNU Guix is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
  You should have received a copy of the GNU General Public License
  along with GNU  .   If not , see < / > .

(define-module (guix download)
  #:use-module (ice-9 match)
  #:use-module (guix derivations)
  #:use-module (guix packages)
  #:use-module (guix store)
  #:use-module ((guix build download) #:prefix build:)
  #:use-module (guix monads)
  #:use-module (guix gexp)
  #:use-module (guix utils)
  #:use-module (web uri)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%mirrors
            url-fetch
            url-fetch/tarbomb
            url-fetch/zipbomb
            download-to-store))

;;; Commentary:
;;;
;;; Produce fixed-output derivations with data fetched over HTTP or FTP.
;;;
;;; Code:

(define %mirrors
  Mirror lists used when ` mirror:// ' URLs are passed .
  (let* ((gnu-mirrors
          '(;; This one redirects to a (supposedly) nearby and (supposedly)
            ;; up-to-date mirror.
            "/"

            "ftp-berlin.de/pub/gnu/"
            "ftp/"

            ;; This one is the master repository, and thus it's always
            ;; up-to-date.
            "/")))
    `((gnu ,@gnu-mirrors)
      (gcc
       "ftp/"
       "ftp-berlin.de/unix/languages/gcc/"
       "ftp/"
       "ftp/"
       ,@(map (cut string-append <> "/gcc") gnu-mirrors))
      (gnupg
       "ftp/"
       "ftp/"
       "ftp/"
       ""
       "ftp/"
       "ftp/"
       "/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/")
      (gnome
       "/"
       "/"
       "/"
       "/"
       "/")
      (hackage
       "/")
      (savannah
       "/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "-noredirect/")
      (sourceforge ; /
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "-sea2.dl.sourceforge.net/project/"
       "/"
       "/"
       "/")
      (kernel.org
       "/"
       "-dresden.de/pub/mirrors/kernel.org/"
       "-kernel.uio.no/pub/"
       "/"
       "ftp/"
       "/"
       "/")
      (apache             ; from 
       "/"
       "/"
       "ftp/"
       "/"
       "/"
       "-mirror.rbc.ru/pub/apache/"

       ;; As a last resort, try the archive.
       "/")
      (xorg               ; from 
       "/" ; main mirrors
  North America
       "ftp/"
       "/"
       "/"
       "/"
  Europe
       "ftp/"
       "ftp-berlin.de/unix/X11/FTP.X.ORG/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp-to-web.de/pub/mirrors/x.org/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
  East Asia
       "ftp-aizu.ac.jp/pub/x11/x.org/"
       "ftp-u.ac.jp/pub/X11/x.org/"
       "ftp/"
       "ftp-part.com/xorg/"
       "/"
  South Africa
      (cpan                              ; from 
       "/"
       "ftp/"
       "ftp/"
       "/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "/"
       "ftp/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/")
      (cran
       ;; Arbitrary mirrors from -project.org/mirrors.html
       ;; This one automatically redirects to servers worldwide
       "-project.org/"
       "/"
       "-lyon1.fr/"
       "/"
       "/"
       "/"
       "/")
      (imagemagick
       ;; from 
       ;; (without mirrors that are unavailable or not up to date)
       ;; mirrors keeping old versions at the top level
       "ftp/"
       ;; mirrors moving old versions to "legacy"
       "-au.go-parts.com/mirrors/ImageMagick/"
       "ftp/"
       "/"
       "ftp/"
       "ftp-aizu.ac.jp/pub/graphics/image/ImageMagick/imagemagick.org/"
       "ftp/"
       "/"
       ""
       "ftp/"
       "-ru.go-parts.com/mirrors/ImageMagick/"
       "/"
       "-uk.go-parts.com/mirrors/ImageMagick/"
       "-usa.go-parts.com/mirrors/ImageMagick/"
       "ftp/"
       "/"
       ;; one legacy location as a last resort
       "/")
      (debian
       "/"
       "/"
       "/"
       "/")
      (kde
       ""
       ;; Mirrors from 
  Europe
       ""
       ""
       "/"
       "/"
       "/"
       "-stud.fht-esslingen.de/Mirrors/ftp.kde.org/pub/kde/"
       "-uwe.me/kde/ftp/"
       "/"
       "/"
       ""
       "-aachen.de/ftp/pub/mirror/kde/"
       "-wuerzburg.de/pub/unix/kde/"
       "/"
       "/"
       "-mirror.freenux.org/"
       "/"
       "-ftp.lip6.fr/pub/X11/kde/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "-connect.vn.ua/"
  North America
       "/"
       "/"
       "/"
       "-usa.go-parts.com/kde"
       "/"
       "/"
       "/"
       "/"
  Oceania
       "/"
       "/"))))

(define %mirror-file
  ;; Copy of the list of mirrors to a file.  This allows us to keep a single
  ;; copy in the store, and computing it here avoids repeated calls to
  ;; 'object->string'.
  (plain-file "mirrors" (object->string %mirrors)))

(define %content-addressed-mirrors
  ;; List of content-addressed mirrors.  Each mirror is represented as a
  ;; procedure that takes a file name, an algorithm (symbol) and a hash
  ( bytevector ) , and returns a URL or # f.
  Note : Avoid ' https ' to mitigate <  > .
  ;; TODO: Add more.
  '(list (lambda (file algo hash)
           ;; Files served by 'guix publish' are accessible under a single
           ;; hash algorithm.
           (string-append "/"
                          file "/" (symbol->string algo) "/"
                          (bytevector->nix-base32-string hash)))
         (lambda (file algo hash)
           ;; 'tarballs.nixos.org' supports several algorithms.
           (string-append "/"
                          (symbol->string algo) "/"
                          (bytevector->nix-base32-string hash)))))

(define %content-addressed-mirror-file
  Content - addressed mirrors stored in a file .
  (plain-file "content-addressed-mirrors"
              (object->string %content-addressed-mirrors)))

(define (gnutls-package)
  "Return the default GnuTLS package."
  (let ((module (resolve-interface '(gnu packages tls))))
    (module-ref module 'gnutls)))

(define built-in-builders*
  (let ((cache (make-weak-key-hash-table)))
    (lambda ()
      "Return, as a monadic value, the list of built-in builders supported by
the daemon."
      (lambda (store)
  Memoize the result to avoid repeated RPCs .
        (values (or (hashq-ref cache store)
                    (let ((result (built-in-builders store)))
                      (hashq-set! cache store result)
                      result))
                store)))))

(define* (built-in-download file-name url
                            #:key system hash-algo hash
                            mirrors content-addressed-mirrors
                            (guile 'unused))
  "Download FILE-NAME from URL using the built-in 'download' builder.

This is an \"out-of-band\" download in that the returned derivation does not
explicitly depend on Guile, GnuTLS, etc.  Instead, the daemon performs the
download by itself using its own dependencies."
  (mlet %store-monad ((mirrors (lower-object mirrors))
                      (content-addressed-mirrors
                       (lower-object content-addressed-mirrors)))
    (raw-derivation file-name "builtin:download" '()
                    #:system system
                    #:hash-algo hash-algo
                    #:hash hash
                    #:inputs `((,mirrors)
                               (,content-addressed-mirrors))

                    ;; Honor the user's proxy and locale settings.
                    #:leaked-env-vars '("http_proxy" "https_proxy"
                                        "LC_ALL" "LC_MESSAGES" "LANG"
                                        "COLUMNS")

                    #:env-vars `(("url" . ,(object->string url))
                                 ("mirrors" . ,mirrors)
                                 ("content-addressed-mirrors"
                                  . ,content-addressed-mirrors))

                    ;; Do not offload this derivation because we cannot be
                    ;; sure that the remote daemon supports the 'download'
                    ;; built-in.  We may remove this limitation when support
                    ;; for that built-in is widespread.
                    #:local-build? #t)))

(define* (in-band-download file-name url
                           #:key system hash-algo hash
                           mirrors content-addressed-mirrors
                           guile)
  "Download FILE-NAME from URL using a normal, \"in-band\" fixed-output
derivation.

This is now deprecated since it has the drawback of causing bootstrapping
issues: we may need to build GnuTLS just to be able to download the source of
GnuTLS itself and its dependencies.  See <>."
  (define need-gnutls?
  True if any of the URLs need TLS support .
    (let ((https? (cut string-prefix? "https://" <>)))
      (match url
        ((? string?)
         (https? url))
        ((url ...)
         (any https? url)))))

  (define builder
    (with-imported-modules '((guix build download)
                             (guix build utils)
                             (guix ftp-client)
                             (guix base32)
                             (guix base64))
      #~(begin
          #+(if need-gnutls?

                ;; Add GnuTLS to the inputs and to the load path.
                #~(eval-when (load expand eval)
                    (set! %load-path
                      (cons (string-append #+(gnutls-package)
                                           "/share/guile/site/"
                                           (effective-version))
                            %load-path)))
                #~#t)

          (use-modules (guix build download)
                       (guix base32))

          (let ((value-from-environment (lambda (variable)
                                          (call-with-input-string
                                              (getenv variable)
                                            read))))
            (url-fetch (value-from-environment "guix download url")
                       #$output
                       #:mirrors (call-with-input-file #$mirrors read)

  Content - addressed mirrors .
                       #:hashes
                       (value-from-environment "guix download hashes")
                       #:content-addressed-mirrors
                       (primitive-load #$content-addressed-mirrors)

                       ;; No need to validate certificates since we know the
                       ;; hash of the expected result.
                       #:verify-certificate? #f)))))

  (mlet %store-monad ((guile (package->derivation guile system)))
    (gexp->derivation file-name builder
                      #:guile-for-build guile
                      #:system system
                      #:hash-algo hash-algo
                      #:hash hash

                      ;; Use environment variables and a fixed script
  name so there 's only one script in store for
                      ;; all the downloads.
                      #:script-name "download"
                      #:env-vars
                      `(("guix download url" . ,(object->string url))
                        ("guix download hashes"
                         . ,(object->string `((,hash-algo . ,hash)))))

                      ;; Honor the user's proxy settings.
                      #:leaked-env-vars '("http_proxy" "https_proxy")

                      ;; In general, offloading downloads is not a good
  idea .    before 0.8.3 would also
                      ;; interpret this as "do not substitute" (see
                      ;; <>.)
                      #:local-build? #t)))

(define* (url-fetch url hash-algo hash
                    #:optional name
                    #:key (system (%current-system))
                    (guile (default-guile)))
  "Return a fixed-output derivation that fetches URL (a string, or a list of
strings denoting alternate URLs), which is expected to have hash HASH of type
HASH-ALGO (a symbol).  By default, the file name is the base name of URL;
optionally, NAME can specify a different file name.

When one of the URL starts with mirror://, then its host part is
interpreted as the name of a mirror scheme, taken from %MIRROR-FILE.

Alternately, when URL starts with file://, return the corresponding file name
in the store."
  (define file-name
    (match url
      ((head _ ...)
       (basename head))
      (_
       (basename url))))

  (let ((uri (and (string? url) (string->uri url))))
    (if (or (and (string? url) (not uri))
            (and uri (memq (uri-scheme uri) '(#f file))))
        (interned-file (if uri (uri-path uri) url)
                       (or name file-name))
        (mlet* %store-monad ((builtins (built-in-builders*))
                             (download -> (if (member "download" builtins)
                                              built-in-download
                                              in-band-download)))
          (download (or name file-name) url
                    #:guile guile
                    #:system system
                    #:hash-algo hash-algo
                    #:hash hash
                    #:mirrors %mirror-file
                    #:content-addressed-mirrors
                    %content-addressed-mirror-file)))))

(define* (url-fetch/tarbomb url hash-algo hash
                            #:optional name
                            #:key (system (%current-system))
                            (guile (default-guile)))
  "Similar to 'url-fetch' but unpack the file from URL in a directory of its
own.  This helper makes it easier to deal with \"tar bombs\"."
  (define file-name
    (match url
      ((head _ ...)
       (basename head))
      (_
       (basename url))))
  (define gzip
    (module-ref (resolve-interface '(gnu packages compression)) 'gzip))
  (define tar
    (module-ref (resolve-interface '(gnu packages base)) 'tar))

  (mlet %store-monad ((drv (url-fetch url hash-algo hash
                                      (string-append "tarbomb-"
                                                     (or name file-name))
                                      #:system system
                                      #:guile guile)))
    ;; Take the tar bomb, and simply unpack it as a directory.
    (gexp->derivation (or name file-name)
                      #~(begin
                          (mkdir #$output)
                          (setenv "PATH" (string-append #$gzip "/bin"))
                          (chdir #$output)
                          (zero? (system* (string-append #$tar "/bin/tar")
                                          "xf" #$drv)))
                      #:local-build? #t)))

(define* (url-fetch/zipbomb url hash-algo hash
                            #:optional name
                            #:key (system (%current-system))
                            (guile (default-guile)))
  "Similar to 'url-fetch' but unpack the zip file at URL in a directory of its
own.  This helper makes it easier to deal with \"zip bombs\"."
  (define file-name
    (match url
      ((head _ ...)
       (basename head))
      (_
       (basename url))))
  (define unzip
    (module-ref (resolve-interface '(gnu packages zip)) 'unzip))

  (mlet %store-monad ((drv (url-fetch url hash-algo hash
                                      (string-append "zipbomb-"
                                                     (or name file-name))
                                      #:system system
                                      #:guile guile)))
    ;; Take the zip bomb, and simply unpack it as a directory.
    (gexp->derivation (or name file-name)
                      #~(begin
                          (mkdir #$output)
                          (chdir #$output)
                          (zero? (system* (string-append #$unzip "/bin/unzip")
                                          #$drv)))
                      #:local-build? #t)))

(define* (download-to-store store url #:optional (name (basename url))
                            #:key (log (current-error-port)) recursive?
                            (verify-certificate? #t))
  "Download from URL to STORE, either under NAME or URL's basename if
omitted.  Write progress reports to LOG.  RECURSIVE? has the same effect as
the same-named parameter of 'add-to-store'.  VERIFY-CERTIFICATE? determines
whether or not to validate HTTPS server certificates."
  (define uri
    (string->uri url))

  (if (or (not uri) (memq (uri-scheme uri) '(file #f)))
      (add-to-store store name recursive? "sha256"
                    (if uri (uri-path uri) url))
      (call-with-temporary-output-file
       (lambda (temp port)
         (let ((result
                (parameterize ((current-output-port log))
                  (build:url-fetch url temp
                                   #:mirrors %mirrors
                                   #:verify-certificate?
                                   verify-certificate?))))
           (close port)
           (and result
                (add-to-store store name recursive? "sha256" temp)))))))

;;; download.scm ends here

 GNU Guix --- Functional package management for GNU

 This file is part of GNU Guix.

 you can redistribute it and/or modify it
 either version 3 of the License , or ( at
 your option) any later version.

 GNU Guix is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 Commentary:

 Produce fixed-output derivations with data fetched over HTTP or FTP.

 Code:
 This one redirects to a (supposedly) nearby and (supposedly)
 up-to-date mirror.
 This one is the master repository, and thus it's always
 up-to-date.
 /
 from 
 As a last resort, try the archive.
 from 
 main mirrors
 from 
 Arbitrary mirrors from -project.org/mirrors.html
 This one automatically redirects to servers worldwide
 from 
 (without mirrors that are unavailable or not up to date)
 mirrors keeping old versions at the top level
 mirrors moving old versions to "legacy"
 one legacy location as a last resort
 Mirrors from 
 Copy of the list of mirrors to a file.  This allows us to keep a single
 copy in the store, and computing it here avoids repeated calls to
 'object->string'.
 List of content-addressed mirrors.  Each mirror is represented as a
 procedure that takes a file name, an algorithm (symbol) and a hash
 TODO: Add more.
 Files served by 'guix publish' are accessible under a single
 hash algorithm.
 'tarballs.nixos.org' supports several algorithms.
 Honor the user's proxy and locale settings.
 Do not offload this derivation because we cannot be
 sure that the remote daemon supports the 'download'
 built-in.  We may remove this limitation when support
 for that built-in is widespread.
 Add GnuTLS to the inputs and to the load path.
 No need to validate certificates since we know the
 hash of the expected result.
 Use environment variables and a fixed script
 all the downloads.
 Honor the user's proxy settings.
 In general, offloading downloads is not a good
 interpret this as "do not substitute" (see
 <>.)

 Take the tar bomb, and simply unpack it as a directory.
 Take the zip bomb, and simply unpack it as a directory.
 download.scm ends here
  Copyright © 2012 , 2013 , 2014 , 2015 , 2016   <  >
  Copyright © 2013 , 2014 , 2015   <  >
  Copyright © 2015   <  >
  Copyright © 2016   <  >
  Copyright © 2016   <  >
  Copyright © 2017     <  >
  under the terms of the GNU General Public License as published by
  You should have received a copy of the GNU General Public License
  along with GNU  .   If not , see < / > .

(define-module (guix download)
  #:use-module (ice-9 match)
  #:use-module (guix derivations)
  #:use-module (guix packages)
  #:use-module (guix store)
  #:use-module ((guix build download) #:prefix build:)
  #:use-module (guix monads)
  #:use-module (guix gexp)
  #:use-module (guix utils)
  #:use-module (web uri)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:export (%mirrors
            url-fetch
            url-fetch/tarbomb
            url-fetch/zipbomb
            download-to-store))


(define %mirrors
  Mirror lists used when ` mirror:// ' URLs are passed .
  (let* ((gnu-mirrors
            "/"

            "ftp-berlin.de/pub/gnu/"
            "ftp/"

            "/")))
    `((gnu ,@gnu-mirrors)
      (gcc
       "ftp/"
       "ftp-berlin.de/unix/languages/gcc/"
       "ftp/"
       "ftp/"
       ,@(map (cut string-append <> "/gcc") gnu-mirrors))
      (gnupg
       "ftp/"
       "ftp/"
       "ftp/"
       ""
       "ftp/"
       "ftp/"
       "/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/")
      (gnome
       "/"
       "/"
       "/"
       "/"
       "/")
      (hackage
       "/")
      (savannah
       "/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "-noredirect/")
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "-sea2.dl.sourceforge.net/project/"
       "/"
       "/"
       "/")
      (kernel.org
       "/"
       "-dresden.de/pub/mirrors/kernel.org/"
       "-kernel.uio.no/pub/"
       "/"
       "ftp/"
       "/"
       "/")
       "/"
       "/"
       "ftp/"
       "/"
       "/"
       "-mirror.rbc.ru/pub/apache/"

       "/")
  North America
       "ftp/"
       "/"
       "/"
       "/"
  Europe
       "ftp/"
       "ftp-berlin.de/unix/X11/FTP.X.ORG/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp-to-web.de/pub/mirrors/x.org/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
  East Asia
       "ftp-aizu.ac.jp/pub/x11/x.org/"
       "ftp-u.ac.jp/pub/X11/x.org/"
       "ftp/"
       "ftp-part.com/xorg/"
       "/"
  South Africa
       "/"
       "ftp/"
       "ftp/"
       "/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "ftp/"
       "/"
       "ftp/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/")
      (cran
       "-project.org/"
       "/"
       "-lyon1.fr/"
       "/"
       "/"
       "/"
       "/")
      (imagemagick
       "ftp/"
       "-au.go-parts.com/mirrors/ImageMagick/"
       "ftp/"
       "/"
       "ftp/"
       "ftp-aizu.ac.jp/pub/graphics/image/ImageMagick/imagemagick.org/"
       "ftp/"
       "/"
       ""
       "ftp/"
       "-ru.go-parts.com/mirrors/ImageMagick/"
       "/"
       "-uk.go-parts.com/mirrors/ImageMagick/"
       "-usa.go-parts.com/mirrors/ImageMagick/"
       "ftp/"
       "/"
       "/")
      (debian
       "/"
       "/"
       "/"
       "/")
      (kde
       ""
  Europe
       ""
       ""
       "/"
       "/"
       "/"
       "-stud.fht-esslingen.de/Mirrors/ftp.kde.org/pub/kde/"
       "-uwe.me/kde/ftp/"
       "/"
       "/"
       ""
       "-aachen.de/ftp/pub/mirror/kde/"
       "-wuerzburg.de/pub/unix/kde/"
       "/"
       "/"
       "-mirror.freenux.org/"
       "/"
       "-ftp.lip6.fr/pub/X11/kde/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "/"
       "-connect.vn.ua/"
  North America
       "/"
       "/"
       "/"
       "-usa.go-parts.com/kde"
       "/"
       "/"
       "/"
       "/"
  Oceania
       "/"
       "/"))))

(define %mirror-file
  (plain-file "mirrors" (object->string %mirrors)))

(define %content-addressed-mirrors
  ( bytevector ) , and returns a URL or # f.
  Note : Avoid ' https ' to mitigate <  > .
  '(list (lambda (file algo hash)
           (string-append "/"
                          file "/" (symbol->string algo) "/"
                          (bytevector->nix-base32-string hash)))
         (lambda (file algo hash)
           (string-append "/"
                          (symbol->string algo) "/"
                          (bytevector->nix-base32-string hash)))))

(define %content-addressed-mirror-file
  Content - addressed mirrors stored in a file .
  (plain-file "content-addressed-mirrors"
              (object->string %content-addressed-mirrors)))

(define (gnutls-package)
  "Return the default GnuTLS package."
  (let ((module (resolve-interface '(gnu packages tls))))
    (module-ref module 'gnutls)))

(define built-in-builders*
  (let ((cache (make-weak-key-hash-table)))
    (lambda ()
      "Return, as a monadic value, the list of built-in builders supported by
the daemon."
      (lambda (store)
  Memoize the result to avoid repeated RPCs .
        (values (or (hashq-ref cache store)
                    (let ((result (built-in-builders store)))
                      (hashq-set! cache store result)
                      result))
                store)))))

(define* (built-in-download file-name url
                            #:key system hash-algo hash
                            mirrors content-addressed-mirrors
                            (guile 'unused))
  "Download FILE-NAME from URL using the built-in 'download' builder.

This is an \"out-of-band\" download in that the returned derivation does not
explicitly depend on Guile, GnuTLS, etc.  Instead, the daemon performs the
download by itself using its own dependencies."
  (mlet %store-monad ((mirrors (lower-object mirrors))
                      (content-addressed-mirrors
                       (lower-object content-addressed-mirrors)))
    (raw-derivation file-name "builtin:download" '()
                    #:system system
                    #:hash-algo hash-algo
                    #:hash hash
                    #:inputs `((,mirrors)
                               (,content-addressed-mirrors))

                    #:leaked-env-vars '("http_proxy" "https_proxy"
                                        "LC_ALL" "LC_MESSAGES" "LANG"
                                        "COLUMNS")

                    #:env-vars `(("url" . ,(object->string url))
                                 ("mirrors" . ,mirrors)
                                 ("content-addressed-mirrors"
                                  . ,content-addressed-mirrors))

                    #:local-build? #t)))

(define* (in-band-download file-name url
                           #:key system hash-algo hash
                           mirrors content-addressed-mirrors
                           guile)
  "Download FILE-NAME from URL using a normal, \"in-band\" fixed-output
derivation.

This is now deprecated since it has the drawback of causing bootstrapping
issues: we may need to build GnuTLS just to be able to download the source of
GnuTLS itself and its dependencies.  See <>."
  (define need-gnutls?
  True if any of the URLs need TLS support .
    (let ((https? (cut string-prefix? "https://" <>)))
      (match url
        ((? string?)
         (https? url))
        ((url ...)
         (any https? url)))))

  (define builder
    (with-imported-modules '((guix build download)
                             (guix build utils)
                             (guix ftp-client)
                             (guix base32)
                             (guix base64))
      #~(begin
          #+(if need-gnutls?

                #~(eval-when (load expand eval)
                    (set! %load-path
                      (cons (string-append #+(gnutls-package)
                                           "/share/guile/site/"
                                           (effective-version))
                            %load-path)))
                #~#t)

          (use-modules (guix build download)
                       (guix base32))

          (let ((value-from-environment (lambda (variable)
                                          (call-with-input-string
                                              (getenv variable)
                                            read))))
            (url-fetch (value-from-environment "guix download url")
                       #$output
                       #:mirrors (call-with-input-file #$mirrors read)

  Content - addressed mirrors .
                       #:hashes
                       (value-from-environment "guix download hashes")
                       #:content-addressed-mirrors
                       (primitive-load #$content-addressed-mirrors)

                       #:verify-certificate? #f)))))

  (mlet %store-monad ((guile (package->derivation guile system)))
    (gexp->derivation file-name builder
                      #:guile-for-build guile
                      #:system system
                      #:hash-algo hash-algo
                      #:hash hash

  name so there 's only one script in store for
                      #:script-name "download"
                      #:env-vars
                      `(("guix download url" . ,(object->string url))
                        ("guix download hashes"
                         . ,(object->string `((,hash-algo . ,hash)))))

                      #:leaked-env-vars '("http_proxy" "https_proxy")

  idea .    before 0.8.3 would also
                      #:local-build? #t)))

(define* (url-fetch url hash-algo hash
                    #:optional name
                    #:key (system (%current-system))
                    (guile (default-guile)))
  "Return a fixed-output derivation that fetches URL (a string, or a list of
strings denoting alternate URLs), which is expected to have hash HASH of type
optionally, NAME can specify a different file name.

When one of the URL starts with mirror://, then its host part is
interpreted as the name of a mirror scheme, taken from %MIRROR-FILE.

Alternately, when URL starts with file://, return the corresponding file name
in the store."
  (define file-name
    (match url
      ((head _ ...)
       (basename head))
      (_
       (basename url))))

  (let ((uri (and (string? url) (string->uri url))))
    (if (or (and (string? url) (not uri))
            (and uri (memq (uri-scheme uri) '(#f file))))
        (interned-file (if uri (uri-path uri) url)
                       (or name file-name))
        (mlet* %store-monad ((builtins (built-in-builders*))
                             (download -> (if (member "download" builtins)
                                              built-in-download
                                              in-band-download)))
          (download (or name file-name) url
                    #:guile guile
                    #:system system
                    #:hash-algo hash-algo
                    #:hash hash
                    #:mirrors %mirror-file
                    #:content-addressed-mirrors
                    %content-addressed-mirror-file)))))

(define* (url-fetch/tarbomb url hash-algo hash
                            #:optional name
                            #:key (system (%current-system))
                            (guile (default-guile)))
  "Similar to 'url-fetch' but unpack the file from URL in a directory of its
own.  This helper makes it easier to deal with \"tar bombs\"."
  (define file-name
    (match url
      ((head _ ...)
       (basename head))
      (_
       (basename url))))
  (define gzip
    (module-ref (resolve-interface '(gnu packages compression)) 'gzip))
  (define tar
    (module-ref (resolve-interface '(gnu packages base)) 'tar))

  (mlet %store-monad ((drv (url-fetch url hash-algo hash
                                      (string-append "tarbomb-"
                                                     (or name file-name))
                                      #:system system
                                      #:guile guile)))
    (gexp->derivation (or name file-name)
                      #~(begin
                          (mkdir #$output)
                          (setenv "PATH" (string-append #$gzip "/bin"))
                          (chdir #$output)
                          (zero? (system* (string-append #$tar "/bin/tar")
                                          "xf" #$drv)))
                      #:local-build? #t)))

(define* (url-fetch/zipbomb url hash-algo hash
                            #:optional name
                            #:key (system (%current-system))
                            (guile (default-guile)))
  "Similar to 'url-fetch' but unpack the zip file at URL in a directory of its
own.  This helper makes it easier to deal with \"zip bombs\"."
  (define file-name
    (match url
      ((head _ ...)
       (basename head))
      (_
       (basename url))))
  (define unzip
    (module-ref (resolve-interface '(gnu packages zip)) 'unzip))

  (mlet %store-monad ((drv (url-fetch url hash-algo hash
                                      (string-append "zipbomb-"
                                                     (or name file-name))
                                      #:system system
                                      #:guile guile)))
    (gexp->derivation (or name file-name)
                      #~(begin
                          (mkdir #$output)
                          (chdir #$output)
                          (zero? (system* (string-append #$unzip "/bin/unzip")
                                          #$drv)))
                      #:local-build? #t)))

(define* (download-to-store store url #:optional (name (basename url))
                            #:key (log (current-error-port)) recursive?
                            (verify-certificate? #t))
  "Download from URL to STORE, either under NAME or URL's basename if
omitted.  Write progress reports to LOG.  RECURSIVE? has the same effect as
the same-named parameter of 'add-to-store'.  VERIFY-CERTIFICATE? determines
whether or not to validate HTTPS server certificates."
  (define uri
    (string->uri url))

  (if (or (not uri) (memq (uri-scheme uri) '(file #f)))
      (add-to-store store name recursive? "sha256"
                    (if uri (uri-path uri) url))
      (call-with-temporary-output-file
       (lambda (temp port)
         (let ((result
                (parameterize ((current-output-port log))
                  (build:url-fetch url temp
                                   #:mirrors %mirrors
                                   #:verify-certificate?
                                   verify-certificate?))))
           (close port)
           (and result
                (add-to-store store name recursive? "sha256" temp)))))))

