@@ -0,0 +1,86 @@
1+{ config, lib, pkgs, ... }:
2+
3+with lib;
4+
5+let
6+ cfg = config.services.dnscache;
7+
8+ dnscache-root = pkgs.runCommand "dnscache-root" {} ''
9+ mkdir -p $out/{servers,ip}
10+
11+ ${concatMapStrings (ip: ''
12+ echo > "$out/ip/"${lib.escapeShellArg ip}
13+ '') cfg.clientIps}
14+
15+ ${concatStrings (mapAttrsToList (host: ips: ''
16+ ${concatMapStrings (ip: ''
17+ echo ${lib.escapeShellArg ip} > "$out/servers/"${lib.escapeShellArg host}
18+ '') ips}
19+ '') cfg.domainServers)}
20+
21+ # djbdns contains an outdated list of root servers;
22+ # if one was not provided in config, provide a current list
23+ if [ ! -e servers/@ ]; then
24+ awk '/^.?.ROOT-SERVERS.NET/ { print $4 }' ${pkgs.dns-root-data}/root.hints > $out/servers/@
25+ fi
26+ '';
27+
28+in {
29+
30+ ###### interface
31+
32+ options = {
33+ services.dnscache = {
34+ enable = mkOption {
35+ default = false;
36+ type = types.bool;
37+ description = "Whether to run the dnscache caching dns server";
38+ };
39+
40+ ip = mkOption {
41+ default = "0.0.0.0";
42+ type = types.str;
43+ description = "IP address on which to listen for connections";
44+ };
45+
46+ clientIps = mkOption {
47+ default = [ "127.0.0.1" ];
48+ type = types.listOf types.str;
49+ description = "client IP addresses (or prefixes) from which to accept connections";
50+ example = ["192.168" "172.23.75.82"];
51+ };
52+
53+ domainServers = mkOption {
54+ default = { };
55+ type = types.attrsOf (types.listOf types.str);
56+ description = "table of {hostname: server} pairs to use as authoritative servers for hosts (and subhosts)";
57+ example = {
58+ "example.com" = ["8.8.8.8" "8.8.4.4"];
59+ };
60+ };
61+ };
62+ };
63+
64+ ###### implementation
65+
66+ config = mkIf config.services.dnscache.enable {
67+ environment.systemPackages = [ pkgs.djbdns ];
68+ users.extraUsers.dnscache = {};
69+
70+ systemd.services.dnscache = {
71+ description = "djbdns dnscache server";
72+ wantedBy = [ "multi-user.target" ];
73+ path = with pkgs; [ bash daemontools djbdns ];
74+ preStart = ''
75+ rm -rf /var/lib/dnscache
76+ dnscache-conf dnscache dnscache /var/lib/dnscache ${config.services.dnscache.ip}
77+ rm -rf /var/lib/dnscache/root
78+ ln -sf ${dnscache-root} /var/lib/dnscache/root
79+ '';
80+ script = ''
81+ cd /var/lib/dnscache/
82+ exec ./run
83+ '';
84+ };
85+ };
86+}