1
0
nixfiles/modules/nginx-port-forward/default.nix

71 lines
2.0 KiB
Nix
Raw Permalink Normal View History

2020-12-26 01:24:40 +01:00
{ config, lib, pkgs, ... }:
with lib;
let
cfg = config.clerie.nginx-port-forward;
2021-01-03 16:03:42 +01:00
certs = config.security.acme.certs;
sslDhparam = config.services.nginx.sslDhparam;
2020-12-26 01:24:40 +01:00
mkServerBlock = isUDP: port: forward: ''
2020-12-26 01:24:40 +01:00
server {
2021-01-03 16:03:42 +01:00
listen ${port}${optionalString isUDP " udp"}${optionalString (forward.certName != null) " ssl"};
listen [::]:${port}${optionalString isUDP " udp"}${optionalString (forward.certName != null) " ssl"};
${ optionalString (forward.certName != null) ''
ssl_certificate ${certs.${forward.certName}.directory}/fullchain.pem;
ssl_certificate_key ${certs.${forward.certName}.directory}/key.pem;
${ optionalString (sslDhparam != null) "ssl_dhparam ${sslDhparam};" }
'' }
2020-12-26 01:24:40 +01:00
proxy_pass ${forward.host}:${toString forward.port};
}
'';
portForwardConf = ''
stream {
${ concatStringsSep "\n" (mapAttrsToList (mkServerBlock false) cfg.tcpPorts) }
${ concatStringsSep "\n" (mapAttrsToList (mkServerBlock true) cfg.udpPorts) }
2020-12-26 01:24:40 +01:00
}
'';
portOpts = { config, ... }@moduleAttrs: {
options = {
host = mkOption {
type = types.str;
};
port = mkOption {
type = types.int;
};
2021-01-03 16:03:42 +01:00
certName = mkOption {
type = with types; nullOr str;
default = null;
};
2020-12-26 01:24:40 +01:00
};
};
in
{
options = {
clerie.nginx-port-forward = {
enable = mkEnableOption "Nginx Port Forward";
tcpPorts = mkOption {
type = with types; attrsOf (submodule portOpts);
default = {};
};
udpPorts = mkOption {
type = with types; attrsOf (submodule portOpts);
default = {};
};
};
};
config = mkIf cfg.enable {
services.nginx.enable = true;
services.nginx.appendConfig = portForwardConf;
networking.firewall.allowedTCPPorts = mapAttrsToList ( port: dontcare: toInt port ) cfg.tcpPorts;
networking.firewall.allowedUDPPorts = mapAttrsToList ( port: dontcare: toInt port ) cfg.udpPorts;
};
}