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 (mkAliasOptionModule ["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 explicitely 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)](http://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 downloadDirPermissions = mkOption {
178 type = with types; nullOr str;
181 description = lib.mdDoc ''
182 If not `null`, is used as the permissions
183 set by `systemd.activationScripts.transmission-daemon`
184 on the directories [](#opt-services.transmission.settings.download-dir),
185 [](#opt-services.transmission.settings.incomplete-dir).
186 and [](#opt-services.transmission.settings.watch-dir).
187 Note that you may also want to change
188 [](#opt-services.transmission.settings.umask).
194 default = "/var/lib/transmission";
195 description = lib.mdDoc ''
196 The directory where Transmission will create `${settingsDir}`.
197 as well as `${downloadsDir}/` unless
198 [](#opt-services.transmission.settings.download-dir) is changed,
199 and `${incompleteDir}/` unless
200 [](#opt-services.transmission.settings.incomplete-dir) is changed.
206 default = "transmission";
207 description = lib.mdDoc "User account under which Transmission runs.";
212 default = "transmission";
213 description = lib.mdDoc "Group account under which Transmission runs.";
216 credentialsFile = mkOption {
218 description = lib.mdDoc ''
219 Path to a JSON file to be merged with the settings.
220 Useful to merge a file which is better kept out of the Nix store
221 to set secret config parameters like `rpc-password`.
223 default = "/dev/null";
224 example = "/var/lib/secrets/transmission/settings.json";
227 extraFlags = mkOption {
228 type = types.listOf types.str;
230 example = [ "--log-debug" ];
231 description = lib.mdDoc ''
232 Extra flags passed to the transmission command in the service definition.
236 openPeerPorts = mkEnableOption (lib.mdDoc "opening of the peer port(s) in the firewall");
238 openRPCPort = mkEnableOption (lib.mdDoc "opening of the RPC port in the firewall");
240 performanceNetParameters = mkEnableOption (lib.mdDoc "performance tweaks") // {
241 description = lib.mdDoc ''
242 Whether to enable tweaking of kernel parameters
243 to open many more connections at the same time.
245 Note that you may also want to increase
247 And be aware that these settings are quite aggressive
248 and might not suite your regular desktop use.
249 For instance, SSH sessions may time out more easily.
255 config = mkIf cfg.enable {
256 # Note that using systemd.tmpfiles would not work here
257 # because it would fail when creating a directory
258 # with a different owner than its parent directory, by saying:
259 # Detected unsafe path transition /home/foo → /home/foo/Downloads during canonicalization of /home/foo/Downloads
260 # when /home/foo is not owned by cfg.user.
261 # Note also that using an ExecStartPre= wouldn't work either
262 # because BindPaths= needs these directories before.
263 system.activationScripts = mkIf (cfg.downloadDirPermissions != null)
264 { transmission-daemon = ''
265 install -d -m 700 '${cfg.home}/${settingsDir}'
266 chown -R '${cfg.user}:${cfg.group}' ${cfg.home}/${settingsDir}
267 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.download-dir}'
268 '' + optionalString cfg.settings.incomplete-dir-enabled ''
269 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.incomplete-dir}'
270 '' + optionalString cfg.settings.watch-dir-enabled ''
271 install -d -m '${cfg.downloadDirPermissions}' -o '${cfg.user}' -g '${cfg.group}' '${cfg.settings.watch-dir}'
275 systemd.services.transmission = {
276 description = "Transmission BitTorrent Service";
277 after = [ "network.target" ] ++ optional apparmor.enable "apparmor.service";
278 requires = optional apparmor.enable "apparmor.service";
279 wantedBy = [ "multi-user.target" ];
280 environment.CURL_CA_BUNDLE = etc."ssl/certs/ca-certificates.crt".source;
283 # Use "+" because credentialsFile may not be accessible to User= or Group=.
284 ExecStartPre = [("+" + pkgs.writeShellScript "transmission-prestart" ''
285 set -eu${lib.optionalString (cfg.settings.message-level >= 3) "x"}
286 ${pkgs.jq}/bin/jq --slurp add ${settingsFile} '${cfg.credentialsFile}' |
287 install -D -m 600 -o '${cfg.user}' -g '${cfg.group}' /dev/stdin \
288 '${cfg.home}/${settingsDir}/settings.json'
290 ExecStart="${pkgs.transmission}/bin/transmission-daemon -f -g ${cfg.home}/${settingsDir} ${escapeShellArgs cfg.extraFlags}";
291 ExecReload = "${pkgs.coreutils}/bin/kill -HUP $MAINPID";
294 # Create rootDir in the host's mount namespace.
295 RuntimeDirectory = [(baseNameOf rootDir)];
296 RuntimeDirectoryMode = "755";
297 # This is for BindPaths= and BindReadOnlyPaths=
298 # to allow traversal of directories they create in RootDirectory=.
300 # Using RootDirectory= makes it possible
301 # to use the same paths download-dir/incomplete-dir
302 # (which appear in user's interfaces) without requiring cfg.user
303 # to have access to their parent directories,
304 # by using BindPaths=/BindReadOnlyPaths=.
305 # Note that TemporaryFileSystem= could have been used instead
306 # but not without adding some BindPaths=/BindReadOnlyPaths=
307 # that would only be needed for ExecStartPre=,
308 # because RootDirectoryStartOnly=true would not help.
309 RootDirectory = rootDir;
310 RootDirectoryStartOnly = true;
313 [ "${cfg.home}/${settingsDir}"
314 cfg.settings.download-dir
316 optional cfg.settings.incomplete-dir-enabled
317 cfg.settings.incomplete-dir ++
318 optional (cfg.settings.watch-dir-enabled && cfg.settings.trash-original-torrent-files)
319 cfg.settings.watch-dir;
320 BindReadOnlyPaths = [
321 # No confinement done of /nix/store here like in systemd-confinement.nix,
322 # an AppArmor profile is provided to get a confinement based upon paths and rights.
327 optional (cfg.settings.script-torrent-done-enabled &&
328 cfg.settings.script-torrent-done-filename != null)
329 cfg.settings.script-torrent-done-filename ++
330 optional (cfg.settings.watch-dir-enabled && !cfg.settings.trash-original-torrent-files)
331 cfg.settings.watch-dir;
334 "transmission/.config/transmission-daemon"
335 "transmission/.incomplete"
336 "transmission/Downloads"
337 "transmission/watch-dir"
339 StateDirectoryMode = mkDefault 750;
340 # The following options are only for optimizing:
341 # systemd-analyze security transmission
342 AmbientCapabilities = "";
343 CapabilityBoundingSet = "";
344 # ProtectClock= adds DeviceAllow=char-rtc r
346 LockPersonality = true;
347 MemoryDenyWriteExecute = true;
348 NoNewPrivileges = true;
349 PrivateDevices = true;
350 PrivateMounts = true;
351 PrivateNetwork = mkDefault false;
355 ProtectControlGroups = true;
356 # ProtectHome=true would not allow BindPaths= to work accross /home,
357 # and ProtectHome=tmpfs would break statfs(),
358 # preventing transmission-daemon to report the available free space.
359 # However, RootDirectory= is used, so this is not a security concern
360 # since there would be nothing in /home but any BindPaths= wanted by the user.
361 ProtectHome = "read-only";
362 ProtectHostname = true;
363 ProtectKernelLogs = true;
364 ProtectKernelModules = true;
365 ProtectKernelTunables = true;
366 ProtectSystem = "strict";
368 # AF_UNIX may become usable one day:
369 # https://github.com/transmission/transmission/issues/441
370 RestrictAddressFamilies = [ "AF_UNIX" "AF_INET" "AF_INET6" ];
371 RestrictNamespaces = true;
372 RestrictRealtime = true;
373 RestrictSUIDSGID = true;
376 # Groups in @system-service which do not contain a syscall
377 # listed by perf stat -e 'syscalls:sys_enter_*' transmission-daemon -f
378 # in tests, and seem likely not necessary for transmission-daemon.
379 "~@aio" "~@chown" "~@keyring" "~@memlock" "~@resources" "~@setuid" "~@timer"
380 # In the @privileged group, but reached when querying infos through RPC (eg. with stig).
383 SystemCallArchitectures = "native";
387 # It's useful to have transmission in path, e.g. for remote control
388 environment.systemPackages = [ pkgs.transmission ];
390 users.users = optionalAttrs (cfg.user == "transmission") ({
393 uid = config.ids.uids.transmission;
394 description = "Transmission BitTorrent user";
399 users.groups = optionalAttrs (cfg.group == "transmission") ({
401 gid = config.ids.gids.transmission;
405 networking.firewall = mkMerge [
406 (mkIf cfg.openPeerPorts (
407 if cfg.settings.peer-port-random-on-start
409 { allowedTCPPortRanges =
410 [ { from = cfg.settings.peer-port-random-low;
411 to = cfg.settings.peer-port-random-high;
414 allowedUDPPortRanges =
415 [ { from = cfg.settings.peer-port-random-low;
416 to = cfg.settings.peer-port-random-high;
421 { allowedTCPPorts = [ cfg.settings.peer-port ];
422 allowedUDPPorts = [ cfg.settings.peer-port ];
425 (mkIf cfg.openRPCPort { allowedTCPPorts = [ cfg.settings.rpc-port ]; })
428 boot.kernel.sysctl = mkMerge [
429 # Transmission uses a single UDP socket in order to implement multiple uTP sockets,
430 # and thus expects large kernel buffers for the UDP socket,
431 # https://trac.transmissionbt.com/browser/trunk/libtransmission/tr-udp.c?rev=11956.
432 # at least up to the values hardcoded here:
433 (mkIf cfg.settings.utp-enabled {
434 "net.core.rmem_max" = mkDefault 4194304; # 4MB
435 "net.core.wmem_max" = mkDefault "1048576"; # 1MB
437 (mkIf cfg.performanceNetParameters {
438 # Increase the number of available source (local) TCP and UDP ports to 49151.
439 # Usual default is 32768 60999, ie. 28231 ports.
440 # Find out your current usage with: ss -s
441 "net.ipv4.ip_local_port_range" = mkDefault "16384 65535";
442 # Timeout faster generic TCP states.
443 # Usual default is 600.
444 # Find out your current usage with: watch -n 1 netstat -nptuo
445 "net.netfilter.nf_conntrack_generic_timeout" = mkDefault 60;
446 # Timeout faster established but inactive connections.
447 # Usual default is 432000.
448 "net.netfilter.nf_conntrack_tcp_timeout_established" = mkDefault 600;
449 # Clear immediately TCP states after timeout.
450 # Usual default is 120.
451 "net.netfilter.nf_conntrack_tcp_timeout_time_wait" = mkDefault 1;
452 # Increase the number of trackable connections.
453 # Usual default is 262144.
454 # Find out your current usage with: conntrack -C
455 "net.netfilter.nf_conntrack_max" = mkDefault 1048576;
459 security.apparmor.policies."bin.transmission-daemon".profile = ''
460 include "${pkgs.transmission.apparmor}/bin.transmission-daemon"
462 security.apparmor.includes."local/bin.transmission-daemon" = ''
463 r ${config.systemd.services.transmission.environment.CURL_CA_BUNDLE},
465 owner rw ${cfg.home}/${settingsDir}/**,
466 rw ${cfg.settings.download-dir}/**,
467 ${optionalString cfg.settings.incomplete-dir-enabled ''
468 rw ${cfg.settings.incomplete-dir}/**,
470 ${optionalString cfg.settings.watch-dir-enabled ''
471 r${optionalString cfg.settings.trash-original-torrent-files "w"} ${cfg.settings.watch-dir}/**,
474 rw ${cfg.settings.download-dir}/**,
475 ${optionalString cfg.settings.incomplete-dir-enabled ''
476 rw ${cfg.settings.incomplete-dir}/**,
478 ${optionalString cfg.settings.watch-dir-enabled ''
479 r${optionalString cfg.settings.trash-original-torrent-files "w"} ${cfg.settings.watch-dir}/**,
483 ${optionalString (cfg.settings.script-torrent-done-enabled &&
484 cfg.settings.script-torrent-done-filename != null) ''
485 # Stack transmission_directories profile on top of
486 # any existing profile for script-torrent-done-filename
487 # FIXME: to be tested as I'm not sure it works well with NoNewPrivileges=
488 # https://gitlab.com/apparmor/apparmor/-/wikis/AppArmorStacking#seccomp-and-no_new_privs
489 px ${cfg.settings.script-torrent-done-filename} -> &@{dirs},
494 meta.maintainers = with lib.maintainers; [ julm ];