code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016, 2017, 2018, 2020 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix 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 Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix scripts perform-download)
  #:use-module (guix ui)
  #:use-module (guix scripts)
  #:use-module (guix derivations)
  #:use-module ((guix store) #:select (derivation-path? store-path?))
  #:use-module (guix build download)
  #:use-module (ice-9 match)
  #:export (guix-perform-download))

;; This program is a helper for the daemon's 'download' built-in builder.

(define-syntax derivation-let
  (syntax-rules ()
    ((_ drv ((id name) rest ...) body ...)
     (let ((id (assoc-ref (derivation-builder-environment-vars drv)
                          name)))
       (derivation-let drv (rest ...) body ...)))
    ((_ drv () body ...)
     (begin body ...))))

(define %user-module
  ;; Module in which content-address mirror procedures are evaluated.
  (let ((module (make-fresh-user-module)))
    (module-use! module (resolve-interface '(guix base32)))
    module))

(define* (perform-download drv #:optional output
                           #:key print-build-trace?)
  "Perform the download described by DRV, a fixed-output derivation, to
OUTPUT.

Note: Unless OUTPUT is #f, we don't read the value of 'out' in DRV since the
actual output is different from that when we're doing a 'bmCheck' or
'bmRepair' build."
  (derivation-let drv ((url "url")
                       (output* "out")
                       (executable "executable")
                       (mirrors "mirrors")
                       (content-addressed-mirrors "content-addressed-mirrors"))
    (unless url
      (leave (G_ "~a: missing URL~%") (derivation-file-name drv)))

    (let* ((output     (or output output*))
           (url        (call-with-input-string url read))
           (drv-output (assoc-ref (derivation-outputs drv) "out"))
           (algo       (derivation-output-hash-algo drv-output))
           (hash       (derivation-output-hash drv-output)))
      (unless (and algo hash)
        (leave (G_ "~a is not a fixed-output derivation~%")
               (derivation-file-name drv)))

      ;; We're invoked by the daemon, which gives us write access to OUTPUT.
      (when (url-fetch url output
                       #:print-build-trace? print-build-trace?
                       #:mirrors (if mirrors
                                     (call-with-input-file mirrors read)
                                     '())
                       #:content-addressed-mirrors
                       (if content-addressed-mirrors
                           (call-with-input-file content-addressed-mirrors
                             (lambda (port)
                               (eval (read port) %user-module)))
                           '())
                       #:hashes `((,algo . ,hash))

                       ;; Since DRV's output hash is known, X.509 certificate
                       ;; validation is pointless.
                       #:verify-certificate? #f)
        (when (and executable (string=? executable "1"))
          (chmod output #o755))))))

(define (assert-low-privileges)
  (when (zero? (getuid))
    (leave (G_ "refusing to run with elevated privileges (UID ~a)~%")
           (getuid))))

(define-command (guix-perform-download . args)
  (category internal)
  (synopsis "perform download described by fixed-output derivations")

  ;; This is an "out-of-band" download in that this code is executed directly
  ;; by the daemon and not explicitly described as an input of the derivation.
  ;; This allows us to sidestep bootstrapping problems, such as downloading
  ;; the source code of GnuTLS over HTTPS before we have built GnuTLS.  See
  ;; <https://bugs.gnu.org/22774>.

  (define print-build-trace?
    (match (getenv "_NIX_OPTIONS")
      (#f #f)
      (str (string-contains str "print-extended-build-trace=1"))))

  ;; This program must be invoked by guix-daemon under an unprivileged UID to
  ;; prevent things downloading from 'file:///etc/shadow' or arbitrary code
  ;; execution via the content-addressed mirror procedures.  (That means we
  ;; exclude users who did not pass '--build-users-group'.)
  (with-error-handling
    (match args
      (((? derivation-path? drv) (? store-path? output))
       (assert-low-privileges)
       (perform-download (read-derivation-from-file drv)
                         output
                         #:print-build-trace? print-build-trace?))
      (((? derivation-path? drv))                 ;backward compatibility
       (assert-low-privileges)
       (perform-download (read-derivation-from-file drv)
                         #:print-build-trace? print-build-trace?))
      (("--version")
       (show-version-and-exit))
      (x
       (leave
        (G_ "fixed-output derivation and output file name expected~%"))))))

;; Local Variables:
;; eval: (put 'derivation-let 'scheme-indent-function 2)
;; End:

;; perform-download.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix 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 Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix scripts processes)
  #:use-module ((guix store) #:select (%store-prefix))
  #:use-module (guix scripts)
  #:use-module (guix ui)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (srfi srfi-37)
  #:use-module (ice-9 ftw)
  #:use-module (ice-9 match)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 format)
  #:export (process?
            process-id
            process-parent-id
            process-command
            processes

            daemon-session?
            daemon-session-process
            daemon-session-client
            daemon-session-children
            daemon-session-locks-held
            daemon-sessions

            guix-processes))

;; Process as can be found in /proc on GNU/Linux.
(define-record-type <process>
  (process id parent command)
  process?
  (id       process-id)                           ;integer
  (parent   process-parent-id)                    ;integer | #f
  (command  process-command))                     ;list of strings

(define (write-process process port)
  (format port "#<process ~a>" (process-id process)))

(set-record-type-printer! <process> write-process)

(define (read-status-ppid port)
  "Read the PPID from PORT, an input port on a /proc/PID/status file.  Return
#f for PID 1 and kernel pseudo-processes."
  (let loop ()
    (match (read-line port)
      ((? eof-object?) #f)
      (line
       (if (string-prefix? "PPid:" line)
           (string->number (string-trim-both (string-drop line 5)))
           (loop))))))

(define %not-nul
  (char-set-complement (char-set #\nul)))

(define (read-command-line port)
  "Read the zero-split command line from PORT, a /proc/PID/cmdline file, and
return it as a list."
  (string-tokenize (read-string port) %not-nul))

(define (processes)
  "Return a list of process records representing the currently alive
processes."
  ;; This assumes a Linux-compatible /proc file system.  There exists one for
  ;; GNU/Hurd.
  (filter-map (lambda (pid)
                ;; There's a TOCTTOU race here.  If we get ENOENT, simply
                ;; ignore PID.
                (catch 'system-error
                  (lambda ()
                    (define ppid
                      (call-with-input-file (string-append "/proc/" pid "/status")
                        read-status-ppid))
                    (define command
                      (call-with-input-file (string-append "/proc/" pid "/cmdline")
                        read-command-line))
                    (process (string->number pid) ppid command))
                  (lambda args
                    (if (= ENOENT (system-error-errno args))
                        #f
                        (apply throw args)))))
              (scandir "/proc" string->number)))

(define (process-open-files process)
  "Return the list of files currently open by PROCESS."
  (let ((directory (string-append "/proc/"
                                  (number->string (process-id process))
                                  "/fd")))
    (filter-map (lambda (fd)
                  ;; There's a TOCTTOU race here, hence the 'catch'.
                  (catch 'system-error
                    (lambda ()
                      (readlink (string-append directory "/" fd)))
                    (lambda args
                      (if (= ENOENT (system-error-errno args))
                          #f
                          (apply throw args)))))
                (or (scandir directory string->number) '()))))

;; Daemon session.
(define-record-type <daemon-session>
  (daemon-session process client children locks)
  daemon-session?
  (process    daemon-session-process)             ;<process>
  (client     daemon-session-client)              ;<process>
  (children   daemon-session-children)            ;list of <process>
  (locks      daemon-session-locks-held))         ;list of strings

(define (daemon-sessions)
  "Return two values: the list of <daemon-session> denoting the currently
active sessions, and the master 'guix-daemon' process."
  (define (lock-file? file)
    (and (string-prefix? (%store-prefix) file)
         (string-suffix? ".lock" file)))

  (let* ((processes (processes))
         (daemons   (filter (lambda (process)
                              (match (process-command process)
                                ((argv0 _ ...)
                                 (string=? (basename argv0) "guix-daemon"))
                                (_ #f)))
                            processes))
         (children  (filter (lambda (process)
                              (match (process-command process)
                                ((argv0 (= string->number argv1) _ ...)
                                 (integer? argv1))
                                (_ #f)))
                            daemons))
         (master    (remove (lambda (process)
                              (memq process children))
                            daemons)))
    (define (lookup-process pid)
      (find (lambda (process)
              (and (process-id process)
                   (= pid (process-id process))))
            processes))

    (define (lookup-children pid)
      (filter (lambda (process)
                (and (process-parent-id process)
                     (= pid (process-parent-id process))))
              processes))

    (define (child-process->session process)
      (match (process-command process)
        ((argv0 (= string->number client) _ ...)
         (let ((files  (process-open-files process))
               (client (lookup-process client)))
           ;; After a client has died, there's a window during which its
           ;; corresponding 'guix-daemon' process is still alive, in which
           ;; case 'lookup-process' returns #f.  In that case ignore the
           ;; session.
           (and client
                (daemon-session process client
                                (lookup-children
                                 (process-id process))
                                (filter lock-file? files)))))))

    (values (filter-map child-process->session children)
            master)))

(define (daemon-session->recutils session port)
  "Display SESSION information in recutils format on PORT."
  (format port "SessionPID: ~a~%"
          (process-id (daemon-session-process session)))
  (format port "ClientPID: ~a~%"
          (process-id (daemon-session-client session)))
  (format port "ClientCommand:~{ ~a~}~%"
          (process-command (daemon-session-client session)))
  (for-each (lambda (lock)
              (format port "LockHeld: ~a~%" lock))
            (daemon-session-locks-held session))
  (for-each (lambda (process)
              (format port "ChildProcess: ~a:~{ ~a~}~%"
                      (process-id process)
                      (process-command process)))
            (daemon-session-children session)))

;;;
;;; Options.
;;;

(define %options
  (list (option '(#\h "help") #f #f
                (lambda args
                  (show-help)
                  (exit 0)))
        (option '(#\V "version") #f #f
                (lambda args
                  (show-version-and-exit "guix processes")))))

(define (show-help)
  (display (G_ "Usage: guix processes
List the current Guix sessions and their processes."))
  (newline)
  (display (G_ "
  -h, --help             display this help and exit"))
  (display (G_ "
  -V, --version          display version information and exit"))
  (newline)
  (show-bug-report-information))

;;;
;;; Entry point.
;;;

(define-command (guix-processes . args)
  (category plumbing)
  (synopsis "list currently running sessions")
  (define options
    (args-fold* args %options
                (lambda (opt name arg result)
                  (leave (G_ "~A: unrecognized option~%") name))
                cons
                '()))

  (with-paginated-output-port port
    (for-each (lambda (session)
                (daemon-session->recutils session port)
                (newline port))
              (daemon-sessions))

    ;; Pass 'R' (instead of 'r') so 'less' correctly estimates line length.
    #:less-options "FRX"))

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015 David Thompson <davet@gnu.org>
;;; Copyright © 2015, 2016, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix 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 Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix scripts publish)
  #:use-module ((system repl server) #:prefix repl:)
  #:use-module (ice-9 binary-ports)
  #:use-module (ice-9 format)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 threads)
  #:use-module (rnrs bytevectors)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-2)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (srfi srfi-19)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-37)
  #:use-module (web http)
  #:use-module (web request)
  #:use-module (web response)
  #:use-module (web server)
  #:use-module (web uri)
  #:autoload   (sxml simple) (sxml->xml)
  #:use-module (guix base32)
  #:use-module (guix base64)
  #:use-module (guix config)
  #:use-module (guix derivations)
  #:use-module (gcrypt hash)
  #:use-module (guix pki)
  #:use-module (gcrypt pk-crypto)
  #:use-module (guix workers)
  #:use-module (guix store)
  #:use-module ((guix serialization) #:select (write-file))
  #:use-module (zlib)
  #:autoload   (lzlib) (call-with-lzip-output-port
                        make-lzip-output-port)
  #:use-module (guix cache)
  #:use-module (guix ui)
  #:use-module (guix scripts)
  #:use-module ((guix utils)
                #:select (with-atomic-file-output compressed-file?))
  #:use-module ((guix build utils)
                #:select (dump-port mkdir-p find-files))
  #:use-module ((guix build syscalls) #:select (set-thread-name))
  #:export (%public-key
            %private-key
            signed-string

            guix-publish))

(define (show-help)
  (format #t (G_ "Usage: guix publish [OPTION]...
Publish ~a over HTTP.\n") %store-directory)
  (display (G_ "
  -p, --port=PORT        listen on PORT"))
  (display (G_ "
      --listen=HOST      listen on the network interface for HOST"))
  (display (G_ "
  -u, --user=USER        change privileges to USER as soon as possible"))
  (display (G_ "
  -C, --compression[=METHOD:LEVEL]
                         compress archives with METHOD at LEVEL"))
  (display (G_ "
  -c, --cache=DIRECTORY  cache published items to DIRECTORY"))
  (display (G_ "
      --workers=N        use N workers to bake items"))
  (display (G_ "
      --ttl=TTL          announce narinfos can be cached for TTL seconds"))
  (display (G_ "
      --nar-path=PATH    use PATH as the prefix for nar URLs"))
  (display (G_ "
      --public-key=FILE  use FILE as the public key for signatures"))
  (display (G_ "
      --private-key=FILE use FILE as the private key for signatures"))
  (display (G_ "
  -r, --repl[=PORT]      spawn REPL server on PORT"))
  (newline)
  (display (G_ "
  -h, --help             display this help and exit"))
  (display (G_ "
  -V, --version          display version information and exit"))
  (newline)
  (show-bug-report-information))

(define (getaddrinfo* host)
  "Like 'getaddrinfo', but properly report errors."
  (catch 'getaddrinfo-error
    (lambda ()
      (getaddrinfo host))
    (lambda (key error)
      (leave (G_ "lookup of host '~a' failed: ~a~%")
             host (gai-strerror error)))))

;; Nar compression parameters.
(define-record-type <compression>
  (compression type level)
  compression?
  (type   compression-type)
  (level  compression-level))

(define %no-compression
  (compression 'none 0))

(define %default-gzip-compression
  ;; Since we compress on the fly, default to fast compression.
  (compression 'gzip 3))

(define (default-compression type)
  (compression type 3))

(define (actual-compressions item requested)
  "Return the actual compressions used for ITEM, which may be %NO-COMPRESSION
if ITEM is already compressed."
  (if (compressed-file? item)
      (list %no-compression)
      requested))

(define %options
  (list (option '(#\h "help") #f #f
                (lambda _
                  (show-help)
                  (exit 0)))
        (option '(#\V "version") #f #f
                (lambda _
                  (show-version-and-exit "guix publish")))
        (option '(#\u "user") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'user arg result)))
        (option '(#\p "port") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'port (string->number* arg) result)))
        (option '("listen") #t #f
                (lambda (opt name arg result)
                  (match (getaddrinfo* arg)
                    ((info _ ...)
                     (alist-cons 'address (addrinfo:addr info)
                                 result))
                    (()
                     (leave (G_ "lookup of host '~a' returned nothing")
                            name)))))
        (option '(#\C "compression") #f #t
                (lambda (opt name arg result)
                  (let* ((colon (string-index arg #\:))
                         (type  (cond
                                 (colon (string-take arg colon))
                                 ((string->number arg) "gzip")
                                 (else arg)))
                         (level (if colon
                                    (string->number*
                                     (string-drop arg (+ 1 colon)))
                                    (or (string->number arg) 3))))
                    (match level
                      (0
                       (alist-cons 'compression %no-compression result))
                      (level
                       (match (string->compression-type type)
                         ((? symbol? type)
                          (alist-cons 'compression
                                      (compression type level)
                                      result))
                         (_
                          (warning (G_ "~a: unsupported compression type~%")
                                   type)
                          result)))))))
        (option '(#\c "cache") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'cache arg result)))
        (option '("workers") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'workers (string->number* arg)
                              result)))
        (option '("ttl") #t #f
                (lambda (opt name arg result)
                  (let ((duration (string->duration arg)))
                    (unless duration
                      (leave (G_ "~a: invalid duration~%") arg))
                    (alist-cons 'narinfo-ttl (time-second duration)
                                result))))
        (option '("nar-path") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'nar-path arg result)))
        (option '("public-key") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'public-key-file arg result)))
        (option '("private-key" "secret-key") #t #f
                (lambda (opt name arg result)
                  (alist-cons 'private-key-file arg result)))
        (option '(#\r "repl") #f #t
                (lambda (opt name arg result)
                  ;; If port unspecified, use default Guile REPL port.
                  (let ((port (and arg (string->number* arg))))
                    (alist-cons 'repl (or port 37146) result))))))

(define %default-options
  `((port . 8080)

    ;; By default, serve nars under "/nar".
    (nar-path . "nar")

    (public-key-file . ,%public-key-file)
    (private-key-file . ,%private-key-file)

    ;; Default number of workers when caching is enabled.
    (workers . ,(current-processor-count))

    (address . ,(make-socket-address AF_INET INADDR_ANY 0))
    (repl . #f)))

;; The key pair used to sign narinfos.
(define %private-key
  (make-parameter #f))
(define %public-key
  (make-parameter #f))

(define %nix-cache-info
  `(("StoreDir" . ,%store-directory)
    ("WantMassQuery" . 0)
    ("Priority" . 100)))

(define (signed-string s)
  "Sign the hash of the string S with the daemon's key.  Return a canonical
sexp for the signature."
  (let* ((public-key (%public-key))
         (hash (bytevector->hash-data (sha256 (string->utf8 s))
                                      #:key-type (key-type public-key))))
    (signature-sexp hash (%private-key) public-key)))

(define base64-encode-string
  (compose base64-encode string->utf8))

(define* (store-item->recutils store-item
                               #:key
                               (nar-path "nar")
                               (compression %no-compression)
                               file-size)
  "Return the 'Compression' and 'URL' fields of the narinfo for STORE-ITEM,
with COMPRESSION, starting at NAR-PATH."
  (let ((url (encode-and-join-uri-path
              `(,@(split-and-decode-uri-path nar-path)
                ,@(match compression
                    (($ <compression> 'none)
                     '())
                    (($ <compression> type)
                     (list (symbol->string type))))
                ,(basename store-item)))))
    (format #f "URL: ~a~%Compression: ~a~%~@[FileSize: ~a~%~]"
            url (compression-type compression) file-size)))

(define* (narinfo-string store store-path key
                         #:key (compressions (list %no-compression))
                         (nar-path "nar") (file-sizes '()))
  "Generate a narinfo key/value string for STORE-PATH; an exception is raised
if STORE-PATH is invalid.  Produce a URL that corresponds to COMPRESSION.  The
narinfo is signed with KEY.  NAR-PATH specifies the prefix for nar URLs.

Optionally, FILE-SIZES is a list of compression/integer pairs, where the
integer is size in bytes of the compressed NAR; it informs the client of how
much needs to be downloaded."
  (let* ((path-info  (query-path-info store store-path))
         (compressions (actual-compressions store-path compressions))
         (hash       (bytevector->nix-base32-string
                      (path-info-hash path-info)))
         (size       (path-info-nar-size path-info))
         (file-sizes `((,%no-compression . ,size) ,@file-sizes))
         (references (string-join
                      (map basename (path-info-references path-info))
                      " "))
         (deriver    (path-info-deriver path-info))
         (base-info  (format #f
                             "\
StorePath: ~a
~{~a~}\
NarHash: sha256:~a
NarSize: ~d
References: ~a~%"
                             store-path
                             (map (lambda (compression)
                                    (let ((size (assoc-ref file-sizes
                                                           compression)))
                                      (store-item->recutils store-path
                                                            #:file-size size
                                                            #:nar-path nar-path
                                                            #:compression
                                                            compression)))
                                  compressions)
                             hash size references))
         ;; Do not render a "Deriver" or "System" line if we are rendering
         ;; info for a derivation.
         (info       (if (not deriver)
                         base-info
                         (catch 'system-error
                           (lambda ()
                             (let ((drv (read-derivation-from-file deriver)))
                               (format #f "~aSystem: ~a~%Deriver: ~a~%"
                                       base-info (derivation-system drv)
                                       (basename deriver))))
                           (lambda args
                             ;; DERIVER might be missing, but that's fine:
                             ;; it's only used for <substitutable> where it's
                             ;; optional.  'System' is currently unused.
                             (if (= ENOENT (system-error-errno args))
                                 base-info
                                 (apply throw args))))))
         (signature  (base64-encode-string
                      (canonical-sexp->string (signed-string info)))))
    (format #f "~aSignature: 1;~a;~a~%" info (gethostname) signature)))

(define* (not-found request
                    #:key (phrase "Resource not found")
                    ttl)
  "Render 404 response for REQUEST."
  (values (build-response #:code 404
                          #:headers (if ttl
                                        `((cache-control (max-age . ,ttl)))
                                        '()))
          (string-append phrase ": "
                         (uri-path (request-uri request)))))

(define (render-nix-cache-info)
  "Render server information."
  (values '((content-type . (text/plain)))
          (lambda (port)
            (for-each (match-lambda
                       ((key . value)
                        (format port "~a: ~a~%" key value)))
                      %nix-cache-info))))

(define* (render-narinfo store request hash
                         #:key ttl (compressions (list %no-compression))
                         (nar-path "nar"))
  "Render metadata for the store path corresponding to HASH.  If TTL is true,
advertise it as the maximum validity period (in seconds) via the
'Cache-Control' header.  This allows 'guix substitute' to cache it for an
appropriate duration.  NAR-PATH specifies the prefix for nar URLs."
  (let ((store-path (hash-part->path store hash)))
    (if (string-null? store-path)
        (not-found request #:phrase "")
        (values `((content-type . (application/x-nix-narinfo))
                  ,@(if ttl
                        `((cache-control (max-age . ,ttl)))
                        '()))
                (cut display
                  (narinfo-string store store-path (%private-key)
                                  #:nar-path nar-path
                                  #:compressions compressions)
                  <>)))))

(define* (nar-cache-file directory item
                             #:key (compression %no-compression))
  (string-append directory "/"
                 (symbol->string (compression-type compression))
                 "/" (basename item) ".nar"))

(define* (narinfo-cache-file directory item
                             #:key (compression %no-compression))
  (string-append directory "/"
                 (symbol->string (compression-type compression))
                 "/" (basename item)
                 ".narinfo"))

(define (hash-part-mapping-cache-file directory hash)
  (string-append directory "/hashes/" hash))

(define run-single-baker
  (let ((baking (make-weak-value-hash-table))
        (mutex  (make-mutex)))
    (lambda (item thunk)
      "Run THUNK, which is supposed to bake ITEM, but make sure only one
thread is baking ITEM at a given time."
      (define selected?
        (with-mutex mutex
          (and (not (hash-ref baking item))
               (begin
                 (hash-set! baking item (current-thread))
                 #t))))

      (when selected?
        (dynamic-wind
          (const #t)
          thunk
          (lambda ()
            (with-mutex mutex
              (hash-remove! baking item))))))))

(define-syntax-rule (single-baker item exp ...)
  "Bake ITEM by evaluating EXP, but make sure there's only one baker for ITEM
at a time."
  (run-single-baker item (lambda () exp ...)))

(define (narinfo-files cache)
  "Return the list of .narinfo files under CACHE."
  (if (file-is-directory? cache)
      (find-files cache
                  (lambda (file stat)
                    (string-suffix? ".narinfo" file)))
      '()))

(define (nar-expiration-time ttl)
  "Return the narinfo expiration time (in seconds since the Epoch).  The
expiration time is +inf.0 when passed an item that is still in the store; in
other cases, it is the last-access time of the item plus TTL.

This policy allows us to keep cached nars that correspond to valid store
items.  Failing that, we could eventually have to recompute them and return
404 in the meantime."
  (let ((expiration-time (file-expiration-time ttl)))
    (lambda (file)
      (let ((item (string-append (%store-prefix) "/"
                                 (basename file ".narinfo"))))
        ;; Note: We don't need to use 'valid-path?' here because FILE would
        ;; not exist if ITEM were not valid in the first place.
        (if (file-exists? item)
            +inf.0
            (expiration-time file))))))

(define (hash-part->path* store hash cache)
  "Like 'hash-part->path' but cached results under CACHE.  This ensures we can
still map HASH to the corresponding store file name, even if said store item
vanished from the store in the meantime."
  (let ((cached (hash-part-mapping-cache-file cache hash)))
    (catch 'system-error
      (lambda ()
        (call-with-input-file cached read-string))
      (lambda args
        (if (= ENOENT (system-error-errno args))
            (match (hash-part->path store hash)
              ("" "")
              (result
               (mkdir-p (dirname cached))
               (call-with-output-file (string-append cached ".tmp")
                 (lambda (port)
                   (display result port)))
               (rename-file (string-append cached ".tmp") cached)
               result))
            (apply throw args))))))

(define* (render-narinfo/cached store request hash
                                #:key ttl (compressions (list %no-compression))
                                (nar-path "nar")
                                cache pool)
  "Respond to the narinfo request for REQUEST.  If the narinfo is available in
CACHE, then send it; otherwise, return 404 and \"bake\" that nar and narinfo
requested using POOL."
  (define (delete-entry narinfo)
    ;; Delete NARINFO and the corresponding nar from CACHE.
    (let* ((nar     (string-append (string-drop-right narinfo
                                                      (string-length ".narinfo"))
                                   ".nar"))
           (base    (basename narinfo ".narinfo"))
           (hash    (string-take base (string-index base #\-)))
           (mapping (hash-part-mapping-cache-file cache hash)))
      (delete-file* narinfo)
      (delete-file* nar)
      (delete-file* mapping)))

  (let* ((item         (hash-part->path* store hash cache))
         (compressions (actual-compressions item compressions))
         (cached       (and (not (string-null? item))
                            (narinfo-cache-file cache item
                                                #:compression
                                                (first compressions)))))
    (cond ((string-null? item)
           (not-found request))
          ((file-exists? cached)
           ;; Narinfo is in cache, send it.
           (values `((content-type . (application/x-nix-narinfo))
                     ,@(if ttl
                           `((cache-control (max-age . ,ttl)))
                           '()))
                   (lambda (port)
                     (display (call-with-input-file cached
                                read-string)
                              port))))
          ((and (file-exists? item)        ;cheaper than the 'valid-path?' RPC
                (valid-path? store item))
           ;; Nothing in cache: bake the narinfo and nar in the background and
           ;; return 404.
           (eventually pool
             (single-baker item
               ;; Check whether CACHED has been produced in the meantime.
               (unless (file-exists? cached)
                 ;; (format #t "baking ~s~%" item)
                 (bake-narinfo+nar cache item
                                   #:ttl ttl
                                   #:compressions compressions
                                   #:nar-path nar-path)))

             (when ttl
               (single-baker 'cache-cleanup
                 (maybe-remove-expired-cache-entries cache
                                                     narinfo-files
                                                     #:entry-expiration
                                                     (nar-expiration-time ttl)
                                                     #:delete-entry delete-entry
                                                     #:cleanup-period ttl))))
           (not-found request
                      #:phrase "We're baking it"
                      #:ttl 300))              ;should be available within 5m
          (else
           (not-found request #:phrase "")))))

(define (compress-nar cache item compression)
  "Save in directory CACHE the nar for ITEM compressed with COMPRESSION."
  (define nar
    (nar-cache-file cache item #:compression compression))

  (mkdir-p (dirname nar))
  (match (compression-type compression)
    ('gzip
     ;; Note: the file port gets closed along with the gzip port.
     (call-with-gzip-output-port (open-output-file (string-append nar ".tmp"))
       (lambda (port)
         (write-file item port))
       #:level (compression-level compression)
       #:buffer-size (* 128 1024))
     (rename-file (string-append nar ".tmp") nar))
    ('lzip
     ;; Note: the file port gets closed along with the lzip port.
     (call-with-lzip-output-port (open-output-file (string-append nar ".tmp"))
       (lambda (port)
         (write-file item port))
       #:level (compression-level compression))
     (rename-file (string-append nar ".tmp") nar))
    ('none
     ;; Cache nars even when compression is disabled so that we can
     ;; guarantee the TTL (see <https://bugs.gnu.org/28664>.)
     (with-atomic-file-output nar
       (lambda (port)
         (write-file item port))))))

(define* (bake-narinfo+nar cache item
                           #:key ttl (compressions (list %no-compression))
                           (nar-path "/nar"))
  "Write the narinfo and nar for ITEM to CACHE."
  (define (compressed-nar-size compression)
    (let* ((nar  (nar-cache-file cache item #:compression compression))
           (stat (stat nar #f)))
      (and stat
           (cons compression (stat:size stat)))))

  (let ((compression (actual-compressions item compressions)))

    (for-each (cut compress-nar cache item <>) compressions)

    (match compressions
      ((main others ...)
       (let ((narinfo (narinfo-cache-file cache item
                                          #:compression main)))
         (with-atomic-file-output narinfo
           (lambda (port)
             ;; Open a new connection to the store.  We cannot reuse the main
             ;; thread's connection to the store since we would end up sending
             ;; stuff concurrently on the same channel.
             (with-store store
               (let ((sizes (filter-map compressed-nar-size compression)))
                 (display (narinfo-string store item
                                          (%private-key)
                                          #:nar-path nar-path
                                          #:compressions compressions
                                          #:file-sizes sizes)
                          port)))))

         ;; Make narinfo files for OTHERS hard links to NARINFO such that the
         ;; atime-based cache eviction considers either all the nars or none
         ;; of them as candidates.
         (for-each (lambda (other)
                     (let ((other (narinfo-cache-file cache item
                                                      #:compression other)))
                       (link narinfo other)))
                   others))))))

;; XXX: Declare the 'X-Nar-Compression' HTTP header, which is in fact for
;; internal consumption: it allows us to pass the compression info to
;; 'http-write', as part of the workaround to <http://bugs.gnu.org/21093>.
(declare-header! "X-Nar-Compression"
                 (lambda (str)
                   (match (call-with-input-string str read)
                     (('compression type level)
                      (compression type level))))
                 compression?
                 (lambda (compression port)
                   (match compression
                     (($ <compression> type level)
                      (write `(compression ,type ,level) port)))))

(define* (render-nar store request store-item
                     #:key (compression %no-compression))
  "Render archive of the store path corresponding to STORE-ITEM."
  (let ((store-path (string-append %store-directory "/" store-item)))
    ;; The ISO-8859-1 charset *must* be used otherwise HTTP clients will
    ;; interpret the byte stream as UTF-8 and arbitrarily change invalid byte
    ;; sequences.
    (if (valid-path? store store-path)
        (values `((content-type . (application/x-nix-archive
                                   (charset . "ISO-8859-1")))
                  (x-nar-compression . ,compression))
                ;; XXX: We're not returning the actual contents, deferring
                ;; instead to 'http-write'.  This is a hack to work around
                ;; <http://bugs.gnu.org/21093>.
                store-path)
        (not-found request))))

(define* (render-nar/cached store cache request store-item
                            #:key ttl (compression %no-compression))
  "Respond to REQUEST with a nar for STORE-ITEM.  If the nar is in CACHE,
return it; otherwise, return 404.  When TTL is true, use it as the
'Cache-Control' expiration time."
  (let ((cached (nar-cache-file cache store-item
                                #:compression compression)))
    (if (file-exists? cached)
        (values `((content-type . (application/octet-stream
                                   (charset . "ISO-8859-1")))
                  ,@(if ttl
                        `((cache-control (max-age . ,ttl)))
                        '())

                  ;; XXX: We're not returning the actual contents, deferring
                  ;; instead to 'http-write'.  This is a hack to work around
                  ;; <http://bugs.gnu.org/21093>.
                  (x-raw-file . ,cached))
                #f)
        (not-found request))))

(define (render-content-addressed-file store request
                                       name algo hash)
  "Return the content of the result of the fixed-output derivation NAME that
has the given HASH of type ALGO."
  ;; TODO: Support other hash algorithms.
  (if (and (eq? algo 'sha256) (= 32 (bytevector-length hash)))
      (let ((item (fixed-output-path name hash
                                     #:hash-algo algo
                                     #:recursive? #f)))
        (if (valid-path? store item)
            (values `((content-type . (application/octet-stream
                                       (charset . "ISO-8859-1")))
                      ;; XXX: We're not returning the actual contents,
                      ;; deferring instead to 'http-write'.  This is a hack to
                      ;; work around <http://bugs.gnu.org/21093>.
                      (x-raw-file . ,item))
                    #f)
            (not-found request)))
      (not-found request)))

(define (render-log-file store request name)
  "Render the log file for NAME, the base name of a store item.  Don't attempt
to compress or decompress the log file; just return it as-is."
  (define (response-headers file)
    ;; XXX: We're not returning the actual contents, deferring instead to
    ;; 'http-write'.  This is a hack to work around
    ;; <http://bugs.gnu.org/21093>.
    (cond ((string-suffix? ".gz" file)
           `((content-type . (text/plain (charset . "UTF-8")))
             (content-encoding . (gzip))
             (x-raw-file . ,file)))
          ((string-suffix? ".bz2" file)
           `((content-type . (application/x-bzip2
                              (charset . "ISO-8859-1")))
             (x-raw-file . ,file)))
          (else                                   ;uncompressed
           `((content-type . (text/plain (charset . "UTF-8")))
             (x-raw-file . ,file)))))

  (let ((log (log-file store
                       (string-append (%store-prefix) "/" name))))
    (if log
        (values (response-headers log) log)
        (not-found request))))

(define (render-home-page request)
  "Render the home page."
  (values `((content-type . (text/html (charset . "UTF-8"))))
          (call-with-output-string
            (lambda (port)
              (sxml->xml '(html
                           (head (title "GNU Guix Substitute Server"))
                           (body
                            (h1 "GNU Guix Substitute Server")
                            (p "Hi, "
                               (a (@ (href
                                      "https://guix.gnu.org/manual/en/html_node/Invoking-guix-publish.html"))
                                  (tt "guix publish"))
                               " speaking.  Welcome!")))
                         port)))))

(define (extract-narinfo-hash str)
  "Return the hash within the narinfo resource string STR, or false if STR
is invalid."
  (and (string-suffix? ".narinfo" str)
       (let ((base (string-drop-right str 8)))
         (and (string-every %nix-base32-charset base)
              base))))

(define (get-request? request)
  "Return #t if REQUEST uses the GET method."
  (eq? (request-method request) 'GET))

(define (request-path-components request)
  "Split the URI path of REQUEST into a list of component strings.  For
example: \"/foo/bar\" yields '(\"foo\" \"bar\")."
  (split-and-decode-uri-path (uri-path (request-uri request))))

;;;
;;; Server.
;;;

(define %http-write
  (@@ (web server http) http-write))

(match (list (major-version) (minor-version) (micro-version))
  (("2" "2" "5")                                  ;Guile 2.2.5
   (let ()
     (define %read-line (@ (ice-9 rdelim) %read-line))
     (define bad-header (@@ (web http) bad-header))

     ;; XXX: Work around <https://bugs.gnu.org/36350> by reverting to the
     ;; definition of 'read-header-line' as found in 2.2.4 and earlier.
     (define (read-header-line port)
       "Read an HTTP header line and return it without its final CRLF or LF.
Raise a 'bad-header' exception if the line does not end in CRLF or LF,
or if EOF is reached."
       (match (%read-line port)
         (((? string? line) . #\newline)
          ;; '%read-line' does not consider #\return a delimiter; so if it's
          ;; there, remove it.  We are more tolerant than the RFC in that we
          ;; tolerate LF-only endings.
          (if (string-suffix? "\r" line)
              (string-drop-right line 1)
              line))
         ((line . _)                              ;EOF or missing delimiter
          (bad-header 'read-header-line line))))

     (set! (@@ (web http) read-header-line) read-header-line)))
  (_ #t))

(define (strip-headers response)
  "Return RESPONSE's headers minus 'Content-Length' and our internal headers."
  (fold alist-delete
        (response-headers response)
        '(content-length x-raw-file x-nar-compression)))

(define (sans-content-length response)
  "Return RESPONSE without its 'content-length' header."
  (set-field response (response-headers)
             (strip-headers response)))

(define (with-content-length response length)
  "Return RESPONSE with a 'content-length' header set to LENGTH."
  (set-field response (response-headers)
             (alist-cons 'content-length length
                         (strip-headers response))))

(define-syntax-rule (swallow-EPIPE exp ...)
  "Swallow EPIPE errors raised by EXP..."
  (catch 'system-error
    (lambda ()
      exp ...)
    (lambda args
      (if (= EPIPE (system-error-errno args))
          (values)
          (apply throw args)))))

(define-syntax-rule (swallow-zlib-error exp ...)
  "Swallow 'zlib-error' exceptions raised by EXP..."
  (catch 'zlib-error
    (lambda ()
      exp ...)
    (const #f)))

(define (nar-response-port response compression)
  "Return a port on which to write the body of RESPONSE, the response of a
/nar request, according to COMPRESSION."
  (match compression
    (($ <compression> 'gzip level)
     ;; Note: We cannot used chunked encoding here because
     ;; 'make-gzip-output-port' wants a file port.
     (make-gzip-output-port (response-port response)
                            #:level level
                            #:buffer-size (* 64 1024)))
    (($ <compression> 'lzip level)
     (make-lzip-output-port (response-port response)
                            #:level level))
    (($ <compression> 'none)
     (response-port response))
    (#f
     (response-port response))))

(define (http-write server client response body)
  "Write RESPONSE and BODY to CLIENT, possibly in a separate thread to avoid
blocking."
  (match (response-content-type response)
    (('application/x-nix-archive . _)
     ;; Sending the the whole archive can take time so do it in a separate
     ;; thread so that the main thread can keep working in the meantime.
     (call-with-new-thread
      (lambda ()
        (set-thread-name "publish nar")
        (let* ((compression (assoc-ref (response-headers response)
                                       'x-nar-compression))
               (response    (write-response (sans-content-length response)
                                            client))
               (port        (begin
                              (force-output client)
                              (nar-response-port response compression))))
          ;; XXX: Given our ugly workaround for <http://bugs.gnu.org/21093> in
          ;; 'render-nar', BODY here is just the file name of the store item.
          ;; We call 'write-file' from here because we know that's the only
          ;; way to avoid building the whole nar in memory, which could
          ;; quickly become a real problem.  As a bonus, we even do
          ;; sendfile(2) directly from the store files to the socket.
          (swallow-zlib-error
           (swallow-EPIPE
            (write-file (utf8->string body) port)))
          (swallow-zlib-error
           (close-port port))
          (values)))))
    (_
     (match (assoc-ref (response-headers response) 'x-raw-file)
       ((? string? file)
        ;; Send a raw file in a separate thread.
        (call-with-new-thread
         (lambda ()
           (set-thread-name "publish file")
           (catch 'system-error
             (lambda ()
               (call-with-input-file file
                 (lambda (input)
                   (let* ((size     (stat:size (stat input)))
                          (response (write-response (with-content-length response
                                                                         size)
                                                    client))
                          (output   (response-port response)))
                     (setsockopt client SOL_SOCKET SO_SNDBUF (* 128 1024))
                     (if (file-port? output)
                         (sendfile output input size)
                         (dump-port input output))
                     (close-port output)
                     (values)))))
             (lambda args
               ;; If the file was GC'd behind our back, that's fine.  Likewise if
               ;; the client closes the connection.
               (unless (memv (system-error-errno args)
                             (list ENOENT EPIPE ECONNRESET))
                 (apply throw args))
               (values))))))
       (#f
        ;; Handle other responses sequentially.
        (%http-write server client response body))))))

(define-server-impl concurrent-http-server
  ;; A variant of Guile's built-in HTTP server that offloads possibly long
  ;; responses to a different thread.
  (@@ (web server http) http-open)
  (@@ (web server http) http-read)
  http-write
  (@@ (web server http) http-close))

(define (string->compression-type string)
  "Return a symbol denoting the compression method expressed by STRING; return
#f if STRING doesn't match any supported method."
  (match string
    ("gzip" 'gzip)
    ("lzip" 'lzip)
    (_      #f)))

(define (effective-compression requested-type compressions)
  "Given the REQUESTED-TYPE for compression and the set of chosen COMPRESSION
methods, return the applicable compression."
  (or (find (match-lambda
              (($ <compression> type)
               (and (eq? type requested-type)
                    compression)))
            compressions)
      (default-compression requested-type)))

(define* (make-request-handler store
                               #:key
                               cache pool
                               narinfo-ttl
                               (nar-path "nar")
                               (compressions (list %no-compression)))
  (define compression-type?
    string->compression-type)

  (define nar-path?
    (let ((expected (split-and-decode-uri-path nar-path)))
      (cut equal? expected <>)))

  (lambda (request body)
    (format #t "~a ~a~%"
            (request-method request)
            (uri-path (request-uri request)))
    (if (get-request? request)                    ;reject POST, PUT, etc.
        (match (request-path-components request)
          ;; /nix-cache-info
          (("nix-cache-info")
           (render-nix-cache-info))
          ;; /
          ((or () ("index.html"))
           (render-home-page request))
          ;; /<hash>.narinfo
          (((= extract-narinfo-hash (? string? hash)))
           (if cache
               (render-narinfo/cached store request hash
                                      #:cache cache
                                      #:pool pool
                                      #:ttl narinfo-ttl
                                      #:nar-path nar-path
                                      #:compressions compressions)
               (render-narinfo store request hash
                               #:ttl narinfo-ttl
                               #:nar-path nar-path
                               #:compressions compressions)))
          ;; /nar/file/NAME/sha256/HASH
          (("file" name "sha256" hash)
           (guard (c ((invalid-base32-character? c)
                      (not-found request)))
             (let ((hash (nix-base32-string->bytevector hash)))
               (render-content-addressed-file store request
                                              name 'sha256 hash))))

          ;; /log/OUTPUT
          (("log" name)
           (render-log-file store request name))

          ;; Use different URLs depending on the compression type.  This
          ;; guarantees that /nar URLs remain valid even when 'guix publish'
          ;; is restarted with different compression parameters.

          ;; /nar/gzip/<store-item>
          ((components ... (? compression-type? type) store-item)
           (if (nar-path? components)
               (let* ((compression-type (string->compression-type type))
                      (compression (effective-compression compression-type
                                                          compressions)))
                 (if cache
                     (render-nar/cached store cache request store-item
                                        #:ttl narinfo-ttl
                                        #:compression compression)
                     (render-nar store request store-item
                                 #:compression compression)))
               (not-found request)))

          ;; /nar/<store-item>
          ((components ... store-item)
           (if (nar-path? components)
               (if cache
                   (render-nar/cached store cache request store-item
                                      #:ttl narinfo-ttl
                                      #:compression %no-compression)
                   (render-nar store request store-item
                               #:compression %no-compression))
               (not-found request)))

          (x (not-found request)))
        (not-found request))))

(define* (run-publish-server socket store
                             #:key
                             (compressions (list %no-compression))
                             (nar-path "nar") narinfo-ttl
                             cache pool)
  (run-server (make-request-handler store
                                    #:cache cache
                                    #:pool pool
                                    #:nar-path nar-path
                                    #:narinfo-ttl narinfo-ttl
                                    #:compressions compressions)
              concurrent-http-server
              `(#:socket ,socket)))

(define (open-server-socket address)
  "Return a TCP socket bound to ADDRESS, a socket address."
  (let ((sock (socket (sockaddr:fam address) SOCK_STREAM 0)))
    (setsockopt sock SOL_SOCKET SO_REUSEADDR 1)
    (bind sock address)
    sock))

(define (gather-user-privileges user)
  "Switch to the identity of USER, a user name."
  (catch 'misc-error
    (lambda ()
      (let ((user (getpw user)))
        (setgroups #())
        (setgid (passwd:gid user))
        (setuid (passwd:uid user))))
    (lambda (key proc message args . rest)
      (leave (G_ "user '~a' not found: ~a~%")
             user (apply format #f message args)))))

;;;
;;; Entry point.
;;;

(define-command (guix-publish . args)
  (category packaging)
  (synopsis "publish build results over HTTP")

  (with-error-handling
    (let* ((opts    (args-fold* args %options
                                (lambda (opt name arg result)
                                  (leave (G_ "~A: unrecognized option~%") name))
                                (lambda (arg result)
                                  (leave (G_ "~A: extraneous argument~%") arg))
                                %default-options))
           (user    (assoc-ref opts 'user))
           (port    (assoc-ref opts 'port))
           (ttl     (assoc-ref opts 'narinfo-ttl))
           (compressions (match (filter-map (match-lambda
                                              (('compression . compression)
                                               compression)
                                              (_ #f))
                                            opts)
                           (()
                            ;; Default to fast & low compression.
                            (list %default-gzip-compression))
                           (lst (reverse lst))))
           (address (let ((addr (assoc-ref opts 'address)))
                      (make-socket-address (sockaddr:fam addr)
                                           (sockaddr:addr addr)
                                           port)))
           (socket  (open-server-socket address))
           (nar-path  (assoc-ref opts 'nar-path))
           (repl-port (assoc-ref opts 'repl))
           (cache     (assoc-ref opts 'cache))
           (workers   (assoc-ref opts 'workers))

           ;; Read the key right away so that (1) we fail early on if we can't
           ;; access them, and (2) we can then drop privileges.
           (public-key  (read-file-sexp (assoc-ref opts 'public-key-file)))
           (private-key (read-file-sexp (assoc-ref opts 'private-key-file))))

      (when user
        ;; Now that we've read the key material and opened the socket, we can
        ;; drop privileges.
        (gather-user-privileges user))

      (when (zero? (getuid))
        (warning (G_ "server running as root; \
consider using the '--user' option!~%")))

      (parameterize ((%public-key public-key)
                     (%private-key private-key))
        (info (G_ "publishing ~a on ~a, port ~d~%")
              %store-directory
              (inet-ntop (sockaddr:fam address) (sockaddr:addr address))
              (sockaddr:port address))

        (for-each (lambda (compression)
                    (info (G_ "using '~a' compression method, level ~a~%")
                          (compression-type compression)
                          (compression-level compression)))
                  compressions)

        (when repl-port
          (repl:spawn-server (repl:make-tcp-server-socket #:port repl-port)))

        ;; Set the name of the main thread.
        (set-thread-name "guix publish")

        (with-store store
          (run-publish-server socket store
                              #:cache cache
                              #:pool (and cache (make-pool workers
                                                           #:thread-name
                                                           "publish worker"))
                              #:nar-path nar-path
                              #:compressions compressions
                              #:narinfo-ttl ttl))))))

;;; Local Variables:
;;; eval: (put 'single-baker 'scheme-indent-function 1)
;;; End:


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2013, 2014, 2015, 2017, 2018, 2019, 2020 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2017 Marius Bakke <mbakke@fastmail.com>
;;;
;;; This file is part of GNU Guix.
;;;
;;; GNU Guix 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 Guix.  If not, see <http://www.gnu.org/licenses/>.

(define-module (guix scripts pull)
  #:use-module ((guix ui) #:hide (display-profile-content))
  #:use-module (guix colors)
  #:use-module (guix utils)
  #:use-module ((guix status) #:select (with-status-verbosity))
  #:use-module (guix scripts)
  #:use-module (guix store)
  #:use-module (guix config)
  #:use-module (guix packages)
  #:use-module (guix derivations)
  #:use-module (guix profiles)
  #:use-module (guix gexp)
  #:use-module (guix grafts)
  #:use-module (guix memoization)
  #:use-module (guix monads)
  #:use-module (guix channels)
  #:autoload   (guix inferior) (open-inferior
                                inferior-available-packages
                                close-inferior)
  #:use-module (guix scripts build)
  #:use-module (guix scripts describe)
  #:autoload   (guix build utils) (which)
  #:use-module ((guix build syscalls)
                #:select (with-file-lock/no-wait))
  #:use-module (guix git)
  #:use-module (git)
  #:use-module (gnu packages)
  #:use-module ((guix scripts package) #:select (build-and-use-profile
                                                 delete-matching-generations))
  #:use-module ((gnu packages base) #:select (canonical-package))
  #:use-module (gnu packages guile)
  #:use-module ((gnu packages bootstrap)
                #:select (%bootstrap-guile))
  #:use-module ((gnu packages certs) #:select (le-certs))
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (srfi srfi-37)
  #:use-module (ice-9 match)
  #:use-module (ice-9 vlist)
  #:use-module (ice-9 format)
  #:re-export (display-profile-content
               channel-commit-hyperlink)
  #:export (channel-list
            guix-pull))

;;;
;;; Command-line options.
;;;

(define %default-options
  ;; Alist of default option values.
  `((system . ,(%current-system))
    (substitutes? . #t)
    (offload? . #t)
    (print-build-trace? . #t)
    (print-extended-build-trace? . #t)
    (multiplexed-build-output? . #t)
    (graft? . #t)
    (debug . 0)
    (verbosity . 1)
    (authenticate-channels? . #t)
    (validate-pull . ,ensure-forward-channel-update)))

(define (show-help)
  (display (G_ "Usage: guix pull [OPTION]...
Download and deploy the latest version of Guix.\n"))
  (display (G_ "
  -C, --channels=FILE    deploy the channels defined in FILE"))
  (display (G_ "
      --url=URL          download from the Git repository at URL"))
  (display (G_ "
      --commit=COMMIT    download the specified COMMIT"))
  (display (G_ "
      --branch=BRANCH    download the tip of the specified BRANCH"))
  (display (G_ "
      --allow-downgrades allow downgrades to earlier channel revisions"))
  (display (G_ "
      --disable-authentication
                         disable channel authentication"))
  (display (G_ "
  -N, --news             display news compared to the previous generation"))
  (display (G_ "
  -l, --list-generations[=PATTERN]
                         list generations matching PATTERN"))
  (display (G_ "
      --roll-back        roll back to the previous generation"))
  (display (G_ "
  -d, --delete-generations[=PATTERN]
                         delete generations matching PATTERN"))
  (display (G_ "
  -S, --switch-generation=PATTERN
                         switch to a generation matching PATTERN"))
  (display (G_ "
  -p, --profile=PROFILE  use PROFILE instead of ~/.config/guix/current"))
  (display (G_ "
  -v, --verbosity=LEVEL  use the given verbosity LEVEL"))
  (display (G_ "
  -s, --system=SYSTEM    attempt to build for SYSTEM--e.g., \"i686-linux\""))
  (display (G_ "
      --bootstrap        use the bootstrap Guile to build the new Guix"))
  (newline)
  (show-build-options-help)
  (display (G_ "
  -h, --help             display this help and exit"))
  (display (G_ "
  -V, --version          display version information and exit"))
  (newline)
  (show-bug-report-information))

(define %options
  ;; Specifications of the command-line options.
  (cons* (option '(#\C "channels") #t #f
                 (lambda (opt name arg result)
                   (alist-cons 'channel-file arg result)))
         (option '(#\l "list-generations") #f #t
                 (lambda (opt name arg result)
                   (cons `(query list-generations ,arg)
                         result)))
         (option '("roll-back") #f #f
                 (lambda (opt name arg result)
                   (cons '(generation roll-back)
                         result)))
         (option '(#\S "switch-generation") #t #f
                 (lambda (opt name arg result)
                   (cons `(generation switch ,arg)
                         result)))
         (option '(#\d "delete-generations") #f #t
                 (lambda (opt name arg result)
                   (cons `(generation delete ,arg)
                         result)))
         (option '(#\N "news") #f #f
                 (lambda (opt name arg result)
                   (cons '(query display-news) result)))
         (option '("url") #t #f
                 (lambda (opt name arg result)
                   (alist-cons 'repository-url arg
                               (alist-delete 'repository-url result))))
         (option '("commit") #t #f
                 (lambda (opt name arg result)
                   (alist-cons 'ref `(commit . ,arg) result)))
         (option '("branch") #t #f
                 (lambda (opt name arg result)
                   (alist-cons 'ref `(branch . ,arg) result)))
         (option '("allow-downgrades") #f #f
                 (lambda (opt name arg result)
                   (alist-cons 'validate-pull warn-about-backward-updates
                               result)))
         (option '("disable-authentication") #f #f
                 (lambda (opt name arg result)
                   (alist-cons 'authenticate-channels? #f result)))
         (option '(#\p "profile") #t #f
                 (lambda (opt name arg result)
                   (alist-cons 'profile (canonicalize-profile arg)
                               result)))
         (option '(#\s "system") #t #f
                 (lambda (opt name arg result)
                   (alist-cons 'system arg
                               (alist-delete 'system result eq?))))
         (option '(#\n "dry-run") #f #f
                 (lambda (opt name arg result)
                   (alist-cons 'dry-run? #t result)))
         (option '(#\v "verbosity") #t #f
                 (lambda (opt name arg result)
                   (let ((level (string->number* arg)))
                     (alist-cons 'verbosity level
                                 (alist-delete 'verbosity result)))))
         (option '("bootstrap") #f #f
                 (lambda (opt name arg result)
                   (alist-cons 'bootstrap? #t result)))

         (option '(#\h "help") #f #f
                 (lambda args
                   (show-help)
                   (exit 0)))
         (option '(#\V "version") #f #f
                 (lambda args
                   (show-version-and-exit "guix pull")))

         %standard-build-options))

(define (warn-about-backward-updates channel start commit relation)
  "Warn about non-forward updates of CHANNEL from START to COMMIT, without
aborting."
  (match relation
    ((or 'ancestor 'self)
     #t)
    ('descendant
     (warning (G_ "rolling back channel '~a' from ~a to ~a~%")
              (channel-name channel) start commit))
    ('unrelated
     (warning (G_ "moving channel '~a' from ~a to unrelated commit ~a~%")
              (channel-name channel) start commit))))

(define* (display-profile-news profile #:key concise?
                               current-is-newer?)
  "Display what's up in PROFILE--new packages, and all that.  If
CURRENT-IS-NEWER? is true, assume that the current process represents the
newest generation of PROFILE.  Return true when there's more info to display."
  (match (memv (generation-number profile)
               (reverse (profile-generations profile)))
    ((current previous _ ...)
     (let ((these (fold-available-packages
                   (lambda* (name version result
                                  #:key supported? deprecated?
                                  #:allow-other-keys)
                     (if (and supported? (not deprecated?))
                         (alist-cons name version result)
                         result))
                   '()))
           (those (profile-package-alist
                   (generation-file-name profile
                                         (if current-is-newer?
                                             previous
                                             current)))))
       (let ((old (if current-is-newer? those these))
             (new (if current-is-newer? these those)))
         (display-new/upgraded-packages old new
                                        #:concise? concise?
                                        #:heading
                                        (G_ "New in this revision:\n")))))
    (_ #f)))

(define (display-channel channel)
  "Display information about CHANNEL."
  (format (current-error-port)
          ;; TRANSLATORS: This describes a "channel"; the first placeholder is
          ;; the channel name (e.g., "guix") and the second placeholder is its
          ;; URL.
          (G_ "    ~a at ~a~%")
          (channel-name channel)
          (channel-url channel)))

(define (channel=? channel1 channel2)
  "Return true if CHANNEL1 and CHANNEL2 are the same for all practical
purposes."
  ;; Assume that the URL matters less than the name.
  (eq? (channel-name channel1) (channel-name channel2)))

(define (display-news-entry-title entry language port)
  "Display the title of ENTRY, a news entry, to PORT."
  (define title
    (channel-news-entry-title entry))

  (let ((title (or (assoc-ref title language)
                   (assoc-ref title (%default-message-language))
                   "")))
    (format port "  ~a~%"
            (highlight
             (string-trim-right
              (catch 'parser-error
                (lambda ()
                  (texi->plain-text title))

                ;; When Texinfo markup is invalid, display it as-is.
                (const title)))))))

(define (display-news-entry entry channel language port)
  "Display ENTRY, a <channel-news-entry> from CHANNEL, in LANGUAGE, a language
code, to PORT."
  (define body
    (channel-news-entry-body entry))

  (define commit
    (channel-news-entry-commit entry))

  (display-news-entry-title entry language port)
  (format port (dim (G_ "    commit ~a~%"))
          (if (supports-hyperlinks?)
              (channel-commit-hyperlink channel commit)
              commit))
  (newline port)
  (let ((body (or (assoc-ref body language)
                  (assoc-ref body (%default-message-language))
                  "")))
    (format port "~a~%"
            (indented-string
             (parameterize ((%text-width (- (%text-width) 4)))
               (string-trim-right
                (catch 'parser-error
                  (lambda ()
                    (texi->plain-text body))
                  (lambda _
                    ;; When Texinfo markup is invalid, display it as-is.
                    (fill-paragraph body (%text-width))))))
             4))))

(define* (display-channel-specific-news new old
                                        #:key (port (current-output-port))
                                        concise?)
  "Display channel news applicable the commits between OLD and NEW, where OLD
and NEW are <channel> records with a proper 'commit' field.  When CONCISE? is
true, display nothing but the news titles.  Return true if there are more news
to display."
  (let ((channel new)
        (old     (channel-commit old))
        (new     (channel-commit new)))
    (when (and old new)
      (let ((language (current-message-language)))
        (match (channel-news-for-commit channel new old)
          (()                                     ;no news is good news
           #f)
          ((entries ...)
           (newline port)
           (format port (G_ "News for channel '~a'~%")
                   (channel-name channel))
           (for-each (if concise?
                         (cut display-news-entry-title <> language port)
                         (cut display-news-entry <> channel language port))
                     entries)
           (newline port)
           #t))))))

(define* (display-channel-news profile
                               #:optional
                               (previous
                                (and=> (relative-generation profile -1)
                                       (cut generation-file-name profile <>))))
  "Display news about the channels of PROFILE compared to PREVIOUS."
  (when previous
    (let ((old-channels (profile-channels previous))
          (new-channels (profile-channels profile)))
      (and (pair? old-channels) (pair? new-channels)
           (begin
             (match (lset-difference channel=? new-channels old-channels)
               (()
                #t)
               (new
                (let ((count (length new)))
                  (format (current-error-port)
                          (N_ "  ~a new channel:~%"
                              "  ~a new channels:~%" count)
                          count)
                  (for-each display-channel new))))
             (match (lset-difference channel=? old-channels new-channels)
               (()
                #t)
               (removed
                (let ((count (length removed)))
                  (format (current-error-port)
                          (N_ "  ~a channel removed:~%"
                              "  ~a channels removed:~%" count)
                          count)
                  (for-each display-channel removed))))

             ;; Display channel-specific news for those channels that were
             ;; here before and are still around afterwards.
             (for-each (match-lambda
                         ((new old)
                          (display-channel-specific-news new old)))
                       (filter-map (lambda (new)
                                     (define old
                                       (find (cut channel=? new <>)
                                             old-channels))

                                     (and old (list new old)))
                                   new-channels)))))))

(define* (display-channel-news-headlines profile)
  "Display the titles of news about the channels of PROFILE compared to its
previous generation.  Return true if there are news to display."
  (define previous
    (and=> (relative-generation profile -1)
           (cut generation-file-name profile <>)))

  (when previous
    (let ((old-channels (profile-channels previous))
          (new-channels (profile-channels profile)))
      ;; Find the channels present in both PROFILE and PREVIOUS, and print
      ;; their news.
      (and (pair? old-channels) (pair? new-channels)
           (let ((channels (filter-map (lambda (new)
                                         (define old
                                           (find (cut channel=? new <>)
                                                 old-channels))

                                         (and old (list new old)))
                                       new-channels)))
             (define more?
               (map (match-lambda
                      ((new old)
                       (display-channel-specific-news new old
                                                      #:concise? #t)))
                    channels))

             (any ->bool more?))))))

(define (display-news profile)
  ;; Display profile news, with the understanding that this process represents
  ;; the newest generation.
  (display-profile-news profile
                        #:current-is-newer? #t)

  (display-channel-news profile))

(define* (build-and-install instances profile)
  "Build the tool from SOURCE, and install it in PROFILE.  When DRY-RUN? is
true, display what would be built without actually building it."
  (define update-profile
    (store-lift build-and-use-profile))

  (define guix-command
    ;; The 'guix' command before we've built the new profile.
    (which "guix"))

  (mlet %store-monad ((manifest (channel-instances->manifest instances)))
    (mbegin %store-monad
      (update-profile profile manifest
                      #:hooks %channel-profile-hooks)

      (return
       (let ((more? (list (display-profile-news profile #:concise? #t)
                          (display-channel-news-headlines profile))))
         (newline)
         (when (any ->bool more?)
           (display-hint
            (G_ "Run @command{guix pull --news} to read all the news.")))))
      (if guix-command
          (let ((new (map (cut string-append <> "/bin/guix")
                          (list (user-friendly-profile profile)
                                profile))))
            ;; Is the 'guix' command previously in $PATH the same as the new
            ;; one?  If the answer is "no", then suggest 'hash guix'.
            (unless (member guix-command new)
              (display-hint (format #f (G_ "After setting @code{PATH}, run
@command{hash guix} to make sure your shell refers to @file{~a}.")
                                    (first new))))
            (return #f))
          (return #f)))))

(define (honor-lets-encrypt-certificates! store)
  "Tell Guile-Git to use the Let's Encrypt certificates."
  (let* ((drv   (package-derivation store le-certs))
         (certs (string-append (derivation->output-path drv)
                               "/etc/ssl/certs")))
    (build-derivations store (list drv))
    (set-tls-certificate-locations! certs)))

(define (honor-x509-certificates store)
  "Use the right X.509 certificates for Git checkouts over HTTPS."
  (unless (honor-system-x509-certificates!)
    (honor-lets-encrypt-certificates! store)))

;;;
;;; Profile.
;;;

(define %current-profile
  ;; The "real" profile under /var/guix.
  (string-append %profile-directory "/current-guix"))

(define %user-profile-directory
  ;; The user-friendly name of %CURRENT-PROFILE.
  (string-append (config-directory #:ensure? #f) "/current"))

(define (migrate-generations profile directory)
  "Migrate the generations of PROFILE to DIRECTORY."
  (format (current-error-port)
          (G_ "Migrating profile generations to '~a'...~%")
          %profile-directory)
  (let ((current (generation-number profile)))
    (for-each (lambda (generation)
                (let ((source (generation-file-name profile generation))
                      (target (string-append directory "/current-guix-"
                                             (number->string generation)
                                             "-link")))
                  ;; Note: Don't use 'rename-file' as SOURCE and TARGET might
                  ;; live on different file systems.
                  (symlink (readlink source) target)
                  (delete-file source)))
              (profile-generations profile))
    (symlink (string-append "current-guix-"
                            (number->string current) "-link")
             (string-append directory "/current-guix"))))

(define (ensure-default-profile)
  (ensure-profile-directory)

  ;; In 0.15.0+ we'd create ~/.config/guix/current-[0-9]*-link symlinks.  Move
  ;; them to %PROFILE-DIRECTORY.
  ;;
  ;; XXX: Ubuntu's 'sudo' preserves $HOME by default, and thus the second
  ;; condition below is always false when one runs "sudo guix pull".  As a
  ;; workaround, skip this code when $SUDO_USER is set.  See
  ;; <https://bugs.gnu.org/36785>.
  (unless (or (getenv "SUDO_USER")
              (not (file-exists? %user-profile-directory))
              (string=? %profile-directory
                        (dirname
                         (canonicalize-profile %user-profile-directory))))
    (migrate-generations %user-profile-directory %profile-directory))

  ;; Make sure ~/.config/guix/current points to /var/guix/profiles/….
  (let ((link %user-profile-directory))
    (unless (equal? (false-if-exception (readlink link))
                    %current-profile)
      (catch 'system-error
        (lambda ()
          (false-if-exception (delete-file link))
          (symlink %current-profile link))
        (lambda args
          (leave (G_ "while creating symlink '~a': ~a~%")
                 link (strerror (system-error-errno args))))))))

;;;
;;; Queries.
;;;

(define profile-package-alist
  (mlambda (profile)
    "Return a name/version alist representing the packages in PROFILE."
    (let* ((inferior (open-inferior profile))
           (packages (inferior-available-packages inferior)))
      (close-inferior inferior)
      packages)))

(define (new/upgraded-packages alist1 alist2)
  "Compare ALIST1 and ALIST2, both of which are lists of package name/version
pairs, and return two values: the list of packages new in ALIST2, and the list
of packages upgraded in ALIST2."
  (let* ((old      (fold (match-lambda*
                           (((name . version) table)
                            (match (vhash-assoc name table)
                              (#f
                               (vhash-cons name version table))
                              ((_ . previous-version)
                               (if (version>? version previous-version)
                                   (vhash-cons name version table)
                                   table)))))
                         vlist-null
                         alist1))
         (new      (remove (match-lambda
                             ((name . _)
                              (vhash-assoc name old)))
                           alist2))
         (upgraded (filter-map (match-lambda
                                 ((name . new-version)
                                  (match (vhash-assoc name old)
                                    (#f #f)
                                    ((_ . old-version)
                                     (and (version>? new-version old-version)
                                          (string-append name "@"
                                                         new-version))))))
                               alist2)))
    (values new upgraded)))

(define* (ellipsis #:optional (port (current-output-port)))
  "Return HORIZONTAL ELLIPSIS three dots if PORT's encoding cannot represent
it."
  (match (port-encoding port)
    ("UTF-8" "…")
    (_       "...")))

(define* (display-new/upgraded-packages alist1 alist2
                                        #:key (heading "") concise?)
  "Given the two package name/version alists ALIST1 and ALIST2, display the
list of new and upgraded packages going from ALIST1 to ALIST2.  When ALIST1
and ALIST2 differ, display HEADING upfront.  When CONCISE? is true, do not
display long package lists that would fill the user's screen.

Return true when there is more package info to display."
  (define (pretty str column)
    (indented-string (fill-paragraph str (- (%text-width) 4)
                                     column)
                     4 #:initial-indent? #f))

  (define concise/max-item-count
    ;; Maximum number of items to display when CONCISE? is true.
    12)

  (define list->enumeration
    (if concise?
        (lambda* (lst #:optional (max concise/max-item-count))
          (if (> (length lst) max)
              (string-append (string-join (take lst max) ", ")
                             ", " (ellipsis))
              (string-join lst ", ")))
        (cut string-join <> ", ")))

  (let-values (((new upgraded) (new/upgraded-packages alist1 alist2)))
    (define new-count (length new))
    (define upgraded-count (length upgraded))

    (unless (and (null? new) (null? upgraded))
      (display heading))

    (match new-count
      (0 #t)
      (count
       (format #t (N_ "  ~h new package: ~a~%"
                      "  ~h new packages: ~a~%" count)
               count
               (pretty (list->enumeration (sort (map first new) string<?))
                       30))))
    (match upgraded-count
      (0 #t)
      (count
       (format #t (N_ "  ~h package upgraded: ~a~%"
                      "  ~h packages upgraded: ~a~%" count)
               count
               (pretty (list->enumeration (sort upgraded string<?))
                       35))))

    (and concise?
         (or (> new-count concise/max-item-count)
             (> upgraded-count concise/max-item-count)))))

(define (display-profile-content-diff profile gen1 gen2)
  "Display the changes in PROFILE GEN2 compared to generation GEN1."
  (define (package-alist generation)
    (profile-package-alist (generation-file-name profile generation)))

  (display-profile-content profile gen2)
  (display-new/upgraded-packages (package-alist gen1)
                                 (package-alist gen2)))

(define (process-query opts profile)
  "Process any query on PROFILE specified by OPTS."
  (match (assoc-ref opts 'query)
    (('list-generations pattern)
     (define (list-generations profile numbers)
       (match numbers
         ((first rest ...)
          (display-profile-content profile first)
          (let loop ((numbers numbers))
            (match numbers
              ((first second rest ...)
               (display-profile-content-diff profile
                                             first second)
               (display-channel-news (generation-file-name profile second)
                                     (generation-file-name profile first))
               (loop (cons second rest)))
              ((_) #t)
              (()  #t))))))

     (leave-on-EPIPE
      (cond ((not (file-exists? profile))         ; XXX: race condition
             (raise (condition (&profile-not-found-error
                                (profile profile)))))
            ((not pattern)
             (list-generations profile (profile-generations profile)))
            ((matching-generations pattern profile)
             =>
             (match-lambda
               (()
                (exit 1))
               ((numbers ...)
                (list-generations profile numbers)))))))
    (('display-news)
     (display-news profile))))

(define (process-generation-change opts profile)
  "Process a request to change the current generation (roll-back, switch, delete)."
  (unless (assoc-ref opts 'dry-run?)
    (match (assoc-ref opts 'generation)
      (('roll-back)
       (with-store store
         (roll-back* store profile)))
      (('switch pattern)
       (let ((number (relative-generation-spec->number profile pattern)))
         (if number
             (switch-to-generation* profile number)
             (leave (G_ "cannot switch to generation '~a'~%") pattern))))
      (('delete pattern)
       (with-store store
         (delete-matching-generations store profile pattern))))))

(define (channel-list opts)
  "Return the list of channels to use.  If OPTS specify a channel file,
channels are read from there; otherwise, if ~/.config/guix/channels.scm
exists, read it; otherwise %DEFAULT-CHANNELS is used.  Apply channel
transformations specified in OPTS (resulting from '--url', '--commit', or
'--branch'), if any."
  (define file
    (assoc-ref opts 'channel-file))

  (define default-file
    (string-append (config-directory) "/channels.scm"))

  (define global-file
    (string-append %sysconfdir "/guix/channels.scm"))

  (define (load-channels file)
    (let ((result (load* file (make-user-module '((guix channels))))))
      (if (and (list? result) (every channel? result))
          result
          (leave (G_ "'~a' did not return a list of channels~%") file))))

  (define channels
    (cond (file
           (load-channels file))
          ((file-exists? default-file)
           (load-channels default-file))
          ((file-exists? global-file)
           (load-channels global-file))
          (else
           %default-channels)))

  (define (environment-variable)
    (match (getenv "GUIX_PULL_URL")
      (#f #f)
      (url
       (warning (G_ "The 'GUIX_PULL_URL' environment variable is deprecated.
Use '~/.config/guix/channels.scm' instead."))
       url)))

  (let ((ref (assoc-ref opts 'ref))
        (url (or (assoc-ref opts 'repository-url)
                 (environment-variable))))
    (if (or ref url)
        (match (find guix-channel? channels)
          ((? channel? guix)
           ;; Apply '--url', '--commit', and '--branch' to the 'guix' channel.
           (let ((url (or url (channel-url guix))))
             (cons (match ref
                     (('commit . commit)
                      (channel (inherit guix)
                               (url url) (commit commit) (branch #f)))
                     (('branch . branch)
                      (channel (inherit guix)
                               (url url) (commit #f) (branch branch)))
                     (#f
                      (channel (inherit guix) (url url))))
                   (remove guix-channel? channels))))
          (#f                           ;no 'guix' channel, failure will ensue
           channels))
        channels)))

(define-command (guix-pull . args)
  (synopsis "pull the latest revision of Guix")

  (with-error-handling
    (with-git-error-handling
     (let* ((opts         (parse-command-line args %options
                                              (list %default-options)))
            (substitutes? (assoc-ref opts 'substitutes?))
            (dry-run?     (assoc-ref opts 'dry-run?))
            (channels     (channel-list opts))
            (profile      (or (assoc-ref opts 'profile) %current-profile))
            (current-channels (profile-channels profile))
            (validate-pull    (assoc-ref opts 'validate-pull))
            (authenticate?    (assoc-ref opts 'authenticate-channels?)))
       (cond ((assoc-ref opts 'query)
              (process-query opts profile))
             ((assoc-ref opts 'generation)
              (process-generation-change opts profile))
             (else
              (with-store store
                (with-status-verbosity (assoc-ref opts 'verbosity)
                  (parameterize ((%current-system (assoc-ref opts 'system))
                                 (%graft? (assoc-ref opts 'graft?)))
                    (with-build-handler (build-notifier #:use-substitutes?
                                                        substitutes?
                                                        #:verbosity
                                                        (assoc-ref opts 'verbosity)
                                                        #:dry-run? dry-run?)
                      (set-build-options-from-command-line store opts)
                      (ensure-default-profile)
                      (honor-x509-certificates store)

                      (let ((instances
                             (latest-channel-instances store channels
                                                       #:current-channels
                                                       current-channels
                                                       #:validate-pull
                                                       validate-pull
                                                       #:authenticate?
                                                       authenticate?)))
                        (format (current-error-port)
                                (N_ "Building from this channel:~%"
                                    "Building from these channels:~%"
                                    (length instances)))
                        (for-each (lambda (instance)
                                    (let ((channel
                                           (channel-instance-channel instance)))
                                      (format (current-error-port)
                                              "  ~10a~a\t~a~%"
                                              (channel-name channel)
                                              (channel-url channel)
                                              (string-take
                                               (channel-instance-commit instance)
                                               7))))
                                  instances)
                        (parameterize ((%guile-for-build
                                        (package-derivation
                                         store
                                         (if (assoc-ref opts 'bootstrap?)
                                             %bootstrap-guile
                                             (default-guile)))))
                          (with-profile-lock profile
                            (run-with-store store
                              (build-and-install instances profile)))))))))))))))

;;; pull.scm ends here