]> git.armaanb.net Git - slock.git/blob - slock.c
add hint for suid to oom error message
[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 #include <linux/oom.h>
64
65 static void
66 dontkillme(void)
67 {
68         int fd;
69         int length;
70         char value[64];
71
72         fd = open("/proc/self/oom_score_adj", O_WRONLY);
73         if (fd < 0 && errno == ENOENT)
74                 return;
75
76         /* convert OOM_SCORE_ADJ_MIN to string for writing */
77         length = snprintf(value, sizeof(value), "%d\n", OOM_SCORE_ADJ_MIN);
78
79         /* bail on truncation */
80         if (length >= sizeof(value))
81                 die("buffer too small\n");
82
83         if (fd < 0 || write(fd, value, length) != length || close(fd) != 0)
84                 die("cannot disable the out-of-memory killer for this process (make sure to suid or sgid slock)\n");
85 }
86 #endif
87
88 #ifndef HAVE_BSD_AUTH
89 /* only run as root */
90 static const char *
91 getpw(void)
92 {
93         const char *rval;
94         struct passwd *pw;
95
96         errno = 0;
97         if (!(pw = getpwuid(getuid()))) {
98                 if (errno)
99                         die("slock: getpwuid: %s\n", strerror(errno));
100                 else
101                         die("slock: cannot retrieve password entry\n");
102         }
103         rval = pw->pw_passwd;
104
105 #if HAVE_SHADOW_H
106         if (rval[0] == 'x' && rval[1] == '\0') {
107                 struct spwd *sp;
108                 if (!(sp = getspnam(getenv("USER"))))
109                         die("slock: cannot retrieve shadow entry (make sure to suid or sgid slock)\n");
110                 rval = sp->sp_pwdp;
111         }
112 #endif
113
114         /* drop privileges */
115         if (geteuid() == 0 &&
116             ((getegid() != pw->pw_gid && setgid(pw->pw_gid) < 0) || setuid(pw->pw_uid) < 0))
117                 die("slock: cannot drop privileges\n");
118         return rval;
119 }
120 #endif
121
122 static void
123 #ifdef HAVE_BSD_AUTH
124 readpw(Display *dpy)
125 #else
126 readpw(Display *dpy, const char *pws)
127 #endif
128 {
129         char buf[32], passwd[256];
130         int num, screen;
131         unsigned int len, color;
132         KeySym ksym;
133         XEvent ev;
134         static int oldc = INIT;
135
136         len = 0;
137         running = True;
138
139         /* As "slock" stands for "Simple X display locker", the DPMS settings
140          * had been removed and you can set it with "xset" or some other
141          * utility. This way the user can easily set a customized DPMS
142          * timeout. */
143         while (running && !XNextEvent(dpy, &ev)) {
144                 if (ev.type == KeyPress) {
145                         buf[0] = 0;
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 #ifdef HAVE_BSD_AUTH
163                                 running = !auth_userokay(getlogin(), NULL, "auth-xlock", passwd);
164 #else
165                                 running = !!strcmp(crypt(passwd, pws), pws);
166 #endif
167                                 if (running) {
168                                         XBell(dpy, 100);
169                                         failure = True;
170                                 }
171                                 len = 0;
172                                 break;
173                         case XK_Escape:
174                                 len = 0;
175                                 break;
176                         case XK_BackSpace:
177                                 if (len)
178                                         --len;
179                                 break;
180                         default:
181                                 if (num && !iscntrl((int)buf[0]) && (len + num < sizeof(passwd))) {
182                                         memcpy(passwd + len, buf, num);
183                                         len += num;
184                                 }
185                                 break;
186                         }
187                         color = len ? INPUT : (failure || failonclear ? FAILED : INIT);
188                         if (running && oldc != color) {
189                                 for (screen = 0; screen < nscreens; screen++) {
190                                         XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[color]);
191                                         XClearWindow(dpy, locks[screen]->win);
192                                 }
193                                 oldc = color;
194                         }
195                 } else if (rr && ev.type == rrevbase + RRScreenChangeNotify) {
196                         XRRScreenChangeNotifyEvent *rre = (XRRScreenChangeNotifyEvent*)&ev;
197                         for (screen = 0; screen < nscreens; screen++) {
198                                 if (locks[screen]->win == rre->window) {
199                                         XResizeWindow(dpy, locks[screen]->win, rre->width, rre->height);
200                                         XClearWindow(dpy, locks[screen]->win);
201                                 }
202                         }
203                 } else for (screen = 0; screen < nscreens; screen++)
204                         XRaiseWindow(dpy, locks[screen]->win);
205         }
206 }
207
208 static void
209 unlockscreen(Display *dpy, Lock *lock)
210 {
211         if(dpy == NULL || lock == NULL)
212                 return;
213
214         XUngrabPointer(dpy, CurrentTime);
215         XFreeColors(dpy, DefaultColormap(dpy, lock->screen), lock->colors, NUMCOLS, 0);
216         XFreePixmap(dpy, lock->pmap);
217         XDestroyWindow(dpy, lock->win);
218
219         free(lock);
220 }
221
222 static Lock *
223 lockscreen(Display *dpy, int screen)
224 {
225         char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
226         unsigned int len;
227         int i;
228         Lock *lock;
229         XColor color, dummy;
230         XSetWindowAttributes wa;
231         Cursor invisible;
232
233         if (!running || dpy == NULL || screen < 0 || !(lock = malloc(sizeof(Lock))))
234                 return NULL;
235
236         lock->screen = screen;
237         lock->root = RootWindow(dpy, lock->screen);
238
239         for (i = 0; i < NUMCOLS; i++) {
240                 XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), colorname[i], &color, &dummy);
241                 lock->colors[i] = color.pixel;
242         }
243
244         /* init */
245         wa.override_redirect = 1;
246         wa.background_pixel = lock->colors[INIT];
247         lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
248                                   0, DefaultDepth(dpy, lock->screen), CopyFromParent,
249                                   DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
250         lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
251         invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
252         XDefineCursor(dpy, lock->win, invisible);
253         XMapRaised(dpy, lock->win);
254         if (rr)
255                 XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
256
257         /* Try to grab mouse pointer *and* keyboard, else fail the lock */
258         for (len = 1000; len; len--) {
259                 if (XGrabPointer(dpy, lock->root, False, ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
260                     GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
261                         break;
262                 usleep(1000);
263         }
264         if (!len) {
265                 fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n", screen);
266         } else {
267                 for (len = 1000; len; len--) {
268                         if (XGrabKeyboard(dpy, lock->root, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess) {
269                                 /* everything fine, we grabbed both inputs */
270                                 XSelectInput(dpy, lock->root, SubstructureNotifyMask);
271                                 return lock;
272                         }
273                         usleep(1000);
274                 }
275                 fprintf(stderr, "slock: unable to grab keyboard for screen %d\n", screen);
276         }
277         /* grabbing one of the inputs failed */
278         running = 0;
279         unlockscreen(dpy, lock);
280         return NULL;
281 }
282
283 static void
284 usage(void)
285 {
286         fprintf(stderr, "usage: slock [-v|POST_LOCK_CMD]\n");
287         exit(1);
288 }
289
290 int
291 main(int argc, char **argv) {
292 #ifndef HAVE_BSD_AUTH
293         const char *pws;
294 #endif
295         Display *dpy;
296         int screen;
297
298         if ((argc == 2) && !strcmp("-v", argv[1]))
299                 die("slock-%s, © 2006-2015 slock engineers\n", VERSION);
300
301         if ((argc == 2) && !strcmp("-h", argv[1]))
302                 usage();
303
304 #ifdef __linux__
305         dontkillme();
306 #endif
307
308         if (!getpwuid(getuid()))
309                 die("slock: no passwd entry for you\n");
310
311 #ifndef HAVE_BSD_AUTH
312         pws = getpw();
313 #endif
314
315         if (!(dpy = XOpenDisplay(0)))
316                 die("slock: cannot open display\n");
317         rr = XRRQueryExtension(dpy, &rrevbase, &rrerrbase);
318         /* Get the number of screens in display "dpy" and blank them all. */
319         nscreens = ScreenCount(dpy);
320         if (!(locks = malloc(sizeof(Lock*) * nscreens)))
321                 die("slock: malloc: %s\n", strerror(errno));
322         int nlocks = 0;
323         for (screen = 0; screen < nscreens; screen++) {
324                 if ((locks[screen] = lockscreen(dpy, screen)) != NULL)
325                         nlocks++;
326         }
327         XSync(dpy, False);
328
329         /* Did we actually manage to lock something? */
330         if (nlocks == 0) { /* nothing to protect */
331                 free(locks);
332                 XCloseDisplay(dpy);
333                 return 1;
334         }
335
336         if (argc >= 2 && fork() == 0) {
337                 if (dpy)
338                         close(ConnectionNumber(dpy));
339                 execvp(argv[1], argv+1);
340                 die("slock: execvp %s failed: %s\n", argv[1], strerror(errno));
341         }
342
343         /* Everything is now blank. Now wait for the correct password. */
344 #ifdef HAVE_BSD_AUTH
345         readpw(dpy);
346 #else
347         readpw(dpy, pws);
348 #endif
349
350         /* Password ok, unlock everything and quit. */
351         for (screen = 0; screen < nscreens; screen++)
352                 unlockscreen(dpy, locks[screen]);
353
354         free(locks);
355         XCloseDisplay(dpy);
356
357         return 0;
358 }