2a3027e5eeada19c451d7becf99c86195f298129
[slock.git] / slock.c
1 /* See LICENSE file for license details. */
2 #define _XOPEN_SOURCE 500
3 #if HAVE_SHADOW_H
4 #include <shadow.h>
5 #endif
6
7 #include <ctype.h>
8 #include <errno.h>
9 #include <grp.h>
10 #include <pwd.h>
11 #include <stdarg.h>
12 #include <stdlib.h>
13 #include <stdio.h>
14 #include <string.h>
15 #include <unistd.h>
16 #include <sys/types.h>
17 #include <X11/extensions/Xrandr.h>
18 #include <X11/keysym.h>
19 #include <X11/Xlib.h>
20 #include <X11/Xutil.h>
21
22 #include "arg.h"
23 #include "util.h"
24
25 char *argv0;
26
27 enum {
28         INIT,
29         INPUT,
30         FAILED,
31         NUMCOLS
32 };
33
34 #include "config.h"
35
36 struct lock {
37         int screen;
38         Window root, win;
39         Pixmap pmap;
40         unsigned long colors[NUMCOLS];
41 };
42
43 struct xrandr {
44         int active;
45         int evbase;
46         int errbase;
47 };
48
49 static void
50 die(const char *errstr, ...)
51 {
52         va_list ap;
53
54         va_start(ap, errstr);
55         vfprintf(stderr, errstr, ap);
56         va_end(ap);
57         exit(1);
58 }
59
60 #ifdef __linux__
61 #include <fcntl.h>
62 #include <linux/oom.h>
63
64 static void
65 dontkillme(void)
66 {
67         FILE *f;
68         const char oomfile[] = "/proc/self/oom_score_adj";
69
70         if (!(f = fopen(oomfile, "w"))) {
71                 if (errno == ENOENT)
72                         return;
73                 die("slock: fopen %s: %s\n", oomfile, strerror(errno));
74         }
75         fprintf(f, "%d", OOM_SCORE_ADJ_MIN);
76         if (fclose(f)) {
77                 if (errno == EACCES)
78                         die("slock: unable to disable OOM killer. "
79                             "Make sure to suid or sgid slock.\n");
80                 else
81                         die("slock: fclose %s: %s\n", oomfile, strerror(errno));
82         }
83 }
84 #endif
85
86 static const char *
87 gethash(void)
88 {
89         const char *hash;
90         struct passwd *pw;
91
92         /* Check if the current user has a password entry */
93         errno = 0;
94         if (!(pw = getpwuid(getuid()))) {
95                 if (errno)
96                         die("slock: getpwuid: %s\n", strerror(errno));
97                 else
98                         die("slock: cannot retrieve password entry\n");
99         }
100         hash = pw->pw_passwd;
101
102 #if HAVE_SHADOW_H
103         if (hash[0] == 'x' && hash[1] == '\0') {
104                 struct spwd *sp;
105                 if (!(sp = getspnam(pw->pw_name)))
106                         die("slock: getspnam: cannot retrieve shadow entry. "
107                             "Make sure to suid or sgid slock.\n");
108                 hash = sp->sp_pwdp;
109         }
110 #else
111         if (hash[0] == '*' && hash[1] == '\0') {
112 #ifdef __OpenBSD__
113                 if (!(pw = getpwuid_shadow(getuid())))
114                         die("slock: getpwnam_shadow: cannot retrieve shadow entry. "
115                             "Make sure to suid or sgid slock.\n");
116                 hash = pw->pw_passwd;
117 #else
118                 die("slock: getpwuid: cannot retrieve shadow entry. "
119                     "Make sure to suid or sgid slock.\n");
120 #endif /* __OpenBSD__ */
121         }
122 #endif /* HAVE_SHADOW_H */
123
124         return hash;
125 }
126
127 static void
128 readpw(Display *dpy, struct xrandr *rr, struct lock **locks, int nscreens,
129        const char *hash)
130 {
131         XRRScreenChangeNotifyEvent *rre;
132         char buf[32], passwd[256], *inputhash;
133         int num, screen, running, failure;
134         unsigned int len, color;
135         KeySym ksym;
136         XEvent ev;
137         static int oldc = INIT;
138
139         len = 0;
140         running = 1;
141         failure = 0;
142
143         while (running && !XNextEvent(dpy, &ev)) {
144                 if (ev.type == KeyPress) {
145                         explicit_bzero(&buf, sizeof(buf));
146                         num = XLookupString(&ev.xkey, buf, sizeof(buf), &ksym, 0);
147                         if (IsKeypadKey(ksym)) {
148                                 if (ksym == XK_KP_Enter)
149                                         ksym = XK_Return;
150                                 else if (ksym >= XK_KP_0 && ksym <= XK_KP_9)
151                                         ksym = (ksym - XK_KP_0) + XK_0;
152                         }
153                         if (IsFunctionKey(ksym) ||
154                             IsKeypadKey(ksym) ||
155                             IsMiscFunctionKey(ksym) ||
156                             IsPFKey(ksym) ||
157                             IsPrivateKeypadKey(ksym))
158                                 continue;
159                         switch (ksym) {
160                         case XK_Return:
161                                 passwd[len] = 0;
162                                 errno = 0;
163                                 if (!(inputhash = crypt(passwd, hash)))
164                                         fprintf(stderr, "slock: crypt: %s\n", strerror(errno));
165                                 else
166                                         running = !!strcmp(inputhash, hash);
167                                 if (running) {
168                                         XBell(dpy, 100);
169                                         failure = True;
170                                 }
171                                 explicit_bzero(&passwd, sizeof(passwd));
172                                 len = 0;
173                                 break;
174                         case XK_Escape:
175                                 explicit_bzero(&passwd, sizeof(passwd));
176                                 len = 0;
177                                 break;
178                         case XK_BackSpace:
179                                 if (len)
180                                         passwd[len--] = 0;
181                                 break;
182                         default:
183                                 if (num && !iscntrl((int)buf[0]) &&
184                                     (len + num < sizeof(passwd))) {
185                                         memcpy(passwd + len, buf, num);
186                                         len += num;
187                                 }
188                                 break;
189                         }
190                         color = len ? INPUT : ((failure || failonclear) ? FAILED : INIT);
191                         if (running && oldc != color) {
192                                 for (screen = 0; screen < nscreens; screen++) {
193                                         XSetWindowBackground(dpy,
194                                                              locks[screen]->win,
195                                                              locks[screen]->colors[color]);
196                                         XClearWindow(dpy, locks[screen]->win);
197                                 }
198                                 oldc = color;
199                         }
200                 } else if (rr->active && ev.type == rr->evbase + RRScreenChangeNotify) {
201                         rre = (XRRScreenChangeNotifyEvent*)&ev;
202                         for (screen = 0; screen < nscreens; screen++) {
203                                 if (locks[screen]->win == rre->window) {
204                                         XResizeWindow(dpy, locks[screen]->win,
205                                                       rre->width, rre->height);
206                                         XClearWindow(dpy, locks[screen]->win);
207                                 }
208                         }
209                 } else for (screen = 0; screen < nscreens; screen++)
210                         XRaiseWindow(dpy, locks[screen]->win);
211         }
212 }
213
214 static struct lock *
215 lockscreen(Display *dpy, struct xrandr *rr, int screen)
216 {
217         char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
218         int i, ptgrab, kbgrab;
219         struct lock *lock;
220         XColor color, dummy;
221         XSetWindowAttributes wa;
222         Cursor invisible;
223
224         if (dpy == NULL || screen < 0 || !(lock = malloc(sizeof(struct lock))))
225                 return NULL;
226
227         lock->screen = screen;
228         lock->root = RootWindow(dpy, lock->screen);
229
230         for (i = 0; i < NUMCOLS; i++) {
231                 XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen),
232                                  colorname[i], &color, &dummy);
233                 lock->colors[i] = color.pixel;
234         }
235
236         /* init */
237         wa.override_redirect = 1;
238         wa.background_pixel = lock->colors[INIT];
239         lock->win = XCreateWindow(dpy, lock->root, 0, 0,
240                                   DisplayWidth(dpy, lock->screen),
241                                   DisplayHeight(dpy, lock->screen),
242                                   0, DefaultDepth(dpy, lock->screen),
243                                   CopyFromParent,
244                                   DefaultVisual(dpy, lock->screen),
245                                   CWOverrideRedirect | CWBackPixel, &wa);
246         lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
247         invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap,
248                                         &color, &color, 0, 0);
249         XDefineCursor(dpy, lock->win, invisible);
250
251         /* Try to grab mouse pointer *and* keyboard for 600ms, else fail the lock */
252         for (i = 0, ptgrab = kbgrab = -1; i < 6; i++) {
253                 if (ptgrab != GrabSuccess) {
254                         ptgrab = XGrabPointer(dpy, lock->root, False,
255                                               ButtonPressMask | ButtonReleaseMask |
256                                               PointerMotionMask, GrabModeAsync,
257                                               GrabModeAsync, None, invisible, CurrentTime);
258                 }
259                 if (kbgrab != GrabSuccess) {
260                         kbgrab = XGrabKeyboard(dpy, lock->root, True,
261                                                GrabModeAsync, GrabModeAsync, CurrentTime);
262                 }
263
264                 /* input is grabbed: we can lock the screen */
265                 if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
266                         XMapRaised(dpy, lock->win);
267                         if (rr->active)
268                                 XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
269
270                         XSelectInput(dpy, lock->root, SubstructureNotifyMask);
271                         return lock;
272                 }
273
274                 /* retry on AlreadyGrabbed but fail on other errors */
275                 if ((ptgrab != AlreadyGrabbed && ptgrab != GrabSuccess) ||
276                     (kbgrab != AlreadyGrabbed && kbgrab != GrabSuccess))
277                         break;
278
279                 usleep(100000);
280         }
281
282         /* we couldn't grab all input: fail out */
283         if (ptgrab != GrabSuccess)
284                 fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n",
285                         screen);
286         if (kbgrab != GrabSuccess)
287                 fprintf(stderr, "slock: unable to grab keyboard for screen %d\n",
288                         screen);
289         return NULL;
290 }
291
292 static void
293 usage(void)
294 {
295         die("usage: slock [-v] [cmd [arg ...]]\n");
296 }
297
298 int
299 main(int argc, char **argv) {
300         struct xrandr rr;
301         struct lock **locks;
302         struct passwd *pwd;
303         struct group *grp;
304         uid_t duid;
305         gid_t dgid;
306         const char *hash;
307         Display *dpy;
308         int s, nlocks, nscreens;
309
310         ARGBEGIN {
311         case 'v':
312                 fprintf(stderr, "slock-"VERSION"\n");
313                 return 0;
314         default:
315                 usage();
316         } ARGEND
317
318         /* validate drop-user and -group */
319         errno = 0;
320         if (!(pwd = getpwnam(user)))
321                 die("slock: getpwnam %s: %s\n", user,
322                     errno ? strerror(errno) : "user entry not found");
323         duid = pwd->pw_uid;
324         errno = 0;
325         if (!(grp = getgrnam(group)))
326                 die("slock: getgrnam %s: %s\n", group,
327                     errno ? strerror(errno) : "group entry not found");
328         dgid = grp->gr_gid;
329
330 #ifdef __linux__
331         dontkillme();
332 #endif
333
334         hash = gethash();
335         errno = 0;
336         if (!crypt("", hash))
337                 die("slock: crypt: %s\n", strerror(errno));
338
339         if (!(dpy = XOpenDisplay(NULL)))
340                 die("slock: cannot open display\n");
341
342         /* drop privileges */
343         if (setgroups(0, NULL) < 0)
344                 die("slock: setgroups: %s\n", strerror(errno));
345         if (setgid(dgid) < 0)
346                 die("slock: setgid: %s\n", strerror(errno));
347         if (setuid(duid) < 0)
348                 die("slock: setuid: %s\n", strerror(errno));
349
350         /* check for Xrandr support */
351         rr.active = XRRQueryExtension(dpy, &rr.evbase, &rr.errbase);
352
353         /* get number of screens in display "dpy" and blank them */
354         nscreens = ScreenCount(dpy);
355         if (!(locks = calloc(nscreens, sizeof(struct lock *))))
356                 die("slock: out of memory\n");
357         for (nlocks = 0, s = 0; s < nscreens; s++) {
358                 if ((locks[s] = lockscreen(dpy, &rr, s)) != NULL)
359                         nlocks++;
360                 else
361                         break;
362         }
363         XSync(dpy, 0);
364
365         /* did we manage to lock everything? */
366         if (nlocks != nscreens)
367                 return 1;
368
369         /* run post-lock command */
370         if (argc > 0) {
371                 switch (fork()) {
372                 case -1:
373                         die("slock: fork failed: %s\n", strerror(errno));
374                 case 0:
375                         if (close(ConnectionNumber(dpy)) < 0)
376                                 die("slock: close: %s\n", strerror(errno));
377                         execvp(argv[0], argv);
378                         fprintf(stderr, "slock: execvp %s: %s\n", argv[0], strerror(errno));
379                         _exit(1);
380                 }
381         }
382
383         /* everything is now blank. Wait for the correct password */
384         readpw(dpy, &rr, locks, nscreens, hash);
385
386         return 0;
387 }