1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7 cfg = config.boot.initrd.network;
8
9 udhcpcScript = pkgs.writeScript "udhcp-script"
10 ''
11 #! /bin/sh
12 if [ "$1" = bound ]; then
13 ip address add "$ip/$mask" dev "$interface"
14 if [ -n "$router" ]; then
15 ip route add "$router" dev "$interface" # just in case if "$router" is not within "$ip/$mask" (e.g. Hetzner Cloud)
16 ip route add default via "$router" dev "$interface"
17 fi
18 if [ -n "$dns" ]; then
19 rm -f /etc/resolv.conf
20 for i in $dns; do
21 echo "nameserver $dns" >> /etc/resolv.conf
22 done
23 fi
24 fi
25 '';
26
27 udhcpcArgs = toString cfg.udhcpc.extraArgs;
28
29in
30
31{
32
33 options = {
34
35 boot.initrd.network.enable = mkOption {
36 type = types.bool;
37 default = false;
38 description = ''
39 Add network connectivity support to initrd. The network may be
40 configured using the <literal>ip</literal> kernel parameter,
41 as described in <link
42 xlink:href="https://www.kernel.org/doc/Documentation/filesystems/nfs/nfsroot.txt">the
43 kernel documentation</link>. Otherwise, if
44 <option>networking.useDHCP</option> is enabled, an IP address
45 is acquired using DHCP.
46
47 You should add the module(s) required for your network card to
48 boot.initrd.availableKernelModules. lspci -v -s <ethernet controller>
49 will tell you which.
50 '';
51 };
52
53 boot.initrd.network.udhcpc.extraArgs = mkOption {
54 default = [];
55 type = types.listOf types.str;
56 description = ''
57 Additional command-line arguments passed verbatim to udhcpc if
58 <option>boot.initrd.network.enable</option> and <option>networking.useDHCP</option>
59 are enabled.
60 '';
61 };
62
63 boot.initrd.network.postCommands = mkOption {
64 default = "";
65 type = types.lines;
66 description = ''
67 Shell commands to be executed after stage 1 of the
68 boot has initialised the network.
69 '';
70 };
71
72
73 };
74
75 config = mkIf cfg.enable {
76
77 boot.initrd.kernelModules = [ "af_packet" ];
78
79 boot.initrd.extraUtilsCommands = ''
80 copy_bin_and_libs ${pkgs.mkinitcpio-nfs-utils}/bin/ipconfig
81 '';
82
83 boot.initrd.preLVMCommands = mkBefore (
84 # Search for interface definitions in command line.
85 ''
86 for o in $(cat /proc/cmdline); do
87 case $o in
88 ip=*)
89 ipconfig $o && hasNetwork=1
90 ;;
91 esac
92 done
93 ''
94
95 # Otherwise, use DHCP.
96 + optionalString config.networking.useDHCP ''
97 if [ -z "$hasNetwork" ]; then
98
99 # Bring up all interfaces.
100 for iface in $(cd /sys/class/net && ls); do
101 echo "bringing up network interface $iface..."
102 ip link set "$iface" up
103 done
104
105 # Acquire a DHCP lease.
106 echo "acquiring IP address via DHCP..."
107 udhcpc --quit --now --script ${udhcpcScript} ${udhcpcArgs} && hasNetwork=1
108 fi
109 ''
110
111 + ''
112 if [ -n "$hasNetwork" ]; then
113 echo "networking is up!"
114 ${cfg.postCommands}
115 fi
116 '');
117
118 };
119
120}