Format repo

This commit is contained in:
Pim Kunis 2024-10-28 14:12:06 +01:00
parent eed797fb13
commit 5341235bc3
21 changed files with 1200 additions and 1076 deletions

View file

@ -1,21 +1,21 @@
{ self, deploy-rs, ... }: {
let self,
deploy-rs,
...
}: let
deployArch = "x86_64-linux"; deployArch = "x86_64-linux";
mkDeployNodes = nodeDef: mkDeployNodes = nodeDef:
builtins.mapAttrs builtins.mapAttrs
(name: machine: nodeDef name machine) (name: machine: nodeDef name machine)
self.machines.${deployArch}; self.machines.${deployArch};
in in {
{
deploy = { deploy = {
sshUser = "root"; sshUser = "root";
user = "root"; user = "root";
nodes = mkDeployNodes (name: machine: nodes = mkDeployNodes (name: machine: let
let
nixosConfiguration = self.nixosConfigurations.${name}; nixosConfiguration = self.nixosConfigurations.${name};
in in {
{
hostname = nixosConfiguration.config.networking.fqdn; hostname = nixosConfiguration.config.networking.fqdn;
profiles.system = { profiles.system = {
remoteBuild = machine.arch != deployArch; remoteBuild = machine.arch != deployArch;

View file

@ -109,6 +109,22 @@
"type": "github" "type": "github"
} }
}, },
"flake-compat_4": {
"flake": false,
"locked": {
"lastModified": 1696426674,
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-parts": { "flake-parts": {
"inputs": { "inputs": {
"nixpkgs-lib": [ "nixpkgs-lib": [
@ -163,6 +179,27 @@
"type": "github" "type": "github"
} }
}, },
"gitignore": {
"inputs": {
"nixpkgs": [
"pre-commit-hooks",
"nixpkgs"
]
},
"locked": {
"lastModified": 1709087332,
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
"owner": "hercules-ci",
"repo": "gitignore.nix",
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "gitignore.nix",
"type": "github"
}
},
"kubenix": { "kubenix": {
"inputs": { "inputs": {
"flake-compat": "flake-compat_2", "flake-compat": "flake-compat_2",
@ -262,6 +299,22 @@
} }
}, },
"nixpkgs-stable": { "nixpkgs-stable": {
"locked": {
"lastModified": 1720386169,
"narHash": "sha256-NGKVY4PjzwAa4upkGtAMz1npHGoRzWotlSnVlqI40mo=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "194846768975b7ad2c4988bdb82572c00222c0d7",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-24.05",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-stable_2": {
"locked": { "locked": {
"lastModified": 1729357638, "lastModified": 1729357638,
"narHash": "sha256-66RHecx+zohbZwJVEPF7uuwHeqf8rykZTMCTqIrOew4=", "narHash": "sha256-66RHecx+zohbZwJVEPF7uuwHeqf8rykZTMCTqIrOew4=",
@ -309,6 +362,45 @@
"type": "github" "type": "github"
} }
}, },
"nixpkgs_3": {
"locked": {
"lastModified": 1726871744,
"narHash": "sha256-V5LpfdHyQkUF7RfOaDPrZDP+oqz88lTJrMT1+stXNwo=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "a1d92660c6b3b7c26fb883500a80ea9d33321be2",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixpkgs-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"pre-commit-hooks": {
"inputs": {
"flake-compat": "flake-compat_4",
"gitignore": "gitignore",
"nixpkgs": [
"nixpkgs-unstable"
],
"nixpkgs-stable": "nixpkgs-stable"
},
"locked": {
"lastModified": 1729104314,
"narHash": "sha256-pZRZsq5oCdJt3upZIU4aslS9XwFJ+/nVtALHIciX/BI=",
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "3c3e88f0f544d6bb54329832616af7eb971b6be6",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "git-hooks.nix",
"type": "github"
}
},
"root": { "root": {
"inputs": { "inputs": {
"deploy-rs": "deploy-rs", "deploy-rs": "deploy-rs",
@ -321,7 +413,9 @@
"nixos-hardware": "nixos-hardware", "nixos-hardware": "nixos-hardware",
"nixpkgs": "nixpkgs_2", "nixpkgs": "nixpkgs_2",
"nixpkgs-unstable": "nixpkgs-unstable", "nixpkgs-unstable": "nixpkgs-unstable",
"sops-nix": "sops-nix" "pre-commit-hooks": "pre-commit-hooks",
"sops-nix": "sops-nix",
"treefmt-nix": "treefmt-nix"
} }
}, },
"sops-nix": { "sops-nix": {
@ -329,7 +423,7 @@
"nixpkgs": [ "nixpkgs": [
"nixpkgs" "nixpkgs"
], ],
"nixpkgs-stable": "nixpkgs-stable" "nixpkgs-stable": "nixpkgs-stable_2"
}, },
"locked": { "locked": {
"lastModified": 1729775275, "lastModified": 1729775275,
@ -410,6 +504,24 @@
"type": "github" "type": "github"
} }
}, },
"treefmt-nix": {
"inputs": {
"nixpkgs": "nixpkgs_3"
},
"locked": {
"lastModified": 1730025913,
"narHash": "sha256-Y9NtFmP8ciLyRsopcCx1tyoaaStKeq+EndwtGCgww7I=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "bae131e525cc8718da22fbeb8d8c7c43c4ea502a",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "treefmt-nix",
"type": "github"
}
},
"utils": { "utils": {
"inputs": { "inputs": {
"systems": "systems" "systems": "systems"

View file

@ -55,8 +55,11 @@
}; };
}; };
outputs = outputs = inputs @ {
inputs@{ nixpkgs, flake-utils, ... }: nixpkgs,
flake-utils,
...
}:
flake-utils.lib.meld inputs [ flake-utils.lib.meld inputs [
./scripts ./scripts
./deploy.nix ./deploy.nix

View file

@ -1,9 +1,14 @@
{ nixpkgs, treefmt-nix, flake-utils, ...}: flake-utils.lib.eachDefaultSystem (system: {
let nixpkgs,
treefmt-nix,
flake-utils,
...
}:
flake-utils.lib.eachDefaultSystem (
system: let
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
treefmtEval = treefmt-nix.lib.evalModule pkgs ./treefmt.nix; treefmtEval = treefmt-nix.lib.evalModule pkgs ./treefmt.nix;
in in {
{
formatter = treefmtEval.config.build.wrapper; formatter = treefmtEval.config.build.wrapper;
} }
) )

View file

@ -1,5 +1,9 @@
{ nixpkgs, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system: {
let nixpkgs,
flake-utils,
...
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
lib = pkgs.lib; lib = pkgs.lib;
@ -43,9 +47,9 @@ let
}; };
}; };
}; };
in in {
{ machines =
machines = (lib.modules.evalModules { (lib.modules.evalModules {
modules = [ modules = [
allOpts allOpts
./warwick.nix ./warwick.nix
@ -55,5 +59,7 @@ in
# ./talos.nix # ./talos.nix
# ./pikvm.nix # ./pikvm.nix
]; ];
}).config.machines; })
.config
.machines;
}) })

View file

@ -3,7 +3,12 @@
arch = "aarch64-linux"; arch = "aarch64-linux";
isRaspberryPi = true; isRaspberryPi = true;
nixosModule = { config, inputs, lib, ... }: { nixosModule = {
config,
inputs,
lib,
...
}: {
# imports = [ "${inputs.nixpkgs}/nixos/modules/installer/sd-card/sd-image-aarch64.nix" ]; # imports = [ "${inputs.nixpkgs}/nixos/modules/installer/sd-card/sd-image-aarch64.nix" ];
lab = { lab = {
storage.profile = "pi"; storage.profile = "pi";

View file

@ -1,5 +1,9 @@
{ pkgs, lib, config, ... }: {
let pkgs,
lib,
config,
...
}: let
cfg = config.lab.backups; cfg = config.lab.backups;
borgmaticConfig = pkgs.writeTextFile { borgmaticConfig = pkgs.writeTextFile {
@ -27,8 +31,7 @@ let
encryption_passcommand = "${pkgs.coreutils}/bin/cat ${config.sops.secrets."borg/borgPassphrase".path}"; encryption_passcommand = "${pkgs.coreutils}/bin/cat ${config.sops.secrets."borg/borgPassphrase".path}";
}; };
}; };
in in {
{
options.lab.backups = { options.lab.backups = {
enable = lib.mkOption { enable = lib.mkOption {
default = false; default = false;

View file

@ -1,5 +1,8 @@
{ lib, config, ... }: {
let lib,
config,
...
}: let
cfg = config.lab.data-sharing; cfg = config.lab.data-sharing;
nfsShares = [ nfsShares = [
@ -13,13 +16,12 @@ let
nfsExports = lib.strings.concatLines ( nfsExports = lib.strings.concatLines (
builtins.map builtins.map
(share: (
"${share} 192.168.30.0/16(rw,sync,no_subtree_check,no_root_squash) 127.0.0.1/8(rw,sync,no_subtree_check,no_root_squash) 10.0.0.0/8(rw,sync,no_subtree_check,no_root_squash)" share: "${share} 192.168.30.0/16(rw,sync,no_subtree_check,no_root_squash) 127.0.0.1/8(rw,sync,no_subtree_check,no_root_squash) 10.0.0.0/8(rw,sync,no_subtree_check,no_root_squash)"
) )
nfsShares nfsShares
); );
in in {
{
options.lab.data-sharing = { options.lab.data-sharing = {
enable = lib.mkOption { enable = lib.mkOption {
default = false; default = false;

View file

@ -1,5 +1,14 @@
{ self, pkgs, config, lib, inputs, machine, ... }: { {
imports = [ self,
pkgs,
config,
lib,
inputs,
machine,
...
}: {
imports =
[
./storage.nix ./storage.nix
./backups.nix ./backups.nix
./networking ./networking
@ -11,7 +20,8 @@
inputs.disko.nixosModules.disko inputs.disko.nixosModules.disko
inputs.sops-nix.nixosModules.sops inputs.sops-nix.nixosModules.sops
inputs.nix-snapshotter.nixosModules.nix-snapshotter inputs.nix-snapshotter.nixosModules.nix-snapshotter
] ++ lib.lists.optional (machine.isRaspberryPi) inputs.nixos-hardware.nixosModules.raspberry-pi-4; ]
++ lib.lists.optional (machine.isRaspberryPi) inputs.nixos-hardware.nixosModules.raspberry-pi-4;
config = { config = {
time.timeZone = "Europe/Amsterdam"; time.timeZone = "Europe/Amsterdam";
@ -31,7 +41,9 @@
i18n = { i18n = {
defaultLocale = "en_US.UTF-8"; defaultLocale = "en_US.UTF-8";
extraLocaleSettings = let extraLocale = "nl_NL.UTF-8"; in { extraLocaleSettings = let
extraLocale = "nl_NL.UTF-8";
in {
LC_ADDRESS = extraLocale; LC_ADDRESS = extraLocale;
LC_IDENTIFICATION = extraLocale; LC_IDENTIFICATION = extraLocale;
LC_MEASUREMENT = extraLocale; LC_MEASUREMENT = extraLocale;

View file

@ -1,8 +1,13 @@
{ self, inputs, pkgs, lib, config, ... }:
let
cfg = config.lab.k3s;
in
{ {
self,
inputs,
pkgs,
lib,
config,
...
}: let
cfg = config.lab.k3s;
in {
options.lab.k3s = { options.lab.k3s = {
enable = lib.mkOption { enable = lib.mkOption {
default = false; default = false;
@ -62,8 +67,7 @@ in
address = "/run/nix-snapshotter/nix-snapshotter.sock"; address = "/run/nix-snapshotter/nix-snapshotter.sock";
}; };
plugins = plugins = let
let
k3s-cni-plugins = pkgs.buildEnv { k3s-cni-plugins = pkgs.buildEnv {
name = "k3s-cni-plugins"; name = "k3s-cni-plugins";
paths = with pkgs; [ paths = with pkgs; [
@ -71,8 +75,7 @@ in
cni-plugin-flannel cni-plugin-flannel
]; ];
}; };
in in {
{
"io.containerd.grpc.v1.cri" = { "io.containerd.grpc.v1.cri" = {
stream_server_address = "127.0.0.1"; stream_server_address = "127.0.0.1";
stream_server_port = "10010"; stream_server_port = "10010";
@ -91,10 +94,12 @@ in
}; };
}; };
"io.containerd.transfer.v1.local".unpack_config = [{ "io.containerd.transfer.v1.local".unpack_config = [
{
platform = "linux/amd64"; platform = "linux/amd64";
snapshotter = "nix"; snapshotter = "nix";
}]; }
];
}; };
}; };
}; };
@ -102,8 +107,7 @@ in
services = { services = {
nix-snapshotter.enable = true; nix-snapshotter.enable = true;
k3s = k3s = let
let
serverFlagList = [ serverFlagList = [
"--image-service-endpoint=unix:///run/nix-snapshotter/nix-snapshotter.sock" "--image-service-endpoint=unix:///run/nix-snapshotter/nix-snapshotter.sock"
"--snapshotter=overlayfs" "--snapshotter=overlayfs"
@ -115,8 +119,7 @@ in
]; ];
serverFlags = builtins.concatStringsSep " " serverFlagList; serverFlags = builtins.concatStringsSep " " serverFlagList;
in in {
{
enable = true; enable = true;
role = cfg.role; role = cfg.role;
tokenFile = config.sops.secrets."k3s/serverToken".path; tokenFile = config.sops.secrets."k3s/serverToken".path;
@ -143,11 +146,14 @@ in
k3s-bootstrap = lib.mkIf (cfg.role == "server") { k3s-bootstrap = lib.mkIf (cfg.role == "server") {
text = ( text = (
let let
k3sBootstrapFile = (inputs.kubenix.evalModules.x86_64-linux { k3sBootstrapFile =
(inputs.kubenix.evalModules.x86_64-linux {
module = import ./bootstrap.nix; module = import ./bootstrap.nix;
}).config.kubernetes.result; })
in .config
'' .kubernetes
.result;
in ''
mkdir -p /var/lib/rancher/k3s/server/manifests mkdir -p /var/lib/rancher/k3s/server/manifests
ln -sf ${k3sBootstrapFile} /var/lib/rancher/k3s/server/manifests/k3s-bootstrap.json ln -sf ${k3sBootstrapFile} /var/lib/rancher/k3s/server/manifests/k3s-bootstrap.json
'' ''
@ -166,11 +172,9 @@ in
}; };
}; };
sops.secrets = sops.secrets = let
let
keyPathBase = "/var/lib/rancher/k3s/server/tls"; keyPathBase = "/var/lib/rancher/k3s/server/tls";
in in {
{
"k3s/serverToken" = {}; "k3s/serverToken" = {};
"k3s/keys/clientCAKey".path = "${keyPathBase}/client-ca.key"; "k3s/keys/clientCAKey".path = "${keyPathBase}/client-ca.key";
"k3s/keys/requestHeaderCAKey".path = "${keyPathBase}/request-header-ca.key"; "k3s/keys/requestHeaderCAKey".path = "${keyPathBase}/request-header-ca.key";

View file

@ -1,8 +1,11 @@
{ lib, config, machines, ... }:
let
cfg = config.lab.monitoring;
in
{ {
lib,
config,
machines,
...
}: let
cfg = config.lab.monitoring;
in {
options = { options = {
lab.monitoring = { lab.monitoring = {
enable = lib.mkOption { enable = lib.mkOption {
@ -18,7 +21,8 @@ in
}; };
config = lib.mkIf cfg.enable { config = lib.mkIf cfg.enable {
networking.firewall.allowedTCPPorts = [ config.services.prometheus.exporters.node.port ] networking.firewall.allowedTCPPorts =
[config.services.prometheus.exporters.node.port]
++ lib.lists.optionals cfg.server.enable [80]; ++ lib.lists.optionals cfg.server.enable [80];
services.prometheus = { services.prometheus = {
@ -32,12 +36,15 @@ in
scrapeConfigs = lib.mkIf cfg.server.enable ( scrapeConfigs = lib.mkIf cfg.server.enable (
let let
generated = lib.attrsets.mapAttrsToList generated =
lib.attrsets.mapAttrsToList
(name: machine: { (name: machine: {
job_name = name; job_name = name;
static_configs = [{ static_configs = [
{
targets = ["${name}.dmz:${toString config.services.prometheus.exporters.node.port}"]; targets = ["${name}.dmz:${toString config.services.prometheus.exporters.node.port}"];
}]; }
];
}) })
machines; machines;
@ -53,9 +60,11 @@ in
password = "admin"; password = "admin";
}; };
static_configs = [{ static_configs = [
{
targets = ["pikvm.dmz"]; targets = ["pikvm.dmz"];
}]; }
];
}; };
in in
generated ++ [pikvm] generated ++ [pikvm]

View file

@ -1,4 +1,8 @@
{ lib, machine, ... }: { {
lib,
machine,
...
}: {
config = { config = {
networking = { networking = {
domain = "dmz"; domain = "dmz";

View file

@ -1,5 +1,8 @@
{ lib, config, ... }: {
let lib,
config,
...
}: let
cfg = config.lab.storage; cfg = config.lab.storage;
modules = [ modules = [
{ {
@ -155,8 +158,7 @@ let
}; };
} }
]; ];
in in {
{
imports = modules; imports = modules;
options.lab.storage = { options.lab.storage = {

View file

@ -1,8 +1,10 @@
{ lib, config, ... }:
let
cfg = config.lab.tailscale;
in
{ {
lib,
config,
...
}: let
cfg = config.lab.tailscale;
in {
options = { options = {
lab.tailscale = { lab.tailscale = {
enable = lib.mkEnableOption "tailscale"; enable = lib.mkEnableOption "tailscale";
@ -21,10 +23,12 @@ in
useRoutingFeatures = "server"; useRoutingFeatures = "server";
openFirewall = true; openFirewall = true;
extraUpFlags = [ extraUpFlags =
[
"--accept-dns=false" "--accept-dns=false"
"--hostname=${config.networking.hostName}" "--hostname=${config.networking.hostName}"
] ++ lib.lists.optional cfg.advertiseExitNode "--advertise-exit-node" ]
++ lib.lists.optional cfg.advertiseExitNode "--advertise-exit-node"
++ lib.lists.optional cfg.advertiseExitNode "--advertise-routes=192.168.30.0/24"; ++ lib.lists.optional cfg.advertiseExitNode "--advertise-routes=192.168.30.0/24";
}; };

View file

@ -1,15 +1,18 @@
{ self, nixpkgs, ... }@inputs: {
let self,
nixpkgs,
...
} @ inputs: let
deployArch = "x86_64-linux"; deployArch = "x86_64-linux";
machines = self.machines.${deployArch}; machines = self.machines.${deployArch};
mkNixosSystems = systemDef: mkNixosSystems = systemDef:
builtins.mapAttrs builtins.mapAttrs
(name: machine: (
name: machine:
nixpkgs.lib.nixosSystem (systemDef name machine) nixpkgs.lib.nixosSystem (systemDef name machine)
) )
machines; machines;
in in {
{
nixosConfigurations = mkNixosSystems (name: machine: { nixosConfigurations = mkNixosSystems (name: machine: {
system = machine.arch; system = machine.arch;

View file

@ -1,8 +1,17 @@
{ nixpkgs, flake-utils, ... }: flake-utils.lib.eachDefaultSystem (system: {
let nixpkgs,
flake-utils,
...
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacyPackages.${system}; pkgs = nixpkgs.legacyPackages.${system};
createScript = { name, runtimeInputs, scriptPath, extraWrapperFlags ? "", ... }: createScript = {
let name,
runtimeInputs,
scriptPath,
extraWrapperFlags ? "",
...
}: let
script = (pkgs.writeScriptBin name (builtins.readFile scriptPath)).overrideAttrs (old: { script = (pkgs.writeScriptBin name (builtins.readFile scriptPath)).overrideAttrs (old: {
buildCommand = "${old.buildCommand}\n patchShebangs $out"; buildCommand = "${old.buildCommand}\n patchShebangs $out";
}); });
@ -13,8 +22,7 @@ let
buildInputs = [pkgs.makeWrapper]; buildInputs = [pkgs.makeWrapper];
postBuild = "wrapProgram $out/bin/${name} --set PATH $out/bin ${extraWrapperFlags}"; postBuild = "wrapProgram $out/bin/${name} --set PATH $out/bin ${extraWrapperFlags}";
}; };
in in {
{
packages.bootstrap = createScript { packages.bootstrap = createScript {
name = "bootstrap"; name = "bootstrap";
runtimeInputs = with pkgs; [sops coreutils nixos-anywhere]; runtimeInputs = with pkgs; [sops coreutils nixos-anywhere];

View file

@ -1,8 +1,11 @@
{ flake-utils, nixpkgs, ... }: flake-utils.lib.eachDefaultSystem (system:
let
pkgs = nixpkgs.legacyPackages.${system};
in
{ {
flake-utils,
nixpkgs,
...
}:
flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacyPackages.${system};
in {
devShells.default = pkgs.mkShell { devShells.default = pkgs.mkShell {
buildInputs = with pkgs; [ansible]; buildInputs = with pkgs; [ansible];
}; };

View file

@ -1,12 +1,12 @@
{ nixpkgs, flake-utils, ... }: {
nixpkgs,
let flake-utils,
systemAttrs = flake-utils.lib.eachDefaultSystem (system: ...
let }: let
systemAttrs = flake-utils.lib.eachDefaultSystem (system: let
pkgs = nixpkgs.legacypackages.${system}; pkgs = nixpkgs.legacypackages.${system};
lib = pkgs.lib; lib = pkgs.lib;
in in {
{
net = import ./net.nix lib; net = import ./net.nix lib;
}); });

View file

@ -1,13 +1,9 @@
# IP address arithmetic and validation in Nix by @duairc: # IP address arithmetic and validation in Nix by @duairc:
# https://gist.github.com/duairc/5c9bb3c922e5d501a1edb9e7b3b845ba # https://gist.github.com/duairc/5c9bb3c922e5d501a1edb9e7b3b845ba
lib: let
lib: net =
{
let
net = {
ip = { ip = {
# add :: (ip | mac | integer) -> ip -> ip # add :: (ip | mac | integer) -> ip -> ip
# #
# Examples: # Examples:
@ -39,8 +35,7 @@ let
# Adding MAC to IPv6: # Adding MAC to IPv6:
# > net.ip.add "fe:ed:fa:ce:f0:0d" "dead:cafe:beef::" # > net.ip.add "fe:ed:fa:ce:f0:0d" "dead:cafe:beef::"
# "dead:cafe:beef::feed:face:f00d" # "dead:cafe:beef::feed:face:f00d"
add = delta: ip: add = delta: ip: let
let
function = "net.ip.add"; function = "net.ip.add";
delta' = typechecks.numeric function "delta" delta; delta' = typechecks.numeric function "delta" delta;
ip' = typechecks.ip function "ip" ip; ip' = typechecks.ip function "ip" ip;
@ -61,8 +56,7 @@ let
# and you just want to calculate the offset between them — a result # and you just want to calculate the offset between them — a result
# like "0.0.0.10" is not very useful (which is what you would get # like "0.0.0.10" is not very useful (which is what you would get
# from net.ip.subtract). # from net.ip.subtract).
diff = minuend: subtrahend: diff = minuend: subtrahend: let
let
function = "net.ip.diff"; function = "net.ip.diff";
minuend' = typechecks.ip function "minuend" minuend; minuend' = typechecks.ip function "minuend" minuend;
subtrahend' = typechecks.ip function "subtrahend" subtrahend; subtrahend' = typechecks.ip function "subtrahend" subtrahend;
@ -84,8 +78,7 @@ let
# parameter. Its implementation takes the "delta" parameter, # parameter. Its implementation takes the "delta" parameter,
# coerces it to be the same type as the "ip" paramter, negates it # coerces it to be the same type as the "ip" paramter, negates it
# (using two's complement), and then adds it to "ip". # (using two's complement), and then adds it to "ip".
subtract = delta: ip: subtract = delta: ip: let
let
function = "net.ip.subtract"; function = "net.ip.subtract";
delta' = typechecks.numeric function "delta" delta; delta' = typechecks.numeric function "delta" delta;
ip' = typechecks.ip function "ip" ip; ip' = typechecks.ip function "ip" ip;
@ -94,7 +87,6 @@ let
}; };
mac = { mac = {
# add :: (ip | mac | integer) -> mac -> mac # add :: (ip | mac | integer) -> mac -> mac
# #
# Examples: # Examples:
@ -114,8 +106,7 @@ let
# Adding MAC to MAC: # Adding MAC to MAC:
# > net.mac.add "fe:ed:fa:00:00:00" "00:00:00:ce:f0:0d" # > net.mac.add "fe:ed:fa:00:00:00" "00:00:00:ce:f0:0d"
# "fe:ed:fa:ce:f0:0d" # "fe:ed:fa:ce:f0:0d"
add = delta: mac: add = delta: mac: let
let
function = "net.mac.add"; function = "net.mac.add";
delta' = typechecks.numeric function "delta" delta; delta' = typechecks.numeric function "delta" delta;
mac' = typechecks.mac function "mac" mac; mac' = typechecks.mac function "mac" mac;
@ -131,8 +122,7 @@ let
# #
# The difference between net.mac.diff and net.mac.subtract is that # The difference between net.mac.diff and net.mac.subtract is that
# net.mac.diff will always return an integer. # net.mac.diff will always return an integer.
diff = minuend: subtrahend: diff = minuend: subtrahend: let
let
function = "net.mac.diff"; function = "net.mac.diff";
minuend' = typechecks.mac function "minuend" minuend; minuend' = typechecks.mac function "minuend" minuend;
subtrahend' = typechecks.mac function "subtrahend" subtrahend; subtrahend' = typechecks.mac function "subtrahend" subtrahend;
@ -148,8 +138,7 @@ let
# #
# The difference between net.mac.subtract and net.mac.diff is that # The difference between net.mac.subtract and net.mac.diff is that
# net.mac.subtract will always return a MAC address. # net.mac.subtract will always return a MAC address.
subtract = delta: mac: subtract = delta: mac: let
let
function = "net.mac.subtract"; function = "net.mac.subtract";
delta' = typechecks.numeric function "delta" delta; delta' = typechecks.numeric function "delta" delta;
mac' = typechecks.mac function "mac" mac; mac' = typechecks.mac function "mac" mac;
@ -165,8 +154,7 @@ let
# #
# > net.cidr.add (-2) "127.0.0.0/8" # > net.cidr.add (-2) "127.0.0.0/8"
# "125.0.0.0/8" # "125.0.0.0/8"
add = delta: cidr: add = delta: cidr: let
let
function = "net.cidr.add"; function = "net.cidr.add";
delta' = typechecks.numeric function "delta" delta; delta' = typechecks.numeric function "delta" delta;
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
@ -180,8 +168,7 @@ let
# #
# > net.cidr.child "127.0.0.0/8" "10.0.0.0/8" # > net.cidr.child "127.0.0.0/8" "10.0.0.0/8"
# false # false
child = subcidr: cidr: child = subcidr: cidr: let
let
function = "net.cidr.child"; function = "net.cidr.child";
subcidr' = typechecks.cidr function "subcidr" subcidr; subcidr' = typechecks.cidr function "subcidr" subcidr;
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
@ -195,8 +182,7 @@ let
# #
# > net.cidr.contains "127.0.0.1" "192.168.0.0/16" # > net.cidr.contains "127.0.0.1" "192.168.0.0/16"
# false # false
contains = ip: cidr: contains = ip: cidr: let
let
function = "net.cidr.contains"; function = "net.cidr.contains";
ip' = typechecks.ip function "ip" ip; ip' = typechecks.ip function "ip" ip;
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
@ -213,8 +199,7 @@ let
# #
# > net.cidr.capacity "dead:cafe:beef::/48" (saturates to maxBound) # > net.cidr.capacity "dead:cafe:beef::/48" (saturates to maxBound)
# 9223372036854775807 # 9223372036854775807
capacity = cidr: capacity = cidr: let
let
function = "net.cidr.capacity"; function = "net.cidr.capacity";
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
in in
@ -233,8 +218,7 @@ let
# #
# Inpsired by: # Inpsired by:
# https://www.terraform.io/docs/configuration/functions/cidrhost.html # https://www.terraform.io/docs/configuration/functions/cidrhost.html
host = hostnum: cidr: host = hostnum: cidr: let
let
function = "net.cidr.host"; function = "net.cidr.host";
hostnum' = typechecks.numeric function "hostnum" hostnum; hostnum' = typechecks.numeric function "hostnum" hostnum;
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
@ -248,8 +232,7 @@ let
# #
# > net.cidr.prefix "dead:cafe:beef::/48" # > net.cidr.prefix "dead:cafe:beef::/48"
# 48 # 48
length = cidr: length = cidr: let
let
function = "net.cidr.length"; function = "net.cidr.length";
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
in in
@ -262,8 +245,7 @@ let
# #
# > net.cidr.make 40 "dead:cafe:beef::feed:face:f00d" # > net.cidr.make 40 "dead:cafe:beef::feed:face:f00d"
# "dead:cafe:be00::/40" # "dead:cafe:be00::/40"
make = length: base: make = length: base: let
let
function = "net.cidr.make"; function = "net.cidr.make";
length' = typechecks.int function "length" length; length' = typechecks.int function "length" length;
base' = typechecks.ip function "base" base; base' = typechecks.ip function "base" base;
@ -277,8 +259,7 @@ let
# #
# > net.cidr.netmask "dead:cafe:beef::/64" # > net.cidr.netmask "dead:cafe:beef::/64"
# "ffff:ffff:ffff:ffff::" # "ffff:ffff:ffff:ffff::"
netmask = cidr: netmask = cidr: let
let
function = "net.cidr.netmask"; function = "net.cidr.netmask";
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
in in
@ -291,8 +272,7 @@ let
# #
# > net.cidr.prefix "dead:cafe:beef::/48" # > net.cidr.prefix "dead:cafe:beef::/48"
# 80 # 80
size = cidr: size = cidr: let
let
function = "net.cidr.size"; function = "net.cidr.size";
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
in in
@ -311,23 +291,26 @@ let
# #
# Inspired by: # Inspired by:
# https://www.terraform.io/docs/configuration/functions/cidrsubnet.html # https://www.terraform.io/docs/configuration/functions/cidrsubnet.html
subnet = length: netnum: cidr: subnet = length: netnum: cidr: let
let
function = "net.cidr.subnet"; function = "net.cidr.subnet";
length' = typechecks.int function "length" length; length' = typechecks.int function "length" length;
netnum' = typechecks.numeric function "netnum" netnum; netnum' = typechecks.numeric function "netnum" netnum;
cidr' = typechecks.cidr function "cidr" cidr; cidr' = typechecks.cidr function "cidr" cidr;
in in
builders.cidr (implementations.cidr.subnet length' netnum' cidr'); builders.cidr (implementations.cidr.subnet length' netnum' cidr');
}; };
} // ({ }
types = // {
let types = let
mkParsedOptionType = {
mkParsedOptionType = { name, description, parser, builder }: name,
let description,
normalize = def: def // { parser,
builder,
}: let
normalize = def:
def
// {
value = builder (parser def.value); value = builder (parser def.value);
}; };
in in
@ -337,31 +320,28 @@ let
merge = loc: defs: lib.mergeEqualOption loc (map normalize defs); merge = loc: defs: lib.mergeEqualOption loc (map normalize defs);
}; };
dependent-ip = type: cidr: dependent-ip = type: cidr: let
let
cidrs = cidrs =
if builtins.isList cidr if builtins.isList cidr
then cidr then cidr
else [cidr]; else [cidr];
in in
lib.types.addCheck type (i: lib.any (net.cidr.contains i) cidrs) // { lib.types.addCheck type (i: lib.any (net.cidr.contains i) cidrs)
// {
description = type.description + " in ${builtins.concatStringsSep " or " cidrs}"; description = type.description + " in ${builtins.concatStringsSep " or " cidrs}";
}; };
dependent-cidr = type: cidr: dependent-cidr = type: cidr: let
let
cidrs = cidrs =
if builtins.isList cidr if builtins.isList cidr
then cidr then cidr
else [cidr]; else [cidr];
in in
lib.types.addCheck type (i: lib.any (net.cidr.child i) cidrs) // { lib.types.addCheck type (i: lib.any (net.cidr.child i) cidrs)
// {
description = type.description + " in ${builtins.concatStringsSep " or " cidrs}"; description = type.description + " in ${builtins.concatStringsSep " or " cidrs}";
}; };
in rec {
in
rec {
ip = mkParsedOptionType { ip = mkParsedOptionType {
name = "ip"; name = "ip";
description = "IPv4 or IPv6 address"; description = "IPv4 or IPv6 address";
@ -422,23 +402,22 @@ let
parser = parsers.mac; parser = parsers.mac;
builder = builders.mac; builder = builders.mac;
}; };
}; };
} };
);
list = { list = {
cons = a: b: [a] ++ b; cons = a: b: [a] ++ b;
}; };
bit = bit = let
let
shift = n: x: shift = n: x:
if n < 0 if n < 0
then x * math.pow 2 (-n) then x * math.pow 2 (-n)
else else let
let safeDiv = n: d:
safeDiv = n: d: if d == 0 then 0 else n / d; if d == 0
then 0
else n / d;
d = math.pow 2 n; d = math.pow 2 n;
in in
if x < 0 if x < 0
@ -458,8 +437,7 @@ let
not = xor (-1); not = xor (-1);
mask = n: and (left n 1 - 1); mask = n: and (left n 1 - 1);
in in {
{
inherit left right and or xor not mask; inherit left right and or xor not mask;
}; };
@ -484,9 +462,7 @@ let
else pow (x * x) (n / 2); else pow (x * x) (n / 2);
}; };
parsers = parsers = let
let
# fmap :: (a -> b) -> parser a -> parser b # fmap :: (a -> b) -> parser a -> parser b
fmap = f: ma: bind ma (a: pure (f a)); fmap = f: ma: bind ma (a: pure (f a));
@ -513,8 +489,7 @@ let
empty = string: null; empty = string: null;
# alt :: parser a -> parser a -> parser a # alt :: parser a -> parser a -> parser a
alt = left: right: string: alt = left: right: string: let
let
result = left string; result = left string;
in in
if builtins.isNull result if builtins.isNull result
@ -522,7 +497,10 @@ let
else result; else result;
# guard :: bool -> parser {} # guard :: bool -> parser {}
guard = condition: if condition then pure { } else empty; guard = condition:
if condition
then pure {}
else empty;
# mfilter :: (a -> bool) -> parser a -> parser a # mfilter :: (a -> bool) -> parser a -> parser a
mfilter = f: parser: bind parser (a: then_ (guard (f a)) (pure a)); mfilter = f: parser: bind parser (a: then_ (guard (f a)) (pure a));
@ -534,8 +512,7 @@ let
many = v: alt (some v) (pure []); many = v: alt (some v) (pure []);
# bind :: parser a -> (a -> parser b) -> parser b # bind :: parser a -> (a -> parser b) -> parser b
bind = parser: f: string: bind = parser: f: string: let
let
a = parser string; a = parser string;
in in
if builtins.isNull a if builtins.isNull a
@ -543,8 +520,7 @@ let
else f a.result a.leftovers; else f a.result a.leftovers;
# run :: parser a -> string -> maybe a # run :: parser a -> string -> maybe a
run = parser: string: run = parser: string: let
let
result = parser string; result = parser string;
in in
if builtins.isNull result || result.leftovers != "" if builtins.isNull result || result.leftovers != ""
@ -560,13 +536,14 @@ let
}; };
# Count how many characters were consumed by a parser # Count how many characters were consumed by a parser
count = parser: string: count = parser: string: let
let
result = parser string; result = parser string;
in in
if builtins.isNull result if builtins.isNull result
then null then null
else result // { else
result
// {
result = { result = {
inherit (result) result; inherit (result) result;
count = with result; count = with result;
@ -587,15 +564,16 @@ let
string = css: string = css:
if css == "" if css == ""
then pure {} then pure {}
else else let
let
c = builtins.substring 0 1 css; c = builtins.substring 0 1 css;
cs = builtins.substring 1 (-1) css; cs = builtins.substring 1 (-1) css;
in in
then_ (char c) (string cs); then_ (char c) (string cs);
digit = set: bind next ( digit = set:
c: then_ bind next (
c:
then_
(guard (builtins.hasAttr c set)) (guard (builtins.hasAttr c set))
(pure (builtins.getAttr c set)) (pure (builtins.getAttr c set))
); );
@ -613,7 +591,9 @@ let
"9" = 9; "9" = 9;
}; };
hexadecimalDigits = decimalDigits // { hexadecimalDigits =
decimalDigits
// {
"a" = 10; "a" = 10;
"b" = 11; "b" = 11;
"c" = 12; "c" = 12;
@ -644,8 +624,7 @@ let
hexadecimal = fmap fromHexadecimalDigits (some (digit hexadecimalDigits)); hexadecimal = fmap fromHexadecimalDigits (some (digit hexadecimalDigits));
ipv4 = ipv4 = let
let
dot = char "."; dot = char ".";
octet = mfilter (n: n < 256) decimal; octet = mfilter (n: n < 256) decimal;
@ -660,8 +639,7 @@ let
# This is more or less a literal translation of # This is more or less a literal translation of
# https://hackage.haskell.org/package/ip/docs/src/Net.IPv6.html#parser # https://hackage.haskell.org/package/ip/docs/src/Net.IPv6.html#parser
ipv6 = ipv6 = let
let
colon = char ":"; colon = char ":";
hextet = limit 4 hexadecimal; hextet = limit 4 hexadecimal;
@ -669,8 +647,7 @@ let
fromHextets = hextets: fromHextets = hextets:
if builtins.length hextets != 8 if builtins.length hextets != 8
then empty then empty
else else let
let
a = builtins.elemAt hextets 0; a = builtins.elemAt hextets 0;
b = builtins.elemAt hextets 1; b = builtins.elemAt hextets 1;
c = builtins.elemAt hextets 2; c = builtins.elemAt hextets 2;
@ -689,21 +666,20 @@ let
}; };
}; };
ipv4' = fmap ipv4' =
fmap
( (
address: address: let
let
upper = bit.right 16 address.ipv4; upper = bit.right 16 address.ipv4;
lower = bit.mask 16 address.ipv4; lower = bit.mask 16 address.ipv4;
in in [upper lower]
[ upper lower ]
) )
ipv4; ipv4;
part = n: part = n: let
let
n' = n + 1; n' = n + 1;
hex = liftA2 list.cons hextet hex =
liftA2 list.cons hextet
( (
then_ colon then_ colon
( (
@ -715,15 +691,13 @@ let
in in
if n == 7 if n == 7
then fmap (a: [a]) hextet then fmap (a: [a]) hextet
else else if n == 6
if n == 6
then alt ipv4' hex then alt ipv4' hex
else hex; else hex;
doubleColon = n: doubleColon = n:
bind (alt afterDoubleColon (pure [])) ( bind (alt afterDoubleColon (pure [])) (
rest: rest: let
let
missing = 8 - n - builtins.length rest; missing = 8 - n - builtins.length rest;
in in
if missing < 0 if missing < 0
@ -741,7 +715,6 @@ let
(pure []) (pure [])
) )
); );
in in
bind bind
( (
@ -767,8 +740,7 @@ let
ipv6 ipv6
(then_ (char "/") (mfilter (n: n <= 128) decimal)); (then_ (char "/") (mfilter (n: n <= 128) decimal));
mac = mac = let
let
colon = char ":"; colon = char ":";
octet = exactly 2 hexadecimal; octet = exactly 2 hexadecimal;
@ -780,9 +752,7 @@ let
}; };
in in
liftA6 fromOctets octet octet' octet' octet' octet' octet'; liftA6 fromOctets octet octet' octet' octet' octet' octet';
in {
in
{
ipv4 = run ipv4; ipv4 = run ipv4;
ipv6 = run ipv6; ipv6 = run ipv6;
ip = run (alt ipv4 ipv6); ip = run (alt ipv4 ipv6);
@ -793,11 +763,8 @@ let
numeric = run (alt (alt ipv4 ipv6) mac); numeric = run (alt (alt ipv4 ipv6) mac);
}; };
builders = builders = let
let ipv4 = address: let
ipv4 = address:
let
abcd = address.ipv4; abcd = address.ipv4;
abc = bit.right 8 abcd; abc = bit.right 8 abcd;
ab = bit.right 8 abc; ab = bit.right 8 abc;
@ -810,31 +777,23 @@ let
# This is more or less a literal translation of # This is more or less a literal translation of
# https://hackage.haskell.org/package/ip/docs/src/Net.IPv6.html#encode # https://hackage.haskell.org/package/ip/docs/src/Net.IPv6.html#encode
ipv6 = address: ipv6 = address: let
let
digits = "0123456789abcdef"; digits = "0123456789abcdef";
toHexString = n: toHexString = n: let
let
rest = bit.right 4 n; rest = bit.right 4 n;
current = bit.mask 4 n; current = bit.mask 4 n;
prefix = prefix =
if rest == 0 if rest == 0
then "" then ""
else toHexString rest; else toHexString rest;
in in "${prefix}${builtins.substring current 1 digits}";
"${prefix}${builtins.substring current 1 digits}";
in in
if (with address.ipv6; a == 0 && b == 0 && c == 0 && d > 65535) if (with address.ipv6; a == 0 && b == 0 && c == 0 && d > 65535)
then "::${ipv4 {ipv4 = address.ipv6.d;}}" then "::${ipv4 {ipv4 = address.ipv6.d;}}"
else else if (with address.ipv6; a == 0 && b == 0 && c == 65535)
if (with address.ipv6; a == 0 && b == 0 && c == 65535)
then "::ffff:${ipv4 {ipv4 = address.ipv6.d;}}" then "::ffff:${ipv4 {ipv4 = address.ipv6.d;}}"
else else let
let
a = bit.right 16 address.ipv6.a; a = bit.right 16 address.ipv6.a;
b = bit.mask 16 address.ipv6.a; b = bit.mask 16 address.ipv6.a;
c = bit.right 16 address.ipv6.b; c = bit.right 16 address.ipv6.b;
@ -848,12 +807,10 @@ let
# calculate the position and size of the longest sequence of # calculate the position and size of the longest sequence of
# zeroes within the list of hextets # zeroes within the list of hextets
longest = longest = let
let
go = i: current: best: go = i: current: best:
if i < builtins.length hextets if i < builtins.length hextets
then then let
let
n = builtins.elemAt hextets i; n = builtins.elemAt hextets i;
current' = current' =
@ -864,7 +821,9 @@ let
size = 1; size = 1;
position = i; position = i;
} }
else current // { else
current
// {
size = current.size + 1; size = current.size + 1;
} }
else null; else null;
@ -874,8 +833,7 @@ let
then then
if builtins.isNull best if builtins.isNull best
then current' then current'
else else if current'.size > best.size
if current'.size > best.size
then current' then current'
else best else best
else best; else best;
@ -890,8 +848,7 @@ let
in in
if builtins.isNull longest if builtins.isNull longest
then format hextets then format hextets
else else let
let
sublist = i: length: xs: sublist = i: length: xs:
map map
(builtins.elemAt xs) (builtins.elemAt xs)
@ -902,52 +859,40 @@ let
before = sublist 0 longest.position hextets; before = sublist 0 longest.position hextets;
after = sublist end (builtins.length hextets - end) hextets; after = sublist end (builtins.length hextets - end) hextets;
in in "${format before}::${format after}";
"${format before}::${format after}";
ip = address: ip = address:
if address ? ipv4 if address ? ipv4
then ipv4 address then ipv4 address
else ipv6 address; else ipv6 address;
cidrv4 = cidr: cidrv4 = cidr: "${ipv4 cidr.base}/${toString cidr.length}";
"${ipv4 cidr.base}/${toString cidr.length}";
cidrv6 = cidr: cidrv6 = cidr: "${ipv6 cidr.base}/${toString cidr.length}";
"${ipv6 cidr.base}/${toString cidr.length}";
cidr = cidr: cidr = cidr: "${ip cidr.base}/${toString cidr.length}";
"${ip cidr.base}/${toString cidr.length}";
mac = address: mac = address: let
let
digits = "0123456789abcdef"; digits = "0123456789abcdef";
octet = n: octet = n: let
let
upper = bit.right 4 n; upper = bit.right 4 n;
lower = bit.mask 4 n; lower = bit.mask 4 n;
in in "${builtins.substring upper 1 digits}${builtins.substring lower 1 digits}";
"${builtins.substring upper 1 digits}${builtins.substring lower 1 digits}"; in let
in
let
a = bit.mask 8 (bit.right 40 address.mac); a = bit.mask 8 (bit.right 40 address.mac);
b = bit.mask 8 (bit.right 32 address.mac); b = bit.mask 8 (bit.right 32 address.mac);
c = bit.mask 8 (bit.right 24 address.mac); c = bit.mask 8 (bit.right 24 address.mac);
d = bit.mask 8 (bit.right 16 address.mac); d = bit.mask 8 (bit.right 16 address.mac);
e = bit.mask 8 (bit.right 8 address.mac); e = bit.mask 8 (bit.right 8 address.mac);
f = bit.mask 8 (bit.right 0 address.mac); f = bit.mask 8 (bit.right 0 address.mac);
in in "${octet a}:${octet b}:${octet c}:${octet d}:${octet e}:${octet f}";
"${octet a}:${octet b}:${octet c}:${octet d}:${octet e}:${octet f}"; in {
in
{
inherit ipv4 ipv6 ip cidrv4 cidrv6 cidr mac; inherit ipv4 ipv6 ip cidrv4 cidrv6 cidr mac;
}; };
arithmetic = rec { arithmetic = rec {
# or :: (ip | mac | integer) -> (ip | mac | integer) -> (ip | mac | integer) # or :: (ip | mac | integer) -> (ip | mac | integer) -> (ip | mac | integer)
or = a_: b: or = a_: b: let
let
a = coerce b a_; a = coerce b a_;
in in
if a ? ipv6 if a ? ipv6
@ -970,8 +915,7 @@ let
else bit.or a b; else bit.or a b;
# and :: (ip | mac | integer) -> (ip | mac | integer) -> (ip | mac | integer) # and :: (ip | mac | integer) -> (ip | mac | integer) -> (ip | mac | integer)
and = a_: b: and = a_: b: let
let
a = coerce b a_; a = coerce b a_;
in in
if a ? ipv6 if a ? ipv6
@ -1015,26 +959,22 @@ let
else bit.not a; else bit.not a;
# add :: (ip | mac | integer) -> (ip | mac | integer) -> (ip | mac | integer) # add :: (ip | mac | integer) -> (ip | mac | integer) -> (ip | mac | integer)
add = add = let
let
split = a: { split = a: {
fst = bit.mask 32 (bit.right 32 a); fst = bit.mask 32 (bit.right 32 a);
snd = bit.mask 32 a; snd = bit.mask 32 a;
}; };
in in
a_: b: a_: b: let
let
a = coerce b a_; a = coerce b a_;
in in
if a ? ipv6 if a ? ipv6
then then let
let
a' = split (a.ipv6.a + b.ipv6.a + b'.fst); a' = split (a.ipv6.a + b.ipv6.a + b'.fst);
b' = split (a.ipv6.b + b.ipv6.b + c'.fst); b' = split (a.ipv6.b + b.ipv6.b + c'.fst);
c' = split (a.ipv6.c + b.ipv6.c + d'.fst); c' = split (a.ipv6.c + b.ipv6.c + d'.fst);
d' = split (a.ipv6.d + b.ipv6.d); d' = split (a.ipv6.d + b.ipv6.d);
in in {
{
ipv6 = { ipv6 = {
a = a'.snd; a = a'.snd;
b = b'.snd; b = b'.snd;
@ -1056,9 +996,8 @@ let
subtract = a: b: add (add 1 (not (coerce b a))) b; subtract = a: b: add (add 1 (not (coerce b a))) b;
# diff :: (ip | mac | integer) -> (ip | mac | integer) -> (ipv6 | integer) # diff :: (ip | mac | integer) -> (ip | mac | integer) -> (ipv6 | integer)
diff = a: b: diff = a: b: let
let toIPv6 = coerce {ipv6.a = 0;};
toIPv6 = coerce ({ ipv6.a = 0; });
result = (subtract b (toIPv6 a)).ipv6; result = (subtract b (toIPv6 a)).ipv6;
max32 = bit.left 32 1 - 1; max32 = bit.left 32 1 - 1;
in in
@ -1072,8 +1011,7 @@ let
left = i: right (-i); left = i: right (-i);
# right :: integer -> (ip | mac | integer) -> (ip | mac | integer) # right :: integer -> (ip | mac | integer) -> (ip | mac | integer)
right = right = let
let
step = i: x: { step = i: x: {
_1 = bit.mask 32 (bit.right (i + 96) x); _1 = bit.mask 32 (bit.right (i + 96) x);
_2 = bit.mask 32 (bit.right (i + 64) x); _2 = bit.mask 32 (bit.right (i + 64) x);
@ -1087,14 +1025,12 @@ let
in in
i: x: i: x:
if x ? ipv6 if x ? ipv6
then then let
let
a' = step i x.ipv6.a; a' = step i x.ipv6.a;
b' = step i x.ipv6.b; b' = step i x.ipv6.b;
c' = step i x.ipv6.c; c' = step i x.ipv6.c;
d' = step i x.ipv6.d; d' = step i x.ipv6.d;
in in {
{
ipv6 = { ipv6 = {
a = ors [a'._4 b'._3 c'._2 d'._1]; a = ors [a'._4 b'._3 c'._2 d'._1];
b = ors [a'._5 b'._4 c'._3 d'._2]; b = ors [a'._5 b'._4 c'._3 d'._2];
@ -1180,8 +1116,7 @@ let
else { else {
mac = bit.mask 48 value; mac = bit.mask 48 value;
} }
else else if value ? ipv6
if value ? ipv6
then then
builtins.foldl' bit.or 0 builtins.foldl' bit.or 0
[ [
@ -1222,18 +1157,15 @@ let
cidr = rec { cidr = rec {
# add :: (ip | mac | integer) -> cidr -> cidr # add :: (ip | mac | integer) -> cidr -> cidr
add = delta: cidr: add = delta: cidr: let
let
size' = size cidr; size' = size cidr;
in in {
{
base = arithmetic.left size' (arithmetic.add delta (arithmetic.right size' cidr.base)); base = arithmetic.left size' (arithmetic.add delta (arithmetic.right size' cidr.base));
inherit (cidr) length; inherit (cidr) length;
}; };
# capacity :: cidr -> integer # capacity :: cidr -> integer
capacity = cidr: capacity = cidr: let
let
size' = size cidr; size' = size cidr;
in in
if size' > 62 if size' > 62
@ -1248,8 +1180,7 @@ let
contains = ip: cidr: host 0 (make cidr.length ip) == host 0 cidr; contains = ip: cidr: host 0 (make cidr.length ip) == host 0 cidr;
# host :: (ip | mac | integer) -> cidr -> ip # host :: (ip | mac | integer) -> cidr -> ip
host = index: cidr: host = index: cidr: let
let
index' = arithmetic.coerce cidr.base index; index' = arithmetic.coerce cidr.base index;
in in
arithmetic.or (arithmetic.shadow cidr.length index') cidr.base; arithmetic.or (arithmetic.shadow cidr.length index') cidr.base;
@ -1261,51 +1192,60 @@ let
netmask = cidr: arithmetic.coshadow cidr.length (arithmetic.coerce cidr.base (-1)); netmask = cidr: arithmetic.coshadow cidr.length (arithmetic.coerce cidr.base (-1));
# size :: cidr -> integer # size :: cidr -> integer
size = cidr: (if cidr.base ? ipv6 then 128 else 32) - cidr.length; size = cidr:
(
if cidr.base ? ipv6
then 128
else 32
)
- cidr.length;
# subnet :: integer -> (ip | mac | integer) -> cidr -> cidr # subnet :: integer -> (ip | mac | integer) -> cidr -> cidr
subnet = length: index: cidr: subnet = length: index: cidr: let
let
length' = cidr.length + length; length' = cidr.length + length;
index' = arithmetic.coerce cidr.base index; index' = arithmetic.coerce cidr.base index;
size = (if cidr.base ? ipv6 then 128 else 32) - length'; size =
(
if cidr.base ? ipv6
then 128
else 32
)
- length';
in in
make length' (host (arithmetic.left size index') cidr); make length' (host (arithmetic.left size index') cidr);
# make :: integer -> ip -> cidr # make :: integer -> ip -> cidr
make = length: base: make = length: base: let
let length' =
length' = math.clamp 0 (if base ? ipv6 then 128 else 32) length; math.clamp 0 (
in if base ? ipv6
{ then 128
else 32
)
length;
in {
base = arithmetic.coshadow length' base; base = arithmetic.coshadow length' base;
length = length'; length = length';
}; };
}; };
}; };
typechecks = typechecks = let
let
fail = description: function: argument: fail = description: function: argument:
builtins.throw "${function}: ${argument} parameter must be ${description}"; builtins.throw "${function}: ${argument} parameter must be ${description}";
meta = parser: description: function: argument: input: meta = parser: description: function: argument: input: let
let
error = fail description function argument; error = fail description function argument;
in in
if !builtins.isString input if !builtins.isString input
then error then error
else else let
let
result = parser input; result = parser input;
in in
if builtins.isNull result if builtins.isNull result
then error then error
else result; else result;
in {
in
{
int = function: argument: input: int = function: argument: input:
if builtins.isInt input if builtins.isInt input
then input then input
@ -1318,6 +1258,5 @@ let
then input then input
else meta parsers.numeric "an integer or IPv4, IPv6 or MAC address" function argument input; else meta parsers.numeric "an integer or IPv4, IPv6 or MAC address" function argument input;
}; };
in in
net net