summaryrefslogtreecommitdiff
path: root/nixos/modules/services/mosquitto.nix
blob: 0934014c80c0c6f78001c50cc13bc24c77cd5c3f (plain)
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
{ config, lib, pkgs, ... }:
with lib;

let

  cfg = config.eth.services.mosquitto;

  systemdDirectoryName = "mosquitto";
  stateDirectory = "/var/lib/${systemdDirectoryName}";
  runtimeDirectory = "/run/${systemdDirectoryName}";

  mosquittoConf = pkgs.writeText "mosquitto.conf" ''
    ${optionalString cfg.mqtt.enable ''
      listener ${toString cfg.mqtt.port} ${optionalString (cfg.mqtt.host != "") cfg.mqtt.host}
    ''}

    ${optionalString cfg.websockets.enable ''
      listener ${toString cfg.websockets.port} ${optionalString (cfg.websockets.host != "") cfg.websockets.host}
      protocol websockets
    ''}

    ${optionalString cfg.persistence ''
      persistence true
      persistence_location ${stateDirectory}/
    ''}

    ${cfg.extraConfig}
  '';

in {

  options.eth.services.mosquitto = {

    enable = mkEnableOption "Whether to enable mosquitto.";

    persistence = mkOption {
      type = types.bool;
      default = true;
    };

    mqtt = {
      enable = mkEnableOption "Whether to listen on unencrypted MQTT.";
      host = mkOption {
        type = types.str;
        default = "";
        example = "10.11.12.14";
      };
      port = mkOption {
        type = types.int;
        default = 1883;
      };
    };

    websockets = {
      enable = mkEnableOption "Whether to listen on unencrypted Websockets.";
      host = mkOption {
        type = types.str;
        default = "";
        example = "10.11.12.14";
      };
      port = mkOption {
        type = types.int;
        default = 1884;
      };
    };

    extraConfig = mkOption {
      type = types.str;
      description = "Config to append to the generated config.";
      example = ''
        log_type all
      '';
    };
  };

  config = mkIf cfg.enable {

    systemd.services.mosquitto = {
      enable = true;
      description = "Mosquitto MQTT broker";
      wants = [ "network.target" ];
      after = [ "network.target" ];
      wantedBy = [ "multi-user.target" ];
      serviceConfig = {
        DynamicUser = true;
        RuntimeDirectory = systemdDirectoryName;
        StateDirectory = systemdDirectoryName;
        ExecStart = "${pkgs.mosquitto}/bin/mosquitto -c ${mosquittoConf}";
        NoNewPrivileges = true;
        ProtectHome = true;
        ProtectKernelTunables = true;
        ProtectControlGroups = true;
        ProtectKernelModules = true;
        RestrictAddressFamilies = "AF_INET AF_INET6 AF_UNIX";
        RestrictNamespaces = true;
      };
    };
  };
}