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