Simplify the oom-taming-function
[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 <pwd.h>
10 #include <stdarg.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <sys/types.h>
16 #include <X11/extensions/Xrandr.h>
17 #include <X11/keysym.h>
18 #include <X11/Xlib.h>
19 #include <X11/Xutil.h>
20
21 #if HAVE_BSD_AUTH
22 #include <login_cap.h>
23 #include <bsd_auth.h>
24 #endif
25
26 enum {
27         INIT,
28         INPUT,
29         FAILED,
30         NUMCOLS
31 };
32
33 #include "config.h"
34
35 typedef struct {
36         int screen;
37         Window root, win;
38         Pixmap pmap;
39         unsigned long colors[NUMCOLS];
40 } Lock;
41
42 static Lock **locks;
43 static int nscreens;
44 static Bool running = True;
45 static Bool failure = False;
46 static Bool rr;
47 static int rrevbase;
48 static int rrerrbase;
49
50 static void
51 die(const char *errstr, ...)
52 {
53         va_list ap;
54
55         va_start(ap, errstr);
56         vfprintf(stderr, errstr, ap);
57         va_end(ap);
58         exit(1);
59 }
60
61 #ifdef __linux__
62 #include <fcntl.h>
63
64 static void
65 dontkillme(void)
66 {
67         int fd;
68
69         fd = open("/proc/self/oom_score_adj", O_WRONLY);
70         if (fd < 0 && errno == ENOENT) {
71                 return;
72         }
73         if (fd < 0 || write(fd, "-1000\n", (sizeof("-1000\n") - 1)) !=
74             (sizeof("-1000\n") - 1) || close(fd) != 0) {
75                 die("can't tame the oom-killer. is suid or sgid set?\n");
76         }
77 }
78 #endif
79
80 #ifndef HAVE_BSD_AUTH
81 /* only run as root */
82 static const char *
83 getpw(void)
84 {
85         const char *rval;
86         struct passwd *pw;
87
88         errno = 0;
89         if (!(pw = getpwuid(getuid()))) {
90                 if (errno)
91                         die("slock: getpwuid: %s\n", strerror(errno));
92                 else
93                         die("slock: cannot retrieve password entry\n");
94         }
95         rval = pw->pw_passwd;
96
97 #if HAVE_SHADOW_H
98         if (rval[0] == 'x' && rval[1] == '\0') {
99                 struct spwd *sp;
100                 if (!(sp = getspnam(getenv("USER"))))
101                         die("slock: cannot retrieve shadow entry (make sure to suid or sgid slock)\n");
102                 rval = sp->sp_pwdp;
103         }
104 #endif
105
106         /* drop privileges */
107         if (geteuid() == 0 &&
108             ((getegid() != pw->pw_gid && setgid(pw->pw_gid) < 0) || setuid(pw->pw_uid) < 0))
109                 die("slock: cannot drop privileges\n");
110         return rval;
111 }
112 #endif
113
114 static void
115 #ifdef HAVE_BSD_AUTH
116 readpw(Display *dpy)
117 #else
118 readpw(Display *dpy, const char *pws)
119 #endif
120 {
121         char buf[32], passwd[256];
122         int num, screen;
123         unsigned int len, color;
124         KeySym ksym;
125         XEvent ev;
126         static int oldc = INIT;
127
128         len = 0;
129         running = True;
130
131         /* As "slock" stands for "Simple X display locker", the DPMS settings
132          * had been removed and you can set it with "xset" or some other
133          * utility. This way the user can easily set a customized DPMS
134          * timeout. */
135         while (running && !XNextEvent(dpy, &ev)) {
136                 if (ev.type == KeyPress) {
137                         buf[0] = 0;
138                         num = XLookupString(&ev.xkey, buf, sizeof(buf), &ksym, 0);
139                         if (IsKeypadKey(ksym)) {
140                                 if (ksym == XK_KP_Enter)
141                                         ksym = XK_Return;
142                                 else if (ksym >= XK_KP_0 && ksym <= XK_KP_9)
143                                         ksym = (ksym - XK_KP_0) + XK_0;
144                         }
145                         if (IsFunctionKey(ksym) ||
146                             IsKeypadKey(ksym) ||
147                             IsMiscFunctionKey(ksym) ||
148                             IsPFKey(ksym) ||
149                             IsPrivateKeypadKey(ksym))
150                                 continue;
151                         switch (ksym) {
152                         case XK_Return:
153                                 passwd[len] = 0;
154 #ifdef HAVE_BSD_AUTH
155                                 running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
156 #else
157                                 running = !!strcmp(crypt(passwd, pws), pws);
158 #endif
159                                 if (running) {
160                                         XBell(dpy, 100);
161                                         failure = True;
162                                 }
163                                 len = 0;
164                                 break;
165                         case XK_Escape:
166                                 len = 0;
167                                 break;
168                         case XK_BackSpace:
169                                 if (len)
170                                         --len;
171                                 break;
172                         default:
173                                 if (num && !iscntrl((int)buf[0]) && (len + num < sizeof(passwd))) {
174                                         memcpy(passwd + len, buf, num);
175                                         len += num;
176                                 }
177                                 break;
178                         }
179                         color = len ? INPUT : (failure || failonclear ? FAILED : INIT);
180                         if (running && oldc != color) {
181                                 for (screen = 0; screen < nscreens; screen++) {
182                                         XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[color]);
183                                         XClearWindow(dpy, locks[screen]->win);
184                                 }
185                                 oldc = color;
186                         }
187                 } else if (rr && ev.type == rrevbase + RRScreenChangeNotify) {
188                         XRRScreenChangeNotifyEvent *rre = (XRRScreenChangeNotifyEvent*)&ev;
189                         for (screen = 0; screen < nscreens; screen++) {
190                                 if (locks[screen]->win == rre->window) {
191                                         XResizeWindow(dpy, locks[screen]->win, rre->width, rre->height);
192                                         XClearWindow(dpy, locks[screen]->win);
193                                 }
194                         }
195                 } else for (screen = 0; screen < nscreens; screen++)
196                         XRaiseWindow(dpy, locks[screen]->win);
197         }
198 }
199
200 static void
201 unlockscreen(Display *dpy, Lock *lock)
202 {
203         if(dpy == NULL || lock == NULL)
204                 return;
205
206         XUngrabPointer(dpy, CurrentTime);
207         XFreeColors(dpy, DefaultColormap(dpy, lock->screen), lock->colors, NUMCOLS, 0);
208         XFreePixmap(dpy, lock->pmap);
209         XDestroyWindow(dpy, lock->win);
210
211         free(lock);
212 }
213
214 static Lock *
215 lockscreen(Display *dpy, int screen)
216 {
217         char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
218         unsigned int len;
219         int i;
220         Lock *lock;
221         XColor color, dummy;
222         XSetWindowAttributes wa;
223         Cursor invisible;
224
225         if (!running || dpy == NULL || screen < 0 || !(lock = malloc(sizeof(Lock))))
226                 return NULL;
227
228         lock->screen = screen;
229         lock->root = RootWindow(dpy, lock->screen);
230
231         for (i = 0; i < NUMCOLS; i++) {
232                 XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), 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, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
240                                   0, DefaultDepth(dpy, lock->screen), CopyFromParent,
241                                   DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
242         lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
243         invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
244         XDefineCursor(dpy, lock->win, invisible);
245         XMapRaised(dpy, lock->win);
246         if (rr)
247                 XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
248
249         /* Try to grab mouse pointer *and* keyboard, else fail the lock */
250         for (len = 1000; len; len--) {
251                 if (XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
252                     GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
253                         break;
254                 usleep(1000);
255         }
256         if (!len) {
257                 fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n", screen);
258         } else {
259                 for (len = 1000; len; len--) {
260                         if (XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess) {
261                                 /* everything fine, we grabbed both inputs */
262                                 XSelectInput(dpy, lock->root, SubstructureNotifyMask);
263                                 return lock;
264                         }
265                         usleep(1000);
266                 }
267                 fprintf(stderr, "slock: unable to grab keyboard for screen %d\n", screen);
268         }
269         /* grabbing one of the inputs failed */
270         running = 0;
271         unlockscreen(dpy, lock);
272         return NULL;
273 }
274
275 static void
276 usage(void)
277 {
278         fprintf(stderr, "usage: slock [-v|POST_LOCK_CMD]\n");
279         exit(1);
280 }
281
282 int
283 main(int argc, char **argv) {
284 #ifndef HAVE_BSD_AUTH
285         const char *pws;
286 #endif
287         Display *dpy;
288         int screen;
289
290         if ((argc == 2) && !strcmp("-v", argv[1]))
291                 die("slock-%s, © 2006-2016 slock engineers\n", VERSION);
292
293         if ((argc == 2) && !strcmp("-h", argv[1]))
294                 usage();
295
296 #ifdef __linux__
297         dontkillme();
298 #endif
299
300         if (!getpwuid(getuid()))
301                 die("slock: no passwd entry for you\n");
302
303 #ifndef HAVE_BSD_AUTH
304         pws = getpw();
305 #endif
306
307         if (!(dpy = XOpenDisplay(0)))
308                 die("slock: cannot open display\n");
309         rr = XRRQueryExtension(dpy, &rrevbase, &rrerrbase);
310         /* Get the number of screens in display "dpy" and blank them all. */
311         nscreens = ScreenCount(dpy);
312         if (!(locks = malloc(sizeof(Lock*) * nscreens)))
313                 die("slock: malloc: %s\n", strerror(errno));
314         int nlocks = 0;
315         for (screen = 0; screen < nscreens; screen++) {
316                 if ((locks[screen] = lockscreen(dpy, screen)) != NULL)
317                         nlocks++;
318         }
319         XSync(dpy, False);
320
321         /* Did we actually manage to lock something? */
322         if (nlocks == 0) { /* nothing to protect */
323                 free(locks);
324                 XCloseDisplay(dpy);
325                 return 1;
326         }
327
328         if (argc >= 2 && fork() == 0) {
329                 if (dpy)
330                         close(ConnectionNumber(dpy));
331                 execvp(argv[1], argv+1);
332                 die("slock: execvp %s failed: %s\n", argv[1], strerror(errno));
333         }
334
335         /* Everything is now blank. Now wait for the correct password. */
336 #ifdef HAVE_BSD_AUTH
337         readpw(dpy);
338 #else
339         readpw(dpy, pws);
340 #endif
341
342         /* Password ok, unlock everything and quit. */
343         for (screen = 0; screen < nscreens; screen++)
344                 unlockscreen(dpy, locks[screen]);
345
346         free(locks);
347         XCloseDisplay(dpy);
348
349         return 0;
350 }