slock

Simple screen locker utility for X
git clone git://git.janpasierb.com/slock.git
Log | Files | Refs | README | LICENSE

slock.c (9710B)


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