1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7 dhcpcd = if !config.boot.isContainer then pkgs.dhcpcd else pkgs.dhcpcd.override { udev = null; };
8
9 cfg = config.networking.dhcpcd;
10
11 interfaces = attrValues config.networking.interfaces;
12
13 enableDHCP = config.networking.dhcpcd.enable &&
14 (config.networking.useDHCP || any (i: i.useDHCP == true) interfaces);
15
16 # Don't start dhcpcd on explicitly configured interfaces or on
17 # interfaces that are part of a bridge, bond or sit device.
18 ignoredInterfaces =
19 map (i: i.name) (filter (i: if i.useDHCP != null then !i.useDHCP else i.ipv4.addresses != [ ]) interfaces)
20 ++ mapAttrsToList (i: _: i) config.networking.sits
21 ++ concatLists (attrValues (mapAttrs (n: v: v.interfaces) config.networking.bridges))
22 ++ flatten (concatMap (i: attrNames (filterAttrs (_: config: config.type != "internal") i.interfaces)) (attrValues config.networking.vswitches))
23 ++ concatLists (attrValues (mapAttrs (n: v: v.interfaces) config.networking.bonds))
24 ++ config.networking.dhcpcd.denyInterfaces;
25
26 arrayAppendOrNull = a1: a2: if a1 == null && a2 == null then null
27 else if a1 == null then a2 else if a2 == null then a1
28 else a1 ++ a2;
29
30 # If dhcp is disabled but explicit interfaces are enabled,
31 # we need to provide dhcp just for those interfaces.
32 allowInterfaces = arrayAppendOrNull cfg.allowInterfaces
33 (if !config.networking.useDHCP && enableDHCP then
34 map (i: i.name) (filter (i: i.useDHCP == true) interfaces) else null);
35
36 # Config file adapted from the one that ships with dhcpcd.
37 dhcpcdConf = pkgs.writeText "dhcpcd.conf"
38 ''
39 # Inform the DHCP server of our hostname for DDNS.
40 hostname
41
42 # A list of options to request from the DHCP server.
43 option domain_name_servers, domain_name, domain_search, host_name
44 option classless_static_routes, ntp_servers, interface_mtu
45
46 # A ServerID is required by RFC2131.
47 # Commented out because of many non-compliant DHCP servers in the wild :(
48 #require dhcp_server_identifier
49
50 # A hook script is provided to lookup the hostname if not set by
51 # the DHCP server, but it should not be run by default.
52 nohook lookup-hostname
53
54 # Ignore peth* devices; on Xen, they're renamed physical
55 # Ethernet cards used for bridging. Likewise for vif* and tap*
56 # (Xen) and virbr* and vnet* (libvirt).
57 denyinterfaces ${toString ignoredInterfaces} lo peth* vif* tap* tun* virbr* vnet* vboxnet* sit*
58
59 # Use the list of allowed interfaces if specified
60 ${optionalString (allowInterfaces != null) "allowinterfaces ${toString allowInterfaces}"}
61
62 # Immediately fork to background if specified, otherwise wait for IP address to be assigned
63 ${{
64 background = "background";
65 any = "waitip";
66 ipv4 = "waitip 4";
67 ipv6 = "waitip 6";
68 both = "waitip 4\nwaitip 6";
69 if-carrier-up = "";
70 }.${cfg.wait}}
71
72 ${optionalString (config.networking.enableIPv6 == false) ''
73 # Don't solicit or accept IPv6 Router Advertisements and DHCPv6 if disabled IPv6
74 noipv6
75 ''}
76
77 ${cfg.extraConfig}
78 '';
79
80 exitHook = pkgs.writeText "dhcpcd.exit-hook"
81 ''
82 if [ "$reason" = BOUND -o "$reason" = REBOOT ]; then
83 # Restart ntpd. We need to restart it to make sure that it
84 # will actually do something: if ntpd cannot resolve the
85 # server hostnames in its config file, then it will never do
86 # anything ever again ("couldn't resolve ..., giving up on
87 # it"), so we silently lose time synchronisation. This also
88 # applies to openntpd.
89 /run/current-system/systemd/bin/systemctl try-reload-or-restart ntpd.service openntpd.service chronyd.service || true
90 fi
91
92 ${cfg.runHook}
93 '';
94
95in
96
97{
98
99 ###### interface
100
101 options = {
102
103 networking.dhcpcd.enable = mkOption {
104 type = types.bool;
105 default = true;
106 description = ''
107 Whether to enable dhcpcd for device configuration. This is mainly to
108 explicitly disable dhcpcd (for example when using networkd).
109 '';
110 };
111
112 networking.dhcpcd.persistent = mkOption {
113 type = types.bool;
114 default = false;
115 description = ''
116 Whenever to leave interfaces configured on dhcpcd daemon
117 shutdown. Set to true if you have your root or store mounted
118 over the network or this machine accepts SSH connections
119 through DHCP interfaces and clients should be notified when
120 it shuts down.
121 '';
122 };
123
124 networking.dhcpcd.denyInterfaces = mkOption {
125 type = types.listOf types.str;
126 default = [];
127 description = ''
128 Disable the DHCP client for any interface whose name matches
129 any of the shell glob patterns in this list. The purpose of
130 this option is to blacklist virtual interfaces such as those
131 created by Xen, libvirt, LXC, etc.
132 '';
133 };
134
135 networking.dhcpcd.allowInterfaces = mkOption {
136 type = types.nullOr (types.listOf types.str);
137 default = null;
138 description = ''
139 Enable the DHCP client for any interface whose name matches
140 any of the shell glob patterns in this list. Any interface not
141 explicitly matched by this pattern will be denied. This pattern only
142 applies when non-null.
143 '';
144 };
145
146 networking.dhcpcd.extraConfig = mkOption {
147 type = types.lines;
148 default = "";
149 description = ''
150 Literal string to append to the config file generated for dhcpcd.
151 '';
152 };
153
154 networking.dhcpcd.runHook = mkOption {
155 type = types.lines;
156 default = "";
157 example = "if [[ $reason =~ BOUND ]]; then echo $interface: Routers are $new_routers - were $old_routers; fi";
158 description = ''
159 Shell code that will be run after all other hooks. See
160 `man dhcpcd-run-hooks` for details on what is possible.
161 '';
162 };
163
164 networking.dhcpcd.wait = mkOption {
165 type = types.enum [ "background" "any" "ipv4" "ipv6" "both" "if-carrier-up" ];
166 default = "any";
167 description = ''
168 This option specifies when the dhcpcd service will fork to background.
169 If set to "background", dhcpcd will fork to background immediately.
170 If set to "ipv4" or "ipv6", dhcpcd will wait for the corresponding IP
171 address to be assigned. If set to "any", dhcpcd will wait for any type
172 (IPv4 or IPv6) to be assigned. If set to "both", dhcpcd will wait for
173 both an IPv4 and an IPv6 address before forking.
174 The option "if-carrier-up" is equivalent to "any" if either ethernet
175 is plugged nor WiFi is powered, and to "background" otherwise.
176 '';
177 };
178
179 };
180
181
182 ###### implementation
183
184 config = mkIf enableDHCP {
185
186 systemd.services.dhcpcd = let
187 cfgN = config.networking;
188 hasDefaultGatewaySet = (cfgN.defaultGateway != null && cfgN.defaultGateway.address != "")
189 && (!cfgN.enableIPv6 || (cfgN.defaultGateway6 != null && cfgN.defaultGateway6.address != ""));
190 in
191 { description = "DHCP Client";
192
193 wantedBy = [ "multi-user.target" ] ++ optional (!hasDefaultGatewaySet) "network-online.target";
194 wants = [ "network.target" ];
195 before = [ "network-online.target" ];
196
197 restartTriggers = [ exitHook ];
198
199 # Stopping dhcpcd during a reconfiguration is undesirable
200 # because it brings down the network interfaces configured by
201 # dhcpcd. So do a "systemctl restart" instead.
202 stopIfChanged = false;
203
204 path = [ dhcpcd pkgs.nettools pkgs.openresolv ];
205
206 unitConfig.ConditionCapability = "CAP_NET_ADMIN";
207
208 serviceConfig =
209 { Type = "forking";
210 PIDFile = "/run/dhcpcd.pid";
211 ExecStart = "@${dhcpcd}/sbin/dhcpcd dhcpcd --quiet ${optionalString cfg.persistent "--persistent"} --config ${dhcpcdConf}";
212 ExecReload = "${dhcpcd}/sbin/dhcpcd --rebind";
213 Restart = "always";
214 };
215 };
216
217 environment.systemPackages = [ dhcpcd ];
218
219 environment.etc."dhcpcd.exit-hook".source = exitHook;
220
221 powerManagement.resumeCommands = mkIf config.systemd.services.dhcpcd.enable
222 ''
223 # Tell dhcpcd to rebind its interfaces if it's running.
224 /run/current-system/systemd/bin/systemctl reload dhcpcd.service
225 '';
226
227 };
228
229}