1 { config, lib, pkgs, options, ... }:
6 cfg = config.services.transmission;
7 opt = options.services.transmission;
8 inherit (config.environment) etc;
9 apparmor = config.security.apparmor;
10 rootDir = "/run/transmission";
11 settingsDir = ".config/transmission-daemon";
12 downloadsDir = "Downloads";
13 incompleteDir = ".incomplete";
14 watchDir = "watchdir";
15 settingsFormat = pkgs.formats.json {};
16 settingsFile = settingsFormat.generate "settings.json" cfg.settings;
20 (mkRenamedOptionModule ["services" "transmission" "port"]
21 ["services" "transmission" "settings" "rpc-port"])
22 (mkAliasOptionModuleMD ["services" "transmission" "openFirewall"]
23 ["services" "transmission" "openPeerPorts"])
26 services.transmission = {
27 enable = mkEnableOption "transmission" // {
29 Whether to enable the headless Transmission BitTorrent daemon.
31 Transmission daemon can be controlled via the RPC interface using
32 transmission-remote, the WebUI (http://127.0.0.1:9091/ by default),
33 or other clients like stig or tremc.
35 Torrents are downloaded to [](#opt-services.transmission.home)/${downloadsDir} by default and are
36 accessible to users in the "transmission" group.
42 Settings whose options overwrite fields in
43 `.config/transmission-daemon/settings.json`
44 (each time the service starts).
46 See [Transmission's Wiki](https://github.com/transmission/transmission/wiki/Editing-Configuration-Files)
47 for documentation of settings not explicitly covered by this module.
50 type = types.submodule {
51 freeformType = settingsFormat.type;
52 options.download-dir = mkOption {
54 default = "${cfg.home}/${downloadsDir}";
55 defaultText = literalExpression ''"''${config.${opt.home}}/${downloadsDir}"'';
56 description = "Directory where to download torrents.";
58 options.incomplete-dir = mkOption {
60 default = "${cfg.home}/${incompleteDir}";
61 defaultText = literalExpression ''"''${config.${opt.home}}/${incompleteDir}"'';
64 services.transmission.home
65 [](#opt-services.transmission.settings.incomplete-dir-enabled),
66 new torrents will download the files to this directory.
67 When complete, the files will be moved to download-dir
68 [](#opt-services.transmission.settings.download-dir).
71 options.incomplete-dir-enabled = mkOption {
76 options.message-level = mkOption {
77 type = types.ints.between 0 6;
79 description = "Set verbosity of transmission messages.";
81 options.peer-port = mkOption {
84 description = "The peer port to listen for incoming connections.";
86 options.peer-port-random-high = mkOption {
90 The maximum peer port to listen to for incoming connections
91 when [](#opt-services.transmission.settings.peer-port-random-on-start) is enabled.
94 options.peer-port-random-low = mkOption {
98 The minimal peer port to listen to for incoming connections
99 when [](#opt-services.transmission.settings.peer-port-random-on-start) is enabled.
102 options.peer-port-random-on-start = mkOption {
105 description = "Randomize the peer port.";
107 options.rpc-bind-address = mkOption {
109 default = "127.0.0.1";
112 Where to listen for RPC connections.
113 Use `0.0.0.0` to listen on all interfaces.
116 options.rpc-port = mkOption {
119 description = "The RPC port to listen to.";
121 options.script-torrent-done-enabled = mkOption {
126 [](#opt-services.transmission.settings.script-torrent-done-filename)
127 at torrent completion.
130 options.script-torrent-done-filename = mkOption {
131 type = types.nullOr types.path;
133 description = "Executable to be run at torrent completion.";
135 options.umask = mkOption {
139 Sets transmission's file mode creation mask.
140 See the umask(2) manpage for more information.
141 Users who want their saved torrents to be world-writable
142 may want to set this value to 0.
143 Bear in mind that the json markup language only accepts numbers in base 10,
144 so the standard umask(2) octal notation "022" is written in settings.json as 18.
147 options.utp-enabled = mkOption {
151 Whether to enable [Micro Transport Protocol (µTP)](https://en.wikipedia.org/wiki/Micro_Transport_Protocol).
154 options.watch-dir = mkOption {
156 default = "${cfg.home}/${watchDir}";
157 defaultText = literalExpression ''"''${config.${opt.home}}/${watchDir}"'';
158 description = "Watch a directory for torrent files and add them to transmission.";
160 options.watch-dir-enabled = mkOption {
163 description = ''Whether to enable the
164 [](#opt-services.transmission.settings.watch-dir).
167 options.trash-original-torrent-files = mkOption {
170 description = ''Whether to delete torrents added from the
171 [](#opt-services.transmission.settings.watch-dir).
177 package = mkPackageOption pkgs "transmission" {
178 default = "transmission_3";
179 example = "pkgs.transmission_4";
182 downloadDirPermissions = mkOption {
183 type = with types; nullOr str;
187 If not `null`, is used as the permissions
188 set by `system.activationScripts.transmission-daemon`
189 on the directories [](#opt-services.transmission.settings.download-dir),
190 [](#opt-services.transmission.settings.incomplete-dir).
191 and [](#opt-services.transmission.settings.watch-dir).
192 Note that you may also want to change
193 [](#opt-services.transmission.settings.umask).
199 default = "/var/lib/transmission";
201 The directory where Transmission will create `${settingsDir}`.
202 as well as `${downloadsDir}/` unless
203 [](#opt-services.transmission.settings.download-dir) is changed,
204 and `${incompleteDir}/` unless
205 [](#opt-services.transmission.settings.incomplete-dir) is changed.
211 default = "transmission";
212 description = "User account under which Transmission runs.";
217 default = "transmission";
218 description = "Group account under which Transmission runs.";
221 credentialsFile = mkOption {
224 Path to a JSON file to be merged with the settings.
225 Useful to merge a file which is better kept out of the Nix store
226 to set secret config parameters like `rpc-password`.
228 default = "/dev/null";
229 example = "/var/lib/secrets/transmission/settings.json";
232 extraFlags = mkOption {
233 type = types.listOf types.str;
235 example = [ "--log-debug" ];
237 Extra flags passed to the transmission command in the service definition.
241 openPeerPorts = mkEnableOption "opening of the peer port(s) in the firewall";
243 openRPCPort = mkEnableOption "opening of the RPC port in the firewall";
245 performanceNetParameters = mkEnableOption "performance tweaks" // {
247 Whether to enable tweaking of kernel parameters
248 to open many more connections at the same time.
250 Note that you may also want to increase
252 And be aware that these settings are quite aggressive
253 and might not suite your regular desktop use.
254 For instance, SSH sessions may time out more easily.
259 type = types.nullOr types.path;
261 example = "pkgs.flood-for-transmission";
263 If not `null`, sets the value of the `TRANSMISSION_WEB_HOME`
264 environment variable used by the service. Useful for overriding
265 the web interface files, without overriding the transmission
266 package and thus requiring rebuilding it locally. Use this if
267 you want to use an alternative web interface, such as
268 `pkgs.flood-for-transmission`.
274 config = mkIf cfg.enable {
275 # Note that using systemd.tmpfiles would not work here
276 # because it would fail when creating a directory
277 # with a different owner than its parent directory, by saying:
278 # Detected unsafe path transition /home/foo → /home/foo/Downloads during canonicalization of /home/foo/Downloads
279 # when /home/foo is not owned by cfg.user.
280 # Note also that using an ExecStartPre= wouldn't work either
281 # because BindPaths= needs these directories before.
282 system.activationScripts = mkIf (cfg.downloadDirPermissions != null)
283 { transmission-daemon = ''
284 install -d -m 700 '${cfg.home}/${settingsDir}'
285 chown -R '${cfg.user}:${cfg.group}' ${cfg.home}/${settingsDir}
286 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.download-dir}'
287 '' + optionalString cfg.settings.incomplete-dir-enabled ''
288 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.incomplete-dir}'
289 '' + optionalString cfg.settings.watch-dir-enabled ''
290 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.watch-dir}'
294 systemd.services.transmission = {
295 description = "Transmission BitTorrent Service";
296 after = [ "network.target" ] ++ optional apparmor.enable "apparmor.service";
297 requires = optional apparmor.enable "apparmor.service";
298 wantedBy = [ "multi-user.target" ];
299 environment.CURL_CA_BUNDLE = etc."ssl/certs/ca-certificates.crt".source;
300 environment.TRANSMISSION_WEB_HOME = lib.mkIf (cfg.webHome != null) cfg.webHome;
303 # Use "+" because credentialsFile may not be accessible to User= or Group=.
304 ExecStartPre = [("+" + pkgs.writeShellScript "transmission-prestart" ''
305 set -eu${lib.optionalString (cfg.settings.message-level >= 3) "x"}
306 ${pkgs.jq}/bin/jq --slurp add ${settingsFile} '${cfg.credentialsFile}' |
307 install -D -m 600 -o '${cfg.user}' -g '${cfg.group}' /dev/stdin \
308 '${cfg.home}/${settingsDir}/settings.json'
310 ExecStart="${cfg.package}/bin/transmission-daemon -f -g ${cfg.home}/${settingsDir} ${escapeShellArgs cfg.extraFlags}";
311 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
314 # Create rootDir in the host's mount namespace.
315 RuntimeDirectory = [(baseNameOf rootDir)];
316 RuntimeDirectoryMode = "755";
317 # This is for BindPaths= and BindReadOnlyPaths=
318 # to allow traversal of directories they create in RootDirectory=.
320 # Using RootDirectory= makes it possible
321 # to use the same paths download-dir/incomplete-dir
322 # (which appear in user's interfaces) without requiring cfg.user
323 # to have access to their parent directories,
324 # by using BindPaths=/BindReadOnlyPaths=.
325 # Note that TemporaryFileSystem= could have been used instead
326 # but not without adding some BindPaths=/BindReadOnlyPaths=
327 # that would only be needed for ExecStartPre=,
328 # because RootDirectoryStartOnly=true would not help.
329 RootDirectory = rootDir;
330 RootDirectoryStartOnly = true;
333 [ "${cfg.home}/${settingsDir}"
334 cfg.settings.download-dir
335 # Transmission may need to read in the host's /run (eg. /run/systemd/resolve)
336 # or write in its private /run (eg. /run/host).
339 optional cfg.settings.incomplete-dir-enabled
340 cfg.settings.incomplete-dir ++
341 optional (cfg.settings.watch-dir-enabled && cfg.settings.trash-original-torrent-files)
342 cfg.settings.watch-dir;
343 BindReadOnlyPaths = [
344 # No confinement done of /nix/store here like in systemd-confinement.nix,
345 # an AppArmor profile is provided to get a confinement based upon paths and rights.
349 optional (cfg.settings.script-torrent-done-enabled &&
350 cfg.settings.script-torrent-done-filename != null)
351 cfg.settings.script-torrent-done-filename ++
352 optional (cfg.settings.watch-dir-enabled && !cfg.settings.trash-original-torrent-files)
353 cfg.settings.watch-dir;
356 "transmission/${settingsDir}"
357 "transmission/${incompleteDir}"
358 "transmission/${downloadsDir}"
359 "transmission/${watchDir}"
361 StateDirectoryMode = mkDefault 750;
362 # The following options are only for optimizing:
363 # systemd-analyze security transmission
364 AmbientCapabilities = "";
365 CapabilityBoundingSet = "";
366 # ProtectClock= adds DeviceAllow=char-rtc r
368 LockPersonality = true;
369 MemoryDenyWriteExecute = true;
370 NoNewPrivileges = true;
371 PrivateDevices = true;
372 PrivateMounts = mkDefault true;
373 PrivateNetwork = mkDefault false;
375 PrivateUsers = mkDefault true;
377 ProtectControlGroups = true;
378 # ProtectHome=true would not allow BindPaths= to work across /home,
379 # and ProtectHome=tmpfs would break statfs(),
380 # preventing transmission-daemon to report the available free space.
381 # However, RootDirectory= is used, so this is not a security concern
382 # since there would be nothing in /home but any BindPaths= wanted by the user.
383 ProtectHome = "read-only";
384 ProtectHostname = true;
385 ProtectKernelLogs = true;
386 ProtectKernelModules = true;
387 ProtectKernelTunables = true;
388 ProtectSystem = "strict";
390 # AF_UNIX may become usable one day:
391 # https://github.com/transmission/transmission/issues/441
392 RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
393 RestrictNamespaces = true;
394 RestrictRealtime = true;
395 RestrictSUIDSGID = true;
398 # Groups in @system-service which do not contain a syscall
399 # listed by perf stat -e 'syscalls:sys_enter_*' transmission-daemon -f
400 # in tests, and seem likely not necessary for transmission-daemon.
401 "~@aio" "~@chown" "~@keyring" "~@memlock" "~@resources" "~@setuid" "~@timer"
402 # In the @privileged group, but reached when querying infos through RPC (eg. with stig).
405 SystemCallArchitectures = "native";
409 # It's useful to have transmission in path, e.g. for remote control
410 environment.systemPackages = [ cfg.package ];
412 users.users = optionalAttrs (cfg.user == "transmission") ({
415 uid = config.ids.uids.transmission;
416 description = "Transmission BitTorrent user";
421 users.groups = optionalAttrs (cfg.group == "transmission") ({
423 gid = config.ids.gids.transmission;
427 networking.firewall = mkMerge [
428 (mkIf cfg.openPeerPorts (
429 if cfg.settings.peer-port-random-on-start
431 { allowedTCPPortRanges =
432 [ { from = cfg.settings.peer-port-random-low;
433 to = cfg.settings.peer-port-random-high;
436 allowedUDPPortRanges =
437 [ { from = cfg.settings.peer-port-random-low;
438 to = cfg.settings.peer-port-random-high;
443 { allowedTCPPorts = [ cfg.settings.peer-port ];
444 allowedUDPPorts = [ cfg.settings.peer-port ];
447 (mkIf cfg.openRPCPort { allowedTCPPorts = [ cfg.settings.rpc-port ]; })
450 boot.kernel.sysctl = mkMerge [
451 # Transmission uses a single UDP socket in order to implement multiple uTP sockets,
452 # and thus expects large kernel buffers for the UDP socket,
453 # https://trac.transmissionbt.com/browser/trunk/libtransmission/tr-udp.c?rev=11956.
454 # at least up to the values hardcoded here:
455 (mkIf cfg.settings.utp-enabled {
456 "net.core.rmem_max" = mkDefault 4194304; # 4MB
457 "net.core.wmem_max" = mkDefault 1048576; # 1MB
459 (mkIf cfg.performanceNetParameters {
460 # Increase the number of available source (local) TCP and UDP ports to 49151.
461 # Usual default is 32768 60999, ie. 28231 ports.
462 # Find out your current usage with: ss -s
463 "net.ipv4.ip_local_port_range" = mkDefault "16384 65535";
464 # Timeout faster generic TCP states.
465 # Usual default is 600.
466 # Find out your current usage with: watch -n 1 netstat -nptuo
467 "net.netfilter.nf_conntrack_generic_timeout" = mkDefault 60;
468 # Timeout faster established but inactive connections.
469 # Usual default is 432000.
470 "net.netfilter.nf_conntrack_tcp_timeout_established" = mkDefault 600;
471 # Clear immediately TCP states after timeout.
472 # Usual default is 120.
473 "net.netfilter.nf_conntrack_tcp_timeout_time_wait" = mkDefault 1;
474 # Increase the number of trackable connections.
475 # Usual default is 262144.
476 # Find out your current usage with: conntrack -C
477 "net.netfilter.nf_conntrack_max" = mkDefault 1048576;
481 security.apparmor.policies."bin.transmission-daemon".profile = ''
482 include "${cfg.package.apparmor}/bin.transmission-daemon"
484 security.apparmor.includes."local/bin.transmission-daemon" = ''
485 r ${config.systemd.services.transmission.environment.CURL_CA_BUNDLE},
487 owner rw ${cfg.home}/${settingsDir}/**,
488 rw ${cfg.settings.download-dir}/**,
489 ${optionalString cfg.settings.incomplete-dir-enabled ''
490 rw ${cfg.settings.incomplete-dir}/**,
492 ${optionalString cfg.settings.watch-dir-enabled ''
493 r${optionalString cfg.settings.trash-original-torrent-files "w"} ${cfg.settings.watch-dir}/**,
496 rw ${cfg.settings.download-dir}/**,
497 ${optionalString cfg.settings.incomplete-dir-enabled ''
498 rw ${cfg.settings.incomplete-dir}/**,
500 ${optionalString cfg.settings.watch-dir-enabled ''
501 r${optionalString cfg.settings.trash-original-torrent-files "w"} ${cfg.settings.watch-dir}/**,
505 ${optionalString (cfg.settings.script-torrent-done-enabled &&
506 cfg.settings.script-torrent-done-filename != null) ''
507 # Stack transmission_directories profile on top of
508 # any existing profile for script-torrent-done-filename
509 # FIXME: to be tested as I'm not sure it works well with NoNewPrivileges=
510 # https://gitlab.com/apparmor/apparmor/-/wikis/AppArmorStacking#seccomp-and-no_new_privs
511 px ${cfg.settings.script-torrent-done-filename} -> &@{dirs},
514 ${optionalString (cfg.webHome != null) ''
520 meta.maintainers = with lib.maintainers; [ julm ];