@@ -16,6 +16,13 @@ let
1616 resolvconfOptions = cfg.resolvconfOptions
1717 ++ optional cfg.dnsSingleRequest "single-request"
1818 ++ optional cfg.dnsExtensionMechanism "edns0";
19+
20+
21+ localhostMapped4 = cfg.hosts ? "127.0.0.1" && elem "localhost" cfg.hosts."127.0.0.1";
22+ localhostMapped6 = cfg.hosts ? "::1" && elem "localhost" cfg.hosts."::1";
23+
24+ localhostMultiple = any (elem "localhost") (attrValues (removeAttrs cfg.hosts [ "127.0.0.1" "::1" ]));
25+
1926in
2027
2128{
@@ -23,8 +30,7 @@ in
2330 options = {
2431
2532 networking.hosts = lib.mkOption {
26− type = types.attrsOf ( types.listOf types.str );
27− default = {};
33+ type = types.attrsOf (types.listOf types.str);
2834 example = literalExample ''
2935 {
3036 "127.0.0.1" = [ "foo.bar.baz" ];
@@ -192,6 +198,27 @@ in
192198
193199 config = {
194200
201+ assertions = [{
202+ assertion = localhostMapped4;
203+ message = ''`networking.hosts` doesn't map "127.0.0.1" to "localhost"'';
204+ } {
205+ assertion = !cfg.enableIPv6 || localhostMapped6;
206+ message = ''`networking.hosts` doesn't map "::1" to "localhost"'';
207+ } {
208+ assertion = !localhostMultiple;
209+ message = ''
210+ `networking.hosts` maps "localhost" to something other than "127.0.0.1"
211+ or "::1". This will break some applications. Please use
212+ `networking.extraHosts` if you really want to add such a mapping.
213+ '';
214+ }];
215+
216+ networking.hosts = {
217+ "127.0.0.1" = [ "localhost" ];
218+ } // optionalAttrs cfg.enableIPv6 {
219+ "::1" = [ "localhost" ];
220+ };
221+
195222 environment.etc =
196223 { # /etc/services: TCP/UDP port assignments.
197224 "services".source = pkgs.iana-etc + "/etc/services";
@@ -203,25 +230,13 @@ in
203230 "rpc".source = pkgs.glibc.out + "/etc/rpc";
204231
205232 # /etc/hosts: Hostname-to-IP mappings.
206− "hosts".text =
207− let oneToString = set : ip : ip + " " + concatStringsSep " " ( getAttr ip set );
208− allToString = set : concatMapStringsSep "\n" ( oneToString set ) ( attrNames set );
209− userLocalHosts = optionalString
210− ( builtins.hasAttr "127.0.0.1" cfg.hosts )
211− ( concatStringsSep " " ( remove "localhost" cfg.hosts."127.0.0.1" ));
212− userLocalHosts6 = optionalString
213− ( builtins.hasAttr "::1" cfg.hosts )
214− ( concatStringsSep " " ( remove "localhost" cfg.hosts."::1" ));
215− otherHosts = allToString ( removeAttrs cfg.hosts [ "127.0.0.1" "::1" ]);
216− in
217− ''
218− 127.0.0.1 ${userLocalHosts} localhost
219− ${optionalString cfg.enableIPv6 ''
220− ::1 ${userLocalHosts6} localhost
221− ''}
222− ${otherHosts}
223− ${cfg.extraHosts}
224− '';
233+ "hosts".text = let
234+ oneToString = set: ip: ip + " " + concatStringsSep " " set.${ip};
235+ allToString = set: concatMapStringsSep "\n" (oneToString set) (attrNames set);
236+ in ''
237+ ${allToString cfg.hosts}
238+ ${cfg.extraHosts}
239+ '';
225240
226241 # /etc/host.conf: resolver configuration file
227242 "host.conf".text = cfg.hostConf;
@@ -296,4 +311,4 @@ in
296311
297312 };
298313
299− }
314+}