aboutsummaryrefslogtreecommitdiff
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2015 Andy Wingo <wingo@igalia.com>
;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2017, 2018 Clément Lassieur <clement@lassieur.org>
;;; Copyright © 2021 Xinglu Chen <public@yoctocell.xyz>
;;; Copyright © 2021, 2022 Maxim Cournoyer <maxim.cournoyer@gmail.com>
;;; Copyright © 2021 Andrew Tropin <andrew@trop.in>
;;; Copyright © 2022 Maxime Devos <maximedevos@telenet.be>
;;; Copyright © 2023 Bruno Victal <mirai@makinata.eu>
;;; Copyright © 2024 Herman Rimm <herman@rimm.ee>
;;;
;;; 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 services configuration)
  #:use-module (guix packages)
  #:use-module (guix records)
  #:use-module (guix gexp)
  #:use-module ((guix utils) #:select (source-properties->location))
  #:use-module ((guix diagnostics)
                #:select (formatted-message location-file &error-location
                          warning))
  #:use-module ((guix modules) #:select (file-name->module-name))
  #:use-module (guix i18n)
  #:autoload   (texinfo) (texi-fragment->stexi)
  #:autoload   (texinfo serialize) (stexi->texi)
  #:use-module (ice-9 curried-definitions)
  #:use-module (ice-9 format)
  #:use-module (ice-9 match)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-26)
  #:use-module (srfi srfi-34)
  #:use-module (srfi srfi-35)
  #:use-module (srfi srfi-171)
  #:export (configuration-field
            configuration-field-name
            configuration-field-type
            configuration-missing-field
            configuration-field-error
            configuration-field-sanitizer
            configuration-field-serializer
            configuration-field-getter
            configuration-field-default-value-thunk
            configuration-field-documentation

            configuration-error?

            define-configuration
            define-configuration/no-serialization
            no-serialization

            empty-serializer?
            tfilter-maybe-value
            base-transducer

            serialize-configuration
            define-maybe
            define-maybe/no-serialization
            %unset-value
            maybe-value
            maybe-value-set?
            generate-documentation
            configuration->documentation
            empty-serializer
            serialize-package

            filter-configuration-fields

            interpose
            list-of

            list-of-packages?
            list-of-strings?
            list-of-symbols?
            alist?
            serialize-file-like
            text-config?
            serialize-text-config
            generic-serialize-alist-entry
            generic-serialize-alist))

;;; Commentary:
;;;
;;; Syntax for creating Scheme bindings to complex configuration files.
;;;
;;; Code:

(define-condition-type &configuration-error &error
  configuration-error?)

(define (configuration-error message)
  (raise (condition (&message (message message))
                    (&configuration-error))))
(define (configuration-field-error loc field value)
  (raise (apply
          make-compound-condition
          (formatted-message (G_ "invalid value ~s for field '~a'")
                             value field)
          (condition (&configuration-error))
          (if loc
              (list (condition
                     (&error-location (location loc))))
              '()))))

(define (configuration-missing-field kind field)
  (configuration-error
   (format #f "~a configuration missing required field ~a" kind field)))
(define (configuration-missing-default-value kind field)
  (configuration-error
   (format #f "The field `~a' of the `~a' configuration record \
does not have a default value" field kind)))

(define-record-type* <configuration-field>
  configuration-field make-configuration-field configuration-field?
  (name configuration-field-name)
  (type configuration-field-type)
  (getter configuration-field-getter)
  (predicate configuration-field-predicate)
  (sanitizer configuration-field-sanitizer)
  (serializer configuration-field-serializer)
  (default-value-thunk configuration-field-default-value-thunk)
  (documentation configuration-field-documentation))

(define (empty-serializer? field)
  "Predicate that checks whether FIELD is exempt from serialization."
  (eq? empty-serializer
       (configuration-field-serializer field)))

(define (tfilter-maybe-value config)
  "Return a transducer for CONFIG that removes all maybe-type fields whose
value is '%unset-marker."
  (tfilter (lambda (field)
             (let ((field-value ((configuration-field-getter field) config)))
               (maybe-value-set? field-value)))))

(define (base-transducer config)
  "Return a transducer for CONFIG that calls the serializing procedures only
for fields marked for serialization and whose values are not '%unset-marker."
  (compose (tremove empty-serializer?)
           ;; Only serialize fields whose value isn't '%unset-marker%.
           (tfilter-maybe-value config)
           (tmap (lambda (field)
                   ((configuration-field-serializer field)
                    (configuration-field-name field)
                    ((configuration-field-getter field) config))))))

(define (serialize-configuration config fields)
  "Return a G-expression that contains the values corresponding to the
FIELDS of CONFIG, a record that has been generated by `define-configuration'.
The G-expression can then be serialized to disk by using something like
`mixed-text-file'."
  #~(string-append
     #$@(list-transduce (base-transducer config) rcons fields)))

(define-syntax-rule (id ctx parts ...)
  "Assemble PARTS into a raw (unhygienic) identifier."
  (datum->syntax ctx (symbol-append (syntax->datum parts) ...)))

(define (define-maybe-helper serialize? prefix syn)
  (syntax-case syn ()
    ((_ stem)
     (with-syntax
         ((stem?            (id #'stem #'stem #'?))
          (maybe-stem?      (id #'stem #'maybe- #'stem #'?))
          (serialize-stem   (if prefix
                                (id #'stem prefix #'serialize- #'stem)
                                (id #'stem #'serialize- #'stem)))
          (serialize-maybe-stem (if prefix
                                    (id #'stem prefix #'serialize-maybe- #'stem)
                                    (id #'stem #'serialize-maybe- #'stem))))
       #`(begin
           (define (maybe-stem? val)
             (or (not (maybe-value-set? val))
                 (stem? val)))
           #,@(if serialize?
                  (list #'(define (serialize-maybe-stem field-name val)
                            (if (stem? val)
                                (serialize-stem field-name val)
                                "")))
                  '()))))))

(define-syntax define-maybe
  (lambda (x)
    (syntax-case x (no-serialization prefix)
      ((_ stem (no-serialization))
       (define-maybe-helper #f #f #'(_ stem)))
      ((_ stem (prefix serializer-prefix))
       (define-maybe-helper #t #'serializer-prefix #'(_ stem)))
      ((_ stem)
       (define-maybe-helper #t #f #'(_ stem))))))

(define-syntax-rule (define-maybe/no-serialization stem)
  (define-maybe stem (no-serialization)))

(define (normalize-field-type+def s)
  (syntax-case s ()
    ((field-type def)
     (identifier? #'field-type)
     (values #'(field-type def)))
    ((field-type)
     (identifier? #'field-type)
     (values #'(field-type %unset-value)))
    (field-type
     (identifier? #'field-type)
     (values #'(field-type %unset-value)))))

(define (define-configuration-helper serialize? serializer-prefix syn)

  (define (normalize-extra-args s)
    "Extract and normalize arguments following @var{doc}."
    (let loop ((s s)
               (sanitizer* #f)
               (serializer* #f))
      (syntax-case s (sanitizer serializer empty-serializer)
        (((sanitizer proc) tail ...)
         (if sanitizer*
             (syntax-violation 'sanitizer
                               "duplicate entry" #'proc)
             (loop #'(tail ...) #'proc serializer*)))
        (((serializer proc) tail ...)
         (if serializer*
             (syntax-violation 'serializer
                               "duplicate or conflicting entry" #'proc)
             (loop #'(tail ...) sanitizer* #'proc)))
        ((empty-serializer tail ...)
         (if serializer*
             (syntax-violation 'empty-serializer
                               "duplicate or conflicting entry" #f)
             (loop #'(tail ...) sanitizer* #'empty-serializer)))
        (()  ; stop condition
         (values (list sanitizer* serializer*)))
        ((proc)  ; TODO: deprecated, to be removed.
         (not (or sanitizer* serializer*))
         (begin
           (warning #f (G_ "specifying serializers after documentation is \
deprecated, use (serializer ~a) instead~%") (syntax->datum #'proc))
           (values (list #f #'proc)))))))

  (syntax-case syn ()
    ((_ stem (field field-type+def doc extra-args ...) ...)
     (with-syntax
         ((((field-type def) ...)
           (map normalize-field-type+def #'(field-type+def ...)))
          (((sanitizer* serializer*) ...)
           (map normalize-extra-args #'((extra-args ...) ...))))
       (with-syntax
           (((field-getter ...)
             (map (lambda (field)
                    (id #'stem #'stem #'- field))
                  #'(field ...)))
            ((field-predicate ...)
             (map (lambda (type)
                    (id #'stem type #'?))
                  #'(field-type ...)))
            ((field-default ...)
             (map (match-lambda
                    ((field-type default-value)
                     default-value))
                  #'((field-type def) ...)))
            ((field-sanitizer ...)
             #'(sanitizer* ...))
            ((field-serializer ...)
             (map (lambda (type proc)
                    (and serialize?
                         (or proc
                             (if serializer-prefix
                                 (id #'stem serializer-prefix #'serialize- type)
                                 (id #'stem #'serialize- type)))))
                  #'(field-type ...)
                  #'(serializer* ...))))
         (define (default-field-sanitizer name pred)
           ;; Define a macro for use as a record field sanitizer, where NAME
           ;; is the name of the field and PRED is the predicate that tells
           ;; whether a value is valid for this field.
           #`(define-syntax #,(id #'stem #'validate- #'stem #'- name)
               (lambda (s)
                 ;; Make sure the given VALUE, for field NAME, passes PRED.
                 (syntax-case s ()
                   ((_ value)
                    (with-syntax ((name #'#,name)
                                  (pred #'#,pred)
                                  (loc (datum->syntax #'value
                                                      (syntax-source #'value))))
                      #'(if (pred value)
                            value
                            (configuration-field-error
                             (and=> 'loc source-properties->location)
                             'name value))))))))

         #`(begin
             ;; Define field validation macros.
             #,@(filter-map (lambda (name pred sanitizer)
                              (if sanitizer
                                  #f
                                  (default-field-sanitizer name pred)))
                            #'(field ...)
                            #'(field-predicate ...)
                            #'(field-sanitizer ...))

             (define-record-type* #,(id #'stem #'< #'stem #'>)
               stem
               #,(id #'stem #'make- #'stem)
               #,(id #'stem #'stem #'?)
               #,@(map (lambda (name getter def sanitizer)
                         #`(#,name #,getter
                                   (default #,def)
                                   (sanitize
                                    #,(or sanitizer
                                          (id #'stem
                                              #'validate- #'stem #'- name)))))
                       #'(field ...)
                       #'(field-getter ...)
                       #'(field-default ...)
                       #'(field-sanitizer ...))
               (%location #,(id #'stem #'stem #'-source-location)
                          (default (and=> (current-source-location)
                                          source-properties->location))
                          (innate)))

             (define #,(id #'stem #'stem #'-fields)
               (list (configuration-field
                      (name 'field)
                      (type 'field-type)
                      (getter field-getter)
                      (predicate field-predicate)
                      (sanitizer
                       (or field-sanitizer
                           (id #'stem #'validate- #'stem #'- #'field)))
                      (serializer field-serializer)
                      (default-value-thunk
                        (lambda ()
                          (if (maybe-value-set? (syntax->datum field-default))
                              field-default
                              (configuration-missing-default-value
                               '#,(id #'stem #'% #'stem) 'field))))
                      (documentation doc))
                     ...))))))))

(define no-serialization         ;syntactic keyword for 'define-configuration'
  '(no serialization))

(define-syntax define-configuration
  (lambda (s)
    (syntax-case s (no-serialization prefix)
      ((_ stem (field field-type+def doc custom-serializer ...) ...
          (no-serialization))
       (define-configuration-helper
         #f #f #'(_ stem (field field-type+def doc custom-serializer ...)
                 ...)))
      ((_ stem  (field field-type+def doc custom-serializer ...) ...
          (prefix serializer-prefix))
       (define-configuration-helper
         #t #'serializer-prefix #'(_ stem (field field-type+def
                                                 doc custom-serializer ...)
                 ...)))
      ((_ stem (field field-type+def doc custom-serializer ...) ...)
       (define-configuration-helper
         #t #f #'(_ stem (field field-type+def doc custom-serializer ...)
                 ...))))))

(define-syntax-rule (define-configuration/no-serialization
                      stem (field field-type+def
                                  doc custom-serializer ...) ...)
  (define-configuration stem (field field-type+def
                                    doc custom-serializer ...) ...
    (no-serialization)))

(define (empty-serializer field-name val) "")
(define serialize-package empty-serializer)

;; Ideally this should be an implementation detail, but we export it
;; to provide a simpler API that enables unsetting a configuration
;; field that has a maybe type, but also a default value.  We give it
;; a value that sticks out to the reader when something goes wrong.
;;
;; An example use-case would be something like a network application
;; that uses a default port, but the field can explicitly be unset to
;; request a random port at startup.
(define %unset-value '%unset-marker%)

(define (maybe-value-set? value)
  "Predicate to check whether a 'maybe' value was explicitly provided."
  (not (eq? %unset-value value)))

;; Ideally there should be a compiler macro for this predicate, that expands
;; to a conditional that only instantiates the default value when needed.
(define* (maybe-value value #:optional (default #f))
  "Returns VALUE, unless it is the unset value, in which case it returns
DEFAULT."
  (if (maybe-value-set? value)
      value
      default))

;; A little helper to make it easier to document all those fields.
(define (generate-documentation documentation documentation-name)
  (define (str x) (object->string x))

  (define (package->symbol package)
    "Return the first symbol name of a package that matches PACKAGE, else #f."
    (let* ((module (file-name->module-name
                    (location-file (package-location package))))
           (symbols (filter-map
                     identity
                     (module-map (lambda (symbol var)
                                   (and (equal? package (variable-ref var))
                                        symbol))
                                 (resolve-module module)))))
      (if (null? symbols)
          #f
          (first symbols))))

  (define (generate configuration-name)
    (match (assq-ref documentation configuration-name)
      ((fields . sub-documentation)
       `((deftp (% (category "Data Type") (name ,(str configuration-name)))
           (para "Available " (code ,(str configuration-name)) " fields are:")
           (table
            (% (formatter (asis)))
            ,@(map
               (lambda (f)
                 (let ((field-name (configuration-field-name f))
                       (field-type (configuration-field-type f))
                       (field-docs (cdr (texi-fragment->stexi
                                         (configuration-field-documentation f))))
                       (default (catch #t
                                  (configuration-field-default-value-thunk f)
                                  (lambda _ '%invalid))))
                   (define (show-default? val)
                     (or (string? val) (number? val) (boolean? val)
                         (package? val)
                         (and (symbol? val) (not (eq? val '%invalid)))
                         (and (list? val) (and-map show-default? val))))

                   (define (show-default val)
                     (cond
                      ((package? val)
                       (symbol->string (package->symbol val)))
                      (((list-of package?) val)
                       (format #f "(~{~a~^ ~})" (map package->symbol val)))
                      (else (str val))))

                   `(entry (% (heading
                               (code ,(str field-name))
                               ,@(if (show-default? default)
                                     `(" (default: "
                                       (code ,(show-default default)) ")")
                                     '())
                               " (type: " ,(str field-type) ")"))
                           (para ,@field-docs)
                           ,@(append-map
                              generate
                              (filter-map
                                (match-lambda
                                  ((name config)
                                   (and (eq? name field-name)
                                        config)))
                                sub-documentation)))))
               fields)))))))
  (stexi->texi `(*fragment* . ,(generate documentation-name))))

(define (configuration->documentation configuration-symbol)
  "Take CONFIGURATION-SYMBOL, the symbol corresponding to the name used when
defining a configuration record with DEFINE-CONFIGURATION, and output the
Texinfo documentation of its fields."
  ;; This is helper for a simple, straight-forward application of
  ;; GENERATE-DOCUMENTATION.
  (let ((fields-getter (module-ref (current-module)
                                   (symbol-append configuration-symbol
                                                  '-fields))))
    (display (generate-documentation `((,configuration-symbol ,fields-getter))
                                     configuration-symbol))))

(define* (filter-configuration-fields configuration-fields fields
                                      #:optional negate?)
  "Retrieve the fields listed in FIELDS from CONFIGURATION-FIELDS.
If NEGATE? is @code{#t}, retrieve all fields except FIELDS."
  (filter (lambda (field)
            (let ((member? (member (configuration-field-name field) fields)))
              (if (not negate?) member? (not member?))))
          configuration-fields))


(define* (interpose ls  #:optional (delimiter "\n") (grammar 'infix))
  "Same as @code{string-join}, but without join and string, returns a
DELIMITER interposed LS.  Support 'infix and 'suffix GRAMMAR values."
  (when (not (member grammar '(infix suffix)))
    (raise
     (formatted-message
      (G_ "The GRAMMAR value must be 'infix or 'suffix, but ~a provided.")
      grammar)))
  (fold-right (lambda (e acc)
                (cons e
                      (if (and (null? acc) (eq? grammar 'infix))
                          acc
                          (cons delimiter acc))))
              '() ls))


;;;
;;; Commonly used predicates
;;;

(define (list-of pred?)
  "Return a procedure that takes a list and check if all the elements of
the list result in @code{#t} when applying PRED? on them."
    (lambda (x)
      (if (list? x)
          (every pred? x)
          #f)))

(define list-of-packages?
  (list-of package?))

(define list-of-strings?
  (list-of string?))

(define list-of-symbols?
  (list-of symbol?))


;;;
;;; Special serializers
;;;

(define alist?
  (list-of pair?))

(define serialize-file-like empty-serializer)

(define (text-config? config)
  (list-of file-like?))

(define (serialize-text-config field-name val)
  #~(string-append
     #$@(interpose
         (map
          (lambda (e)
            #~(begin
                (use-modules (ice-9 rdelim))
                (with-fluids ((%default-port-encoding "UTF-8"))
                  (with-input-from-file #$e read-string))))
          val)
         "\n" 'suffix)))

(define ((generic-serialize-alist-entry serialize-field) entry)
  "Apply the SERIALIZE-FIELD procedure on the field and value of ENTRY."
  (match entry
    ((field . val) (serialize-field field val))))

(define (generic-serialize-alist combine serialize-field fields)
  "Generate a configuration from an association list FIELDS.

SERIALIZE-FIELD is a procedure that takes two arguments, it will be
applied on the fields and values of FIELDS using the
@code{generic-serialize-alist-entry} procedure.

COMBINE is a procedure that takes one or more arguments and combines
all the alist entries into one value, @code{string-append} or
@code{append} are usually good candidates for this."
  (apply combine
         (map (generic-serialize-alist-entry serialize-field) fields)))
n713'>713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
;;; GNU Guix --- Functional package management for GNU
;;; Copyright © 2017 Julien Lepiller <julien@lepiller.eu>
;;; Copyright © 2017 Clément Lassieur <clement@lassieur.org>
;;; Copyright © 2017 Mathieu Othacehe <m.othacehe@gmail.com>
;;; Copyright © 2021 Guillaume Le Vaillant <glv@posteo.net>
;;; Copyright © 2021 Solene Rapenne <solene@perso.pw>
;;; Copyright © 2021 Domagoj Stolfa <ds815@gmx.com>
;;; Copyright © 2021 Tobias Geerinckx-Rice <me@tobias.gr>
;;; Copyright © 2021 Raghav Gururajan <rg@raghavgururajan.name>
;;; Copyright © 2021 jgart <jgart@dismail.de>
;;; Copyright © 2021 Nathan Dehnel <ncdehnel@gmail.com>
;;; Copyright © 2022 Cameron V Chaparro <cameron@cameronchaparro.com>
;;; Copyright © 2022 Timo Wilken <guix@twilken.net>
;;; Copyright © 2023 Maxim Cournoyer <maxim.cournoyer@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 services vpn)
  #:use-module (gnu services)
  #:use-module (gnu services configuration)
  #:use-module (gnu services dbus)
  #:use-module (gnu services mcron)
  #:use-module (gnu services shepherd)
  #:use-module (gnu system shadow)
  #:use-module (gnu packages admin)
  #:use-module (gnu packages vpn)
  #:use-module (guix modules)
  #:use-module (guix packages)
  #:use-module (guix records)
  #:use-module (guix gexp)
  #:use-module (guix i18n)
  #:use-module (guix deprecation)
  #:use-module (srfi srfi-1)
  #:use-module (ice-9 format)
  #:use-module (ice-9 match)
  #:use-module (ice-9 regex)
  #:export (openvpn-client-service  ; deprecated
            openvpn-server-service  ; deprecated
            openvpn-client-service-type
            openvpn-server-service-type
            openvpn-client-configuration
            openvpn-server-configuration
            openvpn-remote-configuration
            openvpn-ccd-configuration
            generate-openvpn-client-documentation
            generate-openvpn-server-documentation

            strongswan-configuration
            strongswan-service-type

            wireguard-peer
            wireguard-peer?
            wireguard-peer-name
            wireguard-peer-endpoint
            wireguard-peer-allowed-ips
            wireguard-peer-public-key
            wireguard-peer-preshared-key
            wireguard-peer-keep-alive

            wireguard-configuration
            wireguard-configuration?
            wireguard-configuration-wireguard
            wireguard-configuration-interface
            wireguard-configuration-addresses
            wireguard-configuration-port
            wireguard-configuration-dns
            wireguard-configuration-monitor-ips?
            wireguard-configuration-monitor-ips-interval
            wireguard-configuration-private-key
            wireguard-configuration-peers
            wireguard-configuration-pre-up
            wireguard-configuration-post-up
            wireguard-configuration-pre-down
            wireguard-configuration-post-down
            wireguard-configuration-table

            wireguard-service-type))

;;;
;;; Bitmask.
;;;

(define-public bitmask-service-type
  (service-type
   (name 'bitmask)
   (description "Setup the @uref{https://bitmask.net, Bitmask} VPN application.")
   (default-value bitmask)
   (extensions
    (list
     ;; Add bitmask to the system profile.
     (service-extension profile-service-type list)
     ;; Configure polkit policy of bitmask.
     (service-extension polkit-service-type list)))))

;;;
;;; OpenVPN.
;;;

(define (uglify-field-name name)
  (match name
    ('verbosity "verb")
    (_ (let ((str (symbol->string name)))
         (if (string-suffix? "?" str)
             (substring str 0 (1- (string-length str)))
             str)))))

(define (serialize-field field-name val)
  (if (eq? field-name 'pid-file)
      (format #t "")
      (format #t "~a ~a\n" (uglify-field-name field-name) val)))
(define serialize-string serialize-field)
(define-maybe string)
(define (serialize-boolean field-name val)
  (if val
      (serialize-field field-name "")
      (format #t "")))

(define (ip-mask? val)
  (and (string? val)
       (if (string-match "^([0-9]+\\.){3}[0-9]+ ([0-9]+\\.){3}[0-9]+$" val)
           (let ((numbers (string-tokenize val char-set:digit)))
             (all-lte numbers (list 255 255 255 255 255 255 255 255)))
           #f)))
(define serialize-ip-mask serialize-string)

(define-syntax define-enumerated-field-type
  (lambda (x)
    (define (id-append ctx . parts)
      (datum->syntax ctx (apply symbol-append (map syntax->datum parts))))
    (syntax-case x ()
      ((_ name (option ...))
       #`(begin
           (define (#,(id-append #'name #'name #'?) x)
             (memq x '(option ...)))
           (define (#,(id-append #'name #'serialize- #'name) field-name val)
             (serialize-field field-name val)))))))

(define-enumerated-field-type proto
  (udp tcp udp6 tcp6))
(define-enumerated-field-type dev
  (tun tap))

(define key-usage? boolean?)
(define (serialize-key-usage field-name value)
  (if value
      (format #t "remote-cert-tls server\n")
      #f))

(define bind? boolean?)
(define (serialize-bind field-name value)
  (if value
      #f
      (format #t "nobind\n")))

(define resolv-retry? boolean?)
(define (serialize-resolv-retry field-name value)
  (if value
      (format #t "resolv-retry infinite\n")
      #f))

(define (serialize-tls-auth role location)
  (if location
      (serialize-field 'tls-auth
                       (string-append location " " (match role
                                                     ('server "0")
                                                     ('client "1"))))
      #f))
(define (tls-auth? val)
  (or (eq? val #f)
      (string? val)))
(define (serialize-tls-auth-server field-name val)
  (serialize-tls-auth 'server val))
(define (serialize-tls-auth-client field-name val)
  (serialize-tls-auth 'client val))
(define tls-auth-server? tls-auth?)
(define tls-auth-client? tls-auth?)

(define (serialize-number field-name val)
  (serialize-field field-name (number->string val)))

(define (all-lte left right)
  (if (eq? left '())
      (eq? right '())
      (and (<= (string->number (car left)) (car right))
           (all-lte (cdr left) (cdr right)))))

(define (cidr4? val)
  (if (string? val)
      (if (string-match "^([0-9]+\\.){3}[0-9]+/[0-9]+$" val)
          (let ((numbers (string-tokenize val char-set:digit)))
            (all-lte numbers (list 255 255 255 255 32)))
          #f)
      (eq? val #f)))

(define (cidr6? val)
  (if (string? val)
      (string-match "^([0-9a-f]{0,4}:){0,8}/[0-9]{1,3}$" val)
      (eq? val #f)))

(define (serialize-cidr4 field-name val)
  (if (eq? val #f) #f (serialize-field field-name val)))

(define (serialize-cidr6 field-name val)
  (if (eq? val #f) #f (serialize-field field-name val)))

(define (ip? val)
  (if (string? val)
      (if (string-match "^([0-9]+\\.){3}[0-9]+$" val)
          (let ((numbers (string-tokenize val char-set:digit)))
            (all-lte numbers (list 255 255 255 255)))
          #f)
      (eq? val #f)))
(define (serialize-ip field-name val)
  (if (eq? val #f) #f (serialize-field field-name val)))

(define (keepalive? val)
  (and (list? val)
       (and (number? (car val))
            (number? (car (cdr val))))))
(define (serialize-keepalive field-name val)
  (format #t "~a ~a ~a\n" (uglify-field-name field-name)
          (number->string (car val)) (number->string (car (cdr val)))))

(define gateway? boolean?)
(define (serialize-gateway field-name val)
  (and val
       (format #t "push \"redirect-gateway\"\n")))


(define-configuration openvpn-remote-configuration
  (name
   (string "my-server")
   "Server name.")
  (port
   (number 1194)
   "Port number the server listens to."))

(define-configuration openvpn-ccd-configuration
  (name
   (string "client")
   "Client name.")
  (iroute
   (ip-mask #f)
   "Client own network")
  (ifconfig-push
   (ip-mask #f)
   "Client VPN IP."))

(define (openvpn-remote-list? val)
  (and (list? val)
       (or (eq? val '())
           (and (openvpn-remote-configuration? (car val))
                (openvpn-remote-list? (cdr val))))))
(define (serialize-openvpn-remote-list field-name val)
  (for-each (lambda (remote)
              (format #t "remote ~a ~a\n" (openvpn-remote-configuration-name remote)
                      (number->string (openvpn-remote-configuration-port remote))))
            val))

(define (openvpn-ccd-list? val)
  (and (list? val)
       (or (eq? val '())
           (and (openvpn-ccd-configuration? (car val))
                (openvpn-ccd-list? (cdr val))))))
(define (serialize-openvpn-ccd-list field-name val)
  #f)

(define (create-ccd-directory val)
  "Create a ccd directory containing files for the ccd configuration option
of OpenVPN.  Each file in this directory represents particular settings for a
client.  Each file is named after the name of the client."
  (let ((files (map (lambda (ccd)
                      (list (openvpn-ccd-configuration-name ccd)
                            (with-output-to-string
                              (lambda ()
                                (serialize-configuration
                                 ccd openvpn-ccd-configuration-fields)))))
                    val)))
    (computed-file "ccd"
                   (with-imported-modules '((guix build utils))
                     #~(begin
                         (use-modules (guix build utils))
                         (use-modules (ice-9 match))
                         (mkdir-p #$output)
                         (for-each
                          (lambda (ccd)
                            (match ccd
                              ((name config-string)
                               (call-with-output-file
                                   (string-append #$output "/" name)
                                 (lambda (port) (display config-string port))))))
                          '#$files))))))

(define-syntax define-split-configuration
  (lambda (x)
    (syntax-case x ()
      ((_ name1 name2 (common-option ...) (first-option ...) (second-option ...))
       #`(begin
           (define-configuration #,#'name1
             common-option ...
             first-option ...)
           (define-configuration #,#'name2
             common-option ...
             second-option ...))))))

(define-split-configuration openvpn-client-configuration
  openvpn-server-configuration
  ((openvpn
    (file-like openvpn)
    "The OpenVPN package.")

   (pid-file
    (string "/var/run/openvpn/openvpn.pid")
    "The OpenVPN pid file.")

   (proto
    (proto 'udp)
    "The protocol (UDP or TCP) used to open a channel between clients and
servers.")

   (dev
    (dev 'tun)
    "The device type used to represent the VPN connection.")

   (ca
    (maybe-string "/etc/openvpn/ca.crt")
    "The certificate authority to check connections against.")

   (cert
    (maybe-string "/etc/openvpn/client.crt")
    "The certificate of the machine the daemon is running on. It should be signed
by the authority given in @code{ca}.")

   (key
    (maybe-string "/etc/openvpn/client.key")
    "The key of the machine the daemon is running on. It must be the key whose
certificate is @code{cert}.")

   (comp-lzo?
    (boolean #t)
    "Whether to use the lzo compression algorithm.")

   (persist-key?
    (boolean #t)
    "Don't re-read key files across SIGUSR1 or --ping-restart.")

   (persist-tun?
    (boolean #t)
    "Don't close and reopen TUN/TAP device or run up/down scripts across
SIGUSR1 or --ping-restart restarts.")

   (fast-io?
     (boolean #f)
     "(Experimental) Optimize TUN/TAP/UDP I/O writes by avoiding a call to
poll/epoll/select prior to the write operation.")

   (verbosity
    (number 3)
    "Verbosity level."))
  ;; client-specific configuration
  ((tls-auth
    (tls-auth-client #f)
    "Add an additional layer of HMAC authentication on top of the TLS control
channel to protect against DoS attacks.")

   (auth-user-pass
    maybe-string
     "Authenticate with server using username/password.  The option is a file
containing username/password on 2 lines.  Do not use a file-like object as it
would be added to the store and readable by any user.")

   (verify-key-usage?
    (key-usage #t)
    "Whether to check the server certificate has server usage extension.")

   (bind?
    (bind #f)
    "Bind to a specific local port number.")

   (resolv-retry?
    (resolv-retry #t)
    "Retry resolving server address.")

   (remote
    (openvpn-remote-list '())
    "A list of remote servers to connect to."))
  ;; server-specific configuration
  ((tls-auth
    (tls-auth-server #f)
    "Add an additional layer of HMAC authentication on top of the TLS control
channel to protect against DoS attacks.")

   (port
    (number 1194)
    "Specifies the port number on which the server listens.")

   (server
    (ip-mask "10.8.0.0 255.255.255.0")
    "An ip and mask specifying the subnet inside the virtual network.")

   (server-ipv6
    (cidr6 #f)
    "A CIDR notation specifying the IPv6 subnet inside the virtual network.")

   (dh
    (string "/etc/openvpn/dh2048.pem")
    "The Diffie-Hellman parameters file.")

   (ifconfig-pool-persist
    (string "/etc/openvpn/ipp.txt")
    "The file that records client IPs.")

   (redirect-gateway?
    (gateway #f)
    "When true, the server will act as a gateway for its clients.")

   (client-to-client?
    (boolean #f)
    "When true, clients are allowed to talk to each other inside the VPN.")

   (keepalive
    (keepalive '(10 120))
    "Causes ping-like messages to be sent back and forth over the link so that
each side knows when the other side has gone down. @code{keepalive} requires
a pair. The first element is the period of the ping sending, and the second
element is the timeout before considering the other side down.")

   (max-clients
    (number 100)
    "The maximum number of clients.")

   (status
    (string "/var/run/openvpn/status")
    "The status file. This file shows a small report on current connection. It
is truncated and rewritten every minute.")

   (client-config-dir
    (openvpn-ccd-list '())
    "The list of configuration for some clients.")))

(define (openvpn-config-file role config)
  (let ((config-str
         (with-output-to-string
           (lambda ()
             (serialize-configuration config
                                      (match role
                                        ('server
                                         openvpn-server-configuration-fields)
                                        ('client
                                         openvpn-client-configuration-fields))))))
        (ccd-dir (match role
                   ('server (create-ccd-directory
                             (openvpn-server-configuration-client-config-dir
                              config)))
                   ('client #f))))
    (computed-file "openvpn.conf"
                   #~(begin
                       (use-modules (ice-9 match))
                       (call-with-output-file #$output
                         (lambda (port)
                           (match '#$role
                             ('server (display "" port))
                             ('client (display "client\n" port)))
                           (display #$config-str port)
                           (match '#$role
                             ('server (display
                                       (string-append "client-config-dir "
                                                      #$ccd-dir "\n") port))
                             ('client (display "" port)))))))))

(define (openvpn-shepherd-service role)
  (lambda (config)
    (let* ((config-file (openvpn-config-file role config))
           (pid-file ((match role
                        ('server openvpn-server-configuration-pid-file)
                        ('client openvpn-client-configuration-pid-file))
                      config))
           (openvpn ((match role
                       ('server openvpn-server-configuration-openvpn)
                       ('client openvpn-client-configuration-openvpn))
                     config))
           (log-file (match role
                       ('server "/var/log/openvpn-server.log")
                       ('client "/var/log/openvpn-client.log"))))
      (list (shepherd-service
             (documentation (string-append "Run the OpenVPN "
                                           (match role
                                             ('server "server")
                                             ('client "client"))
                                           " daemon."))
             (provision (match role
                          ('server '(vpn-server))
                          ('client '(vpn-client))))
             (requirement '(networking))
             (start #~(make-forkexec-constructor
                       (list (string-append #$openvpn "/sbin/openvpn")
                             "--writepid" #$pid-file "--config" #$config-file
                             "--daemon")
                       #:pid-file #$pid-file
                       #:log-file #$log-file))
             (stop #~(make-kill-destructor)))))))

(define %openvpn-accounts
  (list (user-group (name "openvpn") (system? #t))
        (user-account
         (name "openvpn")
         (group "openvpn")
         (system? #t)
         (comment "Openvpn daemon user")
         (home-directory "/var/empty")
         (shell (file-append shadow "/sbin/nologin")))))

(define %openvpn-activation
  #~(begin
      (use-modules (guix build utils))
      (mkdir-p "/var/run/openvpn")))

(define openvpn-server-service-type
  (service-type (name 'openvpn-server)
                (extensions
                 (list (service-extension shepherd-root-service-type
                                          (openvpn-shepherd-service 'server))
                       (service-extension account-service-type
                                          (const %openvpn-accounts))
                       (service-extension activation-service-type
                                          (const %openvpn-activation))))
                (description "Run the OpenVPN server, which allows you to
@emph{host} a @acronym{VPN, virtual private network}.")
                (default-value (openvpn-server-configuration))))

(define openvpn-client-service-type
  (service-type (name 'openvpn-client)
                (extensions
                 (list (service-extension shepherd-root-service-type
                                          (openvpn-shepherd-service 'client))
                       (service-extension account-service-type
                                          (const %openvpn-accounts))
                       (service-extension activation-service-type
                                          (const %openvpn-activation))))
                (description
                 "Run the OpenVPN client service, which allows you to connect
to an existing @acronym{VPN, virtual private network}.")
                (default-value (openvpn-client-configuration))))

(define-deprecated
  (openvpn-client-service #:key (config (openvpn-client-configuration)))
  openvpn-client-service-type
  (service openvpn-client-service-type config))

(define-deprecated
  (openvpn-server-service #:key (config (openvpn-server-configuration)))
  openvpn-server-service-type
  (service openvpn-server-service-type config))

(define (generate-openvpn-server-documentation)
  (generate-documentation
   `((openvpn-server-configuration
      ,openvpn-server-configuration-fields
      (ccd openvpn-ccd-configuration))
     (openvpn-ccd-configuration ,openvpn-ccd-configuration-fields))
   'openvpn-server-configuration))

(define (generate-openvpn-client-documentation)
  (generate-documentation
   `((openvpn-client-configuration
      ,openvpn-client-configuration-fields
      (remote openvpn-remote-configuration))
     (openvpn-remote-configuration ,openvpn-remote-configuration-fields))
   'openvpn-client-configuration))

;;;
;;; Strongswan.
;;;

(define-record-type* <strongswan-configuration>
  strongswan-configuration make-strongswan-configuration
  strongswan-configuration?
  (strongswan      strongswan-configuration-strongswan ;file-like
                   (default strongswan))
  (ipsec-conf      strongswan-configuration-ipsec-conf ;string|#f
                   (default #f))
  (ipsec-secrets   strongswan-configuration-ipsec-secrets ;string|#f
                   (default #f)))

;; In the future, it might be worth implementing a record type to configure
;; all of the plugins, but for *most* basic use cases, simply creating the
;; files will be sufficient. Same is true of charon-plugins.
(define strongswand-configuration-files
  (list "charon" "charon-logging" "pki" "pool" "scepclient"
        "swanctl" "tnc"))

;; Plugins to load. All of these plugins end up as configuration files in
;; strongswan.d/charon/.
(define charon-plugins
  (list "aes" "aesni" "attr" "attr-sql" "chapoly" "cmac" "constraints"
        "counters" "curl" "curve25519" "dhcp" "dnskey" "drbg" "eap-aka-3gpp"
        "eap-aka" "eap-dynamic" "eap-identity" "eap-md5" "eap-mschapv2"
        "eap-peap" "eap-radius" "eap-simaka-pseudonym" "eap-simaka-reauth"
        "eap-simaka-sql" "eap-sim" "eap-sim-file" "eap-tls" "eap-tnc"
        "eap-ttls" "ext-auth" "farp" "fips-prf" "gmp" "ha" "hmac"
        "kernel-netlink" "led" "md4" "md5" "mgf1" "nonce" "openssl" "pem"
        "pgp" "pkcs12" "pkcs1" "pkcs7" "pkcs8" "pubkey" "random" "rc2"
        "resolve" "revocation" "sha1" "sha2" "socket-default" "soup" "sql"
        "sqlite" "sshkey" "tnc-tnccs" "vici" "x509" "xauth-eap" "xauth-generic"
        "xauth-noauth" "xauth-pam" "xcbc"))

(define (strongswan-configuration-file config)
  (match-record config <strongswan-configuration>
    (strongswan ipsec-conf ipsec-secrets)
    (if (eq? (string? ipsec-conf) (string? ipsec-secrets))
        (let* ((strongswan-dir
                (computed-file
                 "strongswan.d"
                 #~(begin
                     (mkdir #$output)
                     ;; Create all of the configuration files strongswan.d/.
                     (map (lambda (conf-file)
                            (let* ((filename (string-append
                                              #$output "/"
                                              conf-file ".conf")))
                              (call-with-output-file filename
                                (lambda (port)
                                  (display
                                   "# Created by 'strongswan-service'\n"
                                   port)))))
                          (list #$@strongswand-configuration-files))
                     (mkdir (string-append #$output "/charon"))
                     ;; Create all of the plugin configuration files.
                     (map (lambda (plugin)
                            (let* ((filename (string-append
                                              #$output "/charon/"
                                              plugin ".conf")))
                              (call-with-output-file filename
                                (lambda (port)
                                  (format port "~a {
  load = yes
}"
                                          plugin)))))
                          (list #$@charon-plugins))))))
          ;; Generate our strongswan.conf to reflect the user configuration.
          (computed-file
           "strongswan.conf"
           #~(begin
               (call-with-output-file #$output
                 (lambda (port)
                   (display "# Generated by 'strongswan-service'.\n" port)
                   (format port "charon {
  load_modular = yes
  plugins {
    include ~a/charon/*.conf"
                           #$strongswan-dir)
                   (if #$ipsec-conf
                       (format port "
    stroke {
      load = yes
      secrets_file = ~a
    }
  }
}

starter {
  config_file = ~a
}

include ~a/*.conf"
                               #$ipsec-secrets
                               #$ipsec-conf
                               #$strongswan-dir)
                       (format port "
  }
}
include ~a/*.conf"
                               #$strongswan-dir)))))))
        (throw 'error
               (G_ "strongSwan ipsec-conf and ipsec-secrets must both be (un)set")))))

(define (strongswan-shepherd-service config)
  (let* ((ipsec (file-append strongswan "/sbin/ipsec"))
        (strongswan-conf-path (strongswan-configuration-file config)))
    (list (shepherd-service
           (requirement '(networking))
           (provision '(ipsec))
           (start #~(make-forkexec-constructor
                     (list #$ipsec "start" "--nofork")
                     #:environment-variables
                     (list (string-append "STRONGSWAN_CONF="
                                          #$strongswan-conf-path))))
           (stop #~(make-kill-destructor))
           (documentation
            "strongSwan's charon IKE keying daemon for IPsec VPN.")))))

(define strongswan-service-type
  (service-type
   (name 'strongswan)
   (extensions
    (list (service-extension shepherd-root-service-type
                             strongswan-shepherd-service)))
   (default-value (strongswan-configuration))
   (description
    "Connect to an IPsec @acronym{VPN, Virtual Private Network} with
strongSwan.")))

;;;
;;; Wireguard.
;;;

(define-record-type* <wireguard-peer>
  wireguard-peer make-wireguard-peer
  wireguard-peer?
  (name              wireguard-peer-name)
  (endpoint          wireguard-peer-endpoint
                     (default #f))     ;string
  (public-key        wireguard-peer-public-key)   ;string
  (preshared-key     wireguard-peer-preshared-key
                     (default #f))     ;string
  (allowed-ips       wireguard-peer-allowed-ips) ;list of strings
  (keep-alive        wireguard-peer-keep-alive
                     (default #f)))    ;integer

(define-record-type* <wireguard-configuration>
  wireguard-configuration make-wireguard-configuration
  wireguard-configuration?
  (wireguard          wireguard-configuration-wireguard ;file-like
                      (default wireguard-tools))
  (interface          wireguard-configuration-interface ;string
                      (default "wg0"))
  (addresses          wireguard-configuration-addresses ;string
                      (default '("10.0.0.1/32")))
  (port               wireguard-configuration-port ;integer
                      (default 51820))
  (private-key        wireguard-configuration-private-key ;string
                      (default "/etc/wireguard/private.key"))
  (peers              wireguard-configuration-peers ;list of <wiregard-peer>
                      (default '()))
  (dns                wireguard-configuration-dns ;list of strings
                      (default '()))
  (monitor-ips?       wireguard-configuration-monitor-ips? ;boolean
                      (default #f))
  (monitor-ips-interval wireguard-configuration-monitor-ips-interval
                        (default '(next-minute (range 0 60 5)))) ;string | list
  (pre-up             wireguard-configuration-pre-up ;list of strings
                      (default '()))
  (post-up            wireguard-configuration-post-up ;list of strings
                      (default '()))
  (pre-down           wireguard-configuration-pre-down ;list of strings
                      (default '()))
  (post-down          wireguard-configuration-post-down ;list of strings
                      (default '()))
  (table              wireguard-configuration-table ;string
                      (default "auto")))

(define (wireguard-configuration-file config)
  (define (peer->config peer)
    (match-record peer <wireguard-peer>
      (name public-key endpoint allowed-ips keep-alive)
      (let ((lines (list
                    (format #f "[Peer]   #~a" name)
                    (format #f "PublicKey = ~a" public-key)
                    (format #f "AllowedIPs = ~{~a~^, ~}" allowed-ips)
                    (format #f "~@[Endpoint = ~a~]" endpoint)
                    (format #f "~@[PersistentKeepalive = ~a~]" keep-alive))))
        (string-join (remove string-null? lines) "\n"))))

  (define (peers->preshared-keys peer keys)
    (let ((public-key (wireguard-peer-public-key peer))
          (preshared-key (wireguard-peer-preshared-key peer)))
      (if preshared-key
          (cons* public-key preshared-key keys)
          keys)))

  (match-record config <wireguard-configuration>
    (wireguard interface addresses port private-key peers dns
               pre-up post-up pre-down post-down table)
    (let* ((config-file (string-append interface ".conf"))
           (peer-keys (fold peers->preshared-keys (list) peers))
           (peers (map peer->config peers))
           (config
            (computed-file
             "wireguard-config"
             #~(begin
                 (use-modules (ice-9 format)
                              (srfi srfi-1))

                 (define lines
                   (list
                    "[Interface]"
                    #$@(if (null? addresses)
                           '()
                           (list (format #f "Address = ~{~a~^, ~}"
                                         addresses)))
                    (format #f "~@[Table = ~a~]" #$table)
                    #$@(if (null? pre-up)
                           '()
                           (list (format #f "~{PreUp = ~a~%~}" pre-up)))
                    (format #f "PostUp = ~a set %i private-key ~a\
~{ peer ~a preshared-key ~a~}" #$(file-append wireguard "/bin/wg")
#$private-key '#$peer-keys)
                    #$@(if (null? post-up)
                           '()
                           (list (format #f "~{PostUp = ~a~%~}" post-up)))
                    #$@(if (null? pre-down)
                           '()
                           (list (format #f "~{PreDown = ~a~%~}" pre-down)))
                    #$@(if (null? post-down)
                           '()
                           (list (format #f "~{PostDown = ~a~%~}" post-down)))
                    (format #f "~@[ListenPort = ~a~]" #$port)
                    #$@(if (null? dns)
                           '()
                           (list (format #f "DNS = ~{~a~^, ~}" dns)))))

                 (mkdir #$output)
                 (chdir #$output)
                 (call-with-output-file #$config-file
                   (lambda (port)
                     (format port "~a~%~%~{~a~%~^~%~}"
                             (string-join (remove string-null? lines) "\n")
                             '#$peers)))))))
      (file-append config "/" config-file))))

(define (wireguard-activation config)
  (match-record config <wireguard-configuration>
    (private-key wireguard)
    #~(begin
        (use-modules (guix build utils)
                     (ice-9 popen)
                     (ice-9 rdelim))
        (mkdir-p (dirname #$private-key))
        (unless (file-exists? #$private-key)
          (let* ((pipe
                  (open-input-pipe (string-append
                                    #$(file-append wireguard "/bin/wg")
                                    " genkey")))
                 (key (read-line pipe)))
            (call-with-output-file #$private-key
              (lambda (port)
                (display key port)))
            (chmod #$private-key #o400)
            (close-pipe pipe))))))

;;; XXX: Copied from (guix scripts pack), changing define to define*.
(define-syntax-rule (define-with-source (variable args ...) body body* ...)
  "Bind VARIABLE to a procedure accepting ARGS defined as BODY, also setting
its source property."
  (begin
    (define* (variable args ...)
      body body* ...)
    (eval-when (load eval)
      (set-procedure-property! variable 'source
                               '(define* (variable args ...) body body* ...)))))

(define (wireguard-service-name interface)
  "Return the WireGuard service name (a symbol) configured to use INTERFACE."
  (symbol-append 'wireguard- (string->symbol interface)))

(define-with-source (strip-port/maybe endpoint #:key ipv6?)
  "Strip the colon and port, if present in ENDPOINT, a string."
  (if ipv6?
      (if (string-prefix? "[" endpoint)
          (first (string-split (string-drop endpoint 1) #\])) ;ipv6
          endpoint)
      (first (string-split endpoint #\:)))) ;ipv4

(define* (ipv4-address? address)
  "Predicate to check whether ADDRESS is a valid IPv4 address."
  (let ((address (strip-port/maybe address)))
    (false-if-exception
     (->bool (getaddrinfo address #f AI_NUMERICHOST AF_INET)))))

(define* (ipv6-address? address)
  "Predicate to check whether ADDRESS is a valid IPv6 address."
  (let ((address (strip-port/maybe address #:ipv6? #t)))
    (false-if-exception
     (->bool (getaddrinfo address #f AI_NUMERICHOST AF_INET6)))))

(define (host-name? name)
  "Predicate to check whether NAME is a host name, i.e. not an IP address."
  (not (or (ipv6-address? name) (ipv4-address? name))))

(define (endpoint-host-names peers)
  "Return an association list of endpoint host names keyed by their peer
public key, if any."
  (reverse
   (fold (lambda (peer host-names)
           (let ((public-key (wireguard-peer-public-key peer))
                 (endpoint (wireguard-peer-endpoint peer)))
             (if (and endpoint (host-name? endpoint))
                 (cons (cons public-key endpoint) host-names)
                 host-names)))
         '()
         peers)))

(define (wireguard-shepherd-service config)
  (match-record config <wireguard-configuration>
    (wireguard interface)
    (let ((wg-quick (file-append wireguard "/bin/wg-quick"))
          (config (wireguard-configuration-file config)))
      (list (shepherd-service
             (requirement '(networking))
             (provision (list (wireguard-service-name interface)))
             (start #~(lambda _
                       (invoke #$wg-quick "up" #$config)))
             (stop #~(lambda _
                       (invoke #$wg-quick "down" #$config)
                       #f))                       ;stopped!
             (actions (list (shepherd-configuration-action config)))
             (documentation "Run the Wireguard VPN tunnel"))))))

(define (wireguard-monitoring-jobs config)
  ;; Loosely based on WireGuard's own 'reresolve-dns.sh' shell script (see:
  ;; https://raw.githubusercontent.com/WireGuard/wireguard-tools/
  ;; master/contrib/reresolve-dns/reresolve-dns.sh).
  (match-record config <wireguard-configuration>
    (interface monitor-ips? monitor-ips-interval peers)
    (let ((host-names (endpoint-host-names peers)))
      (if monitor-ips?
          (if (null? host-names)
              (begin
                (warn "monitor-ips? is #t but no host name to monitor")
                '())
              ;; The mcron monitor job may be a string or a list; ungexp strips
              ;; one quote level, which must be added back when a list is
              ;; provided.
              (list
               #~(job
                  (if (string? #$monitor-ips-interval)
                      #$monitor-ips-interval
                      '#$monitor-ips-interval)
                  #$(program-file
                     (format #f "wireguard-~a-monitoring" interface)
                     (with-imported-modules (source-module-closure
                                             '((gnu services herd)
                                               (guix build utils)))
                       #~(begin
                           (use-modules (gnu services herd)
                                        (guix build utils)
                                        (ice-9 popen)
                                        (ice-9 match)
                                        (ice-9 textual-ports)
                                        (srfi srfi-1)
                                        (srfi srfi-26))

                           (define (resolve-host name)
                             "Return the IP address resolved from NAME."
                             (let* ((ai (car (getaddrinfo name)))
                                    (sa (addrinfo:addr ai)))
                               (inet-ntop (sockaddr:fam sa)
                                          (sockaddr:addr sa))))

                           (define wg #$(file-append wireguard-tools "/bin/wg"))

                           #$(procedure-source strip-port/maybe)

                           (define service-name '#$(wireguard-service-name
                                                    interface))

                           (when (live-service-running
                                  (current-service service-name))
                             (let* ((pipe (open-pipe* OPEN_READ wg "show"
                                                      #$interface "endpoints"))
                                    (lines (string-split (get-string-all pipe)
                                                         #\newline))
                                    ;; IPS is an association list mapping
                                    ;; public keys to IP addresses.
                                    (ips (map (match-lambda
                                                ((public-key ip)
                                                 (cons public-key
                                                       (strip-port/maybe ip))))
                                              (map (cut string-split <> #\tab)
                                                   (remove string-null?
                                                           lines)))))
                               (close-pipe pipe)
                               (for-each
                                (match-lambda
                                  ((key . host-name)
                                   (let ((resolved-ip (resolve-host
                                                       (strip-port/maybe
                                                        host-name)))
                                         (current-ip (assoc-ref ips key)))
                                     (unless (string=? resolved-ip current-ip)
                                       (format #t "resetting `~a' peer \
endpoint to `~a' due to stale IP (`~a' instead of `~a')~%"
                                               key host-name
                                               current-ip resolved-ip)
                                       (invoke wg "set" #$interface "peer" key
                                               "endpoint" host-name)))))
                                '#$host-names)))))))))
          '()))))                     ;monitor-ips? is #f

(define wireguard-service-type
  (service-type
   (name 'wireguard)
   (extensions
    (list (service-extension shepherd-root-service-type
                             wireguard-shepherd-service)
          (service-extension activation-service-type
                             wireguard-activation)
          (service-extension profile-service-type
                             (compose list
                                      wireguard-configuration-wireguard))
          (service-extension mcron-service-type
                             wireguard-monitoring-jobs)))
   (description "Set up Wireguard @acronym{VPN, Virtual Private Network}
tunnels.")))