fork/nix-minecraft

git clone https://git.julia.blue/fork/nix-minecraft

github-actions[bot]Add LazyMC support50d44c8

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