Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions extra/services/userhosts.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
{ pkgs, config, lib, ... }:
with lib;
let
cfg = config.services.userhosts;
hostsFile = pkgs.writeTextFile {
name = "hosts";
text =
let
lines = lib.mapAttrsToList
(ip: hostnames: "${ip} ${builtins.concatStringsSep " " hostnames}")
cfg.hosts;
in
"${builtins.concatStringsSep "\n" lines}\n";
};
in
{
options.services.userhosts = {
package = mkOption {
type = types.package;
default = pkgs.userhosts;
description = ''
The package containing the LD_PRELOAD library libuserhosts.so.
'';
};
hosts = mkOption {
type = types.attrsOf (types.listOf types.string);
default = {};
description = ''
The host entries to use for userhosts.
The top-level entries are the addresses where hostnames are resolved to.
For each address you can supply a list of hostnames.
This structure represents the structure you'd see in /etc/hosts.

Note that, unlike /etc/hosts, you can also use names to resolve to as well.
'';
example = {
"127.0.0.1" = [ "example.org" ];
"myhost.local" = [ "mydomain.test" ];
};
};
};

config = mkIf (cfg.hosts != {}) (
if !pkgs.stdenv.isLinux then
builtins.trace "warning: services.usershosts is only supported on Linux" {}
else
{
env = [
{
name = "HOSTS_FILE";
value = "${hostsFile}";
}
{
name = "LD_PRELOAD";
prefix = "${cfg.package}/lib/libuserhosts.so";
}
];
}
);
}
30 changes: 30 additions & 0 deletions tests/extra/services.userhosts.nix
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{ pkgs, devshell, runTest }:
if !pkgs.stdenv.isLinux then
{}
else
{
# Basic test
simple =
let
shell = devshell.mkShell {
imports = [ ../../extra/services/userhosts.nix ];
packages = [
pkgs.netcat
];
services.userhosts.hosts = {
"127.0.0.1" = [ "example.org" ];
};
devshell.name = "services-userhosts-simple";
};
in
runTest "simple" { } ''
# Load the devshell
source ${shell}/env.bash

nc -l 127.0.0.1 8080 &
LISTENER_PID=$!
trap "kill $LISTENER_PID 2>/dev/null || true" EXIT
sleep 0.1
nc -zv example.org 8080
'';
}