code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2010, 2011, 2013, 2014, 2016, 2018, 2019 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2013 Nikita Karetnikov <nikita@karetnikov.org>
;;; Copyright © 2020 Tobias Geerinckx-Rice <me@tobias.gr>
;;;
;;; 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 gnupg)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 rdelim)
  #:use-module (ice-9 i18n)
  #:use-module (srfi srfi-1)
  #:use-module (guix i18n)
  #:use-module ((guix utils) #:select (config-directory))
  #:use-module ((guix build utils) #:select (mkdir-p))
  #:export (%gpg-command
            %openpgp-key-server
            current-keyring
            gnupg-verify
            gnupg-verify*
            gnupg-status-good-signature?
            gnupg-status-missing-key?))

;;; Commentary:
;;;
;;; GnuPG interface.
;;;
;;; Code:

(define %gpg-command
  ;; The GnuPG 2.x command-line program name.
  (make-parameter (or (getenv "GUIX_GPG_COMMAND") "gpg")))

(define %gpgv-command
  ;; The 'gpgv' program.
  (make-parameter (or (getenv "GUIX_GPGV_COMMAND") "gpgv")))

(define current-keyring
  ;; The default keyring of "trusted keys".
  (make-parameter (string-append (config-directory #:ensure? #f)
                                 "/gpg/trustedkeys.kbx")))

(define %openpgp-key-server
  ;; The default key server.  Note that keys.gnupg.net appears to be
  ;; unreliable.
  (make-parameter "pool.sks-keyservers.net"))

;; Regexps for status lines.  See file `doc/DETAILS' in GnuPG.

(define sigid-rx
  (make-regexp
   "^\\[GNUPG:\\] SIG_ID ([A-Za-z0-9+/]+) ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}) ([[:digit:]]+)"))
(define goodsig-rx
  (make-regexp "^\\[GNUPG:\\] GOODSIG ([[:xdigit:]]+) (.+)$"))
(define validsig-rx
  (make-regexp
   "^\\[GNUPG:\\] VALIDSIG ([[:xdigit:]]+) ([[:digit:]]{4}-[[:digit:]]{2}-[[:digit:]]{2}) ([[:digit:]]+) .*$"))
(define expkeysig-rx                    ; good signature, but expired key
  (make-regexp "^\\[GNUPG:\\] EXPKEYSIG ([[:xdigit:]]+) (.*)$"))
(define revkeysig-rx                    ; good signature, but revoked key
  (make-regexp "^\\[GNUPG:\\] REVKEYSIG ([[:xdigit:]]+) (.*)$"))
(define errsig-rx
  ;; Note: The fingeprint part (the last element of the line) appeared in
  ;; GnuPG 2.2.7 according to 'doc/DETAILS', and it may be missing.
  (make-regexp
   "^\\[GNUPG:\\] ERRSIG ([[:xdigit:]]+) ([^ ]+) ([^ ]+) ([^ ]+) ([[:digit:]]+) ([[:digit:]]+)(.*)"))

(define* (gnupg-verify sig file
                       #:optional (keyring (current-keyring)))
  "Verify signature SIG for FILE against the keys in KEYRING.  All the keys in
KEYRING as assumed to be \"trusted\", whether or not they expired or were
revoked.  Return a status s-exp if GnuPG failed."

  (define (maybe-fingerprint str)
    (match (string-trim-both str)
      ((or "-" "") #f)
      (fpr         fpr)))

  (define (status-line->sexp line)
    (cond ((regexp-exec sigid-rx line)
           =>
           (lambda (match)
             `(signature-id ,(match:substring match 1) ; sig id
                            ,(match:substring match 2) ; date
                            ,(string->number           ; timestamp
                              (match:substring match 3)))))
          ((regexp-exec goodsig-rx line)
           =>
           (lambda (match)
             `(good-signature ,(match:substring match 1)    ; key id
                              ,(match:substring match 2)))) ; user name
          ((regexp-exec validsig-rx line)
           =>
           (lambda (match)
             `(valid-signature ,(match:substring match 1) ; fingerprint
                               ,(match:substring match 2) ; sig creation date
                               ,(string->number           ; timestamp
                                 (match:substring match 3)))))
          ((regexp-exec expkeysig-rx line)
           =>
           (lambda (match)
             `(expired-key-signature ,(match:substring match 1) ; fingerprint
                                     ,(match:substring match 2)))) ; user name
          ((regexp-exec revkeysig-rx line)
           =>
           (lambda (match)
             `(revoked-key-signature ,(match:substring match 1) ; fingerprint
                                     ,(match:substring match 2)))) ; user name
          ((regexp-exec errsig-rx line)
           =>
           (lambda (match)
             `(signature-error ,(match:substring match 1) ; key id
                               ,(match:substring match 2) ; pubkey algo
                               ,(match:substring match 3) ; hash algo
                               ,(match:substring match 4) ; sig class
                               ,(string->number           ; timestamp
                                 (match:substring match 5))
                               ,(let ((rc
                                       (string->number ; return code
                                        (match:substring match 6))))
                                  (case rc
                                    ((9) 'missing-key)
                                    ((4) 'unknown-algorithm)
                                    (else rc)))
                               ,(maybe-fingerprint ; fingerprint or #f
                                 (match:substring match 7)))))
          (else
           `(unparsed-line ,line))))

  (define (parse-status input)
    (let loop ((line   (read-line input))
               (result '()))
      (if (eof-object? line)
          (reverse result)
          (loop (read-line input)
                (cons (status-line->sexp line) result)))))

  (let* ((pipe   (open-pipe* OPEN_READ (%gpgv-command) "--status-fd=1"
                             "--keyring" keyring sig file))
         (status (parse-status pipe)))
    ;; Ignore PIPE's exit status since STATUS above should contain all the
    ;; info we need.
    (close-pipe pipe)
    status))

(define (gnupg-status-good-signature? status)
  "If STATUS, as returned by `gnupg-verify', denotes a good signature, return
a fingerprint/user pair; return #f otherwise."
  (match (assq 'valid-signature status)
    (('valid-signature fingerprint date timestamp)
     (match (or (assq 'good-signature status)
                (assq 'expired-key-signature status)
                (assq 'revoked-key-signature status))
       ((_ key-id user) (cons fingerprint user))
       (_ #f)))
    (_
     #f)))

(define (gnupg-status-missing-key? status)
  "If STATUS denotes a missing-key error, then return the fingerprint of the
missing key or its key id if the fingerprint is unavailable."
  (any (lambda (sexp)
         (match sexp
           (('signature-error key-id _ ... 'missing-key fingerprint)
            (or fingerprint key-id))
           (_ #f)))
       status))

(define* (gnupg-receive-keys fingerprint/key-id server
                             #:optional (keyring (current-keyring)))
  "Download FINGERPRINT/KEY-ID from SERVER, a key server, and add it to
KEYRING."
  (unless (file-exists? keyring)
    (mkdir-p (dirname keyring))
    (call-with-output-file keyring (const #t)))   ;create an empty keybox

  (zero? (system* (%gpg-command) "--keyserver" server
                  "--no-default-keyring" "--keyring" keyring
                  "--recv-keys" fingerprint/key-id)))

(define* (gnupg-verify* sig file
                        #:key
                        (key-download 'interactive)
                        (server (%openpgp-key-server))
                        (keyring (current-keyring)))
  "Like `gnupg-verify', but try downloading the public key if it's missing.
Return two values: 'valid-signature and a fingerprint/name pair upon success,
'missing-key and a fingerprint if the key could not be found, and
'invalid-signature with a fingerprint if the signature is invalid.

KEY-DOWNLOAD specifies a download policy for missing OpenPGP keys; allowed
values: 'always', 'never', and 'interactive' (default).  Return a
fingerprint/user name pair on success and #f otherwise."
  (let ((status (gnupg-verify sig file)))
    (match (gnupg-status-good-signature? status)
      ((fingerprint . user)
       (values 'valid-signature (cons fingerprint user)))
      (#f
       (let ((missing (gnupg-status-missing-key? status)))
         (define (download-and-try-again)
           ;; Download the missing key and try again.
           (if (gnupg-receive-keys missing server keyring)
               (match (gnupg-status-good-signature?
                       (gnupg-verify sig file keyring))
                 (#f
                  (values 'invalid-signature missing))
                 ((fingerprint . user)
                  (values 'valid-signature
                          (cons fingerprint user))))
               (values 'missing-key missing)))

         (define (receive?)
           (let ((answer
                  (begin
                    (format #t (G_ "Would you like to add this key \
to keyring '~a'?~%")
                            keyring)
                    (read-line))))
             (string-match (locale-yes-regexp) answer)))

         (case key-download
           ((never)
            (values 'missing-key missing))
           ((always)
            (download-and-try-again))
           (else
            (if (receive?)
                (download-and-try-again)
                (values 'missing-key missing)))))))))

;;; gnupg.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021 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 grafts)
  #:use-module (guix store)
  #:use-module (guix monads)
  #:use-module (guix records)
  #:use-module (guix combinators)
  #:use-module (guix derivations)
  #:use-module ((guix utils) #:select (%current-system))
  #:use-module (guix sets)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-71)
  #:use-module (ice-9 match)
  #:use-module (ice-9 vlist)
  #:export (graft?
            graft
            graft-origin
            graft-replacement
            graft-origin-output
            graft-replacement-output

            graft-derivation
            graft-derivation/shallow

            %graft?
            set-grafting
            grafting?))

(define-record-type* <graft> graft make-graft
  graft?
  (origin             graft-origin)               ;derivation | store item
  (origin-output      graft-origin-output         ;string | #f
                      (default "out"))
  (replacement        graft-replacement)          ;derivation | store item
  (replacement-output graft-replacement-output    ;string | #f
                      (default "out")))

(define (write-graft graft port)
  "Write a concise representation of GRAFT to PORT."
  (define (->string thing output)
    (if (derivation? thing)
        (derivation->output-path thing output)
        thing))

  (match graft
    (($ <graft> origin origin-output replacement replacement-output)
     (format port "#<graft ~a ==> ~a ~a>"
             (->string origin origin-output)
             (->string replacement replacement-output)
             (number->string (object-address graft) 16)))))

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

(define (graft-origin-file-name graft)
  "Return the output file name of the origin of GRAFT."
  (match graft
    (($ <graft> (? derivation? origin) output)
     (derivation->output-path origin output))
    (($ <graft> (? string? item))
     item)))

(define* (graft-derivation/shallow store drv grafts
                                   #:key
                                   (name (derivation-name drv))
                                   (outputs (derivation-output-names drv))
                                   (guile (%guile-for-build))
                                   (system (%current-system)))
  "Return a derivation called NAME, which applies GRAFTS to the specified
OUTPUTS of DRV.  This procedure performs \"shallow\" grafting in that GRAFTS
are not recursively applied to dependencies of DRV."
  ;; XXX: Someday rewrite using gexps.
  (define mapping
    ;; List of store item pairs.
    (map (match-lambda
          (($ <graft> source source-output target target-output)
           (cons (if (derivation? source)
                     (derivation->output-path source source-output)
                     source)
                 (if (derivation? target)
                     (derivation->output-path target target-output)
                     target))))
         grafts))

  (define output-pairs
    (map (lambda (output)
           (cons output
                 (derivation-output-path
                  (assoc-ref (derivation-outputs drv) output))))
         outputs))

  (define build
    `(begin
       (use-modules (guix build graft)
                    (guix build utils)
                    (ice-9 match))

       (let* ((old-outputs ',output-pairs)
              (mapping (append ',mapping
                               (map (match-lambda
                                      ((name . file)
                                       (cons (assoc-ref old-outputs name)
                                             file)))
                                    %outputs))))
         (graft old-outputs %outputs mapping))))

  (define add-label
    (cut cons "x" <>))

  (define properties
    `((type . graft)
      (graft (count . ,(length grafts)))))

  (match grafts
    ((($ <graft> sources source-outputs targets target-outputs) ...)
     (let ((sources (zip sources source-outputs))
           (targets (zip targets target-outputs)))
       (build-expression->derivation store name build
                                     #:system system
                                     #:guile-for-build guile
                                     #:modules '((guix build graft)
                                                 (guix build utils)
                                                 (guix build debug-link)
                                                 (guix elf))
                                     #:inputs `(,@(map (lambda (out)
                                                         `("x" ,drv ,out))
                                                       outputs)
                                                ,@(append (map add-label sources)
                                                          (map add-label targets)))
                                     #:outputs outputs

                                     ;; Grafts are computationally cheap so no
                                     ;; need to offload or substitute.
                                     #:local-build? #t
                                     #:substitutable? #f

                                     #:properties properties)))))

(define (non-self-references store drv outputs)
  "Return the list of references of the OUTPUTS of DRV, excluding self
references."
  (define (references* items)
    ;; Return the references of ITEMS.
    (guard (c ((store-protocol-error? c)
               ;; ITEMS are not in store so build INPUT first.
               (and (build-derivations store (list drv))
                    (append-map (cut references/cached store <>) items))))
      (append-map (cut references/cached store <>) items)))

  (let ((refs (references* (map (cut derivation->output-path drv <>)
                                outputs)))
        (self (match (derivation->output-paths drv)
                (((names . items) ...)
                 items))))
    (remove (cut member <> self) refs)))

(define %graft-cache
  ;; Cache that maps derivation/outputs/grafts tuples to lists of grafts.
  (allocate-store-connection-cache 'grafts))

(define record-cache-lookup!
  (cache-lookup-recorder "derivation-graft-cache"
                         "Derivation graft cache"))

(define-syntax-rule (with-cache key exp ...)
  "Cache the value of monadic expression EXP under KEY."
  (mlet* %state-monad ((cache (current-state))
                       (result -> (vhash-assoc key cache)))
    (record-cache-lookup! result cache)
    (match result
      ((_ . result)                               ;cache hit
       (return result))
      (#f                                         ;cache miss
       (mlet %state-monad ((result (begin exp ...))
                           (cache  (current-state)))
         (mbegin %state-monad
           (set-current-state (vhash-cons key result cache))
           (return result)))))))

(define (reference-origins drv items)
  "Return the derivation/output pairs among the inputs of DRV, recursively,
that produce ITEMS.  Elements of ITEMS not produced by a derivation (i.e.,
it's a content-addressed \"source\"), or not produced by a dependency of DRV,
have no corresponding element in the resulting list."
  (define (lookup-derivers drv result items)
    ;; Return RESULT augmented by all the drv/output pairs producing one of
    ;; ITEMS, and ITEMS stripped of matching items.
    (fold2 (match-lambda*
             (((output . file) result items)
              (if (member file items)
                  (values (alist-cons drv output result)
                          (delete file items))
                  (values result items))))
           result items
           (derivation->output-paths drv)))

  ;; Perform a breadth-first traversal of the dependency graph of DRV in
  ;; search of the derivations that produce ITEMS.
  (let loop ((drv (list drv))
             (items items)
             (result '())
             (visited (setq)))
    (match drv
      (()
       result)
      ((drv . rest)
       (cond ((null? items)
              result)
             ((set-contains? visited drv)
              (loop rest items result visited))
             (else
              (let* ((inputs
                      (map derivation-input-derivation
                           (derivation-inputs drv)))
                     (result items
                             (fold2 lookup-derivers
                                    result items inputs)))
                (loop (append rest inputs)
                      items result
                      (set-insert drv visited)))))))))

(define* (cumulative-grafts store drv grafts
                            #:key
                            (outputs (derivation-output-names drv))
                            (guile (%guile-for-build))
                            (system (%current-system)))
  "Augment GRAFTS with additional grafts resulting from the application of
GRAFTS to the dependencies of DRV.  Return the resulting list of grafts.

This is a monadic procedure in %STATE-MONAD where the state is a vhash mapping
derivations to the corresponding set of grafts."
  (define (graft-origin? drv graft)
    ;; Return true if DRV corresponds to the origin of GRAFT.
    (match graft
      (($ <graft> (? derivation? origin) output)
       (match (assoc-ref (derivation->output-paths drv) output)
         ((? string? result)
          (string=? result
                    (derivation->output-path origin output)))
         (_
          #f)))
      (_
       #f)))

  (define (dependency-grafts items)
    (mapm %store-monad
          (lambda (drv+output)
            (match drv+output
              ((drv . output)
               ;; If GRAFTS already contains a graft from DRV, do not
               ;; override it.
               (if (find (cut graft-origin? drv <>) grafts)
                   (state-return grafts)
                   (cumulative-grafts store drv grafts
                                      #:outputs (list output)
                                      #:guile guile
                                      #:system system)))))
          (reference-origins drv items)))

  (with-cache (list (derivation-file-name drv) outputs grafts)
    (match (non-self-references store drv outputs)
      (()                                         ;no dependencies
       (return grafts))
      (deps                                       ;one or more dependencies
       (mlet %state-monad ((grafts (dependency-grafts deps)))
         (let ((grafts (delete-duplicates (concatenate grafts) equal?)))
           (match (filter (lambda (graft)
                            (member (graft-origin-file-name graft) deps))
                          grafts)
             (()
              (return grafts))
             ((applicable ..1)
              ;; Use APPLICABLE, the subset of GRAFTS that is really
              ;; applicable to DRV, to avoid creating several identical
              ;; grafted variants of DRV.
              (let* ((new    (graft-derivation/shallow store drv applicable
                                                       #:outputs outputs
                                                       #:guile guile
                                                       #:system system))
                     (grafts (append (map (lambda (output)
                                            (graft
                                              (origin drv)
                                              (origin-output output)
                                              (replacement new)
                                              (replacement-output output)))
                                          outputs)
                                     grafts)))
                (return grafts))))))))))

(define* (graft-derivation store drv grafts
                           #:key
                           (guile (%guile-for-build))
                           (outputs (derivation-output-names drv))
                           (system (%current-system)))
  "Apply GRAFTS to the OUTPUTS of DRV and all their dependencies, recursively.
That is, if GRAFTS apply only indirectly to DRV, graft the dependencies of
DRV, and graft DRV itself to refer to those grafted dependencies."
  (let ((grafts cache
                (run-with-state
                    (cumulative-grafts store drv grafts
                                       #:outputs outputs
                                       #:guile guile #:system system)
                  (store-connection-cache store %graft-cache))))

    ;; Save CACHE in STORE to benefit from it on the next call.
    ;; XXX: Ideally we'd use %STORE-MONAD and 'mcached' and avoid mutating
    ;; STORE.
    (set-store-connection-cache! store %graft-cache cache)

    (match grafts
      ((first . rest)
       ;; If FIRST is not a graft for DRV, it means that GRAFTS are not
       ;; applicable to DRV and nothing needs to be done.
       (if (equal? drv (graft-origin first))
           (graft-replacement first)
           drv)))))

;; The following might feel more at home in (guix packages) but since (guix
;; gexp), which is a lower level, needs them, we put them here.

(define %graft?
  ;; Whether to honor package grafts by default.
  (make-parameter #t))

(define-inlinable (set-grafting enable?)
  ;; This monadic procedure enables grafting when ENABLE? is true, and
  ;; disables it otherwise.  It returns the previous setting.
  (lambda (store)
    (values (%graft? enable?) store)))

(define-inlinable (grafting?)
  ;; Return a Boolean indicating whether grafting is enabled.
  (lambda (store)
    (values (%graft?) store)))

;; Local Variables:
;; eval: (put 'with-cache 'scheme-indent-function 1)
;; End:

;;; grafts.scm ends here

repo_name: maximed/guix

license: mit


code:
// GNU Guix --- Functional package management for GNU
// Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
//
// 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/>.

var outerRadius = Math.max(nodeArray.length * 15, 500) / 2,
    innerRadius = outerRadius - Math.min(nodeArray.length * 5, 200),
    width = outerRadius * 2,
    height = outerRadius * 2,
    colors = d3.scale.category20c(),
    matrix = [];

function neighborsOf (node) {
    return links.filter(function (e) {
        return e.source === node;
    }).map(function (e) {
       return e.target;
    });
}

function zoomed () {
    zoomer.attr("transform",
                "translate(" + d3.event.translate + ")" +
                "scale(" + d3.event.scale + ")");
}

function fade (opacity, root) {
    return function (g, i) {
        root.selectAll("g path.chord")
            .filter(function (d) {
                return d.source.index != i && d.target.index != i;
            })
            .transition()
            .style("opacity", opacity);
    };
}

// Now that we have all nodes in an object we can replace each reference
// with the actual node object.
links.forEach(function (link) {
  link.target = nodes[link.target];
  link.source = nodes[link.source];
});

// Construct a square matrix for package dependencies
nodeArray.forEach(function (d, index, arr) {
    var source = index,
        row = matrix[source];
    if (!row) {
        row = matrix[source] = [];
        for (var i = -1; ++i < arr.length;) row[i] = 0;
    }
    neighborsOf(d).forEach(function (d) { row[d.index]++; });
});

// chord layout
var chord = d3.layout.chord()
    .padding(0.01)
    .sortSubgroups(d3.descending)
    .sortChords(d3.descending)
    .matrix(matrix);

var arc = d3.svg.arc()
    .innerRadius(innerRadius)
    .outerRadius(innerRadius + 20);

var zoom = d3.behavior.zoom()
    .scaleExtent([0.1, 10])
    .on("zoom", zoomed);

var svg = d3.select("body").append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .attr('viewBox', '0 0 ' + Math.min(width, height) + ' ' + Math.min(width, height))
    .attr('preserveAspectRatio', 'xMinYMin')
    .call(zoom);

var zoomer = svg.append("g");

var container = zoomer.append("g")
    .attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");

// Group for arcs and labels
var g = container.selectAll(".group")
    .data(chord.groups)
    .enter().append("g")
    .attr("class", "group")
    .on("mouseout", fade(1, container))
    .on("mouseover", fade(0.1, container));

// Draw one segment per package
g.append("path")
    .style("fill",   function (d) { return colors(d.index); })
    .style("stroke", function (d) { return colors(d.index); })
    .attr("d", arc);

// Add circular labels
g.append("text")
    .each(function (d) { d.angle = (d.startAngle + d.endAngle) / 2; })
    .attr("dy", ".35em")
    .attr("transform", function (d) {
      return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
          + "translate(" + (innerRadius + 26) + ")"
          + (d.angle > Math.PI ? "rotate(180)" : "");
    })
    .style("text-anchor", function (d) { return d.angle > Math.PI ? "end" : null; })
    .text(function (d) { return nodeArray[d.index].label; });

// Draw chords from source to target; color by source.
container.selectAll(".chord")
    .data(chord.chords)
    .enter().append("path")
    .attr("class", "chord")
    .style("stroke", function (d) { return d3.rgb(colors(d.source.index)).darker(); })
    .style("fill", function (d) { return colors(d.source.index); })
    .attr("d", d3.svg.chord().radius(innerRadius));


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015, 2016, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
;;;
;;; 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 graph)
  #:use-module (guix store)
  #:use-module (guix monads)
  #:use-module (guix records)
  #:use-module (guix sets)
  #:use-module (rnrs io ports)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-26)
  #:use-module (ice-9 match)
  #:use-module (ice-9 vlist)
  #:export (node-type
            node-type?
            node-type-identifier
            node-type-label
            node-type-edges
            node-type-convert
            node-type-name
            node-type-description

            node-edges
            node-back-edges
            traverse/depth-first
            node-transitive-edges
            node-reachable-count
            shortest-path

            %graph-backends
            %d3js-backend
            %graphviz-backend
            graph-backend?
            graph-backend
            graph-backend-name
            graph-backend-description

            export-graph))

;;; Commentary:
;;;
;;; This module provides an abstract way to represent graphs and to manipulate
;;; them.  It comes with several such representations for packages,
;;; derivations, and store items.  It also provides a generic interface for
;;; exporting graphs in an external format, including a Graphviz
;;; implementation thereof.
;;;
;;; Code:

;;;
;;; Node types.
;;;

(define-record-type* <node-type> node-type make-node-type
  node-type?
  (identifier  node-type-identifier)              ;node -> M identifier
  (label       node-type-label)                   ;node -> string
  (edges       node-type-edges)                   ;node -> M list of nodes
  (convert     node-type-convert                  ;any -> M list of nodes
               (default (lift1 list %store-monad)))
  (name        node-type-name)                    ;string
  (description node-type-description))            ;string

(define (%node-edges type nodes cons-edge)
  (with-monad %store-monad
    (match type
      (($ <node-type> identifier label node-edges)
       (define (add-edge node edges)
         (>>= (node-edges node)
              (lambda (nodes)
                (return (fold (cut cons-edge node <> <>)
                              edges nodes)))))

       (mlet %store-monad ((edges (foldm %store-monad
                                         add-edge vlist-null nodes)))
         (return (lambda (node)
                   (reverse (vhash-foldq* cons '() node edges)))))))))

(define (node-edges type nodes)
  "Return, as a monadic value, a one-argument procedure that, given a node of TYPE,
returns its edges.  NODES is taken to be the sinks of the global graph."
  (%node-edges type nodes
               (lambda (source target edges)
                 (vhash-consq source target edges))))

(define (node-back-edges type nodes)
  "Return, as a monadic value, a one-argument procedure that, given a node of TYPE,
returns its back edges.  NODES is taken to be the sinks of the global graph."
  (%node-edges type nodes
               (lambda (source target edges)
                 (vhash-consq target source edges))))

(define (traverse/depth-first proc seed nodes node-edges)
  "Do a depth-first traversal of NODES along NODE-EDGES, calling PROC with
each node and the current result, and visiting each reachable node exactly
once.  NODES must be a list of nodes, and NODE-EDGES must be a one-argument
procedure as returned by 'node-edges' or 'node-back-edges'."
  (let loop ((nodes   (append-map node-edges nodes))
             (result  seed)
             (visited (setq)))
    (match nodes
      (()
       result)
      ((head . tail)
       (if (set-contains? visited head)
           (loop tail result visited)
           (let ((edges (node-edges head)))
             (loop (append edges tail)
                   (proc head result)
                   (set-insert head visited))))))))

(define (node-transitive-edges nodes node-edges)
  "Return the list of nodes directly or indirectly connected to NODES
according to the NODE-EDGES procedure.  NODE-EDGES must be a one-argument
procedure that, given a node, returns its list of direct dependents; it is
typically returned by 'node-edges' or 'node-back-edges'."
  (traverse/depth-first cons '() nodes node-edges))

(define (node-reachable-count nodes node-edges)
  "Return the number of nodes reachable from NODES along NODE-EDGES."
  (traverse/depth-first (lambda (_ count)
                          (+ 1 count))
                        0
                        nodes node-edges))

(define (shortest-path node1 node2 type)
  "Return as a monadic value the shortest path, represented as a list, from
NODE1 to NODE2 of the given TYPE.  Return #f when there is no path."
  (define node-edges
    (node-type-edges type))

  (define (find-shortest lst)
    ;; Return the shortest path among LST, where each path is represented as a
    ;; vlist.
    (let loop ((lst lst)
               (best +inf.0)
               (shortest #f))
      (match lst
        (()
         shortest)
        ((head . tail)
         (let ((len (vlist-length head)))
           (if (< len best)
               (loop tail len head)
               (loop tail best shortest)))))))

  (define (find-path node path paths)
    ;; Return the a vhash that maps nodes to paths, with each path from the
    ;; given node to NODE2.
    (define (augment-paths child paths)
      ;; When using %REFERENCE-NODE-TYPE, nodes can contain self references,
      ;; hence this test.
      (if (eq? child node)
          (store-return paths)
          (find-path child vlist-null paths)))

    (cond ((eq? node node2)
           (store-return (vhash-consq node (vlist-cons node path)
                                      paths)))
          ((vhash-assq node paths)
           (store-return paths))
          (else
           ;; XXX: We could stop recursing if one if CHILDREN is NODE2, but in
           ;; practice it's good enough.
           (mlet* %store-monad ((children (node-edges node))
                                (paths    (foldm %store-monad
                                                 augment-paths
                                                 paths
                                                 children)))
             (define sub-paths
               (filter-map (lambda (child)
                             (match (vhash-assq child paths)
                               (#f #f)
                               ((_ . path) path)))
                           children))

             (match sub-paths
               (()
                (return (vhash-consq node #f paths)))
               (lst
                (return (vhash-consq node
                                     (vlist-cons node (find-shortest sub-paths))
                                     paths))))))))

  (mlet %store-monad ((paths (find-path node1
                                        (vlist-cons node1 vlist-null)
                                        vlist-null)))
    (return (match (vhash-assq node1 paths)
              ((_ . #f) #f)
              ((_ . path) (vlist->list path))))))

;;;
;;; Graphviz export.
;;;

(define-record-type <graph-backend>
  (graph-backend name description prologue epilogue node edge)
  graph-backend?
  (name         graph-backend-name)
  (description  graph-backend-description)
  (prologue     graph-backend-prologue)
  (epilogue     graph-backend-epilogue)
  (node         graph-backend-node)
  (edge         graph-backend-edge))

(define %colors
  ;; See colortbl.h in Graphviz.
  #("red" "magenta" "blue" "cyan3" "darkseagreen"
    "peachpuff4" "darkviolet" "dimgrey" "darkgoldenrod"))

(define (pop-color hint)
  "Return a Graphviz color based on HINT, an arbitrary object."
  (let ((index (hash hint (vector-length %colors))))
    (vector-ref %colors index)))

(define (emit-prologue name port)
  (format port "digraph \"Guix ~a\" {\n"
          name))
(define (emit-epilogue port)
  (display "\n}\n" port))
(define (emit-node id label port)
  (format port "  \"~a\" [label = \"~a\", shape = box, fontname = sans];~%"
          id label))
(define (emit-edge id1 id2 port)
  (format port "  \"~a\" -> \"~a\" [color = ~a];~%"
          id1 id2 (pop-color id1)))

(define %graphviz-backend
  (graph-backend "graphviz"
                 "Generate graph in DOT format for use with Graphviz."
                 emit-prologue emit-epilogue
                 emit-node emit-edge))

;;;
;;; d3js export.
;;;

(define (emit-d3js-prologue name port)
  (format port "\
<!DOCTYPE html>

    <meta charset=\"utf-8\">

    "
          (search-path %load-path "guix/graph.js")))

(define (emit-d3js-node id label port)
  (format port "\
nodes[\"~a\"] = {\"id\": \"~a\", \"label\": \"~a\", \"index\": nodeArray.length};
nodeArray.push(nodes[\"~a\"]);~%"
          id id label id))

(define (emit-d3js-edge id1 id2 port)
  (format port "links.push({\"source\": \"~a\", \"target\": \"~a\"});~%"
          id1 id2))

(define %d3js-backend
  (graph-backend "d3js"
                 "Generate chord diagrams with d3js."
                 emit-d3js-prologue emit-d3js-epilogue
                 emit-d3js-node emit-d3js-edge))

;;;
;;; Cypher export.
;;;

(define (emit-cypher-prologue name port)
  (format port ""))

(define (emit-cypher-epilogue port)
  (format port ""))

(define (emit-cypher-node id label port)
  (format port "MERGE (p:Package { id: ~s }) SET p.name = ~s;~%"
          id label ))

(define (emit-cypher-edge id1 id2 port)
  (format port "MERGE (a:Package { id: ~s });~%" id1)
  (format port "MERGE (b:Package { id: ~s });~%" id2)
  (format port "MATCH (a:Package { id: ~s }), (b:Package { id: ~s }) CREATE UNIQUE (a)-[:NEEDS]->(b);~%"
          id1 id2))

(define %cypher-backend
  (graph-backend "cypher"
                 "Generate Cypher queries."
                 emit-cypher-prologue emit-cypher-epilogue
                 emit-cypher-node emit-cypher-edge))

;;;
;;; Shared.
;;;

(define %graph-backends
  (list %graphviz-backend
        %d3js-backend
        %cypher-backend))

(define* (export-graph sinks port
                       #:key
                       reverse-edges? node-type
                       (backend %graphviz-backend))
  "Write to PORT the representation of the DAG with the given SINKS, using the
given BACKEND.  Use NODE-TYPE to traverse the DAG.  When REVERSE-EDGES? is
true, draw reverse arrows."
  (match backend
    (($ <graph-backend> _ _ emit-prologue emit-epilogue emit-node emit-edge)
     (emit-prologue (node-type-name node-type) port)

     (match node-type
       (($ <node-type> node-identifier node-label node-edges)
        (let loop ((nodes   sinks)
                   (visited (set)))
          (match nodes
            (()
             (with-monad %store-monad
               (emit-epilogue port)
               (store-return #t)))
            ((head . tail)
             (mlet %store-monad ((id (node-identifier head)))
               (if (set-contains? visited id)
                   (loop tail visited)
                   (mlet* %store-monad ((dependencies (node-edges head))
                                        (ids          (mapm %store-monad
                                                            node-identifier
                                                            dependencies)))
                     (emit-node id (node-label head) port)
                     (for-each (lambda (dependency dependency-id)
                                 (if reverse-edges?
                                     (emit-edge dependency-id id port)
                                     (emit-edge id dependency-id port)))
                               dependencies ids)
                     (loop (append dependencies tail)
                           (set-insert id visited)))))))))))))

;;; graph.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014, 2015, 2016, 2017, 2019 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2021 Xinglu Chen <public@yoctocell.xyz>
;;;
;;; 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 hg-download)
  #:use-module (guix gexp)
  #:use-module (guix store)
  #:use-module (guix monads)
  #:use-module (guix records)
  #:use-module (guix modules)
  #:use-module (guix packages)
  #:autoload   (guix build-system gnu) (standard-packages)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (ice-9 match)
  #:use-module (ice-9 popen)
  #:use-module (ice-9 rdelim)
  #:export (hg-reference
            hg-reference?
            hg-reference-url
            hg-reference-changeset
            hg-predicate
            hg-fetch
            hg-version
            hg-file-name))

;;; Commentary:
;;;
;;; An <origin> method that fetches a specific changeset from a Mercurial
;;; repository.  The repository URL and changeset ID are specified with a
;;; <hg-reference> object.
;;;
;;; Code:

(define-record-type* <hg-reference>
  hg-reference make-hg-reference
  hg-reference?
  (url        hg-reference-url)
  (changeset  hg-reference-changeset))

(define (hg-package)
  "Return the default Mercurial package."
  (let ((distro (resolve-interface '(gnu packages version-control))))
    (module-ref distro 'mercurial)))

(define* (hg-fetch ref hash-algo hash
                   #:optional name
                   #:key (system (%current-system)) (guile (default-guile))
                   (hg (hg-package)))
  "Return a fixed-output derivation that fetches REF, a <hg-reference>
object.  The output is expected to have recursive hash HASH of type
HASH-ALGO (a symbol).  Use NAME as the file name, or a generic name if #f."
  (define inputs
    ;; The 'swh-download' procedure requires tar and gzip.
    `(("gzip" ,(module-ref (resolve-interface '(gnu packages compression))
                           'gzip))
      ("tar" ,(module-ref (resolve-interface '(gnu packages base))
                          'tar))))

  (define guile-zlib
    (module-ref (resolve-interface '(gnu packages guile)) 'guile-zlib))

  (define guile-json
    (module-ref (resolve-interface '(gnu packages guile)) 'guile-json-4))

  (define gnutls
    (module-ref (resolve-interface '(gnu packages tls)) 'gnutls))

  (define modules
    (delete '(guix config)
            (source-module-closure '((guix build hg)
                                     (guix build download-nar)
                                     (guix swh)))))

  (define build
    (with-imported-modules modules
      (with-extensions (list guile-json gnutls ;for (guix swh)
                             guile-zlib)
        #~(begin
            (use-modules (guix build hg)
                         (guix build utils) ;for `set-path-environment-variable'
                         (guix build download-nar)
                         (guix swh)
                         (ice-9 match))

            (set-path-environment-variable "PATH" '("bin")
                                           (match '#+inputs
                                             (((names dirs outputs ...) ...)
                                              dirs)))

            (setvbuf (current-output-port) 'line)
            (setvbuf (current-error-port) 'line)

            (or (hg-fetch '#$(hg-reference-url ref)
                          '#$(hg-reference-changeset ref)
                          #$output
                          #:hg-command (string-append #+hg "/bin/hg"))
                (download-nar #$output)
                ;; As a last resort, attempt to download from Software Heritage.
                ;; Disable X.509 certificate verification to avoid depending
                ;; on nss-certs--we're authenticating the checkout anyway.
                (parameterize ((%verify-swh-certificate? #f))
                  (format (current-error-port)
                          "Trying to download from Software Heritage...~%")
                  (swh-download #$(hg-reference-url ref)
                                #$(hg-reference-changeset ref)
                                #$output)))))))

  (mlet %store-monad ((guile (package->derivation guile system)))
    (gexp->derivation (or name "hg-checkout") build
                      #:leaked-env-vars '("http_proxy" "https_proxy"
                                          "LC_ALL" "LC_MESSAGES" "LANG"
                                          "COLUMNS")
                      #:system system
                      #:local-build? #t           ;don't offload repo cloning
                      #:hash-algo hash-algo
                      #:hash hash
                      #:recursive? #t
                      #:guile-for-build guile)))

(define (hg-version version revision changeset)
  "Return the version string for packages using hg-download."
  ;; hg-version is almost exclusively executed while modules are being loaded.
  ;; This makes any errors hide their backtrace. Avoid the mysterious error
  ;; "Value out of range 0 to N: 7" when the commit ID is too short, which
  ;; can happen, for example, when the user swapped the revision and commit
  ;; arguments by mistake.
  (when (< (string-length changeset) 7)
    (raise
     (condition
      (&message (message "hg-version: changeset ID unexpectedly short")))))
  (string-append version "-" revision "." (string-take changeset 7)))

(define (hg-file-name name version)
  "Return the file-name for packages using hg-download."
  (string-append name "-" version "-checkout"))

(define (hg-file-list directory)
  "Evaluates to a list of files contained in the repository at path
  @var{directory}"
  (let* ((port (open-input-pipe (format #f "hg files --repository ~s" directory)))
         (files (let loop ((files '()))
                  (let ((line (read-line port)))
                    (cond
                     ((eof-object? line) files)
                     (else
                      (loop (cons line files))))))))
    (close-pipe port)
    (map canonicalize-path files)))

(define (should-select? path-list candidate)
  "Returns #t in case that @var{candidate} is a file that is part of the given
@var{path-list}."
  (let ((canon-candidate (canonicalize-path candidate)))
    (let loop ((xs path-list))
      (cond
       ((null? xs)
        ;; Directories are not part of `hg files', but `local-file' will not
        ;; recurse if we don't return #t for directories.
        (equal? (array-ref (lstat candidate) 13) 'directory))
       ((string-contains candidate (car xs)) #t)
       (else (loop (cdr xs)))))))

(define (hg-predicate directory)
  "This procedure evaluates to a predicate that reports back whether a given
@var{file} - @var{stat} combination is part of the files tracked by
Mercurial."
  (let ((files (hg-file-list directory)))
    (lambda (file stat)
      (should-select? files file))))

;;; hg-download.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2020, 2021 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2015 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2012, 2015 Free Software Foundation, Inc.
;;; Copyright © 2017 Tobias Geerinckx-Rice <me@tobias.gr>
;;;
;;; 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 http-client)
  #:use-module (web uri)
  #:use-module (web http)
  #:use-module ((web client) #:hide (open-socket-for-uri))
  #:use-module (web request)
  #:use-module (web response)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-11)
  #:use-module (srfi srfi-19)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (ice-9 match)
  #:use-module (ice-9 binary-ports)
  #:use-module (rnrs bytevectors)
  #:use-module (guix ui)
  #:use-module (guix utils)
  #:use-module (guix base64)
  #:autoload   (gcrypt hash) (sha256)
  #:autoload   (gnutls) (error/invalid-session error/again error/interrupted)
  #:use-module ((guix build utils)
                #:select (mkdir-p dump-port))
  #:use-module ((guix build download)
                #:select (open-socket-for-uri
                          (open-connection-for-uri
                           . guix:open-connection-for-uri)
                          resolve-uri-reference))
  #:re-export (open-socket-for-uri)
  #:export (&http-get-error
            http-get-error?
            http-get-error-uri
            http-get-error-code
            http-get-error-reason

            http-fetch
            http-multiple-get

            %http-cache-ttl
            http-fetch/cached))

;;; Commentary:
;;;
;;; HTTP client portable among Guile versions, and with proper error condition
;;; reporting.
;;;
;;; Code:

;; HTTP GET error.
(define-condition-type &http-get-error &error
  http-get-error?
  (uri    http-get-error-uri)                     ; URI
  (code   http-get-error-code)                    ; integer
  (reason http-get-error-reason))                 ; string

(define* (http-fetch uri #:key port (text? #f) (buffered? #t)
                     (open-connection guix:open-connection-for-uri)
                     (keep-alive? #f)
                     (verify-certificate? #t)
                     (headers '((user-agent . "GNU Guile")))
                     (log-port (current-error-port))
                     timeout)
  "Return an input port containing the data at URI, and the expected number of
bytes available or #f.  If TEXT? is true, the data at URI is considered to be
textual.  Follow any HTTP redirection.  When BUFFERED? is #f, return an
unbuffered port, suitable for use in `filtered-port'.  HEADERS is an alist of
extra HTTP headers.

When KEEP-ALIVE? is true, the connection is marked as 'keep-alive' and PORT is
not closed upon completion.

When VERIFY-CERTIFICATE? is true, verify HTTPS server certificates.

TIMEOUT specifies the timeout in seconds for connection establishment; when
TIMEOUT is #f, connection establishment never times out.

Write information about redirects to LOG-PORT.

Raise an '&http-get-error' condition if downloading fails."
  (let loop ((uri (if (string? uri)
                      (string->uri uri)
                      uri)))
    (let ((port (or port (open-connection uri
                                          #:verify-certificate?
                                          verify-certificate?
                                          #:timeout timeout)))
          (headers (match (uri-userinfo uri)
                     ((? string? str)
                      (cons (cons 'Authorization
                                  (string-append "Basic "
                                                 (base64-encode
                                                  (string->utf8 str))))
                            headers))
                     (_ headers))))
      (unless (or buffered? (not (file-port? port)))
        (setvbuf port 'none))
      (let*-values (((resp data)
                     (http-get uri #:streaming? #t #:port port
                               #:keep-alive? keep-alive?
                               #:headers headers))
                    ((code)
                     (response-code resp)))
        (case code
          ((200)
           (values data (response-content-length resp)))
          ((301                                   ; moved permanently
            302                                   ; found (redirection)
            303                                   ; see other
            307                                   ; temporary redirection
            308)                                  ; permanent redirection
           (let ((uri (resolve-uri-reference (response-location resp) uri)))
             (close-port port)
             (format log-port (G_ "following redirection to `~a'...~%")
                     (uri->string uri))
             (loop uri)))
          (else
           (raise (condition (&http-get-error
                              (uri uri)
                              (code code)
                              (reason (response-reason-phrase resp)))
                             (&message
                              (message
                               (format
                                #f
                                (G_ "~a: HTTP download failed: ~a (~s)")
                                (uri->string uri) code
                                (response-reason-phrase resp))))))))))))

(define-syntax-rule (false-if-networking-error exp)
  "Return #f if EXP triggers a network related exception as can occur when
reusing stale cached connections."
  ;; FIXME: Duplicated from 'with-cached-connection'.
  (catch #t
    (lambda ()
      exp)
    (lambda (key . args)
      ;; If PORT was cached and the server closed the connection in the
      ;; meantime, we get EPIPE.  In that case, open a fresh connection and
      ;; retry.  We might also get 'bad-response or a similar exception from
      ;; (web response) later on, once we've sent the request, or a
      ;; ERROR/INVALID-SESSION from GnuTLS.
      (if (or (and (eq? key 'system-error)
                   (= EPIPE (system-error-errno `(,key ,@args))))
              (and (eq? key 'gnutls-error)
                   (memq (first args)
                         (list error/invalid-session

                               ;; XXX: These two are not properly handled in
                               ;; GnuTLS < 3.7.2, in
                               ;; 'write_to_session_record_port'; see
                               ;; <https://bugs.gnu.org/47867>.
                               error/again error/interrupted)))
              (memq key
                    '(bad-response bad-header bad-header-component)))
          #f
          (apply throw key args)))))

(define* (http-multiple-get base-uri proc seed requests
                            #:key port (verify-certificate? #t)
                            (open-connection guix:open-connection-for-uri)
                            (keep-alive? #t)
                            (batch-size 1000))
  "Send all of REQUESTS to the server at BASE-URI.  Call PROC for each
response, passing it the request object, the response, a port from which to
read the response body, and the previous result, starting with SEED, à la
'fold'.  Return the final result.

When PORT is specified, use it as the initial connection on which HTTP
requests are sent; otherwise call OPEN-CONNECTION to open a new connection for
a URI.  When KEEP-ALIVE? is false, close the connection port before
returning."
  (let connect ((port     port)
                (requests requests)
                (result   seed))
    (define batch
      (if (>= batch-size (length requests))
          requests
          (take requests batch-size)))

    ;; (format (current-error-port) "connecting (~a requests left)..."
    ;;         (length requests))
    (let ((p (or port (open-connection base-uri
                                       #:verify-certificate?
                                       verify-certificate?))))
      ;; For HTTPS, P is not a file port and does not support 'setvbuf'.
      (when (file-port? p)
        (setvbuf p 'block (expt 2 16)))

      ;; Send BATCH in a row.
      ;; XXX: Do our own caching to work around inefficiencies when
      ;; communicating over TLS: <http://bugs.gnu.org/22966>.
      (let-values (((buffer get) (open-bytevector-output-port)))
        ;; Inherit the HTTP proxying property from P.
        (set-http-proxy-port?! buffer (http-proxy-port? p))

        ;; Swallow networking errors that could occur due to connection reuse
        ;; and the like; they will be handled down the road when trying to
        ;; read responses.
        (false-if-networking-error
         (begin
           (for-each (cut write-request <> buffer) batch)
           (put-bytevector p (get))
           (force-output p))))

      ;; Now start processing responses.
      (let loop ((sent      batch)
                 (processed 0)
                 (result    result))
        (match sent
          (()
           (match (drop requests processed)
             (()
              (unless keep-alive?
                (close-port p))
              (reverse result))
             (remainder
              (connect p remainder result))))
          ((head tail ...)
           (match (false-if-networking-error (read-response p))
             ((? response? resp)
              (let* ((body   (response-body-port resp))
                     (result (proc head resp body result)))
                ;; The server can choose to stop responding at any time,
                ;; in which case we have to try again.  Check whether
                ;; that is the case.  Note that even upon "Connection:
                ;; close", we can read from BODY.
                (match (assq 'connection (response-headers resp))
                  (('connection 'close)
                   (close-port p)
                   (connect #f                    ;try again
                            (drop requests (+ 1 processed))
                            result))
                  (_
                   (loop tail (+ 1 processed) result)))))
             (#f
              (close-port p)
              (connect #f                         ; try again
                       (drop requests processed)
                       result)))))))))

;;;
;;; Caching.
;;;

(define %http-cache-ttl
  ;; Time-to-live in seconds of the HTTP cache of in ~/.cache/guix.
  (make-parameter
   (* 3600 (or (and=> (getenv "GUIX_HTTP_CACHE_TTL")
                      string->number*)
               36))))

(define (cache-file-for-uri uri)
  "Return the name of the file in the cache corresponding to URI."
  (let ((digest (sha256 (string->utf8 (uri->string uri)))))
    ;; Use the "URL" alphabet because it does not contain "/".
    (string-append (cache-directory) "/http/"
                   (base64-encode digest 0 (bytevector-length digest)
                                  #f #f base64url-alphabet))))

(define* (http-fetch/cached uri #:key (ttl (%http-cache-ttl)) text?
                            (write-cache dump-port)
                            (cache-miss (const #t))
                            (log-port (current-error-port))
                            (timeout 10))
  "Like 'http-fetch', return an input port, but cache its contents in
~/.cache/guix.  The cache remains valid for TTL seconds.

Call WRITE-CACHE with the HTTP input port and the cache output port to write
the data to cache.  Call CACHE-MISS with URI just before fetching data from
URI.

TIMEOUT specifies the timeout in seconds for connection establishment.

Write information about redirects to LOG-PORT."
  (let ((file (cache-file-for-uri uri)))
    (define (update-cache cache-port)
      (define cache-time
        (and cache-port
             (stat:mtime (stat cache-port))))

      (define headers
        `((user-agent . "GNU Guile")
          ,@(if cache-time
                `((if-modified-since
                   . ,(time-utc->date (make-time time-utc 0 cache-time))))
                '())))

      ;; Update the cache and return an input port.
      (guard (c ((http-get-error? c)
                 (if (= 304 (http-get-error-code c)) ;"Not Modified"
                     (begin
                       (utime file)               ;update FILE's mtime
                       cache-port)
                     (raise c))))
        (let ((port (http-fetch uri #:text? text?
                                #:log-port log-port
                                #:headers headers #:timeout timeout)))
          (cache-miss uri)
          (mkdir-p (dirname file))
          (when cache-port
            (close-port cache-port))
          (with-atomic-file-output file
            (cut write-cache port <>))
          (close-port port)
          (open-input-file file))))

    (define (old? port)
      ;; Return true if PORT has passed TTL.
      (let* ((s   (stat port))
             (now (current-time time-utc)))
        (< (+ (stat:mtime s) ttl) (time-second now))))

    (catch 'system-error
      (lambda ()
        (let ((port (open-input-file file)))
          (if (old? port)
              (update-cache port)
              port)))
      (lambda args
        (if (= ENOENT (system-error-errno args))
            (update-cache #f)
            (apply throw args))))))

;;; http-client.scm ends here


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2012, 2013, 2014, 2015, 2016, 2017 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 i18n)
  #:use-module (srfi srfi-26)
  #:export (G_
            N_
            P_
            %gettext-domain
            %package-text-domain))

;;; Commentary:
;;;
;;; Internationalization support.
;;;
;;; Code:

(define %gettext-domain
  ;; Text domain for strings used in the tools.
  "guix")

(define %package-text-domain
  ;; Text domain for package synopses and descriptions.
  "guix-packages")

(define G_ (cut gettext <> %gettext-domain))
(define N_ (cut ngettext <> <> <> %gettext-domain))

(define (P_ msgid)
  "Return the translation of the package description or synopsis MSGID."
  ;; Descriptions/synopses might occasionally be empty strings, even if that
  ;; is something we try to avoid.  Since (gettext "") can return a non-empty
  ;; string, explicitly check for that case.
  (if (string-null? msgid)
      msgid
      (gettext msgid %package-text-domain)))