code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015 Taylan Ulrich Bayırlı/Kammer <taylanbayirli@gmail.com>
;;; Copyright © 2016 Mark H Weaver <mhw@netris.org>
;;; Copyright © 2016 Ricardo Wurmus <rekado@elephly.net>
;;; Copyright © 2016, 2017 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2016 John Darrington <jmd@gnu.org>
;;; Copyright © 2016 Nikita <nikita@n0.is>
;;; Copyright © 2016, 2017, 2018, 2019, 2020 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2016, 2020 Marius Bakke <mbakke@fastmail.com>
;;; Copyright © 2017 Vasile Dumitrascu <va511e@yahoo.com>
;;; Copyright © 2017 Gregor Giesen <giesen@zaehlwerk.net>
;;; Copyright © 2018 Oleg Pykhalov <go.wigust@gmail.com>
;;; Copyright © 2019 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2019 Chris Marusich <cmmarusich@gmail.com>
;;; Copyright © 2019 Rutger Helling <rhelling@mykolab.com>
;;; Copyright © 2020 Pierre Langlois <pierre.langlois@gmx.com>
;;; Copyright © 2020 Arun Isaac <arunisaac@systemreboot.net>
;;; Copyright © 2020 Leo Famulari <leo@famulari.name>
;;; Copyright © 2020 Brice Waegeneire <brice@waegenei.re>
;;;
;;; 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 (gnu packages dns)
  #:use-module (gnu packages admin)
  #:use-module (gnu packages autotools)
  #:use-module (gnu packages base)
  #:use-module (gnu packages bash)
  #:use-module (gnu packages certs)
  #:use-module (gnu packages check)
  #:use-module (gnu packages databases)
  #:use-module (gnu packages documentation)
  #:use-module (gnu packages compression)
  #:use-module (gnu packages crypto)
  #:use-module (gnu packages datastructures)
  #:use-module (gnu packages flex)
  #:use-module (gnu packages freedesktop)
  #:use-module (gnu packages gcc)
  #:use-module (gnu packages glib)
  #:use-module (gnu packages groff)
  #:use-module (gnu packages groff)
  #:use-module (gnu packages gtk)
  #:use-module (gnu packages libedit)
  #:use-module (gnu packages libevent)
  #:use-module (gnu packages libidn)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages lua)
  #:use-module (gnu packages ncurses)
  #:use-module (gnu packages nettle)
  #:use-module (gnu packages networking)
  #:use-module (gnu packages perl)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages protobuf)
  #:use-module (gnu packages python)
  #:use-module (gnu packages python-xyz)
  #:use-module (gnu packages shells)
  #:use-module (gnu packages sphinx)
  #:use-module (gnu packages swig)
  #:use-module (gnu packages tls)
  #:use-module (gnu packages web)
  #:use-module (gnu packages xml)
  #:use-module (gnu packages)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix git-download)
  #:use-module (guix utils)
  #:use-module (guix build-system glib-or-gtk)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system meson)
  #:use-module (guix build-system trivial))

(define-public ldns
  (package
    (name "ldns")
    (version "1.7.1")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "https://www.nlnetlabs.nl/downloads/"
                       name "/" name "-" version ".tar.gz"))
       (sha256
        (base32 "0ac242n7996fswq1a3nlh1bbbhrsdwsq4mx7xq8ffq6aplb4rj4a"))
       (patches
        (search-patches
         ;; To create make-flag vairables,
         ;; for splitting installation of drill and examples.
         "ldns-drill-examples.patch"))))
    (build-system gnu-build-system)
    (outputs '("out" "drill" "examples" "pyldns"))
    (arguments
     `( ;; Tests require Tpkg.
       ;; https://tpkg.github.io/
       #:tests? #f
       #:configure-flags
       (list
        "--disable-static"
        "--enable-gost-anyway"
        "--enable-rrtype-ninfo"
        "--enable-rrtype-rkey"
        "--enable-rrtype-ta"
        "--enable-rrtype-avc"
        "--enable-rrtype-doa"
        "--enable-rrtype-amtrelay"
        "--with-drill"
        "--with-examples"
        "--with-pyldns"
        ;; Perl module DNS::LDNS not available.
        ;; https://github.com/erikoest/DNS-LDNS.git
        ;; "--with-p5-dns-ldns"
        (string-append "--with-ssl="
                       (assoc-ref %build-inputs "openssl"))
        (string-append "--with-ca-path="
                       (assoc-ref %build-inputs "nss-certs")
                       "/etc/ssl/certs"))
       #:make-flags
       (list
        (string-append "drillbindir="
                       (assoc-ref %outputs "drill")
                       "/bin")
        (string-append "drillmandir="
                       (assoc-ref %outputs "drill")
                       "/share/man")
        (string-append "examplesbindir="
                       (assoc-ref %outputs "examples")
                       "/bin")
        (string-append "examplesmandir="
                       (assoc-ref %outputs "examples")
                       "/share/man")
        (string-append "python_site="
                       (assoc-ref %outputs "pyldns")
                       "/lib/python"
                       ,(version-major+minor
                         (package-version python))
                       "/site-packages"))))
    (native-inputs
     `(("doxygen" ,doxygen)
       ("ksh" ,oksh)
       ("perl" ,perl)
       ("perl-devel-checklib" ,perl-devel-checklib)
       ("pkg-config" ,pkg-config)
       ("python" ,python-wrapper)
       ("swig" ,swig)))
    (inputs
     `(("libpcap" ,libpcap)
       ("nss-certs" ,nss-certs)
       ("openssl" ,openssl)))
    (synopsis "DNS library that facilitates DNS tool programming")
    (description "LDNS aims to simplify DNS programming, it supports recent
RFCs like the DNSSEC documents, and allows developers to easily create
software conforming to current RFCs, and experimental software for current
Internet Drafts.  A secondary benefit of using ldns is speed; ldns is written in
C it should be a lot faster than Perl.")
    (home-page "https://nlnetlabs.nl/projects/ldns/about/")
    (license license:bsd-3)))

(define-public dnssec-trigger
  (package
    (name "dnssec-trigger")
    (version "0.17")
    (source
     (origin
       (method url-fetch)
       (uri
        (string-append "https://www.nlnetlabs.nl/downloads/"
                       name "/" name "-" version ".tar.gz"))
       (sha256
        (base32 "10928q406x9r66a090xl5kznzgyxpja88w4srwcv454hd351j9f0"))))
    (build-system glib-or-gtk-build-system)
    (outputs '("out" "gui" "nm"))
    (arguments
     `(#:test-target "test"
       #:configure-flags
       (list
        (string-append "--with-ssl="
                       (assoc-ref %build-inputs "openssl"))
        "--with-hooks=networkmanager"
        (string-append "--with-networkmanager-dispatch="
                       (assoc-ref %outputs "nm")
                       "/etc/NetworkManager/dispatcher.d")
        (string-append "--with-xdg-autostart="
                       (assoc-ref %outputs "gui")
                       "/etc/xdg/autostart")
        (string-append "--with-uidir="
                       (assoc-ref %outputs "gui")
                       "/share/dnssec-trigger")
        (string-append "--with-python="
                       (assoc-ref %build-inputs "python")
                       "/bin/python")
        (string-append "--with-unbound-control="
                       (assoc-ref %build-inputs "unbound")
                       "/sbin/unbound-control")
        "--with-forward-zones-support")
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'patch-configure
           (lambda _
             (substitute* "configure"
               (("appindicator-0.1")
                "appindicator3-0.1"))
             #t))
         (add-before 'configure 'patch-makefile
           (lambda _
             (substitute* "Makefile.in"
               (("/usr")
                "$(prefix)")
               (("/etc")
                "$(prefix)/etc")
               ((".*gtk-update-icon-cache.*")
                ""))
             #t))
         (add-after 'install 'remove-systemd
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out")))
               (delete-file-recursively
                (string-append out "/lib/systemd"))
               #t)))
         (add-after 'remove-systemd 'move-gui
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (gui (assoc-ref outputs "gui")))
               (mkdir-p (string-append gui "/bin"))
               (mkdir-p (string-append gui "/share"))
               (rename-file
                (string-append out "/bin")
                (string-append gui "/bin"))
               (rename-file
                (string-append out "/share/icons")
                (string-append gui "/share/icons"))
               #t)))
         (add-after 'move-gui 'move-nm
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (nm (assoc-ref outputs "nm")))
               (mkdir-p (string-append nm "/libexec"))
               (rename-file
                (string-append out "/libexec")
                (string-append nm "/libexec"))
               #t))))))
    (native-inputs
     `(("cmocka" ,cmocka)
       ("pkg-config" ,pkg-config)
       ("python" ,python-wrapper)))
    (inputs
     `(("gtk+-2" ,gtk+-2)
       ("ldns" ,ldns)
       ("libappindicator" ,libappindicator)
       ("openssl" ,openssl)
       ("unbound" ,unbound)))
    (synopsis "DNSSEC protection for the DNS traffic")
    (description "DNSSEC-Trigger enables your computer to use DNSSEC protection
for the DNS traffic.  It relies on the Unbound DNS resolver running locally on
your system, which performs DNSSEC validation.  It reconfigures Unbound in such
a way that it will signal it to to use the DHCP obtained forwarders if possible,
fallback to doing its own AUTH queries if that fails, and if that fails it will
prompt the user with the option to go with insecure DNS only.")
    (home-page "https://www.nlnetlabs.nl/projects/dnssec-trigger/about/")
    (license license:bsd-3)))

(define-public dnsmasq
  (package
    (name "dnsmasq")
    (version "2.82")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "http://www.thekelleys.org.uk/dnsmasq/dnsmasq-"
                    version ".tar.xz"))
              (sha256
               (base32
                "0cn1xd1s6xs78jmrmwjnh9m6w3q38pk6dyqy2phvasqiyd33cll4"))))
    (build-system gnu-build-system)
    (native-inputs
     `(("pkg-config" ,pkg-config)))
    (inputs
     `(("dbus" ,dbus)))
    (arguments
     `(#:phases
       (modify-phases %standard-phases (delete 'configure))
       #:make-flags (list (string-append "PREFIX=" (assoc-ref %outputs "out"))
                          "CC=gcc"
                          "COPTS=\"-DHAVE_DBUS\"")
       #:tests? #f))                    ; no ‘check’ target
    (home-page "http://www.thekelleys.org.uk/dnsmasq/doc.html")
    (synopsis "Small caching DNS proxy and DHCP/TFTP server")
    (description
     "Dnsmasq is a light-weight DNS forwarder and DHCP server.  It is designed
to provide DNS and, optionally, DHCP to a small network.  It can serve the
names of local machines which are not in the global DNS.  The DHCP server
integrates with the DNS server and allows machines with DHCP-allocated
addresses to appear in the DNS with names configured either on each host or in
a central configuration file.  Dnsmasq supports static and dynamic DHCP leases
and BOOTP/TFTP for network booting of diskless machines.")
    ;; Source files only say GPL2 and GPL3 are allowed.
    (license (list license:gpl2 license:gpl3))))

;; 'bind' is the name of a built-in Guile procedure, which is why we choose a
;; different name here.
(define-public isc-bind
  (package
    (name "bind")
    ;; When updating, check whether isc-dhcp's bundled copy should be as well.
    (version "9.16.6")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://ftp.isc.org/isc/bind9/" version
                    "/bind-" version ".tar.xz"))
              (sha256
               (base32
                "1jvi6ms51vyrhpflx05xlb7gblyd59zsyj28b8s3pl3xnkrv0rxm"))))
    (build-system gnu-build-system)
    (outputs `("out" "utils"))
    (inputs
     ;; It would be nice to add GeoIP and gssapi once there are packages.
     `(("libcap" ,libcap)
       ("libuv" ,libuv)
       ("libxml2" ,libxml2)
       ("openssl" ,openssl)
       ("p11-kit" ,p11-kit)
       ("python" ,python)
       ("python-ply" ,python-ply)))
    (native-inputs
     `(("perl" ,perl)
       ("pkg-config" ,pkg-config)))
    (arguments
     `(#:configure-flags
       (list (string-append "--with-pkcs11="
                            (assoc-ref %build-inputs "p11-kit")))
       #:phases
       (modify-phases %standard-phases
         (add-after 'strip 'move-to-utils
           (lambda _
             (for-each
              (lambda (file)
                (let ((target  (string-append (assoc-ref %outputs "utils") file))
                      (src  (string-append (assoc-ref %outputs "out") file)))
                  (mkdir-p (dirname target))
                  (link src target)
                  (delete-file src)))
              '("/bin/dig" "/bin/delv" "/bin/nslookup" "/bin/host" "/bin/nsupdate"
                "/share/man/man1/dig.1"
                "/share/man/man1/host.1"
                "/share/man/man1/nslookup.1"
                "/share/man/man1/nsupdate.1"))
             #t))
         ;; When and if guix provides user namespaces for the build process,
         ;; then the following can be uncommented and the subsequent "force-test"
         ;; will not be necessary.
         ;;
         ;;   (add-before 'check 'set-up-loopback
         ;;     (lambda _
         ;;          (system "bin/tests/system/ifconfig.sh up")))
         (replace 'check
           (lambda _
             ;; XXX Even ‘make force-test’ tries to create network interfaces
             ;; and fails.  The only working target is the (trivial) fuzz test.
             (with-directory-excursion "fuzz"
               (invoke "make" "check"))
             #t)))))
    (synopsis "Domain Name System (DNS) implementation")
    (description "BIND is an implementation of the @dfn{Domain Name System}
(DNS) protocols for the Internet.  It is a reference implementation of those
protocols, but it is also production-grade software, suitable for use in
high-volume and high-reliability applications.  The name BIND stands for
\"Berkeley Internet Name Domain\", because the software originated in the
early 1980s at the University of California at Berkeley.  The @code{utils}
output of this package contains the following DNS name servers related command
line utilities:
@table @code
@item delv
DNS lookup and validation utility
@item dig
DNS lookup utility
@item host
DNS lookup utility
@item nslookup
Internet name servers interactive query utility
@item nsupdate
Dynamic DNS update utility
@end table")
    (home-page "https://www.isc.org/bind/")
    (license (list license:mpl2.0))))

(define-public dnscrypt-proxy
  (package
    (name "dnscrypt-proxy")
    (version "1.9.5")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://download.dnscrypt.org/dnscrypt-proxy/"
                    "dnscrypt-proxy-" version ".tar.bz2"))
              (sha256
               (base32
                "1dhvklr4dg2vlw108n11xbamacaryyg3dbrg629b76lp7685p7z8"))
              (modules '((guix build utils)))
              (snippet
               ;; Delete bundled libltdl. XXX: This package also bundles
               ;; a modified libevent that cannot currently be removed.
               '(begin
                  (delete-file-recursively "libltdl")
                  #t))))
    (build-system gnu-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'autoreconf
           (lambda _
             ;; Re-generate build files due to unbundling ltdl.
             ;; TODO: Prevent generating new libltdl and building it.
             ;; The system version is still favored and referenced.
             (invoke "autoreconf" "-vif"))))))
    (native-inputs
     `(("pkg-config" ,pkg-config)
       ("automake" ,automake)
       ("autoconf" ,autoconf)
       ("libtool" ,libtool)))
    (inputs
     `(("libltdl" ,libltdl)
       ("libsodium" ,libsodium)))
    (home-page "https://www.dnscrypt.org/")
    (synopsis "Securely send DNS requests to a remote server")
    (description
     "@command{dnscrypt-proxy} is a tool for securing communications
between a client and a DNS resolver.  It verifies that responses you get
from a DNS provider was actually sent by that provider, and haven't been
tampered with.  For optimal performance it is recommended to use this as
a forwarder for a caching DNS resolver such as @command{dnsmasq}, but it
can also be used as a normal DNS \"server\".  A list of public dnscrypt
servers is included, and an up-to-date version is available at
@url{https://download.dnscrypt.org/dnscrypt-proxy/dnscrypt-resolvers.csv}.")
    (license (list license:isc
                   ;; Libevent and src/ext/queue.h is 3-clause BSD.
                   license:bsd-3))))

(define-public dnscrypt-wrapper
  (package
    (name "dnscrypt-wrapper")
    (version "0.2.2")
    (source (origin
              (method url-fetch)
              (uri (string-append
                    "https://github.com/cofyc/dnscrypt-wrapper/releases"
                    "/download/v" version "/" name "-v" version ".tar.bz2"))
              (sha256
               (base32
                "1vhg4g0r687f51wcdn7z9w1hxapazx6vyh5rsr8wa48sljzd583g"))))
    (build-system gnu-build-system)
    (arguments
     `(#:make-flags '("CC=gcc")
       ;; TODO: Tests require ruby-cucumber and ruby-aruba.
       #:tests? #f
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'create-configure
           (lambda _
             (invoke "make" "configure"))))))
    (native-inputs
     `(("autoconf" ,autoconf)))
    (inputs
     `(("libevent" ,libevent)
       ("libsodium" ,libsodium)))
    (home-page "https://github.com/Cofyc/dnscrypt-wrapper")
    (synopsis "Server-side dnscrypt proxy")
    (description
     "@command{dnscrypt-wrapper} is a tool to expose a name server over
the @code{dnscrypt} protocol.  It can be used as an endpoint for the
@command{dnscrypt-proxy} client to securely tunnel DNS requests between
the two.")
    (license (list license:isc
                   ;; Bundled argparse is MIT. TODO: package and unbundle.
                   license:expat
                   ;; dns-protocol.h and rfc1035.{c,h} is gpl2 or gpl3 (either).
                   license:gpl2
                   license:gpl3))))

(define-public libasr
  (package
    (name "libasr")
    (version "1.0.4")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "https://www.opensmtpd.org/archives/"
                           "libasr-" version ".tar.gz"))
       (sha256
        (base32 "1d6s8njqhvayx2gp47409sp1fn8m608ws26hr1srfp6i23nnpyqr"))))
    (build-system gnu-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-after 'install 'install-documentation
           (lambda* (#:key outputs #:allow-other-keys)
             (let ((out (assoc-ref outputs "out")))
               (install-file "src/asr_run.3"
                             (string-append out "/share/man/man3"))
               #t))))))
    (native-inputs
     `(("autoconf" ,autoconf)
       ("automake" ,automake)
       ("libtool" ,libtool)
       ("pkg-config" ,pkg-config)))
    (home-page "https://www.opensmtpd.org")
    (synopsis "Asynchronous resolver library by the OpenBSD project")
    (description
     "libasr is a free, simple and portable asynchronous resolver library.
It runs DNS queries and performs hostname resolution in a fully
asynchronous fashion.")
    (license (list license:isc
                   license:bsd-2 ; last part of getrrsetbyname_async.c
                   license:bsd-3
                   (license:non-copyleft "file://LICENSE") ; includes.h
                   license:openssl))))

(define-public nsd
  (package
    (name "nsd")
    (version "4.3.2")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "https://www.nlnetlabs.nl/downloads/nsd/nsd-"
                           version ".tar.gz"))
       (sha256
        (base32 "0ac3mbn5z4nc18782m9aswdpi2m9f4665vidw0ciyigdh0pywp2v"))))
    (build-system gnu-build-system)
    (arguments
     `(#:configure-flags
       (list "--enable-pie"             ; fully benefit from ASLR
             "--enable-ratelimit"
             "--enable-recvmmsg"
             "--enable-relro-now"       ; protect GOT and .dtor areas
             "--disable-radix-tree"
             (string-append "--with-libevent="
                            (assoc-ref %build-inputs "libevent"))
             (string-append "--with-ssl="
                            (assoc-ref %build-inputs "openssl"))
             "--with-configdir=/etc"
             "--with-nsd_conf_file=/etc/nsd/nsd.conf"
             "--with-logfile=/var/log/nsd.log"
             "--with-pidfile=/var/db/nsd/nsd.pid"
             "--with-dbfile=/var/db/nsd/nsd.db"
             "--with-zonesdir=/etc/nsd"
             "--with-xfrdfile=/var/db/nsd/xfrd.state"
             "--with-zonelistfile=/var/db/nsd/zone.list")
       #:phases
       (modify-phases %standard-phases
         (add-before 'configure 'patch-installation-paths
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (doc (string-append out "/share/doc/" ,name "-" ,version)))
               ;; The ‘make install’ target tries to create the parent
               ;; directories of run-time things like ‘pidfile’ above, and
               ;; useless empty directories like 'configdir'.  Remove such
               ;; '$(INSTALL)' lines and install the example configuration file
               ;; in an appropriate location.
               (substitute* "Makefile.in"
                 ((".*INSTALL.*\\$\\((config|pid|xfr|db)dir" command)
                  (string-append "#" command))
                 (("\\$\\(nsdconfigfile\\)\\.sample" file-name)
                  (string-append doc "/examples/" file-name)))
               #t))))
       #:tests? #f))                    ; no tests
    (inputs
     `(("libevent" ,libevent)
       ("openssl" ,openssl)))
    (home-page "https://www.nlnetlabs.nl/projects/nsd/about/")
    (synopsis "Authoritative DNS name server")
    (description "@dfn{NSD}, short for Name Server Daemon, is an authoritative
name server for the Domain Name System (@dfn{DNS}).  It aims to be a fast and
RFC-compliant nameserver.

NSD uses zone information compiled via @command{zonec} into a binary database
file (@file{nsd.db}).  This allows fast startup of the name service daemon and
allows syntax-structural errors in zone files to be flagged at compile time,
before being made available to NSD service itself.  However, most traditional
BIND-style zone files can be directly imported into NSD without modification.

The collection of programs and processes that make up NSD are designed so that
the daemon itself runs as a non-privileged user and can be easily configured to
run in a @code{chroot} jail, thus making any security flaws in NSD less likely
to result in system-wide compromise.")
    (license (list license:bsd-3))))

(define-public unbound
  (package
    (name "unbound")
    (version "1.10.1")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "https://www.unbound.net/downloads/unbound-"
                           version ".tar.gz"))
       (sha256
        (base32 "0dnmh9jjh2v274f0hl31bgv40pl77mmfgky8bkqr5kvi3b17fdmp"))))
    (build-system gnu-build-system)
    (outputs '("out" "python"))
    (native-inputs
     `(("flex" ,flex)
       ("swig" ,swig)))
    (inputs
     `(("expat" ,expat)
       ("libevent" ,libevent)
       ("protobuf" ,protobuf)
       ("python-wrapper" ,python-wrapper)
       ("openssl" ,openssl)))
    (arguments
     `(#:configure-flags
       (list "--disable-static" ; save space and non-determinism in libunbound.a
             (string-append
              "--with-ssl=" (assoc-ref %build-inputs "openssl"))
             (string-append
              "--with-libevent=" (assoc-ref %build-inputs "libevent"))
             (string-append
              "--with-libexpat=" (assoc-ref %build-inputs "expat"))
             "--with-pythonmodule" "--with-pyunbound")
       #:phases
       (modify-phases %standard-phases
         (add-after 'configure 'fix-python-site-package-path
           ;; Move python modules into their own output.
           (lambda* (#:key outputs #:allow-other-keys)
             (let ((pyout (assoc-ref outputs "python"))
                   (ver ,(version-major+minor (package-version python))))
               (substitute* "Makefile"
                 (("^PYTHON_SITE_PKG=.*$")
                  (string-append
                   "PYTHON_SITE_PKG="
                   pyout "/lib/python-" ver "/site-packages\n"))))
             #t))
         (add-before 'check 'fix-missing-nss-for-tests
           ;; Unfortunately, the package's unittests involve some checks
           ;; looking up protocols and services which are not provided
           ;; by the minimalistic build environment, in particular,
           ;; /etc/protocols and /etc/services are missing.
           ;; Also, after plain substitution of protocol and service names
           ;; in the test data, the tests still fail because the
           ;; corresponding Resource Records have been signed by
           ;; RRSIG records.
           ;; The following LD_PRELOAD library overwrites the glibc
           ;; functions ‘get{proto,serv}byname’, ‘getprotobynumber’ and
           ;; ‘getservbyport’ providing the few records required for the
           ;; unit tests to pass.
           (lambda* (#:key inputs outputs #:allow-other-keys)
             (let* ((source (assoc-ref %build-inputs "source"))
                    (gcc (assoc-ref %build-inputs "gcc")))
               (call-with-output-file "/tmp/nss_preload.c"
                 (lambda (port)
                   (display "#include <stdlib.h>
#include <string.h>
#include <strings.h>

#include <netdb.h>

struct protoent *getprotobyname(const char *name) {
  struct protoent *p = malloc(sizeof(struct protoent));
  p->p_aliases = malloc(sizeof(char*));
  if (strcasecmp(name, \"tcp\") == 0) {
    p->p_name = \"tcp\";
    p->p_proto = 6;
    p->p_aliases[0] = \"TCP\";
  } else if (strcasecmp(name, \"udp\") == 0) {
    p->p_name = \"udp\";
    p->p_proto = 17;
    p->p_aliases[0] = \"UDP\";
  } else
    p = NULL;
  return p;
}

struct protoent *getprotobynumber(int proto) {
  struct protoent *p = malloc(sizeof(struct protoent));
  p->p_aliases = malloc(sizeof(char*));
  switch(proto) {
  case 6:
    p->p_name = \"tcp\";
    p->p_proto = 6;
    p->p_aliases[0] = \"TCP\";
    break;
  case 17:
    p->p_name = \"udp\";
    p->p_proto = 17;
    p->p_aliases[0] = \"UDP\";
    break;
  default:
    p = NULL;
    break;
  }
  return p;
}

struct servent *getservbyname(const char *name, const char *proto) {
  struct servent *s = malloc(sizeof(struct servent));
  char* buf = malloc((strlen(proto)+1)*sizeof(char));
  strcpy(buf, proto);
  s->s_aliases = malloc(sizeof(char*));
  s->s_aliases[0] = NULL;
  if (strcasecmp(name, \"domain\") == 0) {
    s->s_name = \"domain\";
    s->s_port = htons(53);
    s->s_proto = buf;
  } else
    s = NULL;
  return s;
}

struct servent *getservbyport(int port, const char *proto) {
  char buf[32];
  struct servent *s = malloc(sizeof(struct servent));
  strcpy(buf, proto);
  s->s_aliases = malloc(sizeof(char*));
  s->s_aliases[0] = NULL;
  switch(port) {
  case 53:
    s->s_name = \"domain\";
    s->s_port = 53;
    s->s_proto = \"udp\";
    break;
  default:
    s = NULL;
    break;
  }
  return s;
}" port)))
               (invoke (string-append gcc "/bin/gcc")
                       "-shared" "-fPIC" "-o" "/tmp/nss_preload.so"
                       "/tmp/nss_preload.c")
               ;; The preload library only affects the unittests.
               (substitute* "Makefile"
                 (("./unittest")
                  "LD_PRELOAD=/tmp/nss_preload.so ./unittest")))
             #t)))))
    (home-page "https://www.unbound.net")
    (synopsis "Validating, recursive, and caching DNS resolver")
    (description
     "Unbound is a recursive-only caching DNS server which can perform DNSSEC
validation of results.  It implements only a minimal amount of authoritative
service to prevent leakage to the root nameservers: forward lookups for
localhost, reverse for @code{127.0.0.1} and @code{::1}, and NXDOMAIN for zones
served by AS112.  Stub and forward zones are supported.")
    (license license:bsd-4)))

(define-public yadifa
  (package
    (name "yadifa")
    (version "2.3.9")
    (source
     (let ((build "8497"))
       (origin
         (method url-fetch)
         (uri
          (string-append "http://cdn.yadifa.eu/sites/default/files/releases/"
                         "yadifa-" version "-" build ".tar.gz"))
         (sha256
          (base32 "0xvyr91sfgzkpw6g3h893ldbwnki3w2472n56rr18w67qghs1sa5")))))
    (build-system gnu-build-system)
    (native-inputs
     `(("which" ,which)))
    (inputs
     `(("openssl" ,openssl)))
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-before 'configure 'omit-example-configurations
           (lambda _
             (substitute* "Makefile.in"
               ((" (etc|var)") ""))
             #t)))
       #:configure-flags
       (list "--sysconfdir=/etc"
             "--localstatedir=/var"
             "--disable-build-timestamp" ; build reproducibly
             "--enable-shared"
             "--disable-static"
             "--enable-acl"
             "--enable-caching"
             "--enable-ctrl"            ; enable remote control
             "--enable-nsec"
             "--enable-nsec3"
             "--enable-tsig")))
    (home-page "https://www.yadifa.eu/")
    (synopsis "Authoritative DNS name server")
    (description "YADIFA is an authoritative name server for the @dfn{Domain
Name System} (DNS).  It aims for both higher performance and a smaller memory
footprint than other implementations, while remaining fully RFC-compliant.
YADIFA supports dynamic record updates and the @dfn{Domain Name System Security
Extensions} (DNSSEC).")
    (license license:bsd-3)))

(define-public knot
  (package
    (name "knot")
    (version "2.9.6")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "https://secure.nic.cz/files/knot-dns/"
                           "knot-" version ".tar.xz"))
       (sha256
        (base32 "1rxjjisr6rz1wa4279ghvj5zzhgyjhncmb9dkzqm8nw2qs1jhx5z"))
       (modules '((guix build utils)))
       (snippet
        '(begin
           ;; Delete bundled libraries.
           (with-directory-excursion "src/contrib"
             (delete-file-recursively "lmdb"))
           #t))))
    (build-system gnu-build-system)
    (native-inputs
     `(("pkg-config" ,pkg-config)))
    (inputs
     `(("fstrm" ,fstrm)
       ("gnutls" ,gnutls)
       ("jansson" ,jansson)
       ("libcap-ng" ,libcap-ng)
       ("libedit" ,libedit)
       ("libidn" ,libidn)
       ("liburcu" ,liburcu)
       ("lmdb" ,lmdb)
       ("ncurses" ,ncurses)
       ("protobuf-c" ,protobuf-c)))
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-before 'configure 'disable-directory-pre-creation
           (lambda _
             ;; Don't install empty directories like ‘/etc’ outside the store.
             ;; This is needed even when using ‘make config_dir=... install’.
             (substitute* "src/Makefile.in" (("\\$\\(INSTALL\\) -d") "true"))
             #t))
         (replace 'install
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (doc (string-append out "/share/doc/" ,name "-" ,version))
                    (etc (string-append doc "/examples/etc")))
               (invoke "make"
                       (string-append "config_dir=" etc)
                       "install")))))
       #:configure-flags
       (list "--sysconfdir=/etc"
             "--localstatedir=/var"
             "--enable-dnstap"          ; let tools read/write capture files
             "--with-module-dnstap=yes" ; detailed query capturing & logging
             (string-append "--with-bash-completions="
                            (assoc-ref %outputs "out")
                            "/etc/bash_completion.d"))))
    (home-page "https://www.knot-dns.cz/")
    (synopsis "Authoritative DNS name server")
    (description "Knot DNS is an authoritative name server for the @dfn{Domain
Name System} (DNS), designed to meet the needs of root and @dfn{top-level
domain} (TLD) name servers.  It is implemented as a threaded daemon and uses a
number of programming techniques to improve speed.  For example, the responder
is completely lock-free, resulting in a very high response rate.  Other features
include automatic @dfn{DNS Security Extensions} (DNSSEC) signing, dynamic record
synthesis, and on-the-fly re-configuration.")
    (license
     (list
      ;; src/contrib/{hat-trie,murmurhash3,openbsd},
      ;; src/dnssec/contrib/vpool.[ch], and parts of libtap/ are ‘MIT’ (expat).
      license:expat
      license:lgpl2.0+              ; parts of scr/contrib/ucw
      license:public-domain         ; src/contrib/fnv and possibly murmurhash3
      license:gpl3+))))             ; everything else

(define-public knot-resolver
  (package
    (name "knot-resolver")
    (version "4.3.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://secure.nic.cz/files/knot-resolver/"
                                  "knot-resolver-" version ".tar.xz"))
              (sha256
               (base32
                "09ffmqx79lv5psr433x4n946njgsn071b9b7161pcb9bmrqz380c"))))
    (build-system meson-build-system)
    (arguments
     '(#:configure-flags '("-Ddoc=enabled")
       #:phases
       (modify-phases %standard-phases
         (add-before 'configure 'disable-default-ta
           (lambda _
             ;;  Disable the default managed root TA, since we don't have
             ;;  write access to the keyfile and its directory in store.
             (substitute* "daemon/lua/sandbox.lua.in"
               (("^trust_anchors\\.add_file.*") ""))
             #t))
         (add-after 'build 'build-doc
           (lambda _
             (invoke "ninja" "doc")))
         (add-after 'install 'wrap-binary
           (lambda* (#:key inputs outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (lua-* (map cdr (filter
                                     (lambda (input)
                                       (string-prefix? "lua-" (car input)))
                                     inputs)))
                    (lua-path (lambda (p)
                                (string-append p "/share/lua/5.1/?.lua")))
                    (lua-cpath (lambda (p)
                                 (string-append p "/lib/lua/5.1/?.so"))))
               (wrap-program (string-append out "/sbin/kresd")
                 `("LUA_PATH" ";" prefix ,(map lua-path lua-*))
                 `("LUA_CPATH" ";" prefix ,(map lua-cpath lua-*)))
               #t))))))
    (native-inputs
     `(("cmocka" ,cmocka)               ; for unit tests
       ("doxygen" ,doxygen)
       ("protobuf-c" ,protobuf-c)
       ("pkg-config" ,pkg-config)
       ("python-breathe" ,python-breathe)
       ("python-sphinx" ,python-sphinx)
       ("python-sphinx-rtd-theme" ,python-sphinx-rtd-theme)))
    (inputs
     `(("fstrm" ,fstrm)
       ("gnutls" ,gnutls)
       ("knot" ,knot)
       ("libuv" ,libuv)
       ("lmdb" ,lmdb)
       ("luajit" ,luajit)
       ;; TODO: Add optional lua modules: basexx and psl.
       ("lua-bitop" ,lua5.1-bitop)
       ("lua-cqueues" ,lua5.1-cqueues)
       ("lua-filesystem" ,lua5.1-filesystem)
       ("lua-sec" ,lua5.1-sec)
       ("lua-socket" ,lua5.1-socket)))
    (home-page "https://www.knot-resolver.cz/")
    (synopsis "Caching validating DNS resolver")
    (description
     "Knot Resolver is a caching full resolver implementation written in C and
LuaJIT, both a resolver library and a daemon.")
    (license (list license:gpl3+
                   ;; Some 'contrib' files are under MIT, CC0 and LGPL2.
                   license:expat
                   license:cc0
                   license:lgpl2.0))))

(define-public ddclient
  (package
    (name "ddclient")
    (version "3.9.1")
    (source
     (origin
       (method git-fetch)
       (uri (git-reference
             (url "https://github.com/ddclient/ddclient")
             (commit (string-append "v" version))))
       (file-name (git-file-name name version))
       (sha256
        (base32 "0hf377g4j9r9sac75xp17nk2h58mazswz4vkg4g2gl2yyhvzq91w"))))
    (build-system trivial-build-system) ; no Makefile.PL
    (native-inputs
     `(("bash" ,bash)
       ("perl" ,perl)))
    (inputs
     `(("inetutils" ,inetutils)         ; logger
       ("net-tools" ,net-tools)
       ("perl-data-validate-ip" ,perl-data-validate-ip)
       ("perl-digest-sha1" ,perl-digest-sha1)
       ("perl-io-socket-ssl" ,perl-io-socket-ssl)))
    (arguments
     `(#:modules ((guix build utils)
                  (ice-9 match)
                  (srfi srfi-26))
       #:builder
       (begin
         (use-modules (guix build utils)
                      (ice-9 match)
                      (srfi srfi-26))
         (setenv "PATH" (string-append
                         (assoc-ref %build-inputs "bash") "/bin" ":"
                         (assoc-ref %build-inputs "perl") "/bin"))

         ;; Copy the (read-only) source into the (writable) build directory.
         (copy-recursively (assoc-ref %build-inputs "source") ".")

         ;; Install.
         (let* ((out (assoc-ref %outputs "out"))
                (bin (string-append out "/bin")))
           (let ((file "ddclient"))
             (substitute* file
               (("/usr/bin/perl") (which "perl"))
               ;; Strictly use ‘/etc/ddclient/ddclient.conf’.
               (("\\$\\{program\\}\\.conf") "/etc/ddclient/ddclient.conf")
               (("\\$etc\\$program.conf") "/etc/ddclient/ddclient.conf")
               ;; Strictly use ‘/var/cache/ddclient/ddclient.cache’
               (("\\$cachedir\\$program\\.cache")
                "/var/cache/ddclient/ddclient.cache"))
             (install-file file bin)
             (wrap-program (string-append bin "/" file)
               `("PATH" ":" =
                 ("$PATH"
                  ,@(map (lambda (input)
                           (match input
                                  ((name . store)
                                   (string-append store "/bin"))))
                         %build-inputs)))
               `("PERL5LIB" ":" =
                 ,(delete
                   ""
                   (map (match-lambda
                         (((? (cut string-prefix? "perl-" <>) name) . dir)
                          (string-append dir "/lib/perl5/site_perl"))
                         (_ ""))
                        %build-inputs)))))
           (for-each (cut install-file <> (string-append out
                                                         "/share/ddclient"))
                     (find-files "." "sample.*$"))))))
    (home-page "https://ddclient.net/")
    (synopsis "Address updating utility for dynamic DNS services")
    (description "This package provides a client to update dynamic IP
addresses with several dynamic DNS service providers, such as
@uref{https://www.dyndns.com/account/login.html,DynDNS.com}.

This makes it possible to use a fixed hostname (such as myhost.dyndns.org) to
access a machine with a dynamic IP address.

The client supports both dynamic and (near) static services, as well as MX
record and alternative name management.  It caches the address, and only
attempts the update when it has changed.")
    (license license:gpl2+)))

(define-public hnsd
  ;; There have been no releases yet, hence this commit.
  (let ((revision "0")
        (commit "895d89c25d316d18df9d374fe78aae3902bc89fb"))
   (package
     (name "hnsd")
     (version (git-version "0.0" revision commit))
     (source (origin
               (method git-fetch)
               (uri (git-reference
                     (url "https://github.com/handshake-org/hnsd")
                     (commit commit)))
               (sha256
                (base32
                 "0704y73sddn24jga9csw4gxyfb3pnrfnk0vdcph84n1h38490l16"))
               (file-name (git-file-name name version))
               (modules '((guix build utils)))
               (snippet
                '(begin
                   ;; Delete the bundled copy of libuv.
                   (delete-file-recursively "uv")
                   (substitute* "configure.ac"
                     (("AC_CONFIG_SUBDIRS\\(\\[uv\\]\\)") ""))
                   (substitute* "Makefile.am"
                     (("SUBDIRS = uv") "\n")
                     (("\\$\\(top_builddir\\)/uv/libuv.la") "-luv")

                     ;; Make sure the 'hnsd' binary is installed and
                     ;; dynamically-linked.
                     (("noinst_PROGRAMS") "bin_PROGRAMS")
                     (("hnsd_LDFLAGS = -static") ""))

                   ;; This script tries to chdir to "uv" and doesn't do more
                   ;; than "autoreconf" so remove it.
                   (delete-file "autogen.sh")
                   #t))))
     (build-system gnu-build-system)
     (arguments
      '(#:configure-flags '("--disable-static"))) ;no need for libhsk.a
     (native-inputs
      `(("autoconf" ,autoconf)
        ("automake" ,automake)
        ("libtool" ,libtool)))
     (inputs
      `(("unbound" ,unbound)
        ("libuv" ,libuv)))
     (home-page "https://www.handshake.org/")
     (synopsis "Resolver daemon for the Handshake naming protocol")
     (description
      "@command{hnsd} is a @dfn{host name resolver} for the Handshake Naming
System (HNS) peer-to-peer network.")
     (license license:expat))))

(define-public libmicrodns
  (package
    (name "libmicrodns")
    (version "0.1.2")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://github.com/videolabs/libmicrodns/"
                                  "releases/download/" version "/microdns-"
                                  version ".tar.xz"))
              (sha256
               (base32
                "0p4va18zxgmzcdwhlbg2mmjwswlbgqy4ay5vaxrw7cxmhsflnv36"))))
    (build-system meson-build-system)
    (home-page "https://github.com/videolabs/libmicrodns")
    (synopsis "Minimal mDNS resolver library")
    (description "@code{libmicrodns} provides a minimal implementation of a
mDNS resolver as well as an announcer.  mDNS (Multicast Domain Name System) is
a zero-config service that allows one to resolve host names to IP addresses in
local networks.")
    (license license:lgpl2.1)))

(define-public public-suffix-list
  ;; Mozilla releases the official list here:
  ;;
  ;;   https://publicsuffix.org/list/public_suffix_list.dat
  ;;
  ;; However, Mozilla syncs that file from the GitHub repository periodically,
  ;; so its contents will change over time.  If you update this commit, please
  ;; make sure that the new commit refers to a list which is identical to the
  ;; officially published list available from the URL above.
  (let ((commit "9375b697baddb0827a5995c81bd3c75877a0b35d"))
    (package
      (name "public-suffix-list")
      (version (git-version "0" "1" commit))
      (source (origin
                (method git-fetch)
                (uri (git-reference
                      (url "https://github.com/publicsuffix/list")
                      (commit commit)))
                (file-name (git-file-name name version))
                (sha256
                 (base32
                  "1sm7pni01rnl4ldzi8z8nc4cbgq8nxda9gwc68v0s3ij7jd1jmik"))))
      (build-system trivial-build-system)
      (arguments
       `(#:modules ((guix build utils))
         #:builder
         (begin
           (use-modules (guix build utils))
           (let* ((out (assoc-ref %outputs "out"))
                  ;; Install to /share because that is where "read-only
                  ;; architecture-independent data files" should go (see:
                  ;; (standards) Directory Variables).  Include the version in
                  ;; the directory name so that if multiple versions are ever
                  ;; installed in the same profile, they will not conflict.
                  (destination (string-append
                                out "/share/public-suffix-list-" ,version))
                  (source (assoc-ref %build-inputs "source")))
             (with-directory-excursion source
             (install-file "public_suffix_list.dat" destination)
             (install-file "LICENSE" destination))
             #t))))
      (home-page "https://publicsuffix.org/")
      (synopsis "Database of current and historical DNS suffixes")
      (description "This is the Public Suffix List maintained by Mozilla.  A
\"public suffix\" is one under which Internet users can (or historically
could) directly register names in the Domain Name System (DNS).  Some examples
of public suffixes are .com, .co.uk and pvt.k12.ma.us.  This is a list of all
known public suffixes.")
      (license license:mpl2.0))))

(define-public maradns
  (package
    (name "maradns")
    (version "3.5.0007")
    (source
     (origin
       (method url-fetch)
       (uri (string-append "https://maradns.samiam.org/download/"
                           (version-major+minor version) "/"
                           version "/maradns-" version ".tar.xz"))
       (sha256
        (base32 "0bc19xylg4whww9qaj5i4izwxcrh0c0ja7l1pfcn2la02hlvg1a6"))))
    (build-system gnu-build-system)
    (arguments
     `(#:tests? #f                      ; need to be root to run tests
       #:make-flags
       (list
        ,(string-append "CC=" (cc-for-target))
        (string-append "PREFIX=" %output)
        (string-append "RPM_BUILD_ROOT=" %output))
       #:phases
       (modify-phases %standard-phases
         (replace 'configure
           (lambda* (#:key native-inputs target #:allow-other-keys)
             ;; make_32bit_tables generates a header file that is used during
             ;; compilation. Hence, during cross compilation, it should be
             ;; built for the host system.
             (when target
               (substitute* "rng/Makefile"
                 (("\\$\\(CC\\) -o make_32bit_tables")
                  (string-append (assoc-ref native-inputs "gcc")
                                 "/bin/gcc -o make_32bit_tables"))))
             (invoke "./configure")))
         (add-before 'install 'create-install-directories
           (lambda* (#:key outputs #:allow-other-keys)
             (let ((out (assoc-ref outputs "out")))
               (for-each (lambda (dir)
                           (mkdir-p (string-append out dir)))
                         (list "/bin" "/sbin" "/etc"
                               "/share/man/man1"
                               "/share/man/man5"
                               "/share/man/man8"))
               #t))))))
    (home-page "https://maradns.samiam.org")
    (synopsis "Small lightweight DNS server")
    (description "MaraDNS is a small and lightweight DNS server.  MaraDNS
consists of a UDP-only authoritative DNS server for hosting domains, and a UDP
and TCP-capable recursive DNS server for finding domains on the internet.")
    (license license:bsd-2)))

(define-public openresolv
  (package
    (name "openresolv")
    (version "3.10.0")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://roy.marples.name/downloads/openresolv/"
                                  "openresolv-" version ".tar.xz"))
              (sha256
               (base32
                "01ms6c087la4hk0f0w6n2vpsb7dg4kklah2rqyhz88p0vr9bqy20"))
              (patches
               (search-patches "openresolv-restartcmd-guix.patch"))))
    (build-system gnu-build-system)
    (arguments
     `(#:tests? #f                      ; No test suite
       #:configure-flags
       (list (string-append "--sysconfdir=/etc"))
       #:make-flags
       (list (string-append "SYSCONFDIR=/" (assoc-ref %outputs "out") "/etc"))))
    (home-page "https://roy.marples.name/projects/openresolv/")
    (synopsis "Resolvconf POSIX compliant implementation, a middleman for resolv.conf")
    (description "openresolv is an implementation of @command{resolvconf}, the
middleman between the network configuration services and
@file{/etc/resolv.conf}.  @command{resolvconf} itself is just a script that
stores, removes and lists a full @file{resolv.conf} generated for the
interface.  It then calls all the helper scripts it knows about so it can
configure the real @file{/etc/resolv.conf} and optionally any local
nameservers other than libc.")
    (license license:bsd-2)))


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2014 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2014 Eric Bavier <bavier@member.fsf.org>
;;; Copyright © 2016 Mathieu Lirzin <mthl@gnu.org>
;;; Copyright © 2018 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2020 Marius Bakke <marius@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 (gnu packages docbook)
  #:use-module (gnu packages)
  #:use-module (gnu packages compression)
  #:use-module (gnu packages imagemagick)
  #:use-module (gnu packages inkscape)
  #:use-module (gnu packages tex)
  #:use-module (gnu packages python)
  #:use-module (gnu packages base)
  #:use-module (gnu packages xml)
  #:use-module (guix licenses)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix build-system trivial)
  #:use-module (guix build-system python))

(define-public docbook-xml-5
  (package
    (name "docbook-xml")
    (version "5.0.1")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://www.docbook.org/xml/" version
                                  "/docbook-" version ".zip"))
              (sha256
               (base32
                "1iz3hq1lqgnshvlz4j9gvh4jy1ml74qf90vqf2ikbq0h4i2xzybs"))))
    (build-system trivial-build-system)
    (arguments
     `(#:modules ((guix build utils))
       #:builder
       (begin
         (use-modules (guix build utils))
         (let* ((unzip
                 (string-append (assoc-ref %build-inputs "unzip")
                                "/bin/unzip"))
                (source (assoc-ref %build-inputs "source"))
                (out    (assoc-ref %outputs "out"))
                (dtd    (string-append out "/xml/dtd/docbook")))
           (invoke unzip source)
           (mkdir-p dtd)
           (copy-recursively (string-append "docbook-" ,version) dtd)
           (with-directory-excursion dtd
             (substitute* (string-append out "/xml/dtd/docbook/catalog.xml")
               (("uri=\"")
                (string-append
                 "uri=\"file://" dtd "/")))
             #t)))))
    (native-inputs `(("unzip" ,unzip)))
    (home-page "https://docbook.org")
    (synopsis "DocBook XML DTDs for document authoring")
    (description
     "DocBook is general purpose XML and SGML document type particularly well
suited to books and papers about computer hardware and software (though it is
by no means limited to these applications.)  This package provides XML DTDs.")
    (license (x11-style "" "See file headers."))))

(define-public docbook-xml
  (package
    (inherit docbook-xml-5)
    (name "docbook-xml")
    (version "4.5")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://www.docbook.org/xml/" version
                                  "/docbook-xml-" version ".zip"))
              (sha256
               (base32
                "1d671lcjckjri28xfbf6dq7y3xnkppa910w1jin8rjc35dx06kjf"))))
    (arguments
     '(#:builder (begin
                   (use-modules (guix build utils))

                   (let* ((unzip
                           (string-append (assoc-ref %build-inputs "unzip")
                                          "/bin/unzip"))
                          (source (assoc-ref %build-inputs "source"))
                          (out    (assoc-ref %outputs "out"))
                          (dtd    (string-append out "/xml/dtd/docbook")))
                     (mkdir-p dtd)
                     (with-directory-excursion dtd
                       (invoke unzip source))
                     (substitute* (string-append out "/xml/dtd/docbook/catalog.xml")
                       (("uri=\"")
                        (string-append
                         "uri=\"file://" dtd "/")))
                     #t))
                 #:modules ((guix build utils))))))

(define-public docbook-xml-4.4
  (package (inherit docbook-xml)
    (version "4.4")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://www.docbook.org/xml/" version
                                  "/docbook-xml-" version ".zip"))
              (sha256
               (base32
                "141h4zsyc71sfi2zzd89v4bb4qqq9ca1ri9ix2als9f4i3mmkw82"))))))

(define-public docbook-xml-4.3
  (package (inherit docbook-xml)
    (version "4.3")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://www.docbook.org/xml/" version
                                  "/docbook-xml-" version ".zip"))
              (sha256
               (base32
                "0r1l2if1z4wm2v664sqdizm4gak6db1kx9y50jq89m3gxaa8l1i3"))))))

(define-public docbook-xml-4.2
  (package (inherit docbook-xml)
    (version "4.2")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://www.docbook.org/xml/" version
                                  "/docbook-xml-" version ".zip"))
              (sha256
               (base32
                "18hgwvmywh6a5jh38szjmg3hg2r4v5lb6r3ydc3rd8cp9wg61i5c"))))))

(define-public docbook-xml-4.1.2
  (package (inherit docbook-xml)
    (version "4.1.2")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://www.docbook.org/xml/" version
                                  "/docbkx412.zip"))
              (sha256
               (base32
                "0wkp5rvnqj0ghxia0558mnn4c7s3n501j99q2isp3sp0ci069w1h"))))
    (arguments
     '(#:modules ((guix build utils))
       #:builder
       (begin
         (use-modules (guix build utils))
         (let ((source (assoc-ref %build-inputs "source"))
               (unzip  (string-append (assoc-ref %build-inputs "unzip")
                                      "/bin/unzip"))
               (dtd    (string-append (assoc-ref %outputs "out")
                                      "/xml/dtd/docbook")))
           (mkdir-p dtd)
           (invoke unzip source "-d" dtd)))))))

(define-public docbook-xsl
  (package
    (name "docbook-xsl")
    (version "1.79.2")
    (source (origin
              (method url-fetch)
              (uri (string-append "https://github.com/docbook/xslt10-stylesheets"
                                  "/releases/download/release%2F" version
                                  "/docbook-xsl-" version ".tar.bz2"))
              (patches (search-patches "docbook-xsl-support-old-url.patch"
                                       "docbook-xsl-nonrecursive-string-subst.patch"))
              (sha256
               (base32
                "0wd33z41kdsybyx3ay21w6bdlmgpd9kyn3mr5y520lsf8km28r9i"))
              (modules '((guix build utils)))
              (snippet
               '(begin
                  (for-each delete-file (find-files "." "\\.jar$"))
                  #t))))
    (build-system trivial-build-system)
    (arguments
     `(#:builder (let ((name-version (string-append ,name "-" ,version)))
                   (use-modules (guix build utils))

                   (let* ((bzip2  (assoc-ref %build-inputs "bzip2"))
                          (xz     (assoc-ref %build-inputs "xz"))
                          (tar    (assoc-ref %build-inputs "tar"))
                          (source (assoc-ref %build-inputs "source"))
                          (out    (assoc-ref %outputs "out"))
                          (xsl    (string-append out "/xml/xsl")))
                     (setenv "PATH" (string-append bzip2 "/bin" ":" xz "/bin"))
                     (invoke (string-append tar "/bin/tar") "xvf" source)

                     (mkdir-p xsl)
                     (copy-recursively name-version
                                       (string-append xsl "/" name-version))

                     (substitute* (string-append xsl "/" name-version "/catalog.xml")
                       (("rewritePrefix=\"./")
                        (string-append "rewritePrefix=\"file://" xsl "/"
                                       name-version "/")))
                     #t))
       #:modules ((guix build utils))))
    (native-inputs `(("bzip2" ,bzip2)
                     ("xz" ,xz)         ;needed for repacked tarballs
                     ("tar" ,tar)))
    (home-page "https://docbook.org")
    (synopsis "DocBook XSL style sheets for document authoring")
    (description
     "This package provides XSL style sheets for DocBook.")
    (license (x11-style "" "See 'COPYING' file."))))

(define-public dblatex
  (package
    (name "dblatex")
    (version "0.3.11")
    (source (origin
              (method url-fetch)
              (uri (string-append "mirror://sourceforge/dblatex/dblatex/"
                                  "dblatex-" version "/dblatex-"
                                  version ".tar.bz2"))
              (sha256
               (base32
                "0rp1bc2lgisigscq1i7zxfd2qdaxxxld6khbcxss4pq7fpi9fzkv"))))
    (build-system python-build-system)
    ;; TODO: Add xfig/transfig for fig2dev utility
    (inputs
     `(("texlive" ,(texlive-union (list texlive-amsfonts
                                        texlive-latex-anysize
                                        texlive-latex-appendix
                                        texlive-latex-changebar
                                        texlive-latex-colortbl
                                        texlive-latex-eepic
                                        texlive-latex-eso-pic
                                        texlive-latex-fancybox
                                        texlive-latex-fancyhdr
                                        texlive-latex-fancyvrb
                                        texlive-latex-float
                                        texlive-latex-footmisc
                                        texlive-latex-hyperref
                                        texlive-latex-jknapltx
                                        texlive-latex-listings
                                        texlive-latex-multirow
                                        texlive-latex-oberdiek
                                        texlive-latex-overpic
                                        texlive-latex-pdfpages
                                        texlive-latex-subfigure
                                        texlive-latex-titlesec
                                        texlive-latex-url
                                        texlive-latex-wasysym

                                        texlive-fonts-ec
                                        texlive-fonts-rsfs
                                        texlive-fonts-stmaryrd

                                        texlive-generic-ifxetex)))
       ("imagemagick" ,imagemagick)     ;for convert
       ("inkscape" ,inkscape)           ;for svg conversion
       ("docbook" ,docbook-xml)
       ("libxslt" ,libxslt)))           ;for xsltproc
    (arguments
     `(#:python ,python-2               ;'print' syntax
       ;; Using setuptools causes an invalid "package_base" path in
       ;; out/bin/.dblatex-real due to a missing leading '/'.  This is caused
       ;; by dblatex's setup.py stripping the root path when creating the
       ;; script.  (dblatex's setup.py still uses distutils and thus has to
       ;; create the script by itself. The feature for creating scripts is one
       ;; of setuptools' features.)
       ;; See this thread for details:
       ;; https://lists.gnu.org/archive/html/guix-devel/2016-12/msg00030.html
       #:use-setuptools? #f
       #:tests? #f                      ;no 'test' command
       #:phases
       (modify-phases %standard-phases
         (add-after 'wrap 'set-path
           (lambda* (#:key inputs outputs #:allow-other-keys)
             (let ((out (assoc-ref outputs "out")))
               ;; dblatex executes helper programs at runtime.
               (wrap-program (string-append out "/bin/dblatex")
                 `("PATH" ":" prefix
                   ,(map (lambda (input)
                           (string-append (assoc-ref inputs input)
                                          "/bin"))
                         '("libxslt" "texlive"
                           "imagemagick" "inkscape"))))
               #t))))))
    (home-page "http://dblatex.sourceforge.net")
    (synopsis "DocBook to LaTeX Publishing")
    (description
     "DocBook to LaTeX Publishing transforms your SGML/XML DocBook documents
to DVI, PostScript or PDF by translating them in pure LaTeX as a first
process.  MathML 2.0 markups are supported too.  It started as a clone of
DB2LaTeX.")
    ;; lib/contrib/which is under an X11 license
    (license gpl2+)))

license: mit


code:
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2016 David Thompson <davet@gnu.org>
;;; Copyright © 2018 Efraim Flashner <efraim@flashner.co.il>
;;; Copyright © 2019, 2020 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2019 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;; Copyright © 2020 Michael Rohleder <mike@rohleder.de>
;;; Copyright © 2020 Katherine Cox-Buday <cox.katherine.e@gmail.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 (gnu packages docker)
  #:use-module ((guix licenses) #:prefix license:)
  #:use-module (gnu packages)
  #:use-module (guix packages)
  #:use-module (guix download)
  #:use-module (guix git-download)
  #:use-module (guix build-system cmake)
  #:use-module (guix build-system gnu)
  #:use-module (guix build-system go)
  #:use-module (guix build-system python)
  #:use-module (guix utils)
  #:use-module (gnu packages autotools)
  #:use-module (gnu packages base)
  #:use-module (gnu packages check)
  #:use-module (gnu packages compression)
  #:use-module (gnu packages glib)
  #:use-module (gnu packages golang)
  #:use-module (gnu packages linux)
  #:use-module (gnu packages networking)
  #:use-module (gnu packages pkg-config)
  #:use-module (gnu packages python)
  #:use-module (gnu packages python-crypto)
  #:use-module (gnu packages python-web)
  #:use-module (gnu packages python-xyz)
  #:use-module (gnu packages version-control)
  #:use-module (gnu packages virtualization))

(define %docker-version "19.03.12")

(define-public python-docker
  (package
    (name "python-docker")
    (version "3.7.3")
    (source
     (origin
       (method url-fetch)
       (uri (pypi-uri "docker" version))
       (sha256
        (base32
         "0qmrcvpaz37p85hfddsd4yc8hgqlkzs4cz09q9wmy0pz5pwajqm0"))))
    (build-system python-build-system)
    ;; TODO: Tests require a running Docker daemon.
    (arguments '(#:tests? #f))
    (inputs
     `(("python-requests" ,python-requests-2.20)
       ("python-six" ,python-six)
       ("python-urllib3" ,python-urllib3-1.24)
       ("python-websocket-client" ,python-websocket-client)))
    (propagated-inputs
     `(("python-docker-pycreds" ,python-docker-pycreds)
       ("python-paramiko" ,python-paramiko))) ; adds SSH support
    (home-page "https://github.com/docker/docker-py/")
    (synopsis "Python client for Docker")
    (description "Docker-Py is a Python client for the Docker container
management tool.")
    (license license:asl2.0)))

(define-public python-dockerpty
  (package
    (name "python-dockerpty")
    (version "0.4.1")
    (source
     (origin
       (method url-fetch)
       (uri (pypi-uri "dockerpty" version))
       (sha256
        (base32
         "1kjn64wx23jmr8dcc6g7bwlmrhfmxr77gh6iphqsl39sayfxdab9"))))
    (build-system python-build-system)
    (native-inputs
     `(("python-six" ,python-six)))
    (home-page "https://github.com/d11wtq/dockerpty")
    (synopsis "Python library to use the pseudo-TTY of a Docker container")
    (description "Docker PTY provides the functionality needed to operate the
pseudo-terminal (PTY) allocated to a Docker container using the Python
client.")
    (license license:asl2.0)))

(define-public docker-compose
  (package
    (name "docker-compose")
    (version "1.25.4")
    (source
     (origin
       (method url-fetch)
       (uri (pypi-uri "docker-compose" version))
       (sha256
        (base32
         "1ww8ckpj3n5jdg63qvmiqx3gk0fsrnynnnqj17fppymbwjzf5fps"))))
    (build-system python-build-system)
    ;; TODO: Tests require running Docker daemon.
    (arguments '(#:tests? #f))
    (inputs
     `(("python-cached-property"
        ,python-cached-property)
       ("python-docker" ,python-docker)
       ("python-dockerpty" ,python-dockerpty)
       ("python-docopt" ,python-docopt)
       ("python-jsonschema" ,python-jsonschema)
       ("python-pyyaml" ,python-pyyaml)
       ("python-requests" ,python-requests)
       ("python-six" ,python-six)
       ("python-texttable" ,python-texttable)
       ("python-websocket-client" ,python-websocket-client)))
    (home-page "https://www.docker.com/")
    (synopsis "Multi-container orchestration for Docker")
    (description "Docker Compose is a tool for defining and running
multi-container Docker applications.  A Compose file is used to configure an
application’s services.  Then, using a single command, the containers are
created and all the services are started as specified in the configuration.")
    (license license:asl2.0)))

(define-public python-docker-pycreds
  (package
    (name "python-docker-pycreds")
    (version "0.4.0")
    (source
      (origin
        (method url-fetch)
        (uri (pypi-uri "docker-pycreds" version))
        (sha256
         (base32
          "1m44smrggnqghxkqfl7vhapdw89m1p3vdr177r6cq17lr85jgqvc"))))
    (build-system python-build-system)
    (arguments
     `(#:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'fix-versioning
           (lambda _
             (substitute* "test-requirements.txt"
               (("3.0.2") ,(package-version python-pytest))
               (("2.3.1") ,(package-version python-pytest-cov))
               (("2.4.1") ,(package-version python-flake8)))
             #t)))))
    (native-inputs
     `(("python-flake8" ,python-flake8)
       ("python-pytest" ,python-pytest)
       ("python-pytest-cov" ,python-pytest-cov)))
    (propagated-inputs
     `(("python-six" ,python-six)))
    (home-page "https://github.com/shin-/dockerpy-creds")
    (synopsis
     "Python bindings for the Docker credentials store API")
    (description
     "Docker-Pycreds contains the Python bindings for the docker credentials
store API.  It allows programmers to interact with a Docker registry using
Python without keeping their credentials in a Docker configuration file.")
    (license license:asl2.0)))

(define-public containerd
  (package
    (name "containerd")
    (version "1.2.5")
    (source
     (origin
      (method git-fetch)
      (uri (git-reference
            (url "https://github.com/containerd/containerd")
            (commit (string-append "v" version))))
      (file-name (git-file-name name version))
      (sha256
       (base32 "0npbzixf3c0jvzm159vygvkydrr8h36c9sq50yv0mdinrys2bvg0"))
      (patches
        (search-patches "containerd-test-with-go1.13.patch"))))
    (build-system go-build-system)
    (arguments
     `(#:import-path "github.com/containerd/containerd"
       #:phases
       (modify-phases %standard-phases
         (add-before 'build 'chdir
           (lambda _
             (chdir "src/github.com/containerd/containerd")
             #t))
         (add-after 'chdir 'patch-paths
           (lambda* (#:key inputs outputs #:allow-other-keys)
             ;; TODO: Patch "socat", "unpigz".
             (substitute* "./runtime/v1/linux/runtime.go"
              (("defaultRuntime[ \t]*=.*")
               (string-append "defaultRuntime = \""
                              (assoc-ref inputs "runc")
                              "/sbin/runc\"\n"))
              (("defaultShim[ \t]*=.*")
               (string-append "defaultShim = \""
                              (assoc-ref outputs "out")
                              "/bin/containerd-shim\"\n")))
            (substitute* "./vendor/github.com/containerd/go-runc/runc.go"
              (("DefaultCommand[ \t]*=.*")
               (string-append "DefaultCommand = \""
                              (assoc-ref inputs "runc")
                              "/sbin/runc\"\n")))
            (substitute* "vendor/github.com/containerd/continuity/testutil/loopback/loopback_linux.go"
             (("exec\\.Command\\(\"losetup\"") ; )
              (string-append "exec.Command(\""
                             (assoc-ref inputs "util-linux")
                             "/sbin/losetup\""))) ;)
             #t))
         (replace 'build
           (lambda* (#:key (make-flags '()) #:allow-other-keys)
             (apply invoke "make" make-flags)))
         (replace 'install
           (lambda* (#:key outputs (make-flags '()) #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out")))
               (apply invoke "make" (string-append "DESTDIR=" out) "install"
                      make-flags)))))))
    (inputs
     `(("btrfs-progs" ,btrfs-progs)
       ("libseccomp" ,libseccomp)
       ("runc" ,runc)
       ("util-linux" ,util-linux)))
    (native-inputs
     `(("go" ,go)
       ("pkg-config" ,pkg-config)))
    (synopsis "Docker container runtime")
    (description "This package provides the container daemon for Docker.
It includes image transfer and storage, container execution and supervision,
network attachments.")
    (home-page "https://containerd.io/")
    (license license:asl2.0)))

;;; Private package that shouldn't be used directly; its purposes is to be
;;; used as a template for the various packages it contains.  It doesn't build
;;; anyway, as it needs many dependencies that aren't being satisfied.
(define docker-libnetwork
  ;; There are no recent release for libnetwork, so choose the last commit of
  ;; the branch that Docker uses, as can be seen in the Docker source file
  ;; 'hack/dockerfile/install/proxy.installer'.
  (let ((commit "4725f2163fb214a6312f3beae5991f838ec36326")
        (version "18.09")
        (revision "1"))
    (package
      (name "docker-libnetwork")
      (version (git-version version "1" commit))
      (source (origin
                (method git-fetch)
                (uri (git-reference
                      (url "https://github.com/docker/libnetwork")
                      (commit commit)))
                (file-name (git-file-name name version))
                (sha256
                 (base32
                  "1zpnxki8qfzha6ljahpwd3vkzmjhsvkmf73w6crm4ilxxw5vnpfb"))
                ;; Delete bundled ("vendored") free software source code.
                (modules '((guix build utils)))
                (snippet '(begin
                            (delete-file-recursively "vendor")
                            #t))))
      (build-system go-build-system)
      (arguments
       `(#:import-path "github.com/docker/libnetwork/"))
      (home-page "https://github.com/docker/libnetwork/")
      (synopsis "Networking for containers")
      (description "Libnetwork provides a native Go implementation for
connecting containers.  The goal of @code{libnetwork} is to deliver a robust
container network model that provides a consistent programming interface and
the required network abstractions for applications.")
      (license license:asl2.0))))

(define-public docker-libnetwork-cmd-proxy
  (package
    (inherit docker-libnetwork)
    (name "docker-libnetwork-cmd-proxy")
    (arguments
     `(#:import-path "github.com/docker/libnetwork/cmd/proxy"
       #:unpack-path "github.com/docker/libnetwork"
       #:install-source? #f))
    (native-inputs
     `(("go-sctp" ,go-sctp)
       ;; For tests.
       ("logrus" ,go-github-com-sirupsen-logrus)
       ("go-netlink" ,go-netlink)
       ("go-netns" ,go-netns)
       ("go-golang-org-x-crypto"
        ,go-golang-org-x-crypto)
       ("go-golang-org-x-sys" ,go-golang-org-x-sys)))
    (synopsis "Docker user-space proxy")
    (description "A proxy running in the user space.  It is used by the
built-in registry server of Docker.")
    (license license:asl2.0)))

;; TODO: Patch out modprobes for ip_vs, nf_conntrack,
;; brige, nf_conntrack_netlink, aufs.
(define-public docker
  (package
    (name "docker")
    (version %docker-version)
    (source
     (origin
       (method git-fetch)
       (uri (git-reference
             (url "https://github.com/docker/engine")
             (commit (string-append "v" version))))
       (file-name (git-file-name name version))
       (sha256
        (base32 "1dj6llfcgcbpq9q9j6b4wb0anbn1g5wzm8ikq2lyhg54i3154m93"))
       (patches
        (search-patches "docker-fix-tests.patch"))))
    (build-system gnu-build-system)
    (arguments
     `(#:modules
       ((guix build gnu-build-system)
        ((guix build go-build-system) #:prefix go:)
        (guix build union)
        (guix build utils))
       #:imported-modules
       (,@%gnu-build-system-modules
        (guix build union)
        (guix build go-build-system))
       #:phases
       (modify-phases %standard-phases
         (add-after 'unpack 'patch-paths
           (lambda* (#:key inputs #:allow-other-keys)
             (substitute* "builder/builder-next/executor_unix.go"
               (("CommandCandidates:.*runc.*")
                (string-append "CommandCandidates: []string{\""
                               (assoc-ref inputs "runc")
                               "/sbin/runc\"},\n")))
             (substitute* "vendor/github.com/containerd/go-runc/runc.go"
               (("DefaultCommand = .*")
                (string-append "DefaultCommand = \""
                               (assoc-ref inputs "runc")
                               "/sbin/runc\"\n")))
             (substitute* "vendor/github.com/containerd/containerd/runtime/v1/linux/runtime.go"
               (("defaultRuntime[ \t]*=.*")
                (string-append "defaultRuntime = \""
                               (assoc-ref inputs "runc")
                               "/sbin/runc\"\n"))
               (("defaultShim[ \t]*=.*")
                (string-append "defaultShim = \""
                               (assoc-ref inputs "containerd")
                               "/bin/containerd-shim\"\n")))
             (substitute* "daemon/daemon_unix.go"
               (("DefaultShimBinary = .*")
                (string-append "DefaultShimBinary = \""
                               (assoc-ref inputs "containerd")
                               "/bin/containerd-shim\"\n"))
               (("DefaultRuntimeBinary = .*")
                (string-append "DefaultRuntimeBinary = \""
                               (assoc-ref inputs "runc")
                               "/sbin/runc\"\n"))
               (("DefaultRuntimeName = .*")
                (string-append "DefaultRuntimeName = \""
                               (assoc-ref inputs "runc")
                               "/sbin/runc\"\n")))
             (substitute* "daemon/config/config.go"
               (("StockRuntimeName = .*")
                (string-append "StockRuntimeName = \""
                               (assoc-ref inputs "runc")
                               "/sbin/runc\"\n"))
               (("DefaultInitBinary = .*")
                (string-append "DefaultInitBinary = \""
                               (assoc-ref inputs "tini")
                               "/bin/tini\"\n")))
             (substitute* "daemon/config/config_common_unix_test.go"
               (("expectedInitPath: \"docker-init\"")
                (string-append "expectedInitPath: \""
                               (assoc-ref inputs "tini")
                               "/bin/tini\"")))
             (substitute* "vendor/github.com/moby/buildkit/executor/runcexecutor/executor.go"
               (("var defaultCommandCandidates = .*")
                (string-append "var defaultCommandCandidates = []string{\""
                               (assoc-ref inputs "runc") "/sbin/runc\"}")))
             (substitute* "vendor/github.com/docker/libnetwork/portmapper/proxy.go"
               (("var userlandProxyCommandName = .*")
                (string-append "var userlandProxyCommandName = \""
                               (assoc-ref inputs "docker-proxy")
                               "/bin/proxy\"\n")))
             (substitute* "pkg/archive/archive.go"
               (("string\\{\"xz")
                (string-append "string{\"" (assoc-ref inputs "xz") "/bin/xz")))
             ;; TODO: Remove when Docker proper uses v1.14.x to build
             (substitute* "registry/resumable/resumablerequestreader_test.go"
               (("I%27m%20not%20an%20url" all)
                (string-append "\"" all "\"")))
             ;; TODO: Remove when Docker proper uses v1.14.x to build
             (substitute* "vendor/gotest.tools/x/subtest/context.go"
               (("func \\(tc \\*testcase\\) Cleanup\\(" all)
                (string-append all "func()"))
               (("tc\\.Cleanup\\(" all)
                (string-append all "nil")))

             (let ((source-files (filter (lambda (name)
                                           (not (string-contains name "test")))
                                         (find-files "." "\\.go$"))))
               (let-syntax ((substitute-LookPath*
                             (syntax-rules ()
                               ((_ (source-text package relative-path) ...)
                                (substitute* source-files
                                  (((string-append "\\<exec\\.LookPath\\(\""
                                                   source-text
                                                   "\")"))
                                   (string-append "\""
                                                  (assoc-ref inputs package)
                                                  "/" relative-path
                                                  "\", error(nil)")) ...))))
                            (substitute-Command*
                             (syntax-rules ()
                               ((_ (source-text package relative-path) ...)
                                (substitute* source-files
                                  (((string-append "\\<(re)?exec\\.Command\\(\""
                                                   source-text
                                                   "\"") _ re?)
                                   (string-append (if re? re? "")
                                                  "exec.Command(\""
                                                  (assoc-ref inputs package)
                                                  "/" relative-path
                                                  "\"")) ...)))))
                 (substitute-LookPath*
                  ("containerd" "containerd" "bin/containerd")
                  ("ps" "procps" "bin/ps")
                  ("mkfs.xfs" "xfsprogs" "bin/mkfs.xfs")
                  ("lvmdiskscan" "lvm2" "sbin/lvmdiskscan")
                  ("pvdisplay" "lvm2" "sbin/pvdisplay")
                  ("blkid" "util-linux" "sbin/blkid")
                  ("unpigz" "pigz" "bin/unpigz")
                  ("iptables" "iptables" "sbin/iptables")
                  ("iptables-legacy" "iptables" "sbin/iptables")
                  ("ip" "iproute2" "sbin/ip"))

                 (substitute-Command*
                  ("modprobe" "kmod" "bin/modprobe")
                  ("pvcreate" "lvm2" "sbin/pvcreate")
                  ("vgcreate" "lvm2" "sbin/vgcreate")
                  ("lvcreate" "lvm2" "sbin/lvcreate")
                  ("lvconvert" "lvm2" "sbin/lvconvert")
                  ("lvchange" "lvm2" "sbin/lvchange")
                  ("mkfs.xfs" "xfsprogs" "sbin/mkfs.xfs")
                  ("xfs_growfs" "xfsprogs" "sbin/xfs_growfs")
                  ("mkfs.ext4" "e2fsprogs" "sbin/mkfs.ext4")
                  ("tune2fs" "e2fsprogs" "sbin/tune2fs")
                  ("blkid" "util-linux" "sbin/blkid")
                  ("resize2fs" "e2fsprogs" "sbin/resize2fs")
                  ("ps" "procps" "bin/ps")
                  ("losetup" "util-linux" "sbin/losetup")
                  ("uname" "coreutils" "bin/uname")
                  ("dbus-launch" "dbus" "bin/dbus-launch")
                  ("git" "git" "bin/git")))
               ;; docker-mountfrom ??
               ;; docker
               ;; docker-untar ??
               ;; docker-applyLayer ??
               ;; /usr/bin/uname
               ;; grep
               ;; apparmor_parser

               ;; Make compilation fail when, in future versions, Docker
               ;; invokes other programs we don't know about and thus don't
               ;; substitute.
               (substitute* source-files
                 ;; Search for Java in PATH.
                 (("\\<exec\\.Command\\(\"java\"")
                  "xxec.Command(\"java\"")
                 ;; Search for AUFS in PATH (mainline Linux doesn't support it).
                 (("\\<exec\\.Command\\(\"auplink\"")
                  "xxec.Command(\"auplink\"")
                 ;; Fail on other unsubstituted commands.
                 (("\\<exec\\.Command\\(\"([a-zA-Z0-9][a-zA-Z0-9_-]*)\""
                   _ executable)
                  (string-append "exec.Guix_doesnt_want_Command(\""
                                 executable "\""))
                 (("\\<xxec\\.Command")
                  "exec.Command")
                 ;; Search for ZFS in PATH.
                 (("\\<LookPath\\(\"zfs\"\\)") "LooxPath(\"zfs\")")
                 ;; Fail on other unsubstituted LookPaths.
                 (("\\<LookPath\\(\"") "Guix_doesnt_want_LookPath\\(\"")
                 (("\\<LooxPath") "LookPath")))
             #t))
         (add-after 'patch-paths 'delete-failing-tests
           (lambda _
             ;; Needs internet access.
             (delete-file "builder/remotecontext/git/gitutils_test.go")
             ;; Permission denied.
             (delete-file "daemon/graphdriver/devmapper/devmapper_test.go")
             ;; Operation not permitted (idtools.MkdirAllAndChown).
             (delete-file "daemon/graphdriver/vfs/vfs_test.go")
             ;; Timeouts after 5 min.
             (delete-file "plugin/manager_linux_test.go")
             ;; Operation not permitted.
             (delete-file "daemon/graphdriver/aufs/aufs_test.go")
             (delete-file "daemon/graphdriver/btrfs/btrfs_test.go")
             (delete-file "daemon/graphdriver/overlay/overlay_test.go")
             (delete-file "daemon/graphdriver/overlay2/overlay_test.go")
             (delete-file "pkg/chrootarchive/archive_unix_test.go")
             (delete-file "daemon/container_unix_test.go")
             ;; This file uses cgroups and /proc.
             (delete-file "pkg/sysinfo/sysinfo_linux_test.go")
             ;; This file uses cgroups.
             (delete-file "runconfig/config_test.go")
             ;; This file uses /var.
             (delete-file "daemon/oci_linux_test.go")
             #t))
         (replace 'configure
           (lambda _
             (setenv "DOCKER_GITCOMMIT" (string-append "v" ,%docker-version))
             (setenv "VERSION" (string-append ,%docker-version "-ce"))
             ;; Automatically use bundled dependencies.
             ;; TODO: Unbundle - see file "vendor.conf".
             (setenv "AUTO_GOPATH" "1")
             ;; Respectively, strip the symbol table and debug
             ;; information, and the DWARF symbol table.
             (setenv "LDFLAGS" "-s -w")
             ;; Make build faster
             (setenv "GOCACHE" "/tmp")
             #t))
         (add-before 'build 'setup-go-environment
           (assoc-ref go:%standard-phases 'setup-go-environment))
         (replace 'build
           (lambda _
             ;; Our LD doesn't like the statically linked relocatable things
             ;; that go produces, so install the dynamic version of
             ;; dockerd instead.
             (invoke "hack/make.sh" "dynbinary")))
         (replace 'check
           (lambda _
             ;; The build process generated a file because the environment
             ;; variable "AUTO_GOPATH" was set.  Use it.
             (setenv "GOPATH" (string-append (getcwd) "/.gopath"))
             ;; ".gopath/src/github.com/docker/docker" is a link to the current
             ;; directory and chdir would canonicalize to that.
             ;; But go needs to have the uncanonicalized directory name, so
             ;; store that.
             (setenv "PWD" (string-append (getcwd)
                                          "/.gopath/src/github.com/docker/docker"))
             (with-directory-excursion ".gopath/src/github.com/docker/docker"
               (invoke "hack/test/unit"))
             (setenv "PWD" #f)
             #t))
         (replace 'install
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (out-bin (string-append out "/bin")))
               (install-file "bundles/dynbinary-daemon/dockerd" out-bin)
               (install-file (string-append "bundles/dynbinary-daemon/dockerd-"
                                            (getenv "VERSION"))
                             out-bin)
               #t)))
         (add-after 'install 'remove-go-references
           (assoc-ref go:%standard-phases 'remove-go-references)))))
    (inputs
     `(("btrfs-progs" ,btrfs-progs)
       ("containerd" ,containerd)       ; for containerd-shim
       ("coreutils" ,coreutils)
       ("dbus" ,dbus)
       ("docker-proxy" ,docker-libnetwork-cmd-proxy)
       ("e2fsprogs" ,e2fsprogs)
       ("git" ,git)
       ("iproute2" ,iproute)
       ("iptables" ,iptables)
       ("kmod" ,kmod)
       ("libseccomp" ,libseccomp)
       ("pigz" ,pigz)
       ("procps" ,procps)
       ("runc" ,runc)
       ("util-linux" ,util-linux)
       ("lvm2" ,lvm2)
       ("tini" ,tini)
       ("xfsprogs" ,xfsprogs)
       ("xz" ,xz)))
    (native-inputs
     `(("eudev" ,eudev)      ; TODO: Should be propagated by lvm2 (.pc -> .pc)
       ("go" ,go)
       ("gotestsum" ,gotestsum)
       ("pkg-config" ,pkg-config)))
    (synopsis "Docker container component library, and daemon")
    (description "This package provides a framework to assemble specialized
container systems.  It includes components for orchestration, image
management, secret management, configuration management, networking,
provisioning etc.")
    (home-page "https://mobyproject.org/")
    (license license:asl2.0)))

(define-public docker-cli
  (package
    (name "docker-cli")
    (version %docker-version)
    (source
     (origin
      (method git-fetch)
      (uri (git-reference
            (url "https://github.com/docker/cli")
            (commit (string-append "v" version))))
      (file-name (git-file-name name version))
      (sha256
       (base32 "1bynmnaykhh1m42v6bxparlpm9kajpqsvlrlwgz1b9ivcklf5ik6"))))
    (build-system go-build-system)
    (arguments
     `(#:import-path "github.com/docker/cli"
       ;; TODO: Tests require a running Docker daemon.
       #:tests? #f
       #:phases
       (modify-phases %standard-phases
         (add-before 'build 'setup-environment-2
           (lambda _
             ;; Respectively, strip the symbol table and debug
             ;; information, and the DWARF symbol table.
             (setenv "LDFLAGS" "-s -w")

             ;; Make sure "docker -v" prints a usable version string.
             (setenv "VERSION" ,%docker-version)

             ;; Make build reproducible.
             (setenv "BUILDTIME" "1970-01-01 00:00:01.000000000+00:00")
             (symlink "src/github.com/docker/cli/scripts" "./scripts")
             (symlink "src/github.com/docker/cli/docker.Makefile" "./docker.Makefile")
             #t))
         (replace 'build
           (lambda _
             (invoke "./scripts/build/dynbinary")))
         (replace 'check
           (lambda* (#:key make-flags tests? #:allow-other-keys)
             (setenv "PATH" (string-append (getcwd) "/build:" (getenv "PATH")))
             (if tests?
                 ;; Use the newly-built docker client for the tests.
                 (with-directory-excursion "src/github.com/docker/cli"
                   ;; TODO: Run test-e2e as well?
                   (apply invoke "make" "-f" "docker.Makefile" "test-unit"
                          (or make-flags '())))
                 #t)))
         (replace 'install
           (lambda* (#:key outputs #:allow-other-keys)
             (let* ((out (assoc-ref outputs "out"))
                    (out-bin (string-append out "/bin"))
                    (etc (string-append out "/etc")))
               (with-directory-excursion "src/github.com/docker/cli/contrib/completion"
                 (install-file "bash/docker"
                               (string-append etc "/bash_completion.d"))
                 (install-file "fish/docker.fish"
                               (string-append etc "/fish/completions"))
                 (install-file "zsh/_docker"
                               (string-append etc "/zsh/site-functions")))
               (chdir "build")
               (install-file "docker" out-bin)
               #t))))))
    (native-inputs
     `(("go" ,go)
       ("libltdl" ,libltdl)
       ("pkg-config" ,pkg-config)))
    (synopsis "Command line interface to Docker")
    (description "This package provides a command line interface to Docker.")
    (home-page "https://www.docker.com/")
    (license license:asl2.0)))

(define-public cqfd
  (package
    (name "cqfd")
    (version "5.1.0")
    (source (origin
              (method git-fetch)
              (uri (git-reference
                    (url "https://github.com/savoirfairelinux/cqfd")
                    (commit (string-append "v" version))))
              (file-name (git-file-name name version))
              (sha256
               (base32
                "1xhydz01f2rrnw7rmnaxh3f3q1ariq7j2ig0i0w1p3wn10l3q0nv"))))
    (build-system gnu-build-system)
    (arguments
     ;; The test suite requires a docker daemon and connectivity.
     `(#:tests? #f
       #:phases
       (modify-phases %standard-phases
         (delete 'configure)
         (delete 'build)
         (replace 'install
           (lambda* (#:key outputs #:allow-other-keys)
             (let ((out (assoc-ref outputs "out")))
               ;; Fix the directory of the bash completion.
               (substitute* "Makefile"
                 (("completionsdir=.*$")
                  (string-append "completionsdir=" out
                                 "/etc/bash_completion.d; \\\n")))
               (invoke "make" "install"
                       (string-append "PREFIX=" out))))))))
    (home-page "https://github.com/savoirfairelinux/cqfd")
    (synopsis "Convenience wrapper for Docker")
    (description "cqfd is a Bash script that provides a quick and convenient
way to run commands in the current directory, but within a Docker container
defined in a per-project configuration file.")
    (license license:gpl3+)))

(define-public tini
  (package
    (name "tini")
    (version "0.18.0")
    (source (origin
              (method git-fetch)
              (uri (git-reference
                    (url "https://github.com/krallin/tini")
                    (commit (string-append "v" version))))
              (file-name (git-file-name name version))
              (sha256
               (base32
                "1h20i3wwlbd8x4jr2gz68hgklh0lb0jj7y5xk1wvr8y58fip1rdn"))))
    (build-system cmake-build-system)
    (arguments
     `(#:tests? #f                    ;tests require a Docker daemon
       #:phases (modify-phases %standard-phases
                  (add-after 'unpack 'disable-static-build
                    ;; Disable the static build as it fails to install, with
                    ;; the error: "No valid ELF RPATH or RUNPATH entry exists
                    ;; in the file".
                    (lambda _
                      (substitute* "CMakeLists.txt"
                        ((".*tini-static.*") ""))
                      #t)))))
    (home-page "https://github.com/krallin/tini")
    (synopsis "Tiny but valid init for containers")
    (description "Tini is an init program specifically designed for use with
containers.  It manages a single child process and ensures that any zombie
processes produced from it are reaped and that signals are properly forwarded.
Tini is integrated with Docker.")
    (license license:expat)))