blob: 0ec63bd3d92e8de536bb6383e8908980d1a2d9cc (
plain) (
blame)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
|
{ config, lib, ... }: with lib; {
options.srv = {
static = mkOption {
type = types.nullOr (types.submodule {
options = {
ip = mkOption {
type = types.str;
example = "10.0.0.0";
};
prefixLength = mkOption {
type = types.ints.between 0 32;
default = 24;
example = 32;
};
interface = mkOption {
type = types.str;
example = "ens3";
};
};
});
default = null;
};
tld = mkOption {
type = types.nullOr types.str;
default = null;
example = "local";
};
slds = mkOption {
type = types.listOf types.str;
default = [];
};
};
config = let
netinterfaces = config:
{
${config.srv.static.interface}.ipv4.addresses = [{
address = config.srv.static.ip;
prefixLength = config.srv.static.prefixLength;
}];
};
in {
networking = mkIf
(config.srv.static != null)
{
interfaces = netinterfaces config;
# Calculate the gateway using the given static ip and prefix
# We're assuming the gateway is the first (min) host on the network
defaultGateway.address =
let
# 192.168.0.100 -> [ "192" "168" "0" "100" ]
ipBytes = builtins.map
(x: lib.toInt x)
(lib.splitString "." config.srv.static.ip);
# 2 ^^ x
pow2 = x: if x == 0 then 1 else 2 * (pow2 (x - 1));
# 24 -> 0b11111111_11111111_11111111_00000000
mask = 4294967295 - ((pow2 (32 - config.srv.static.prefixLength)) - 1);
# 0b11111111_11111111_11111111_00000000 -> [ 255 255 255 0 ]
maskBytes = [
(builtins.bitAnd (mask / 16777216) 255)
(builtins.bitAnd (mask / 65536) 255)
(builtins.bitAnd (mask / 256) 255)
(builtins.bitAnd mask 255)
];
# ipBytes & maskBytes
networkIP = lib.zipListsWith lib.bitAnd ipBytes maskBytes;
# min possible host
gatewayIP = (lib.take 3 networkIP) ++ [ ((lib.last networkIP) + 1) ];
in
lib.mkDefault
(lib.concatMapStringsSep
"."
builtins.toString
gatewayIP);
};
virtualisation.vmVariant.networking.interfaces = mkIf
(config.srv.static != null)
(lib.mkVMOverride
(netinterfaces
(lib.recursiveUpdate
config
{ srv.static.interface = "eth0"; })));
services.dnsmasq.settings.address = mkIf
(config.srv.static != null && config.srv.tld != null)
(builtins.map
(sld: "/${sld}.${config.srv.tld}/${config.srv.static.ip}")
config.srv.slds);
};
}
|