fork/nix-minecraft
git clone https://git.julia.blue/fork/nix-minecraft
50d44c8
lazymc
1{ 2config , 3lib , 4options , 5pkgs , 6 ... 7} : 8with lib ; 9let 10cfg = config . services . minecraft-servers ; 11 12mkOpt = type :default :mkOption { inherit type default ; }; 13 14mkOpt' = 15type :default :description : 16mkOption { inherit type default description ; }; 17 18mkBoolOpt = 19default : 20mkOption { 21inherit default ; 22type = types . bool ; 23example = true ; 24}; 25 26mkBoolOpt' = 27default :description : 28mkOption { 29inherit default description ; 30type = types . bool ; 31example = true ; 32}; 33 34minecraftUUID = 35types . strMatching "([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{32})" 36// { 37description = "Minecraft UUID" ; 38}; 39 40normalizeFiles = files :mapAttrs configToPath ( filterAttrs ( _ :nonEmptyValue ) files ); 41nonEmptyValue = x :nonEmpty x && ( x ?value -> nonEmpty x . value ); 42nonEmpty = x :x != { } && x != [ ]; 43 44configToPath = 45name :config : 46if 47isStringLike config # Includes paths and packages 48then 49config 50else 51( getFormat name config ). generate name config . value ; 52getFormat = 53name :config :if config ?format && config . format != null then config . format else inferFormat name ; 54inferFormat = 55name : 56let 57error = throw "nix-minecraft: Could not infer format from file ' ${ name } '. Specify one using 'format'." ; 58extension = builtins . match "[^.]*\\.(.+)" name ; 59in 60if extension != null && extension != [ ] then 61formatExtensions .${ head extension } or error 62else 63error ; 64 65txtList = 66{ } : 67{ 68type = with lib . types ; listOf str ; 69generate = name :value :pkgs . writeText name ( lib . concatStringsSep "\n" value ); 70}; 71 72formatExtensions = with pkgs . formats ; { 73"yml" = yaml { }; 74"yaml" = yaml { }; 75"json" = json { }; 76"props" = keyValue { }; 77"properties" = keyValue { }; 78"toml" = toml { }; 79"ini" = ini { }; 80"txt" = txtList { }; 81}; 82 83configType = types . submodule { 84options = { 85format = mkOption { 86type = with types ; nullOr attrs ; 87default = null ; 88description = '' 89The format to use when converting "value" into a file. If set to 90null (the default), we'll try to infer it from the file name. 91'' ; 92example = literalExpression "pkgs.formats.yaml { }" ; 93}; 94value = mkOption { 95type = with types ; either ( attrsOf anything ) ( listOf anything ); 96description = '' 97A value that can be converted into the specified format. 98'' ; 99}; 100}; 101}; 102 103managementSystem = types . submodule { 104options = { 105tmux = { 106enable = mkEnableOption "management via a TMUX socket" ; 107socketPath = mkOption { 108type = with types ; functionTo path ; 109description = '' 110Function from a server name to the path at which the server's tmux socket is placed. 111To connect to the console, run `tmux -S <path to socket> attach`, 112press `Ctrl + b` then `d` to detach. 113 114Note that while currently the default respects <option>services.minecraft-servers.runDir</option>, 115that option is deprecated and will be removed. 116The default will then change to `name: "/run/minecraft/''${name}.sock`. 117'' ; 118default = name :" ${ cfg . runDir } / ${ name } .sock" ; 119defaultText = literalExpression ''name: "''${cfg.runDir}/''${name}.sock"'' ; 120}; 121}; 122systemd-socket = { 123enable = mkEnableOpt "management through the systemd journal & a command socket" ; 124stdinSocket = { 125path = mkOption { 126type = with types ; functionTo path ; 127description = '' 128Function from a server name to the path at which the server's stdin socket is placed. 129You can send the server commands by writing to this socket, 130for example with shell redirection: `echo 'list' > <path to socket>`. 131 132Note that while currently the default respects <option>services.minecraft-servers.runDir</option>, 133that option is deprecated and will be removed. 134The default will then change to `name: "/run/minecraft/''${name}.stdin`. 135'' ; 136default = name :" ${ cfg . runDir } / ${ name } .stdin" ; 137defaultText = literalExpression ''name: "''${cfg.runDir}/''${name}.stdin"'' ; 138}; 139mode = mkOption { 140type = types . strMatching "[0-7]{4}" ; 141description = "Access mode of the socket file in octal notation" ; 142default = "0660" ; 143}; 144}; 145}; 146}; 147}; 148 149managementSystemConfig = 150name :server : 151let 152ms = server . managementSystem ; 153tmux = " ${ getBin pkgs . tmux } /bin/tmux" ; 154runCommand = 155if server . lazymc . enable then 156" ${ server . lazymc . package } /bin/lazymc start --config lazymc.toml" 157else 158" ${ getExe server . package } ${ server . jvmOpts } " ; 159in 160assert assertMsg ( 161! ( ms . tmux . enable && ms . systemd-socket . enable ) 162) "Only one server management system can be enabled at a time." ; 163if ms . tmux . enable then 164let 165sock = ms . tmux . socketPath name ; 166in 167{ 168serviceConfig = { 169Type = "forking" ; 170GuessMainPID = true ; 171}; 172hooks = { 173start = '' 174${ tmux } -S ${ sock } new -d ${ runCommand } 175 176# HACK: PrivateUsers makes every user besides root/minecraft `nobody`, so this restores old tmux behavior 177# See https://github.com/Infinidoge/nix-minecraft/issues/5 178${ tmux } -S ${ sock } server-access -aw nobody 179'' ; 180postStart = '' 181${ pkgs . coreutils } /bin/chmod 660 ${ sock } 182'' ; 183stop = optionalString ( ! server . lazymc . enable ) '' 184function server_running { 185${ tmux } -S ${ sock } has-session 186} 187 188if ! server_running ; then 189exit 0 190fi 191 192${ tmux } -S ${ sock } send-keys C-u ${ escapeShellArg server . stopCommand } Enter 193 194while server_running; do sleep 1s; done 195'' ; 196}; 197} 198else if ms . systemd-socket . enable then 199{ 200serviceConfig = { 201Type = "simple" ; 202StandardInput = "socket" ; 203StandardOutput = "journal" ; 204StandardError = "journal" ; 205}; 206hooks = { 207start = runCommand ; 208postStart = "" ; 209stop = '' 210${ optionalString ( server . stopCommand != null && ! server . lazymc . enable ) '' 211echo ${ escapeShellArg server . stopCommand } > ${ escapeShellArg ( ms . systemd-socket . stdinSocket . path name )} 212 213while kill -0 "$1" 2> /dev/null; do sleep 1s; done 214'' } 215'' ; 216}; 217} 218else 219builtins . throw "At least one server management system must be enabled." ; 220 221mkEnableOpt = description :mkBoolOpt' false description ; 222in 223{ 224options . services . minecraft-servers = { 225enable = mkEnableOpt '' 226If enabled, the servers in <option>services.minecraft-servers.servers</option> 227will be created and started as applicable. 228The data for the servers will be loaded from and 229saved to <option>services.minecraft-servers.dataDir</option> 230'' ; 231 232eula = mkEnableOpt '' 233Whether you agree to 234<link xlink:href="https://account.mojang.com/documents/minecraft_eula"> 235Mojang's EULA</link>. This option must be set to 236<literal>true</literal> to run Minecraft server. 237'' ; 238 239openFirewall = mkEnableOpt '' 240Whether to open ports in the firewall for each server. 241Sets the default for <option>services.minecraft-servers.servers.<name>.openFirewall</option>. 242'' ; 243 244dataDir = mkOpt' types . path "/srv/minecraft" '' 245Directory to store the Minecraft servers. 246Each server will be under a subdirectory named after 247the server name in this directory, such as <literal>/srv/minecraft/servername</literal>. 248'' ; 249 250runDir = mkOpt' types . path "/run/minecraft" '' 251Deprecated: Directory to place the runtime tmux sockets into. 252Each server's console will be a tmux socket file in the form of <literal>servername.sock</literal>. 253To connect to the console, run `tmux -S /run/minecraft/servername.sock attach`, 254press `Ctrl + b` then `d` to detach. 255 256Plase use <option>services.minecraft-servers.managementSystem.tmux.socketPath</option>` instead. 257'' ; 258 259user = mkOption { 260type = types . str ; 261default = "minecraft" ; 262description = '' 263Name of the user to create and run servers under. 264It is recommended to leave this as the default, as it is 265the same user as <option>services.minecraft-server</option>. 266'' ; 267internal = true ; 268visible = false ; 269}; 270 271group = mkOption { 272type = types . str ; 273default = "minecraft" ; 274description = '' 275Name of the group to create and run servers under. 276In order to modify the server files your user must be a part of this 277group. If you are using the tmux management system (the default), you also need to be a part of this group to attach to the tmux socket. 278It is recommended to leave this as the default, as it is 279the same group as <option>services.minecraft-server</option>. 280'' ; 281}; 282 283environmentFile = mkOpt' ( types . nullOr types . path ) null '' 284File consisting of lines in the form varname=value to define environment 285variables for the minecraft servers. 286 287Secrets (database passwords, secret keys, etc.) can be provided to server 288files without adding them to the Nix store by defining them in the 289environment file and referring to them in option 290<option>services.minecraft-servers.servers.<name>.files</option> with the 291syntax @varname@. 292'' ; 293 294managementSystem = mkOption { 295type = managementSystem ; 296description = '' 297The default management system for all servers. 298'' ; 299default = { 300tmux . enable = true ; 301}; 302example = '' 303{ 304tmux.enable = false; 305systemd-socket.enable = true; 306} 307'' ; 308}; 309 310servers = mkOption { 311default = { }; 312description = '' 313Servers to create and manage using this module. 314Each server can be stopped with <literal>systemctl stop minecraft-server-servername</literal>. 315::: {.warning} 316If the server is not stopped using `systemctl`, the service will automatically restart the server. 317See <option>services.minecraft-servers.servers.<name>.restart</option>. 318::: 319'' ; 320type = types . attrsOf ( 321types . submodule ( 322{ name , ...} : 323{ 324options = { 325enable = mkEnableOpt '' 326Whether to enable this server. 327If set to <literal>false</literal>, does NOT delete any data in the data directory, 328just does not generate the service file. 329'' ; 330 331autoStart = mkBoolOpt' true '' 332Whether to start this server on boot. 333If set to <literal>false</literal>, can still be started with 334<literal>systemctl start minecraft-server-servername</literal>. 335Requires the server to be enabled. 336'' ; 337 338openFirewall = mkOption { 339type = types . bool ; 340default = cfg . openFirewall ; 341defaultText = "The value of <literal>services.minecraft-servers.openFirewall</literal>" ; 342description = '' 343Whether to open ports in the firewall for this server. 344'' ; 345}; 346 347restart = mkOpt' types . str "always" '' 348Value of systemd's <literal>Restart=</literal> service configuration option. 349If you are using the tmux management system (the default), values other than 350<literal>"no"</literal> and <literal>"always"</literal> may not work properly. 351As a consequence of the <literal>"always"</literal> option, stopping the server 352in-game with the <literal>stop</literal> command will cause the server to automatically restart. 353'' ; 354 355enableReload = mkOpt' types . bool false '' 356Reload server when configuration changes (instead of restart). 357 358This action re-links/copies the declared symlinks/files. You can 359include additional actions (even in-game commands) by setting 360<option>services.minecraft-servers.<name>.extraReload</option>. 361'' ; 362 363extraReload = mkOpt' types . lines "" '' 364Extra commands to run when reloading the service. Only has an 365effect if 366<option>services.minecraft-servers.<name>.enableReload</option> is 367true. 368'' ; 369 370extraStartPre = mkOpt' types . lines "" '' 371Extra commands to run before starting the service. 372'' ; 373 374extraStartPost = mkOpt' types . lines "" '' 375Extra commands to run after starting the service. 376'' ; 377 378extraStopPre = mkOpt' types . lines "" '' 379Extra commands to run before stopping the service. 380'' ; 381 382extraStopPost = mkOpt' types . lines "" '' 383Extra commands to run after stopping the service. 384'' ; 385 386stopCommand = mkOption { 387type = types . nullOr types . str ; 388description = '' 389Console command to run when cleanly stopping the server (ExecStop). 390Defaults to <literal>stop</literal>, which works for most servers. 391For proxies (bungeecord, velocity), you should set 392<literal>end</literal>. 393 394If set to <literal>null</literal>, the server will be stopped by 395systemd without issuing any command. 396'' ; 397default = "stop" ; 398}; 399 400whitelist = mkOption { 401type = types . attrsOf minecraftUUID ; 402default = { }; 403description = '' 404Whitelisted players, only has an effect when 405enabled via <option>services.minecraft-servers.<name>.serverProperties</option> 406by setting <literal>white-list</literal> to <literal>true</literal. 407 408To use a non-declarative whitelist, enable the whitelist and don't fill in this value. 409As long as it is empty, no whitelist file is generated. 410'' ; 411example = literalExpression '' 412{ 413username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 414username2 = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 415} 416'' ; 417}; 418 419operators = mkOption { 420type = types . attrsOf ( 421types . coercedTo minecraftUUID ( v :{ uuid = v ; }) ( 422types . submodule { 423options = { 424uuid = mkOption { 425type = minecraftUUID ; 426description = "The operator's UUID" ; 427example = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ; 428}; 429level = mkOption { 430type = types . ints . between 0 4 ; 431description = "The operator's permission level" ; 432default = 4 ; 433}; 434bypassesPlayerLimit = mkOption { 435type = types . bool ; 436description = "If true, the operator can join the server even if the player limit has been reached" ; 437default = false ; 438}; 439}; 440} 441) 442); 443default = { }; 444description = '' 445Server operators. See <link xlink:href="https://minecraft.wiki/w/Ops.json_format"/>. 446 447To use a non-declarative operator list, don't fill in this value. 448As long as it is empty, no operators file is generated. 449'' ; 450example = literalExpression '' 451{ 452username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 453username2 = { 454uuid = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 455level = 3; 456bypassesPlayerLimit = true; 457}; 458} 459'' ; 460}; 461 462bannedPlayers = mkOption { 463type = types . attrsOf ( 464types . coercedTo minecraftUUID ( v :{ uuid = v ; }) ( 465types . submodule { 466options = { 467uuid = mkOption { 468type = minecraftUUID ; 469description = "The banned player's UUID" ; 470example = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx" ; 471}; 472created = mkOption { 473type = lib . types . nullOr lib . types . str ; 474description = "The date of the ban" ; 475default = null ; 476example = "2025-12-01 09:00:00 -0500" ; 477}; 478source = mkOption { 479type = lib . types . nullOr lib . types . str ; 480description = "The source of the ban" ; 481default = null ; 482example = "Server" ; 483}; 484expires = mkOption { 485type = lib . types . nullOr lib . types . str ; 486description = "When the ban expires, if ever" ; 487default = null ; 488example = "forever" ; 489}; 490reason = mkOption { 491type = lib . types . nullOr lib . types . str ; 492description = "The reason for the ban, if any." ; 493default = null ; 494example = "Banned by an operator." ; 495}; 496}; 497} 498) 499); 500default = { }; 501description = '' 502Banned players. See <link xlink:href="https://docs.papermc.io/paper/reference/vanilla-data-files/"/>. 503 504To use a non-declarative banned player list, don't fill in this value. 505As long as it is empty, no banned players file is generated. 506'' ; 507example = literalExpression '' 508{ 509username1 = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"; 510username2 = { 511uuid = "yyyyyyyy-yyyy-yyyy-yyyy-yyyyyyyyyyyy"; 512created = "2025-12-01 09:00:00 -0500"; 513source = "(Unknown)"; 514expires = "forever"; 515reason = "Banned by an operator."; 516}; 517} 518'' ; 519}; 520 521serverProperties = mkOption { 522type = 523with types ; 524attrsOf ( oneOf [ 525bool 526int 527str 528]); 529default = { }; 530example = literalExpression '' 531{ 532server-port = 43000; 533difficulty = 3; 534gamemode = 1; 535max-players = 5; 536motd = "NixOS Minecraft server!"; 537white-list = true; 538enable-rcon = true; 539"rcon.password" = "hunter2"; 540} 541'' ; 542description = '' 543Minecraft server properties for the server.properties file of this server. See 544<link xlink:href="https://minecraft.gamepedia.com/Server.properties#Java_Edition_3"/> 545for documentation on these values. 546 547To use a non-declarative server.properties, don't fill in this value. 548As long as it is empty, no server.properties file is generated. 549'' ; 550}; 551 552allowedSymlinks = mkOption { 553default = [ ]; 554type = with types ; listOf str ; 555example = literalExpression '' 556[ 557"/mnt/worlds" 558] 559'' ; 560description = '' 561Minecraft 1.20+ disallows symlinks inside world directories, unless 562its destinations are allow-listed. /nix/store is allowed by default, 563but you may add more destinations through this option. See 564<link xlink:href="https://help.minecraft.net/hc/en-us/articles/16165590199181"/> 565for more information. 566 567Use lib.mkForce to shadow the default value (i.e. if you want to exclude /nix/store). 568'' ; 569}; 570 571package = mkOption { 572description = "The Minecraft server package to use." ; 573type = types . package ; 574default = pkgs . minecraft-server ; 575defaultText = literalExpression "pkgs.minecraft-server" ; 576example = "pkgs.minecraftServers.vanilla-1_18_2" ; 577}; 578 579jvmOpts = mkOpt' ( 580with types ; coercedTo ( listOf str ) ( lib . concatStringsSep " " ) ( separatedString " " ) 581) "-Xmx2G -Xms1G" "JVM options for this server." ; 582 583path = 584with types ; 585mkOpt' ( listOf ( either path str )) [ ] '' 586Packages added to the Minecraft server's <literal>PATH</literal> environment variable. 587Works as <option>systemd.services.<name>.path</option>. 588'' ; 589 590environment = 591with types ; 592mkOpt' 593( attrsOf ( 594nullOr ( oneOf [ 595str 596path 597package 598]) 599)) 600{ } 601'' 602Environment variables added to the Minecraft server's processes. 603Works as <option>systemd.services.<name>.environment</option>. 604'' ; 605 606symlinks = 607with types ; 608mkOpt' ( attrsOf ( either path configType )) { } '' 609Things to symlink into this server's data directory, in the form of 610a nix package/derivation. Can be used to declaratively manage 611arbitrary files in the server's data directory. 612'' ; 613files = 614with types ; 615mkOpt' ( attrsOf ( either path configType )) { } '' 616Things to copy into this server's data directory. Similar to symlinks, 617but these are actual, writable, files. Useful for configuration files 618that don't behave well when read-only. Directories are copied recursively and 619dereferenced. They will be deleted after the server stops, so any modification 620is discarded. 621 622These files may include placeholders to substitute with values from 623<option>services.minecraft-servers.environmentFile</option> 624(i.e. @variable_name@). 625'' ; 626 627managementSystem = mkOption { 628type = types . submodule ( 629managementSystem . getSubModules 630++ [ 631{ config = mkDefault cfg . managementSystem ; } 632] 633); 634description = '' 635Configuration for the system used to manage this server. Overrides the global configuration on an option-by-option basis. 636'' ; 637default = { }; 638example = options . services . minecraft-servers . managementSystem . example ; 639}; 640lazymc = { 641enable = mkEnableOpt "Puts your Minecraft server to rest when idle, and wakes it up when players connect." ; 642package = mkOption { 643type = types . package ; 644default = pkgs . lazymc ; 645defaultText = literalExpression "pkgs.lazymc" ; 646description = "The lazymc package to use." ; 647}; 648config = mkOption { 649type = types . submodule { 650freeformType = types . attrs ; 651options = { 652public = mkOption { 653type = types . submodule { 654freeformType = types . attrs ; 655options = { 656address = mkOption { 657type = types . strMatching "^[^:]+:[0-9]+$" ; 658default = "0.0.0.0:25565" ; 659description = "Public address in format 'address:port'" ; 660}; 661}; 662}; 663default = { }; 664}; 665}; 666}; 667default = { }; 668description = '' 669Configuration for lazymc, mirroring its TOML structure. 670Some values like server.command, server.directory and server.address will 671be automatically configured by this module when generating lazymc.toml. 672 673See <link xlink:href="https://github.com/timvisee/lazymc/blob/master/res/lazymc.toml"/> 674for documentation on these values. 675'' ; 676example = literalExpression '' 677{ 678public.address = "0.0.0.0:25565"; # Public port for players 679time.sleep_after = 900; # Sleep after 15 minutes 680motd.sleeping = "Shhh, the server is napping!"; 681server.forge = false; # Set to true if this is a Forge server 682} 683'' ; 684}; 685}; 686}; 687 688config = { 689allowedSymlinks = [ "/nix/store" ]; 690}; 691} 692) 693); 694}; 695}; 696 697config = mkIf cfg . enable ( 698let 699servers = filterAttrs ( _ :cfg :cfg . enable ) cfg . servers ; 700 701getPublicPort = 702conf : 703if conf . lazymc . enable then 704let 705addr = conf . lazymc . config . public . address or "0.0.0.0:25565" ; 706portStr = lib . last ( lib . splitString ":" addr ); 707in 708lib . toInt portStr 709else 710conf . serverProperties . server-port or 25565 ; 711in 712{ 713users = { 714users . minecraft = mkIf ( cfg . user == "minecraft" ) { 715description = "Minecraft server service user" ; 716home = cfg . dataDir ; 717createHome = true ; 718homeMode = "770" ; 719isSystemUser = true ; 720group = "minecraft" ; 721}; 722groups . minecraft = mkIf ( cfg . group == "minecraft" ) { }; 723}; 724 725assertions = [ 726{ 727assertion = cfg . eula ; 728message = 729"You must agree to Mojangs EULA to run minecraft-servers." 730+ " Read https://account.mojang.com/documents/minecraft_eula and" 731+ " set `services.minecraft-servers.eula` to `true` if you agree." ; 732} 733{ 734assertion = 735config . services . minecraft-server . enable -> cfg . dataDir != config . services . minecraft-server . dataDir ; 736message = 737"`services.minecraft-servers.dataDir` and `services.minecraft-server.dataDir` conflict." 738+ " Set one to use a different data directory." ; 739} 740{ 741assertion = 742let 743serverPorts = mapAttrsToList ( name :conf :getPublicPort conf ) ( 744filterAttrs ( _ :cfg :cfg . openFirewall ) servers 745); 746 747counts = map ( port :count ( x :x == port ) serverPorts ) ( unique serverPorts ); 748in 749lib . all ( x :x == 1 ) counts ; 750message = "Multiple servers are set to use the same public port (either through lazymc public.address or server.properties server-port). Change one to use a different port." ; 751} 752( 753let 754lazymcPortConflicts = filter ( x :x . hasConflict ) ( 755mapAttrsToList ( name :conf :{ 756inherit name ; 757hasConflict = 758conf . lazymc . enable && getPublicPort conf == ( conf . serverProperties . server-port or 25565 ); 759}) servers 760); 761conflictingServerNames = map ( x :x . name ) lazymcPortConflicts ; 762in 763{ 764assertion = lazymcPortConflicts == [ ]; 765message = '' 766Server(s): ${ concatStringsSep ", " conflictingServerNames } has the same port set for serverProperties.server-port and lazymc.config.public.address 767Please set for example: `serverName.serverProperties.server-port = 25566;`, lazymc's internal server.address will automatically point to it 768Lazymc's public.address is "0.0.0.0:25565" by default 769'' ; 770} 771) 772]; 773 774warnings = lib . optional ( cfg . runDir != options . services . minecraft-servers . runDir . default ) '' 775`runDir` has been deprecated. 776 777Please use `services.minecraft-servers.managementSystem.tmux.socketPath` instead. 778For example, `name: " ${ cfg . runDir } /''${name}.sock"`. 779 780See the changelog file for more information. 781'' ; 782 783networking . firewall = 784let 785toOpen = filterAttrs ( _ :cfg :cfg . openFirewall ) servers ; 786# Minecraft and RCON 787getTCPPorts = 788n :c : 789[ 790( getPublicPort c ) 791] 792++ ( optional ( c . serverProperties . enable-rcon or false ) ( c . serverProperties . "rcon.port" or 25575 )); 793# Query 794getUDPPorts = 795n :c : 796optional ( c . serverProperties . enable-query or false ) ( c . serverProperties . "query.port" or 25565 ); 797in 798{ 799allowedUDPPorts = flatten ( mapAttrsToList getUDPPorts toOpen ); 800allowedTCPPorts = flatten ( mapAttrsToList getTCPPorts toOpen ); 801}; 802 803systemd . tmpfiles . rules = mapAttrsToList ( 804name :_ :"d ' ${ cfg . dataDir } / ${ name } ' 0770 ${ cfg . user } ${ cfg . group } - -" 805) servers ; 806 807systemd . sockets = pipe servers [ 808( filterAttrs ( name :server :server . managementSystem . systemd-socket . enable )) 809( mapAttrs' ( 810name :server :{ 811name = "minecraft-server- ${ name } " ; 812value = { 813requires = [ "minecraft-server- ${ name } .service" ]; 814partOf = [ "minecraft-server- ${ name } .service" ]; 815socketConfig = 816let 817socketConf = server . managementSystem . systemd-socket . stdinSocket ; 818in 819{ 820ListenFIFO = socketConf . path name ; 821SocketMode = socketConf . mode ; 822SocketUser = cfg . user ; 823SocketGroup = cfg . group ; 824RemoveOnStop = true ; 825FlushPending = true ; 826}; 827}; 828} 829)) 830]; 831 832systemd . services = mapAttrs' ( 833name :conf : 834let 835symlinks = normalizeFiles ( 836{ 837"eula.txt" . value = { 838eula = true ; 839}; 840"eula.txt" . format = pkgs . formats . keyValue { }; 841} 842// conf . symlinks 843); 844files = normalizeFiles ( 845{ 846"whitelist.json" . value = mapAttrsToList ( n :v :{ 847name = n ; 848uuid = v ; 849}) conf . whitelist ; 850"ops.json" . value = mapAttrsToList ( n :v :{ 851name = n ; 852uuid = v . uuid ; 853level = v . level ; 854bypassesPlayerLimit = v . bypassesPlayerLimit ; 855}) conf . operators ; 856"banned-players.json" . value = mapAttrsToList ( 857n :v : 858{ 859name = n ; 860uuid = v . uuid ; 861} 862// lib . optionalAttrs ( v . created != null ) { 863created = v . created ; 864} 865// lib . optionalAttrs ( v . source != null ) { 866source = v . source ; 867} 868// lib . optionalAttrs ( v . expires != null ) { 869expires = v . expires ; 870} 871// lib . optionalAttrs ( v . reason != null ) { 872reason = v . reason ; 873} 874) conf . bannedPlayers ; 875"server.properties" . value = conf . serverProperties ; 876"allowed_symlinks.txt" . value = conf . allowedSymlinks ; 877} 878// ( optionalAttrs conf . lazymc . enable { 879"lazymc.toml" . value = lib . recursiveUpdate { 880server = { 881command = " ${ getExe conf . package } ${ conf . jvmOpts } " ; 882directory = "." ; 883address = "127.0.0.1: ${ toString conf . serverProperties . server-port or 25565 } " ; 884}; 885} conf . lazymc . config ; 886}) 887// conf . files 888); 889 890msConfig = managementSystemConfig name conf ; 891 892markManaged = file :"echo ${ file } >> .nix-minecraft-managed" ; 893cleanAllManaged = '' 894if [ -e .nix-minecraft-managed ]; then 895readarray -t to_delete < .nix-minecraft-managed 896rm -rf "''${to_delete[@]}" 897rm .nix-minecraft-managed 898fi 899'' ; 900 901ExecStartPre = 902let 903backup = file :'' 904if [[ -e ${ file } ]]; then 905echo ${ file } "already exists, moving" 906mv ${ file } ${ file } .bak 907fi 908'' ; 909mkSymlinks = concatStringsSep "\n" ( 910mapAttrsToList ( 911n_ :v_ : 912let 913n = escapeShellArg n_ ; 914v = escapeShellArg v_ ; 915in 916'' 917${ backup n } 918mkdir -p "$(dirname ${ n } )" 919 920ln -sf ${ v } ${ n } 921 922${ markManaged n } 923'' 924) symlinks 925); 926 927mkFiles = concatStringsSep "\n" ( 928mapAttrsToList ( 929n_ :v_ : 930let 931n = escapeShellArg n_ ; 932v = escapeShellArg v_ ; 933in 934'' 935${ backup n } 936mkdir -p "$(dirname ${ n } )" 937 938# If it's not a binary, substitute env vars. Else, copy it normally 939if ${ pkgs . file } /bin/file --mime-encoding ${ v } | grep -v '\bbinary$' -q; then 940${ pkgs . gawk } /bin/awk '{ 941for(varname in ENVIRON) 942gsub("@"varname"@", ENVIRON[varname]) 943}' ${ v } > ${ n } 945else 946cp -r --dereference ${ v } -T ${ n } 947chmod +w -R ${ n } 948fi 949 950${ markManaged n } 951'' 952) files 953); 954in 955getExe ( 956pkgs . writeShellApplication { 957name = "minecraft-server- ${ name } -start-pre" ; 958 959excludeShellChecks = [ "SC2016" ]; 960 961text = '' 962${ cleanAllManaged } 963${ mkSymlinks } 964${ mkFiles } 965${ conf . extraStartPre } 966'' ; 967} 968); 969 970ExecStart = getExe ( 971pkgs . writeShellApplication { 972name = "minecraft-server- ${ name } -start" ; 973text = '' 974${ msConfig . hooks . start } 975'' ; 976} 977); 978 979ExecStartPost = getExe ( 980pkgs . writeShellApplication { 981name = "minecraft-server- ${ name } -start-post" ; 982text = '' 983${ msConfig . hooks . postStart } 984${ conf . extraStartPost } 985'' ; 986} 987); 988 989execStopScript = getExe ( 990pkgs . writeShellApplication { 991name = "minecraft-server- ${ name } -stop" ; 992text = '' 993# systemd has no ExecStopPre hook, so we just run it here. 994${ conf . extraStopPre } 995 996${ msConfig . hooks . stop } 997'' ; 998} 999); 1000 1001ExecStopPost = getExe ( 1002pkgs . writeShellApplication { 1003name = "minecraft-server- ${ name } -stop-post" ; 1004text = '' 1005${ cleanAllManaged } 1006${ conf . extraStopPost } 1007'' ; 1008} 1009); 1010 1011ExecReload = getExe ( 1012pkgs . writeShellApplication { 1013name = "minecraft-server- ${ name } -reload" ; 1014text = '' 1015${ ExecStopPost } 1016${ ExecStartPre } 1017${ conf . extraReload } 1018'' ; 1019} 1020); 1021in 1022{ 1023name = "minecraft-server- ${ name } " ; 1024value = { 1025description = "Minecraft Server ${ name } " ; 1026wantedBy = mkIf conf . autoStart [ "multi-user.target" ]; 1027requires = optional conf . managementSystem . systemd-socket . enable "minecraft-server- ${ name } .socket" ; 1028partOf = optional conf . managementSystem . systemd-socket . enable "minecraft-server- ${ name } .socket" ; 1029after = [ 1030"network.target" 1031] 1032++ optional conf . managementSystem . systemd-socket . enable "minecraft-server- ${ name } .socket" ; 1033 1034enable = conf . enable ; 1035 1036startLimitIntervalSec = 120 ; 1037startLimitBurst = 5 ; 1038 1039serviceConfig = { 1040inherit 1041ExecStartPre 1042ExecStart 1043ExecStartPost 1044ExecStopPost 1045ExecReload 1046; 1047ExecStop = " ${ execStopScript } $MAINPID" ; 1048 1049# the Minecraft server (as of 1.20.6) has a 60s timeout for saving each world. 1050# let's let it handle potential lock-ups by itself before resorting to killing it. 1051TimeoutStopSec = "1min 15s" ; 1052 1053Restart = conf . restart ; 1054WorkingDirectory = " ${ cfg . dataDir } / ${ name } " ; 1055User = cfg . user ; 1056Group = cfg . group ; 1057EnvironmentFile = mkIf ( cfg . environmentFile != null ) ( toString cfg . environmentFile ); 1058 1059# Default directory for management sockets 1060RuntimeDirectory = "minecraft" ; 1061RuntimeDirectoryPreserve = "yes" ; 1062 1063# Hardening 1064CapabilityBoundingSet = [ "" ]; 1065DeviceAllow = [ "" ]; 1066LockPersonality = true ; 1067PrivateDevices = true ; 1068PrivateTmp = true ; 1069PrivateUsers = true ; 1070ProtectClock = true ; 1071ProtectControlGroups = true ; 1072ProtectHome = true ; 1073ProtectHostname = true ; 1074ProtectKernelLogs = true ; 1075ProtectKernelModules = true ; 1076ProtectKernelTunables = true ; 1077ProtectProc = "invisible" ; 1078RestrictAddressFamilies = [ 1079"AF_UNIX" 1080"AF_INET" 1081"AF_INET6" 1082]; 1083RestrictNamespaces = true ; 1084RestrictRealtime = true ; 1085RestrictSUIDSGID = true ; 1086SystemCallArchitectures = "native" ; 1087UMask = "0007" ; 1088} 1089// msConfig . serviceConfig ; 1090 1091restartIfChanged = ! conf . enableReload ; 1092reloadIfChanged = conf . enableReload ; 1093 1094inherit ( conf ) path environment ; 1095}; 1096} 1097) servers ; 1098} 1099); 1100}