summary refs log tree commit diff
path: root/nixos/modules/services/torrent/deluge.nix
blob: cb0da9e83b42e093b4c0290c42b48355d2f40e72 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
{ config, lib, pkgs, ... }:

with lib;

let
  cfg = config.services.deluge;
  cfg_web = config.services.deluge.web;
  isDeluge1 = versionOlder cfg.package.version "2.0.0";

  openFilesLimit = 4096;
  listenPortsDefault = [ 6881 6889 ];

  listToRange = x: { from = elemAt x 0; to = elemAt x 1; };

  configDir = "${cfg.dataDir}/.config/deluge";
  configFile = pkgs.writeText "core.conf" (builtins.toJSON cfg.config);
  declarativeLockFile = "${configDir}/.declarative";

  preStart = if cfg.declarative then ''
    if [ -e ${declarativeLockFile} ]; then
      # Was declarative before, no need to back up anything
      ${if isDeluge1 then "ln -sf" else "cp"} ${configFile} ${configDir}/core.conf
      ln -sf ${cfg.authFile} ${configDir}/auth
    else
      # Declarative for the first time, backup stateful files
      ${if isDeluge1 then "ln -s" else "cp"} -b --suffix=.stateful ${configFile} ${configDir}/core.conf
      ln -sb --suffix=.stateful ${cfg.authFile} ${configDir}/auth
      echo "Autogenerated file that signifies that this server configuration is managed declaratively by NixOS" \
        > ${declarativeLockFile}
    fi
  '' else ''
    if [ -e ${declarativeLockFile} ]; then
      rm ${declarativeLockFile}
    fi
  '';
in {
  options = {
    services = {
      deluge = {
        enable = mkEnableOption "Deluge daemon";

        openFilesLimit = mkOption {
          default = openFilesLimit;
          type = types.either types.int types.str;
          description = ''
            Number of files to allow deluged to open.
          '';
        };

        config = mkOption {
          type = types.attrs;
          default = {};
          example = literalExpression ''
            {
              download_location = "/srv/torrents/";
              max_upload_speed = "1000.0";
              share_ratio_limit = "2.0";
              allow_remote = true;
              daemon_port = 58846;
              listen_ports = [ ${toString listenPortsDefault} ];
            }
          '';
          description = ''
            Deluge core configuration for the core.conf file. Only has an effect
            when <option>services.deluge.declarative</option> is set to
            <literal>true</literal>. String values must be quoted, integer and
            boolean values must not. See
            <link xlink:href="https://git.deluge-torrent.org/deluge/tree/deluge/core/preferencesmanager.py#n41"/>
            for the availaible options.
          '';
        };

        declarative = mkOption {
          type = types.bool;
          default = false;
          description = ''
            Whether to use a declarative deluge configuration.
            Only if set to <literal>true</literal>, the options
            <option>services.deluge.config</option>,
            <option>services.deluge.openFirewall</option> and
            <option>services.deluge.authFile</option> will be
            applied.
          '';
        };

        openFirewall = mkOption {
          default = false;
          type = types.bool;
          description = ''
            Whether to open the firewall for the ports in
            <option>services.deluge.config.listen_ports</option>. It only takes effet if
            <option>services.deluge.declarative</option> is set to
            <literal>true</literal>.

            It does NOT apply to the daemon port nor the web UI port. To access those
            ports secuerly check the documentation
            <link xlink:href="https://dev.deluge-torrent.org/wiki/UserGuide/ThinClient#CreateSSHTunnel"/>
            or use a VPN or configure certificates for deluge.
          '';
        };

        dataDir = mkOption {
          type = types.path;
          default = "/var/lib/deluge";
          description = ''
            The directory where deluge will create files.
          '';
        };

        authFile = mkOption {
          type = types.path;
          example = "/run/keys/deluge-auth";
          description = ''
            The file managing the authentication for deluge, the format of this
            file is straightforward, each line contains a
            username:password:level tuple in plaintext. It only has an effect
            when <option>services.deluge.declarative</option> is set to
            <literal>true</literal>.
            See <link xlink:href="https://dev.deluge-torrent.org/wiki/UserGuide/Authentication"/> for
            more informations.
          '';
        };

        user = mkOption {
          type = types.str;
          default = "deluge";
          description = ''
            User account under which deluge runs.
          '';
        };

        group = mkOption {
          type = types.str;
          default = "deluge";
          description = ''
            Group under which deluge runs.
          '';
        };

        extraPackages = mkOption {
          type = types.listOf types.package;
          default = [];
          description = ''
            Extra packages available at runtime to enable Deluge's plugins. For example,
            extraction utilities are required for the built-in "Extractor" plugin.
            This always contains unzip, gnutar, xz and bzip2.
          '';
        };

        package = mkOption {
          type = types.package;
          example = literalExpression "pkgs.deluge-2_x";
          description = ''
            Deluge package to use.
          '';
        };
      };

      deluge.web = {
        enable = mkEnableOption "Deluge Web daemon";

        port = mkOption {
          type = types.port;
          default = 8112;
          description = ''
            Deluge web UI port.
          '';
        };

        openFirewall = mkOption {
          type = types.bool;
          default = false;
          description = ''
            Open ports in the firewall for deluge web daemon
          '';
        };
      };
    };
  };

  config = mkIf cfg.enable {

    services.deluge.package = mkDefault (
      if versionAtLeast config.system.stateVersion "20.09" then
        pkgs.deluge-2_x
      else
        # deluge-1_x is no longer packaged and this will resolve to an error
        # thanks to the alias for this name.  This is left here so that anyone
        # using NixOS older than 20.09 receives that error when they upgrade
        # and is forced to make an intentional choice to switch to deluge-2_x.
        # That might be slightly inconvenient but there is no path to
        # downgrade from 2.x to 1.x so NixOS should not automatically perform
        # this state migration.
        pkgs.deluge-1_x
    );

    # Provide a default set of `extraPackages`.
    services.deluge.extraPackages = with pkgs; [ unzip gnutar xz bzip2 ];

    systemd.tmpfiles.rules = [
      "d '${cfg.dataDir}' 0770 ${cfg.user} ${cfg.group}"
      "d '${cfg.dataDir}/.config' 0770 ${cfg.user} ${cfg.group}"
      "d '${cfg.dataDir}/.config/deluge' 0770 ${cfg.user} ${cfg.group}"
    ]
    ++ optional (cfg.config ? download_location)
      "d '${cfg.config.download_location}' 0770 ${cfg.user} ${cfg.group}"
    ++ optional (cfg.config ? torrentfiles_location)
      "d '${cfg.config.torrentfiles_location}' 0770 ${cfg.user} ${cfg.group}"
    ++ optional (cfg.config ? move_completed_path)
      "d '${cfg.config.move_completed_path}' 0770 ${cfg.user} ${cfg.group}";

    systemd.services.deluged = {
      after = [ "network.target" ];
      description = "Deluge BitTorrent Daemon";
      wantedBy = [ "multi-user.target" ];
      path = [ cfg.package ] ++ cfg.extraPackages;
      serviceConfig = {
        ExecStart = ''
          ${cfg.package}/bin/deluged \
            --do-not-daemonize \
            --config ${configDir}
        '';
        # To prevent "Quit & shutdown daemon" from working; we want systemd to
        # manage it!
        Restart = "on-success";
        User = cfg.user;
        Group = cfg.group;
        UMask = "0002";
        LimitNOFILE = cfg.openFilesLimit;
      };
      preStart = preStart;
    };

    systemd.services.delugeweb = mkIf cfg_web.enable {
      after = [ "network.target" "deluged.service"];
      requires = [ "deluged.service" ];
      description = "Deluge BitTorrent WebUI";
      wantedBy = [ "multi-user.target" ];
      path = [ cfg.package ];
      serviceConfig = {
        ExecStart = ''
          ${cfg.package}/bin/deluge-web \
            ${optionalString (!isDeluge1) "--do-not-daemonize"} \
            --config ${configDir} \
            --port ${toString cfg.web.port}
        '';
        User = cfg.user;
        Group = cfg.group;
      };
    };

    networking.firewall = mkMerge [
      (mkIf (cfg.declarative && cfg.openFirewall && !(cfg.config.random_port or true)) {
        allowedTCPPortRanges = singleton (listToRange (cfg.config.listen_ports or listenPortsDefault));
        allowedUDPPortRanges = singleton (listToRange (cfg.config.listen_ports or listenPortsDefault));
      })
      (mkIf (cfg.web.openFirewall) {
        allowedTCPPorts = [ cfg.web.port ];
      })
    ];

    environment.systemPackages = [ cfg.package ];

    users.users = mkIf (cfg.user == "deluge") {
      deluge = {
        group = cfg.group;
        uid = config.ids.uids.deluge;
        home = cfg.dataDir;
        description = "Deluge Daemon user";
      };
    };

    users.groups = mkIf (cfg.group == "deluge") {
      deluge = {
        gid = config.ids.gids.deluge;
      };
    };
  };
}