fork/nix-minecraft

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

Gabriel Fontesmodule: add allowedSymlinks optionff6604f

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