1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6 cfg = config.services.dnsmasq;
7 dnsmasq = pkgs.dnsmasq;
8 stateDir = "/var/lib/dnsmasq";
9
10 dnsmasqConf = pkgs.writeText "dnsmasq.conf" ''
11 dhcp-leasefile=${stateDir}/dnsmasq.leases
12 ${optionalString cfg.resolveLocalQueries ''
13 conf-file=/etc/dnsmasq-conf.conf
14 resolv-file=/etc/dnsmasq-resolv.conf
15 ''}
16 ${flip concatMapStrings cfg.servers (server: ''
17 server=${server}
18 '')}
19 ${cfg.extraConfig}
20 '';
21
22in
23
24{
25
26 ###### interface
27
28 options = {
29
30 services.dnsmasq = {
31
32 enable = mkOption {
33 type = types.bool;
34 default = false;
35 description = ''
36 Whether to run dnsmasq.
37 '';
38 };
39
40 resolveLocalQueries = mkOption {
41 type = types.bool;
42 default = true;
43 description = ''
44 Whether dnsmasq should resolve local queries (i.e. add 127.0.0.1 to
45 /etc/resolv.conf).
46 '';
47 };
48
49 servers = mkOption {
50 type = types.listOf types.str;
51 default = [];
52 example = [ "8.8.8.8" "8.8.4.4" ];
53 description = ''
54 The DNS servers which dnsmasq should query.
55 '';
56 };
57
58 extraConfig = mkOption {
59 type = types.lines;
60 default = "";
61 description = ''
62 Extra configuration directives that should be added to
63 <literal>dnsmasq.conf</literal>.
64 '';
65 };
66
67 };
68
69 };
70
71
72 ###### implementation
73
74 config = mkIf config.services.dnsmasq.enable {
75
76 networking.nameservers =
77 optional cfg.resolveLocalQueries "127.0.0.1";
78
79 services.dbus.packages = [ dnsmasq ];
80
81 users.extraUsers = singleton {
82 name = "dnsmasq";
83 uid = config.ids.uids.dnsmasq;
84 description = "Dnsmasq daemon user";
85 };
86
87 systemd.services.dnsmasq = {
88 description = "Dnsmasq Daemon";
89 after = [ "network.target" "systemd-resolved.service" ];
90 wantedBy = [ "multi-user.target" ];
91 path = [ dnsmasq ];
92 preStart = ''
93 mkdir -m 755 -p ${stateDir}
94 touch ${stateDir}/dnsmasq.leases
95 chown -R dnsmasq ${stateDir}
96 touch /etc/dnsmasq-{conf,resolv}.conf
97 dnsmasq --test
98 '';
99 serviceConfig = {
100 Type = "dbus";
101 BusName = "uk.org.thekelleys.dnsmasq";
102 ExecStart = "${dnsmasq}/bin/dnsmasq -k --enable-dbus --user=dnsmasq -C ${dnsmasqConf}";
103 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
104 };
105 restartTriggers = [ config.environment.etc.hosts.source ];
106 };
107
108 };
109
110}