fork/nix-minecraft
git clone https://git.julia.blue/fork/nix-minecraft
a3fd606
develop
1{ config , lib , pkgs , ...} : 2with lib ; 3let 4cfg = config . services . minecraft-servers ; 5 6mkOpt = type :default : 7mkOption { inherit type default ; }; 8 9mkOpt' = type :default :description : 10mkOption { inherit type default description ; }; 11 12mkBoolOpt = default :mkOption { 13inherit default ; 14type = types . bool ; 15example = true ; 16}; 17 18mkBoolOpt' = default :description :mkOption { 19inherit default description ; 20type = types . bool ; 21example = true ; 22}; 23 24normalizeFiles = files :mapAttrs configToPath ( filterAttrs ( _ :nonEmptyValue ) files ); 25nonEmptyValue = x :nonEmpty x && ( x ?value -> nonEmpty x . value ); 26nonEmpty = x :x != { } && x != [ ]; 27 28configToPath = name :config : 29if isStringLike config # Includes paths and packages 30then config 31else ( getFormat name config ). generate name config . value ; 32getFormat = name :config : 33if config ?format && config . format != null 34then config . format 35else inferFormat name ; 36inferFormat = name : 37let 38error = throw "nix-minecraft: Could not infer format from file ' ${ name } '. Specify one using 'format'." ; 39extension = builtins . match "[^.]*\\.(.+)" name ; 40in 41if extension != null && extension != [ ] 42then formatExtensions .${ head extension } or error 43else error ; 44 45formatExtensions = with pkgs . formats ; { 46"yml" = yaml { }; 47"yaml" = yaml { }; 48"json" = json { }; 49"props" = keyValue { }; 50"properties" = keyValue { }; 51"toml" = toml { }; 52"ini" = ini { }; 53}; 54 55configType = types . submodule { 56options = { 57format = mkOption { 58type = with types ; nullOr attrs ; 59default = null ; 60description = '' 61The format to use when converting "value" into a file. If set to 62null (the default), we'll try to infer it from the file name. 63'' ; 64example = literalExpression "pkgs.formats.yaml { }" ; 65}; 66value = mkOption { 67type = with types ; either ( attrsOf anything ) ( listOf anything ); 68description = '' 69A value that can be converted into the specified format. 70'' ; 71}; 72}; 73}; 74 75mkEnableOpt = description :mkBoolOpt' false description ; 76in 77{ 78options . services . minecraft-servers = { 79enable = mkEnableOpt '' 80If enabled, the servers in <option>services.minecraft-servers.servers</option> 81will be created and started as applicable. 82The data for the servers will be loaded from and 83saved to <option>services.minecraft-servers.dataDir</option> 84'' ; 85 86eula = mkEnableOpt '' 87Whether you agree to 88<link xlink:href="https://account.mojang.com/documents/minecraft_eula"> 89Mojang's EULA</link>. This option must be set to 90<literal>true</literal> to run Minecraft server. 91'' ; 92 93openFirewall = mkEnableOpt '' 94Whether to open ports in the firewall for each server. 95Sets the default for <option>services.minecraft-servers.servers.<name>.openFirewall</option>. 96'' ; 97 98dataDir = mkOpt' types . path "/srv/minecraft" '' 99Directory to store the Minecraft servers. 100Each server will be under a subdirectory named after 101the server name in this directory, such as <literal>/srv/minecraft/servername</literal>. 102'' ; 103 104runDir = mkOpt' types . path "/run/minecraft" '' 105Directory to place the runtime tmux sockets into. 106Each server's console will be a tmux socket file in the form of <literal>servername.sock</literal>. 107To connect to the console, run `tmux -S /run/minecraft/servername.sock attach`, 108press `Ctrl + b` then `d` to detach. 109'' ; 110 111user = mkOption { 112type = types . str ; 113default = "minecraft" ; 114description = '' 115Name of the user to create and run servers under. 116It is recommended to leave this as the default, as it is 117the same user as <option>services.minecraft-server</option>. 118'' ; 119internal = true ; 120visible = false ; 121}; 122 123group = mkOption { 124type = types . str ; 125default = "minecraft" ; 126description = '' 127Name of the group to create and run servers under. 128In order to modify the server files or attach to the tmux socket, 129your user must be a part of this group. 130It is recommended to leave this as the default, as it is 131the same group as <option>services.minecraft-server</option>. 132'' ; 133}; 134 135environmentFile = mkOpt' ( types . nullOr types . path ) null '' 136File consisting of lines in the form varname=value to define environment 137variables for the minecraft servers. 138 139Secrets (database passwords, secret keys, etc.) can be provided to server 140files without adding them to the Nix store by defining them in the 141environment file and referring to them in option 142<option>services.minecraft-servers.servers.<name>.files</option> with the 143syntax @varname@. 144'' ; 145 146servers = mkOption { 147default = { }; 148description = '' 149Servers to create and manage using this module. 150Each server can be stopped with <literal>systemctl stop minecraft-server-servername</literal>. 151::: {.warning} 152If the server is not stopped using `systemctl`, the service will automatically restart the server. 153See <option>services.minecraft-servers.servers.<name>.restart</option>. 154::: 155'' ; 156type = types . attrsOf ( types . submodule { 157options = { 158enable = mkEnableOpt '' 159Whether to enable this server. 160If set to <literal>false</literal>, does NOT delete any data in the data directory, 161just does not generate the service file. 162'' ; 163 164autoStart = mkBoolOpt' true '' 165Whether to start this server on boot. 166If set to <literal>false</literal>, can still be started with 167<literal>systemctl start minecraft-server-servername</literal>. 168Requires the server to be enabled. 169'' ; 170 171openFirewall = mkOption { 172type = types . bool ; 173default = cfg . openFirewall ; 174defaultText = "The value of <literal>services.minecraft-servers.openFirewall</literal>" ; 175description = '' 176Whether to open ports in the firewall for this server. 177'' ; 178}; 179 180restart = mkOpt' types . str "always" '' 181Value of systemd's <literal>Restart=</literal> service configuration option. 182Due to the servers being started in tmux sockets, values other than 183<literal>"no"</literal> and <literal>"always"</literal> may not work properly. 184As a consequence of the <literal>"always"</literal> option, stopping the server 185in-game with the <literal>stop</literal> command will cause the server to automatically restart. 186'' ; 187 188enableReload = mkOpt' types . bool false '' 189Reload server when configuration changes (instead of restart). 190 191This action re-links/copies the declared symlinks/files. You can 192include additional actions (even in-game commands) by setting 193<option>services.minecraft-servers.<name>.extraReload</option>. 194'' ; 195 196extraReload = mkOpt' types . lines "" '' 197Extra commands to run when reloading the service. Only has an 198effect if 199<option>services.minecraft-servers.<name>.enableReload</option> is 200true. 201'' ; 202 203whitelist = mkOption { 204type = 205let 206minecraftUUID = types . strMatching 207"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" // { 208description = "Minecraft UUID" ; 209}; 210in 211types . attrsOf minecraftUUID ; 212default = { }; 213description = '' 214Whitelisted players, only has an effect when 215enabled via <option>services.minecraft-servers.<name>.serverProperties</option> 216by setting <literal>white-list</literal> to <literal>true</literal. 217'' ; 218example = literalExpression '' 219{ 220username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 221username2 = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 222} 223'' ; 224}; 225 226serverProperties = mkOption { 227type = with types ; attrsOf ( oneOf [ bool int str ]); 228default = { }; 229example = literalExpression '' 230{ 231server-port = 43000; 232difficulty = 3; 233gamemode = 1; 234max-players = 5; 235motd = "NixOS Minecraft server!"; 236white-list = true; 237enable-rcon = true; 238"rcon.password" = "hunter2"; 239} 240'' ; 241description = '' 242Minecraft server properties for the server.properties file of this server. See 243<link xlink:href="https://minecraft.gamepedia.com/Server.properties#Java_Edition_3"/> 244for documentation on these values. 245'' ; 246}; 247 248package = mkOption { 249description = "The Minecraft server package to use." ; 250type = types . package ; 251default = pkgs . minecraft-server ; 252defaultText = literalExpression "pkgs.minecraft-server" ; 253example = "pkgs.minecraftServers.vanilla-1_18_2" ; 254}; 255 256jvmOpts = mkOpt' ( types . separatedString " " ) "-Xmx2G -Xms1G" "JVM options for this server." ; 257 258symlinks = with types ; mkOpt' ( attrsOf ( either path configType )) { } '' 259Things to symlink into this server's data directory, in the form of 260a nix package/derivation. Can be used to declaratively manage 261arbitrary files in the server's data directory. 262'' ; 263files = with types ; mkOpt' ( attrsOf ( either path configType )) { } '' 264Things to copy into this server's data directory. Similar to 265symlinks, but these are actual files. Useful for configuration 266files that don't behave well when read-only. 267'' ; 268}; 269}); 270}; 271}; 272 273config = mkIf cfg . enable 274( 275let 276servers = filterAttrs ( _ :cfg :cfg . enable ) cfg . servers ; 277in 278{ 279users = { 280users . minecraft = { 281description = "Minecraft server service user" ; 282home = cfg . dataDir ; 283createHome = true ; 284homeMode = "770" ; 285isSystemUser = true ; 286group = "minecraft" ; 287}; 288groups . minecraft = { }; 289}; 290 291assertions = [ 292{ 293assertion = cfg . eula ; 294message = "You must agree to Mojangs EULA to run minecraft-servers." 295+ " Read https://account.mojang.com/documents/minecraft_eula and" 296+ " set `services.minecraft-servers.eula` to `true` if you agree." ; 297} 298{ 299assertion = ! config . services . minecraft-server . enable && cfg . dataDir != config . services . minecraft-server . dataDir ; 300message = "`services.minecraft-servers.dataDir` and `services.minecraft-server.dataDir` conflict." 301+ " Set one to use a different data directory." ; 302} 303{ 304assertion = 305let 306serverPorts = mapAttrsToList 307( name :conf :conf . serverProperties . server-port or 25565 ) 308( filterAttrs ( _ :cfg :cfg . openFirewall ) servers ); 309 310counts = map ( port :count ( x :x == port ) serverPorts ) ( unique serverPorts ); 311in 312lib . all ( x :x == 1 ) counts ; 313message = "Multiple servers are set to use the same port. Change one to use a different port." ; 314} 315]; 316 317networking . firewall = 318let 319toOpen = filterAttrs ( _ :cfg :cfg . openFirewall ) servers ; 320# Minecraft and RCON 321getTCPPorts = n :c : 322[ c . serverProperties . server-port or 25565 ] ++ 323( optional ( c . serverProperties . enable-rcon or false ) ( c . serverProperties . "rcon.port" or 25575 )); 324# Query 325getUDPPorts = n :c : 326optional ( c . serverProperties . enable-query or false ) ( c . serverProperties . "query.port" or 25565 ); 327in 328{ 329allowedUDPPorts = flatten ( mapAttrsToList getUDPPorts toOpen ); 330allowedTCPPorts = flatten ( mapAttrsToList getTCPPorts toOpen ); 331}; 332 333systemd . tmpfiles . rules = mapAttrsToList 334( name :_ : 335"d ' ${ cfg . dataDir } / ${ name } ' 0770 ${ cfg . user } - - -" 336) 337servers ; 338 339systemd . services = mapAttrs' 340( name :conf : 341let 342tmux = " ${ getBin pkgs . tmux } /bin/tmux" ; 343tmuxSock = " ${ cfg . runDir } / ${ name } .sock" ; 344 345symlinks = normalizeFiles ({ 346"eula.txt" . value = { eula = true ; }; 347"eula.txt" . format = pkgs . formats . keyValue { }; 348} // conf . symlinks ); 349files = normalizeFiles ({ 350"whitelist.json" . value = mapAttrsToList ( n :v :{ name = n ; uuid = v ; }) conf . whitelist ; 351"server.properties" . value = conf . serverProperties ; 352} // conf . files ); 353 354startScript = pkgs . writeScript "minecraft-start- ${ name } " '' 355#! ${ pkgs . runtimeShell } 356${ tmux } -S ${ tmuxSock } new -d ${ getExe conf . package } ${ conf . jvmOpts } 357 358# HACK: PrivateUsers makes every user besides root/minecraft `nobody`, so this restores old tmux behavior 359# See https://github.com/Infinidoge/nix-minecraft/issues/5 360${ tmux } -S ${ tmuxSock } server-access -aw nobody 361'' ; 362 363stopScript = pkgs . writeScript "minecraft-stop- ${ name } " '' 364#! ${ pkgs . runtimeShell } 365 366if ! [ -d "/proc/$1" ]; then 367exit 0 368fi 369 370${ tmux } -S ${ tmuxSock } send-keys stop Enter 371'' ; 372in 373{ 374name = "minecraft-server- ${ name } " ; 375value = rec { 376description = "Minecraft Server ${ name } " ; 377wantedBy = mkIf conf . autoStart [ "multi-user.target" ]; 378after = [ "network.target" ]; 379 380enable = conf . enable ; 381 382serviceConfig = { 383ExecStart = " ${ startScript } " ; 384ExecStop = " ${ stopScript } $MAINPID" ; 385Restart = conf . restart ; 386WorkingDirectory = " ${ cfg . dataDir } / ${ name } " ; 387User = "minecraft" ; 388Type = "forking" ; 389GuessMainPID = true ; 390RuntimeDirectory = "minecraft" ; 391RuntimeDirectoryPreserve = "yes" ; 392EnvironmentFile = mkIf ( cfg . environmentFile != null ) 393( toString cfg . environmentFile ); 394 395# Hardening 396CapabilityBoundingSet = [ "" ]; 397DeviceAllow = [ "" ]; 398LockPersonality = true ; 399PrivateDevices = true ; 400PrivateTmp = true ; 401PrivateUsers = true ; 402ProtectClock = true ; 403ProtectControlGroups = true ; 404ProtectHome = true ; 405ProtectHostname = true ; 406ProtectKernelLogs = true ; 407ProtectKernelModules = true ; 408ProtectKernelTunables = true ; 409ProtectProc = "invisible" ; 410RestrictNamespaces = true ; 411RestrictRealtime = true ; 412RestrictSUIDSGID = true ; 413SystemCallArchitectures = "native" ; 414UMask = "0007" ; 415}; 416restartIfChanged = ! conf . enableReload ; 417reloadIfChanged = conf . enableReload ; 418 419reload = '' 420${ postStop } 421${ preStart } 422'' + conf . extraReload ; 423 424preStart = 425let 426mkSymlinks = pkgs . writeShellScript "minecraft-server- ${ name } -symlinks" 427( concatStringsSep "\n" 428( mapAttrsToList 429( n :v :'' 430if [[ -L " ${ n } " ]]; then 431unlink " ${ n } " 432elif [[ -e " ${ n } " ]]; then 433echo " ${ n } already exists, moving" 434mv " ${ n } " " ${ n } .bak" 435fi 436mkdir -p "$(dirname " ${ n } ")" 437ln -sf " ${ v } " " ${ n } " 438'' ) 439symlinks )); 440 441mkFiles = pkgs . writeShellScript "minecraft-server- ${ name } -files" 442( concatStringsSep "\n" 443( mapAttrsToList 444( n :v :'' 445if [[ -L " ${ n } " ]]; then 446unlink " ${ n } " 447elif ${ pkgs . diffutils } /bin/cmp -s " ${ n } " " ${ v } "; then 448rm " ${ n } " 449elif [[ -e " ${ n } " ]]; then 450echo " ${ n } already exists, moving" 451mv " ${ n } " " ${ n } .bak" 452fi 453mkdir -p $(dirname " ${ n } ") 454${ pkgs . gawk } /bin/awk '{ 455for(varname in ENVIRON) 456gsub("@"varname"@", ENVIRON[varname]) 457}' " ${ v } " > " ${ n } " 459'' ) 460files )); 461in 462'' 463${ mkSymlinks } 464${ mkFiles } 465'' ; 466 467postStart = '' 468${ pkgs . coreutils } /bin/chmod 660 ${ tmuxSock } 469'' ; 470 471postStop = 472let 473rmSymlinks = pkgs . writeShellScript "minecraft-server- ${ name } -rm-symlinks" 474( concatStringsSep "\n" 475( mapAttrsToList ( n :v :"unlink \" ${ n } \"" ) symlinks ) 476); 477rmFiles = pkgs . writeShellScript "minecraft-server- ${ name } -rm-files" 478( concatStringsSep "\n" 479( mapAttrsToList ( n :v :"rm -f \" ${ n } \"" ) files ) 480); 481in 482'' 483${ rmSymlinks } 484${ rmFiles } 485'' ; 486}; 487}) 488servers ; 489} 490); 491}