summaryrefslogtreecommitdiffstats
path: root/modules/slock.nix
blob: d96ae42d5367e5fa50726906681f600dd90d362a (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
{ config, lib, mylib, pkgs, ... }: let
  cfg = config.tv.slock;
in {
  options.tv.slock = {
    enable = lib.mkEnableOption "tv.slock";
    package = lib.mkOption {
      default = pkgs.writeDashBin "slock" ''
        set -efu
        display=''${DISPLAY#:}
        service=slock-$LOGNAME@$display.service
        exec ${pkgs.systemd}/bin/systemctl start "$service"
      '';
      type = lib.types.package;
    };
    user = lib.mkOption {
      type = mylib.types.user;
    };
  };
  config = lib.mkIf cfg.enable {
    security.polkit.extraConfig = /* js */ ''
      polkit.addRule(function(action, subject) {
        if (action.id === "org.freedesktop.systemd1.manage-units" &&
            subject.user === ${builtins.toJSON cfg.user.name} &&
            /^slock-${cfg.user.name}@[0-9]+\.service$/.test(action.lookup("unit")) ) {
          return polkit.Result.YES;
        }
      });
    '';
    systemd.services."slock-${cfg.user.name}@" = {
      conflicts = [
        "picom@%i.target"
      ];
      environment = {
        DISPLAY = ":%I";
        LD_PRELOAD = pkgs.runCommandCC "slock-${cfg.user.name}.so" {
          passAsFile = ["text"];
          text = /* c */ ''
            #include <shadow.h>
            #include <unistd.h>

            static struct spwd entry = {
              .sp_namp = "",
              .sp_pwdp =
                ${mylib.toC config.users.users.${cfg.user.name}.hashedPassword},
              .sp_lstchg = 0,
              .sp_min = 0,
              .sp_max = 0,
              .sp_warn = 0,
              .sp_inact = 0,
              .sp_expire = 0,
              .sp_flag = 0,
            };

            extern struct spwd *getspnam(const char *name) { return &entry; }
            extern int setgroups(size_t size, const gid_t *list) { return 0; }
            extern int setgid(gid_t gid) { return 0; }
            extern int setuid(uid_t uid) { return 0; }
          '';
        } /* sh */ ''
          gcc -Wall -shared -o $out -xc "$textPath"
        '';
      };
      restartIfChanged = false;
      serviceConfig = {
        ExecStart = "${pkgs.slock}/bin/slock";
        ExecStopPost =
          "+${pkgs.systemd}/bin/systemctl start xsession@%i.target";
        OOMScoreAdjust = -1000;
        Restart = "on-failure";
        RestartSec = "100ms";
        StartLimitBurst = 0;
        SyslogIdentifier = "slock";
        User = cfg.user.name;
      };
    };
  };
}