700acfb4f5c969adc503fbabfb2b9ffd58932f0b
[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 struct lock {
35         int screen;
36         Window root, win;
37         Pixmap pmap;
38         unsigned long colors[NUMCOLS];
39 };
40
41 struct xrandr {
42         int active;
43         int evbase;
44         int errbase;
45 };
46
47 #include "config.h"
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 (!strcmp(hash, "x")) {
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 (!strcmp(hash, "*")) {
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, oldc;
134         unsigned int len, color;
135         KeySym ksym;
136         XEvent ev;
137
138         len = 0;
139         running = 1;
140         failure = 0;
141         oldc = INIT;
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 = 1;
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                                         if (rre->rotation == RR_Rotate_90 ||
205                                             rre->rotation == RR_Rotate_270)
206                                                 XResizeWindow(dpy, locks[screen]->win,
207                                                               rre->height, rre->width);
208                                         else
209                                                 XResizeWindow(dpy, locks[screen]->win,
210                                                               rre->width, rre->height);
211                                         XClearWindow(dpy, locks[screen]->win);
212                                         break;
213                                 }
214                         }
215                 } else for (screen = 0; screen < nscreens; screen++)
216                         XRaiseWindow(dpy, locks[screen]->win);
217         }
218 }
219
220 static struct lock *
221 lockscreen(Display *dpy, struct xrandr *rr, int screen)
222 {
223         char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
224         int i, ptgrab, kbgrab;
225         struct lock *lock;
226         XColor color, dummy;
227         XSetWindowAttributes wa;
228         Cursor invisible;
229
230         if (dpy == NULL || screen < 0 || !(lock = malloc(sizeof(struct lock))))
231                 return NULL;
232
233         lock->screen = screen;
234         lock->root = RootWindow(dpy, lock->screen);
235
236         for (i = 0; i < NUMCOLS; i++) {
237                 XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen),
238                                  colorname[i], &color, &dummy);
239                 lock->colors[i] = color.pixel;
240         }
241
242         /* init */
243         wa.override_redirect = 1;
244         wa.background_pixel = lock->colors[INIT];
245         lock->win = XCreateWindow(dpy, lock->root, 0, 0,
246                                   DisplayWidth(dpy, lock->screen),
247                                   DisplayHeight(dpy, lock->screen),
248                                   0, DefaultDepth(dpy, lock->screen),
249                                   CopyFromParent,
250                                   DefaultVisual(dpy, lock->screen),
251                                   CWOverrideRedirect | CWBackPixel, &wa);
252         lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
253         invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap,
254                                         &color, &color, 0, 0);
255         XDefineCursor(dpy, lock->win, invisible);
256
257         /* Try to grab mouse pointer *and* keyboard for 600ms, else fail the lock */
258         for (i = 0, ptgrab = kbgrab = -1; i < 6; i++) {
259                 if (ptgrab != GrabSuccess) {
260                         ptgrab = XGrabPointer(dpy, lock->root, False,
261                                               ButtonPressMask | ButtonReleaseMask |
262                                               PointerMotionMask, GrabModeAsync,
263                                               GrabModeAsync, None, invisible, CurrentTime);
264                 }
265                 if (kbgrab != GrabSuccess) {
266                         kbgrab = XGrabKeyboard(dpy, lock->root, True,
267                                                GrabModeAsync, GrabModeAsync, CurrentTime);
268                 }
269
270                 /* input is grabbed: we can lock the screen */
271                 if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
272                         XMapRaised(dpy, lock->win);
273                         if (rr->active)
274                                 XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
275
276                         XSelectInput(dpy, lock->root, SubstructureNotifyMask);
277                         return lock;
278                 }
279
280                 /* retry on AlreadyGrabbed but fail on other errors */
281                 if ((ptgrab != AlreadyGrabbed && ptgrab != GrabSuccess) ||
282                     (kbgrab != AlreadyGrabbed && kbgrab != GrabSuccess))
283                         break;
284
285                 usleep(100000);
286         }
287
288         /* we couldn't grab all input: fail out */
289         if (ptgrab != GrabSuccess)
290                 fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n",
291                         screen);
292         if (kbgrab != GrabSuccess)
293                 fprintf(stderr, "slock: unable to grab keyboard for screen %d\n",
294                         screen);
295         return NULL;
296 }
297
298 static void
299 usage(void)
300 {
301         die("usage: slock [-v] [cmd [arg ...]]\n");
302 }
303
304 int
305 main(int argc, char **argv) {
306         struct xrandr rr;
307         struct lock **locks;
308         struct passwd *pwd;
309         struct group *grp;
310         uid_t duid;
311         gid_t dgid;
312         const char *hash;
313         Display *dpy;
314         int s, nlocks, nscreens;
315
316         ARGBEGIN {
317         case 'v':
318                 fprintf(stderr, "slock-"VERSION"\n");
319                 return 0;
320         default:
321                 usage();
322         } ARGEND
323
324         /* validate drop-user and -group */
325         errno = 0;
326         if (!(pwd = getpwnam(user)))
327                 die("slock: getpwnam %s: %s\n", user,
328                     errno ? strerror(errno) : "user entry not found");
329         duid = pwd->pw_uid;
330         errno = 0;
331         if (!(grp = getgrnam(group)))
332                 die("slock: getgrnam %s: %s\n", group,
333                     errno ? strerror(errno) : "group entry not found");
334         dgid = grp->gr_gid;
335
336 #ifdef __linux__
337         dontkillme();
338 #endif
339
340         hash = gethash();
341         errno = 0;
342         if (!crypt("", hash))
343                 die("slock: crypt: %s\n", strerror(errno));
344
345         if (!(dpy = XOpenDisplay(NULL)))
346                 die("slock: cannot open display\n");
347
348         /* drop privileges */
349         if (setgroups(0, NULL) < 0)
350                 die("slock: setgroups: %s\n", strerror(errno));
351         if (setgid(dgid) < 0)
352                 die("slock: setgid: %s\n", strerror(errno));
353         if (setuid(duid) < 0)
354                 die("slock: setuid: %s\n", strerror(errno));
355
356         /* check for Xrandr support */
357         rr.active = XRRQueryExtension(dpy, &rr.evbase, &rr.errbase);
358
359         /* get number of screens in display "dpy" and blank them */
360         nscreens = ScreenCount(dpy);
361         if (!(locks = calloc(nscreens, sizeof(struct lock *))))
362                 die("slock: out of memory\n");
363         for (nlocks = 0, s = 0; s < nscreens; s++) {
364                 if ((locks[s] = lockscreen(dpy, &rr, s)) != NULL)
365                         nlocks++;
366                 else
367                         break;
368         }
369         XSync(dpy, 0);
370
371         /* did we manage to lock everything? */
372         if (nlocks != nscreens)
373                 return 1;
374
375         /* run post-lock command */
376         if (argc > 0) {
377                 switch (fork()) {
378                 case -1:
379                         die("slock: fork failed: %s\n", strerror(errno));
380                 case 0:
381                         if (close(ConnectionNumber(dpy)) < 0)
382                                 die("slock: close: %s\n", strerror(errno));
383                         execvp(argv[0], argv);
384                         fprintf(stderr, "slock: execvp %s: %s\n", argv[0], strerror(errno));
385                         _exit(1);
386                 }
387         }
388
389         /* everything is now blank. Wait for the correct password */
390         readpw(dpy, &rr, locks, nscreens, hash);
391
392         return 0;
393 }