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 (lib.mdDoc "transmission") // {
28 description = lib.mdDoc ''
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.
41 description = lib.mdDoc ''
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 = lib.mdDoc "Directory where to download torrents.";
58 options.incomplete-dir = mkOption {
60 default = "${cfg.home}/${incompleteDir}";
61 defaultText = literalExpression ''"''${config.${opt.home}}/${incompleteDir}"'';
62 description = lib.mdDoc ''
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 {
74 description = lib.mdDoc "";
76 options.message-level = mkOption {
77 type = types.ints.between 0 3;
79 description = lib.mdDoc "Set verbosity of transmission messages.";
81 options.peer-port = mkOption {
84 description = lib.mdDoc "The peer port to listen for incoming connections.";
86 options.peer-port-random-high = mkOption {
89 description = lib.mdDoc ''
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 {
97 description = lib.mdDoc ''
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 = lib.mdDoc "Randomize the peer port.";
107 options.rpc-bind-address = mkOption {
109 default = "127.0.0.1";
111 description = lib.mdDoc ''
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 = lib.mdDoc "The RPC port to listen to.";
121 options.script-torrent-done-enabled = mkOption {
124 description = lib.mdDoc ''
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 = lib.mdDoc "Executable to be run at torrent completion.";
135 options.umask = mkOption {
138 description = lib.mdDoc ''
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 {
150 description = lib.mdDoc ''
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 = lib.mdDoc "Watch a directory for torrent files and add them to transmission.";
160 options.watch-dir-enabled = mkOption {
163 description = lib.mdDoc ''Whether to enable the
164 [](#opt-services.transmission.settings.watch-dir).
167 options.trash-original-torrent-files = mkOption {
170 description = lib.mdDoc ''Whether to delete torrents added from the
171 [](#opt-services.transmission.settings.watch-dir).
177 package = mkPackageOptionMD pkgs "transmission" {};
179 downloadDirPermissions = mkOption {
180 type = with types; nullOr str;
183 description = lib.mdDoc ''
184 If not `null`, is used as the permissions
185 set by `system.activationScripts.transmission-daemon`
186 on the directories [](#opt-services.transmission.settings.download-dir),
187 [](#opt-services.transmission.settings.incomplete-dir).
188 and [](#opt-services.transmission.settings.watch-dir).
189 Note that you may also want to change
190 [](#opt-services.transmission.settings.umask).
196 default = "/var/lib/transmission";
197 description = lib.mdDoc ''
198 The directory where Transmission will create `${settingsDir}`.
199 as well as `${downloadsDir}/` unless
200 [](#opt-services.transmission.settings.download-dir) is changed,
201 and `${incompleteDir}/` unless
202 [](#opt-services.transmission.settings.incomplete-dir) is changed.
208 default = "transmission";
209 description = lib.mdDoc "User account under which Transmission runs.";
214 default = "transmission";
215 description = lib.mdDoc "Group account under which Transmission runs.";
218 credentialsFile = mkOption {
220 description = lib.mdDoc ''
221 Path to a JSON file to be merged with the settings.
222 Useful to merge a file which is better kept out of the Nix store
223 to set secret config parameters like `rpc-password`.
225 default = "/dev/null";
226 example = "/var/lib/secrets/transmission/settings.json";
229 extraFlags = mkOption {
230 type = types.listOf types.str;
232 example = [ "--log-debug" ];
233 description = lib.mdDoc ''
234 Extra flags passed to the transmission command in the service definition.
238 openPeerPorts = mkEnableOption (lib.mdDoc "opening of the peer port(s) in the firewall");
240 openRPCPort = mkEnableOption (lib.mdDoc "opening of the RPC port in the firewall");
242 performanceNetParameters = mkEnableOption (lib.mdDoc "performance tweaks") // {
243 description = lib.mdDoc ''
244 Whether to enable tweaking of kernel parameters
245 to open many more connections at the same time.
247 Note that you may also want to increase
249 And be aware that these settings are quite aggressive
250 and might not suite your regular desktop use.
251 For instance, SSH sessions may time out more easily.
257 config = mkIf cfg.enable {
258 # Note that using systemd.tmpfiles would not work here
259 # because it would fail when creating a directory
260 # with a different owner than its parent directory, by saying:
261 # Detected unsafe path transition /home/foo → /home/foo/Downloads during canonicalization of /home/foo/Downloads
262 # when /home/foo is not owned by cfg.user.
263 # Note also that using an ExecStartPre= wouldn't work either
264 # because BindPaths= needs these directories before.
265 system.activationScripts = mkIf (cfg.downloadDirPermissions != null)
266 { transmission-daemon = ''
267 install -d -m 700 '${cfg.home}/${settingsDir}'
268 chown -R '${cfg.user}:${cfg.group}' ${cfg.home}/${settingsDir}
269 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.download-dir}'
270 '' + optionalString cfg.settings.incomplete-dir-enabled ''
271 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.incomplete-dir}'
272 '' + optionalString cfg.settings.watch-dir-enabled ''
273 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.watch-dir}'
277 systemd.services.transmission = {
278 description = "Transmission BitTorrent Service";
279 after = [ "network.target" ] ++ optional apparmor.enable "apparmor.service";
280 requires = optional apparmor.enable "apparmor.service";
281 wantedBy = [ "multi-user.target" ];
282 environment.CURL_CA_BUNDLE = etc."ssl/certs/ca-certificates.crt".source;
285 # Use "+" because credentialsFile may not be accessible to User= or Group=.
286 ExecStartPre = [("+" + pkgs.writeShellScript "transmission-prestart" ''
287 set -eu${lib.optionalString (cfg.settings.message-level >= 3) "x"}
288 ${pkgs.jq}/bin/jq --slurp add ${settingsFile} '${cfg.credentialsFile}' |
289 install -D -m 600 -o '${cfg.user}' -g '${cfg.group}' /dev/stdin \
290 '${cfg.home}/${settingsDir}/settings.json'
292 ExecStart="${cfg.package}/bin/transmission-daemon -f -g ${cfg.home}/${settingsDir} ${escapeShellArgs cfg.extraFlags}";
293 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
296 # Create rootDir in the host's mount namespace.
297 RuntimeDirectory = [(baseNameOf rootDir)];
298 RuntimeDirectoryMode = "755";
299 # This is for BindPaths= and BindReadOnlyPaths=
300 # to allow traversal of directories they create in RootDirectory=.
302 # Using RootDirectory= makes it possible
303 # to use the same paths download-dir/incomplete-dir
304 # (which appear in user's interfaces) without requiring cfg.user
305 # to have access to their parent directories,
306 # by using BindPaths=/BindReadOnlyPaths=.
307 # Note that TemporaryFileSystem= could have been used instead
308 # but not without adding some BindPaths=/BindReadOnlyPaths=
309 # that would only be needed for ExecStartPre=,
310 # because RootDirectoryStartOnly=true would not help.
311 RootDirectory = rootDir;
312 RootDirectoryStartOnly = true;
315 [ "${cfg.home}/${settingsDir}"
316 cfg.settings.download-dir
318 optional cfg.settings.incomplete-dir-enabled
319 cfg.settings.incomplete-dir ++
320 optional (cfg.settings.watch-dir-enabled && cfg.settings.trash-original-torrent-files)
321 cfg.settings.watch-dir;
322 BindReadOnlyPaths = [
323 # No confinement done of /nix/store here like in systemd-confinement.nix,
324 # an AppArmor profile is provided to get a confinement based upon paths and rights.
329 optional (cfg.settings.script-torrent-done-enabled &&
330 cfg.settings.script-torrent-done-filename != null)
331 cfg.settings.script-torrent-done-filename ++
332 optional (cfg.settings.watch-dir-enabled && !cfg.settings.trash-original-torrent-files)
333 cfg.settings.watch-dir;
336 "transmission/.config/transmission-daemon"
337 "transmission/.incomplete"
338 "transmission/Downloads"
339 "transmission/watch-dir"
341 StateDirectoryMode = mkDefault 750;
342 # The following options are only for optimizing:
343 # systemd-analyze security transmission
344 AmbientCapabilities = "";
345 CapabilityBoundingSet = "";
346 # ProtectClock= adds DeviceAllow=char-rtc r
348 LockPersonality = true;
349 MemoryDenyWriteExecute = true;
350 NoNewPrivileges = true;
351 PrivateDevices = true;
352 PrivateMounts = true;
353 PrivateNetwork = mkDefault false;
357 ProtectControlGroups = true;
358 # ProtectHome=true would not allow BindPaths= to work across /home,
359 # and ProtectHome=tmpfs would break statfs(),
360 # preventing transmission-daemon to report the available free space.
361 # However, RootDirectory= is used, so this is not a security concern
362 # since there would be nothing in /home but any BindPaths= wanted by the user.
363 ProtectHome = "read-only";
364 ProtectHostname = true;
365 ProtectKernelLogs = true;
366 ProtectKernelModules = true;
367 ProtectKernelTunables = true;
368 ProtectSystem = "strict";
370 # AF_UNIX may become usable one day:
371 # https://github.com/transmission/transmission/issues/441
372 RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
373 RestrictNamespaces = true;
374 RestrictRealtime = true;
375 RestrictSUIDSGID = true;
378 # Groups in @system-service which do not contain a syscall
379 # listed by perf stat -e 'syscalls:sys_enter_*' transmission-daemon -f
380 # in tests, and seem likely not necessary for transmission-daemon.
381 "~@aio" "~@chown" "~@keyring" "~@memlock" "~@resources" "~@setuid" "~@timer"
382 # In the @privileged group, but reached when querying infos through RPC (eg. with stig).
385 SystemCallArchitectures = "native";
389 # It's useful to have transmission in path, e.g. for remote control
390 environment.systemPackages = [ cfg.package ];
392 users.users = optionalAttrs (cfg.user == "transmission") ({
395 uid = config.ids.uids.transmission;
396 description = "Transmission BitTorrent user";
401 users.groups = optionalAttrs (cfg.group == "transmission") ({
403 gid = config.ids.gids.transmission;
407 networking.firewall = mkMerge [
408 (mkIf cfg.openPeerPorts (
409 if cfg.settings.peer-port-random-on-start
411 { allowedTCPPortRanges =
412 [ { from = cfg.settings.peer-port-random-low;
413 to = cfg.settings.peer-port-random-high;
416 allowedUDPPortRanges =
417 [ { from = cfg.settings.peer-port-random-low;
418 to = cfg.settings.peer-port-random-high;
423 { allowedTCPPorts = [ cfg.settings.peer-port ];
424 allowedUDPPorts = [ cfg.settings.peer-port ];
427 (mkIf cfg.openRPCPort { allowedTCPPorts = [ cfg.settings.rpc-port ]; })
430 boot.kernel.sysctl = mkMerge [
431 # Transmission uses a single UDP socket in order to implement multiple uTP sockets,
432 # and thus expects large kernel buffers for the UDP socket,
433 # https://trac.transmissionbt.com/browser/trunk/libtransmission/tr-udp.c?rev=11956.
434 # at least up to the values hardcoded here:
435 (mkIf cfg.settings.utp-enabled {
436 "net.core.rmem_max" = mkDefault 4194304; # 4MB
437 "net.core.wmem_max" = mkDefault "1048576"; # 1MB
439 (mkIf cfg.performanceNetParameters {
440 # Increase the number of available source (local) TCP and UDP ports to 49151.
441 # Usual default is 32768 60999, ie. 28231 ports.
442 # Find out your current usage with: ss -s
443 "net.ipv4.ip_local_port_range" = mkDefault "16384 65535";
444 # Timeout faster generic TCP states.
445 # Usual default is 600.
446 # Find out your current usage with: watch -n 1 netstat -nptuo
447 "net.netfilter.nf_conntrack_generic_timeout" = mkDefault 60;
448 # Timeout faster established but inactive connections.
449 # Usual default is 432000.
450 "net.netfilter.nf_conntrack_tcp_timeout_established" = mkDefault 600;
451 # Clear immediately TCP states after timeout.
452 # Usual default is 120.
453 "net.netfilter.nf_conntrack_tcp_timeout_time_wait" = mkDefault 1;
454 # Increase the number of trackable connections.
455 # Usual default is 262144.
456 # Find out your current usage with: conntrack -C
457 "net.netfilter.nf_conntrack_max" = mkDefault 1048576;
461 security.apparmor.policies."bin.transmission-daemon".profile = ''
462 include "${cfg.package.apparmor}/bin.transmission-daemon"
464 security.apparmor.includes."local/bin.transmission-daemon" = ''
465 r ${config.systemd.services.transmission.environment.CURL_CA_BUNDLE},
467 owner rw ${cfg.home}/${settingsDir}/**,
468 rw ${cfg.settings.download-dir}/**,
469 ${optionalString cfg.settings.incomplete-dir-enabled ''
470 rw ${cfg.settings.incomplete-dir}/**,
472 ${optionalString cfg.settings.watch-dir-enabled ''
473 r${optionalString cfg.settings.trash-original-torrent-files "w"} ${cfg.settings.watch-dir}/**,
476 rw ${cfg.settings.download-dir}/**,
477 ${optionalString cfg.settings.incomplete-dir-enabled ''
478 rw ${cfg.settings.incomplete-dir}/**,
480 ${optionalString cfg.settings.watch-dir-enabled ''
481 r${optionalString cfg.settings.trash-original-torrent-files "w"} ${cfg.settings.watch-dir}/**,
485 ${optionalString (cfg.settings.script-torrent-done-enabled &&
486 cfg.settings.script-torrent-done-filename != null) ''
487 # Stack transmission_directories profile on top of
488 # any existing profile for script-torrent-done-filename
489 # FIXME: to be tested as I'm not sure it works well with NoNewPrivileges=
490 # https://gitlab.com/apparmor/apparmor/-/wikis/AppArmorStacking#seccomp-and-no_new_privs
491 px ${cfg.settings.script-torrent-done-filename} -> &@{dirs},
496 meta.maintainers = with lib.maintainers; [ julm ];