aboutsummaryrefslogtreecommitdiffstats
path: root/host.nix
blob: 73640c6c8c80164476175d21480894593599aa8a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Host side of the guests' network: a bridge with tap devices fctap0,
# fctap1, ... owned by the user running the VMs, a DHCP server and DNS
# resolver, and NAT to the outside world.  Each running VM takes one tap device, so taps is the
# number of VMs that can run at the same time.
# usage (in the host's configuration.nix):
#   imports = [ (import ./host.nix { user = "tv"; }) ];
# The host's firewall has to let the guests in on fcbr0: DHCP (udp 67) and
# DNS (udp and tcp 53)
# as input, and anything from fcbr0 (plus the return traffic) as forward.
{ user, taps ? 8 }: { lib, pkgs, ... }: let
  tapNames = map (i: "fctap${toString i}") (lib.range 0 (taps - 1));
in {
  networking.interfaces = lib.genAttrs tapNames (_: {
    virtual = true;
    virtualType = "tap";
    virtualOwner = user;
  }) // {
    fcbr0.ipv4.addresses = [{ address = "172.16.0.1"; prefixLength = 24; }];
  };
  networking.bridges.fcbr0.interfaces = tapNames;

  networking.nat = {
    enable = true;
    internalInterfaces = [ "fcbr0" ];
  };

  # A dnsmasq of its own, so it doesn't get mixed up with one the host might
  # run otherwise.  It forwards DNS queries to the servers in the host's
  # /etc/resolv.conf (and answers from its /etc/hosts).  It only listens on
  # fcbr0 (except-interface=lo, else it would also take 127.0.0.1:53 from a
  # resolver the host runs there); bind-dynamic copes with fcbr0 not being
  # there yet.
  systemd.services.fcbr0-dnsmasq = {
    wantedBy = [ "multi-user.target" ];
    after = [ "network.target" ];
    serviceConfig = {
      RuntimeDirectory = "fcbr0-dnsmasq";
      Restart = "on-failure";
      ExecStart = lib.escapeShellArgs [
        "${pkgs.dnsmasq}/bin/dnsmasq"
        "--keep-in-foreground"
        "--conf-file=/dev/null"
        "--bind-dynamic"
        "--interface=fcbr0"
        "--except-interface=lo"
        "--dhcp-authoritative"
        "--dhcp-range=172.16.0.2,172.16.0.254,1h"
        "--dhcp-leasefile=/run/fcbr0-dnsmasq/leases"
      ];
    };
  };
}