Xinqi Bao's Git

Unify how we check passwords between different OSes
[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 #include "arg.h"
22 #include "util.h"
23
24 char *argv0;
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 rr;
45 static int rrevbase;
46 static int rrerrbase;
47
48 static void
49 die(const char *errstr, ...)
50 {
51 va_list ap;
52
53 va_start(ap, errstr);
54 vfprintf(stderr, errstr, ap);
55 va_end(ap);
56 exit(1);
57 }
58
59 #ifdef __linux__
60 #include <fcntl.h>
61 #include <linux/oom.h>
62
63 static void
64 dontkillme(void)
65 {
66 FILE *f;
67 const char oomfile[] = "/proc/self/oom_score_adj";
68
69 if (!(f = fopen(oomfile, "w"))) {
70 if (errno == ENOENT)
71 return;
72 die("slock: fopen %s: %s\n", oomfile, strerror(errno));
73 }
74 fprintf(f, "%d", OOM_SCORE_ADJ_MIN);
75 if (fclose(f)) {
76 if (errno == EACCES)
77 die("slock: unable to disable OOM killer. "
78 "suid or sgid set?\n");
79 else
80 die("slock: fclose %s: %s\n", oomfile,
81 strerror(errno));
82 }
83 }
84 #endif
85
86 /* only run as root */
87 static const char *
88 getpw(void)
89 {
90 const char *rval;
91 struct passwd *pw;
92
93 /* Check if the current user has a password entry */
94 errno = 0;
95 if (!(pw = getpwuid(getuid()))) {
96 if (errno)
97 die("slock: getpwuid: %s\n", strerror(errno));
98 else
99 die("slock: cannot retrieve password entry\n");
100 }
101 rval = pw->pw_passwd;
102
103 #if HAVE_SHADOW_H
104 if (rval[0] == 'x' && rval[1] == '\0') {
105 struct spwd *sp;
106 if (!(sp = getspnam(getenv("USER"))))
107 die("slock: getspnam: cannot retrieve shadow entry (make sure to suid or sgid slock)\n");
108 rval = sp->sp_pwdp;
109 }
110 #else
111 if (rval[0] == '*' && rval[1] == '\0') {
112 #ifdef __OpenBSD__
113 if (!(pw = getpwnam_shadow(getenv("USER"))))
114 die("slock: getpwnam_shadow: cannot retrieve shadow entry (make sure to suid or sgid slock)\n");
115 rval = pw->pw_passwd;
116 #else
117 die("slock: getpwuid: cannot retrieve shadow entry (make sure to suid or sgid slock)\n");
118 #endif /* __OpenBSD__ */
119 }
120 #endif /* HAVE_SHADOW_H */
121
122 /* drop privileges */
123 if (geteuid() == 0 &&
124 ((getegid() != pw->pw_gid && setgid(pw->pw_gid) < 0) || setuid(pw->pw_uid) < 0))
125 die("slock: cannot drop privileges\n");
126 return rval;
127 }
128
129 static void
130 readpw(Display *dpy, const char *pws)
131 {
132 char buf[32], passwd[256], *encrypted;
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 /* As "slock" stands for "Simple X display locker", the DPMS settings
144 * had been removed and you can set it with "xset" or some other
145 * utility. This way the user can easily set a customized DPMS
146 * timeout. */
147 while (running && !XNextEvent(dpy, &ev)) {
148 if (ev.type == KeyPress) {
149 explicit_bzero(&buf, sizeof(buf));
150 num = XLookupString(&ev.xkey, buf, sizeof(buf), &ksym, 0);
151 if (IsKeypadKey(ksym)) {
152 if (ksym == XK_KP_Enter)
153 ksym = XK_Return;
154 else if (ksym >= XK_KP_0 && ksym <= XK_KP_9)
155 ksym = (ksym - XK_KP_0) + XK_0;
156 }
157 if (IsFunctionKey(ksym) ||
158 IsKeypadKey(ksym) ||
159 IsMiscFunctionKey(ksym) ||
160 IsPFKey(ksym) ||
161 IsPrivateKeypadKey(ksym))
162 continue;
163 switch (ksym) {
164 case XK_Return:
165 passwd[len] = 0;
166 errno = 0;
167 if (!(encrypted = crypt(passwd, pws)))
168 fprintf(stderr, "slock: crypt: %s\n", strerror(errno));
169 else
170 running = !!strcmp(encrypted, pws);
171 if (running) {
172 XBell(dpy, 100);
173 failure = True;
174 }
175 explicit_bzero(&passwd, sizeof(passwd));
176 len = 0;
177 break;
178 case XK_Escape:
179 explicit_bzero(&passwd, sizeof(passwd));
180 len = 0;
181 break;
182 case XK_BackSpace:
183 if (len)
184 passwd[len--] = 0;
185 break;
186 default:
187 if (num && !iscntrl((int)buf[0]) && (len + num < sizeof(passwd))) {
188 memcpy(passwd + len, buf, num);
189 len += num;
190 }
191 break;
192 }
193 color = len ? INPUT : (failure || failonclear ? FAILED : INIT);
194 if (running && oldc != color) {
195 for (screen = 0; screen < nscreens; screen++) {
196 XSetWindowBackground(dpy, locks[screen]->win, locks[screen]->colors[color]);
197 XClearWindow(dpy, locks[screen]->win);
198 }
199 oldc = color;
200 }
201 } else if (rr && ev.type == rrevbase + RRScreenChangeNotify) {
202 XRRScreenChangeNotifyEvent *rre = (XRRScreenChangeNotifyEvent*)&ev;
203 for (screen = 0; screen < nscreens; screen++) {
204 if (locks[screen]->win == rre->window) {
205 XResizeWindow(dpy, locks[screen]->win, 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 void
215 unlockscreen(Display *dpy, Lock *lock)
216 {
217 if(dpy == NULL || lock == NULL)
218 return;
219
220 XUngrabPointer(dpy, CurrentTime);
221 XUngrabKeyboard(dpy, CurrentTime);
222 XFreeColors(dpy, DefaultColormap(dpy, lock->screen), lock->colors, NUMCOLS, 0);
223 XFreePixmap(dpy, lock->pmap);
224 XDestroyWindow(dpy, lock->win);
225
226 free(lock);
227 }
228
229 static void
230 cleanup(Display *dpy)
231 {
232 int s;
233
234 for (s = 0; s < nscreens; ++s)
235 unlockscreen(dpy, locks[s]);
236
237 free(locks);
238 XCloseDisplay(dpy);
239 }
240
241 static Lock *
242 lockscreen(Display *dpy, int screen)
243 {
244 char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
245 int i, ptgrab, kbgrab;
246 Lock *lock;
247 XColor color, dummy;
248 XSetWindowAttributes wa;
249 Cursor invisible;
250
251 if (dpy == NULL || screen < 0 || !(lock = malloc(sizeof(Lock))))
252 return NULL;
253
254 lock->screen = screen;
255 lock->root = RootWindow(dpy, lock->screen);
256
257 for (i = 0; i < NUMCOLS; i++) {
258 XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen), colorname[i], &color, &dummy);
259 lock->colors[i] = color.pixel;
260 }
261
262 /* init */
263 wa.override_redirect = 1;
264 wa.background_pixel = lock->colors[INIT];
265 lock->win = XCreateWindow(dpy, lock->root, 0, 0, DisplayWidth(dpy, lock->screen), DisplayHeight(dpy, lock->screen),
266 0, DefaultDepth(dpy, lock->screen), CopyFromParent,
267 DefaultVisual(dpy, lock->screen), CWOverrideRedirect | CWBackPixel, &wa);
268 lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
269 invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap, &color, &color, 0, 0);
270 XDefineCursor(dpy, lock->win, invisible);
271
272 /* Try to grab mouse pointer *and* keyboard for 600ms, else fail the lock */
273 for (i = 0, ptgrab = kbgrab = -1; i < 6; i++) {
274 if (ptgrab != GrabSuccess) {
275 ptgrab = XGrabPointer(dpy, lock->root, False,
276 ButtonPressMask | ButtonReleaseMask |
277 PointerMotionMask, GrabModeAsync,
278 GrabModeAsync, None, invisible, CurrentTime);
279 }
280 if (kbgrab != GrabSuccess) {
281 kbgrab = XGrabKeyboard(dpy, lock->root, True,
282 GrabModeAsync, GrabModeAsync, CurrentTime);
283 }
284
285 /* input is grabbed: we can lock the screen */
286 if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
287 XMapRaised(dpy, lock->win);
288 if (rr)
289 XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
290
291 XSelectInput(dpy, lock->root, SubstructureNotifyMask);
292 return lock;
293 }
294
295 /* retry on AlreadyGrabbed but fail on other errors */
296 if ((ptgrab != AlreadyGrabbed && ptgrab != GrabSuccess) ||
297 (kbgrab != AlreadyGrabbed && kbgrab != GrabSuccess))
298 break;
299
300 usleep(100000);
301 }
302
303 /* we couldn't grab all input: fail out */
304 if (ptgrab != GrabSuccess)
305 fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n", screen);
306 if (kbgrab != GrabSuccess)
307 fprintf(stderr, "slock: unable to grab keyboard for screen %d\n", screen);
308 return NULL;
309 }
310
311 static void
312 usage(void)
313 {
314 die("usage: slock [-v] [cmd [arg ...]]\n");
315 }
316
317 int
318 main(int argc, char **argv) {
319 const char *pws;
320 Display *dpy;
321 int s, nlocks;
322
323 ARGBEGIN {
324 case 'v':
325 fprintf(stderr, "slock-"VERSION"\n");
326 return 0;
327 default:
328 usage();
329 } ARGEND
330
331 #ifdef __linux__
332 dontkillme();
333 #endif
334
335 pws = getpw();
336 if (strlen(pws) < 2)
337 die("slock: failed to get user password hash.\n");
338
339 if (!(dpy = XOpenDisplay(NULL)))
340 die("slock: cannot open display\n");
341
342 /* check for Xrandr support */
343 rr = XRRQueryExtension(dpy, &rrevbase, &rrerrbase);
344
345 /* get number of screens in display "dpy" and blank them */
346 nscreens = ScreenCount(dpy);
347 if (!(locks = calloc(nscreens, sizeof(Lock *)))) {
348 XCloseDisplay(dpy);
349 die("slock: out of memory\n");
350 }
351 for (nlocks = 0, s = 0; s < nscreens; s++) {
352 if ((locks[s] = lockscreen(dpy, s)) != NULL)
353 nlocks++;
354 else
355 break;
356 }
357 XSync(dpy, 0);
358
359 /* did we manage to lock everything? */
360 if (nlocks != nscreens) {
361 cleanup(dpy);
362 return 1;
363 }
364
365 /* run post-lock command */
366 if (argc > 0) {
367 switch (fork()) {
368 case -1:
369 cleanup(dpy);
370 die("slock: fork failed: %s\n", strerror(errno));
371 case 0:
372 if (close(ConnectionNumber(dpy)) < 0)
373 die("slock: close: %s\n", strerror(errno));
374 execvp(argv[0], argv);
375 fprintf(stderr, "slock: execvp %s: %s\n", argv[0],
376 strerror(errno));
377 _exit(1);
378 }
379 }
380
381 /* everything is now blank. Wait for the correct password */
382 readpw(dpy, pws);
383
384 /* password ok, unlock everything and quit */
385 cleanup(dpy);
386
387 return 0;
388 }