Another copy of my dotfiles. Because I don't completely trust GitHub.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

516 lines
12 KiB

  1. /* See LICENSE file for license details. */
  2. #define _XOPEN_SOURCE 500
  3. #if HAVE_SHADOW_H
  4. #include <shadow.h>
  5. #endif
  6. #include <ctype.h>
  7. #include <errno.h>
  8. #include <grp.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/extensions/Xinerama.h>
  18. #include <X11/keysym.h>
  19. #include <X11/Xlib.h>
  20. #include <X11/Xutil.h>
  21. #include <X11/XKBlib.h>
  22. #include "arg.h"
  23. #include "util.h"
  24. char *argv0;
  25. /* global count to prevent repeated error messages */
  26. int count_error = 0;
  27. enum {
  28. INIT,
  29. INPUT,
  30. FAILED,
  31. CAPS,
  32. NUMCOLS
  33. };
  34. struct lock {
  35. int screen;
  36. Window root, win;
  37. Pixmap pmap;
  38. unsigned long colors[NUMCOLS];
  39. };
  40. struct xrandr {
  41. int active;
  42. int evbase;
  43. int errbase;
  44. };
  45. #include "config.h"
  46. static void
  47. die(const char *errstr, ...)
  48. {
  49. va_list ap;
  50. va_start(ap, errstr);
  51. vfprintf(stderr, errstr, ap);
  52. va_end(ap);
  53. exit(1);
  54. }
  55. #ifdef __linux__
  56. #include <fcntl.h>
  57. #include <linux/oom.h>
  58. static void
  59. dontkillme(void)
  60. {
  61. FILE *f;
  62. const char oomfile[] = "/proc/self/oom_score_adj";
  63. if (!(f = fopen(oomfile, "w"))) {
  64. if (errno == ENOENT)
  65. return;
  66. die("slock: fopen %s: %s\n", oomfile, strerror(errno));
  67. }
  68. fprintf(f, "%d", OOM_SCORE_ADJ_MIN);
  69. if (fclose(f)) {
  70. if (errno == EACCES)
  71. die("slock: unable to disable OOM killer. "
  72. "Make sure to suid or sgid slock.\n");
  73. else
  74. die("slock: fclose %s: %s\n", oomfile, strerror(errno));
  75. }
  76. }
  77. #endif
  78. static void
  79. writemessage(Display *dpy, Window win, int screen)
  80. {
  81. int len, line_len, width, height, s_width, s_height, i, j, k, tab_replace, tab_size;
  82. XGCValues gr_values;
  83. XFontStruct *fontinfo;
  84. XColor color, dummy;
  85. XineramaScreenInfo *xsi;
  86. GC gc;
  87. fontinfo = XLoadQueryFont(dpy, font_name);
  88. if (fontinfo == NULL) {
  89. if (count_error == 0) {
  90. fprintf(stderr, "slock: Unable to load font \"%s\"\n", font_name);
  91. fprintf(stderr, "slock: Try listing fonts with 'slock -f'\n");
  92. count_error++;
  93. }
  94. return;
  95. }
  96. tab_size = 8 * XTextWidth(fontinfo, " ", 1);
  97. XAllocNamedColor(dpy, DefaultColormap(dpy, screen),
  98. text_color, &color, &dummy);
  99. gr_values.font = fontinfo->fid;
  100. gr_values.foreground = color.pixel;
  101. gc=XCreateGC(dpy,win,GCFont+GCForeground, &gr_values);
  102. /* To prevent "Uninitialized" warnings. */
  103. xsi = NULL;
  104. /*
  105. * Start formatting and drawing text
  106. */
  107. len = strlen(message);
  108. /* Max max line length (cut at '\n') */
  109. line_len = 0;
  110. k = 0;
  111. for (i = j = 0; i < len; i++) {
  112. if (message[i] == '\n') {
  113. if (i - j > line_len)
  114. line_len = i - j;
  115. k++;
  116. i++;
  117. j = i;
  118. }
  119. }
  120. /* If there is only one line */
  121. if (line_len == 0)
  122. line_len = len;
  123. if (XineramaIsActive(dpy)) {
  124. xsi = XineramaQueryScreens(dpy, &i);
  125. s_width = xsi[0].width;
  126. s_height = xsi[0].height;
  127. } else {
  128. s_width = DisplayWidth(dpy, screen);
  129. s_height = DisplayHeight(dpy, screen);
  130. }
  131. height = s_height*3/7 - (k*20)/3;
  132. width = (s_width - XTextWidth(fontinfo, message, line_len))/2;
  133. /* Look for '\n' and print the text between them. */
  134. for (i = j = k = 0; i <= len; i++) {
  135. /* i == len is the special case for the last line */
  136. if (i == len || message[i] == '\n') {
  137. tab_replace = 0;
  138. while (message[j] == '\t' && j < i) {
  139. tab_replace++;
  140. j++;
  141. }
  142. XDrawString(dpy, win, gc, width + tab_size*tab_replace, height + 20*k, message + j, i - j);
  143. while (i < len && message[i] == '\n') {
  144. i++;
  145. j = i;
  146. k++;
  147. }
  148. }
  149. }
  150. /* xsi should not be NULL anyway if Xinerama is active, but to be safe */
  151. if (XineramaIsActive(dpy) && xsi != NULL)
  152. XFree(xsi);
  153. }
  154. static const char *
  155. gethash(void)
  156. {
  157. const char *hash;
  158. struct passwd *pw;
  159. /* Check if the current user has a password entry */
  160. errno = 0;
  161. if (!(pw = getpwuid(getuid()))) {
  162. if (errno)
  163. die("slock: getpwuid: %s\n", strerror(errno));
  164. else
  165. die("slock: cannot retrieve password entry\n");
  166. }
  167. hash = pw->pw_passwd;
  168. #if HAVE_SHADOW_H
  169. if (!strcmp(hash, "x")) {
  170. struct spwd *sp;
  171. if (!(sp = getspnam(pw->pw_name)))
  172. die("slock: getspnam: cannot retrieve shadow entry. "
  173. "Make sure to suid or sgid slock.\n");
  174. hash = sp->sp_pwdp;
  175. }
  176. #else
  177. if (!strcmp(hash, "*")) {
  178. #ifdef __OpenBSD__
  179. if (!(pw = getpwuid_shadow(getuid())))
  180. die("slock: getpwnam_shadow: cannot retrieve shadow entry. "
  181. "Make sure to suid or sgid slock.\n");
  182. hash = pw->pw_passwd;
  183. #else
  184. die("slock: getpwuid: cannot retrieve shadow entry. "
  185. "Make sure to suid or sgid slock.\n");
  186. #endif /* __OpenBSD__ */
  187. }
  188. #endif /* HAVE_SHADOW_H */
  189. return hash;
  190. }
  191. static void
  192. readpw(Display *dpy, struct xrandr *rr, struct lock **locks, int nscreens,
  193. const char *hash)
  194. {
  195. XRRScreenChangeNotifyEvent *rre;
  196. char buf[32], passwd[256], *inputhash;
  197. int caps, num, screen, running, failure, oldc;
  198. unsigned int len, color, indicators;
  199. KeySym ksym;
  200. XEvent ev;
  201. len = 0;
  202. caps = 0;
  203. running = 1;
  204. failure = 0;
  205. oldc = INIT;
  206. if (!XkbGetIndicatorState(dpy, XkbUseCoreKbd, &indicators))
  207. caps = indicators & 1;
  208. while (running && !XNextEvent(dpy, &ev)) {
  209. if (ev.type == KeyPress) {
  210. explicit_bzero(&buf, sizeof(buf));
  211. num = XLookupString(&ev.xkey, buf, sizeof(buf), &ksym, 0);
  212. if (IsKeypadKey(ksym)) {
  213. if (ksym == XK_KP_Enter)
  214. ksym = XK_Return;
  215. else if (ksym >= XK_KP_0 && ksym <= XK_KP_9)
  216. ksym = (ksym - XK_KP_0) + XK_0;
  217. }
  218. if (IsFunctionKey(ksym) ||
  219. IsKeypadKey(ksym) ||
  220. IsMiscFunctionKey(ksym) ||
  221. IsPFKey(ksym) ||
  222. IsPrivateKeypadKey(ksym))
  223. continue;
  224. switch (ksym) {
  225. case XK_Return:
  226. passwd[len] = '\0';
  227. errno = 0;
  228. if (!(inputhash = crypt(passwd, hash)))
  229. fprintf(stderr, "slock: crypt: %s\n", strerror(errno));
  230. else
  231. running = !!strcmp(inputhash, hash);
  232. if (running) {
  233. XBell(dpy, 100);
  234. failure = 1;
  235. }
  236. explicit_bzero(&passwd, sizeof(passwd));
  237. len = 0;
  238. break;
  239. case XK_Escape:
  240. explicit_bzero(&passwd, sizeof(passwd));
  241. len = 0;
  242. break;
  243. case XK_BackSpace:
  244. if (len)
  245. passwd[--len] = '\0';
  246. break;
  247. case XK_Caps_Lock:
  248. caps = !caps;
  249. break;
  250. default:
  251. if (num && !iscntrl((int)buf[0]) &&
  252. (len + num < sizeof(passwd))) {
  253. memcpy(passwd + len, buf, num);
  254. len += num;
  255. }
  256. break;
  257. }
  258. color = len ? (caps ? CAPS : INPUT) : (failure || failonclear ? FAILED : INIT);
  259. if (running && oldc != color) {
  260. for (screen = 0; screen < nscreens; screen++) {
  261. XSetWindowBackground(dpy,
  262. locks[screen]->win,
  263. locks[screen]->colors[color]);
  264. XClearWindow(dpy, locks[screen]->win);
  265. writemessage(dpy, locks[screen]->win, screen);
  266. }
  267. oldc = color;
  268. }
  269. } else if (rr->active && ev.type == rr->evbase + RRScreenChangeNotify) {
  270. rre = (XRRScreenChangeNotifyEvent*)&ev;
  271. for (screen = 0; screen < nscreens; screen++) {
  272. if (locks[screen]->win == rre->window) {
  273. if (rre->rotation == RR_Rotate_90 ||
  274. rre->rotation == RR_Rotate_270)
  275. XResizeWindow(dpy, locks[screen]->win,
  276. rre->height, rre->width);
  277. else
  278. XResizeWindow(dpy, locks[screen]->win,
  279. rre->width, rre->height);
  280. XClearWindow(dpy, locks[screen]->win);
  281. break;
  282. }
  283. }
  284. } else {
  285. for (screen = 0; screen < nscreens; screen++)
  286. XRaiseWindow(dpy, locks[screen]->win);
  287. }
  288. }
  289. }
  290. static struct lock *
  291. lockscreen(Display *dpy, struct xrandr *rr, int screen)
  292. {
  293. char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
  294. int i, ptgrab, kbgrab;
  295. struct lock *lock;
  296. XColor color, dummy;
  297. XSetWindowAttributes wa;
  298. Cursor invisible;
  299. if (dpy == NULL || screen < 0 || !(lock = malloc(sizeof(struct lock))))
  300. return NULL;
  301. lock->screen = screen;
  302. lock->root = RootWindow(dpy, lock->screen);
  303. for (i = 0; i < NUMCOLS; i++) {
  304. XAllocNamedColor(dpy, DefaultColormap(dpy, lock->screen),
  305. colorname[i], &color, &dummy);
  306. lock->colors[i] = color.pixel;
  307. }
  308. /* init */
  309. wa.override_redirect = 1;
  310. wa.background_pixel = lock->colors[INIT];
  311. lock->win = XCreateWindow(dpy, lock->root, 0, 0,
  312. DisplayWidth(dpy, lock->screen),
  313. DisplayHeight(dpy, lock->screen),
  314. 0, DefaultDepth(dpy, lock->screen),
  315. CopyFromParent,
  316. DefaultVisual(dpy, lock->screen),
  317. CWOverrideRedirect | CWBackPixel, &wa);
  318. lock->pmap = XCreateBitmapFromData(dpy, lock->win, curs, 8, 8);
  319. invisible = XCreatePixmapCursor(dpy, lock->pmap, lock->pmap,
  320. &color, &color, 0, 0);
  321. XDefineCursor(dpy, lock->win, invisible);
  322. /* Try to grab mouse pointer *and* keyboard for 600ms, else fail the lock */
  323. for (i = 0, ptgrab = kbgrab = -1; i < 6; i++) {
  324. if (ptgrab != GrabSuccess) {
  325. ptgrab = XGrabPointer(dpy, lock->root, False,
  326. ButtonPressMask | ButtonReleaseMask |
  327. PointerMotionMask, GrabModeAsync,
  328. GrabModeAsync, None, invisible, CurrentTime);
  329. }
  330. if (kbgrab != GrabSuccess) {
  331. kbgrab = XGrabKeyboard(dpy, lock->root, True,
  332. GrabModeAsync, GrabModeAsync, CurrentTime);
  333. }
  334. /* input is grabbed: we can lock the screen */
  335. if (ptgrab == GrabSuccess && kbgrab == GrabSuccess) {
  336. XMapRaised(dpy, lock->win);
  337. if (rr->active)
  338. XRRSelectInput(dpy, lock->win, RRScreenChangeNotifyMask);
  339. XSelectInput(dpy, lock->root, SubstructureNotifyMask);
  340. return lock;
  341. }
  342. /* retry on AlreadyGrabbed but fail on other errors */
  343. if ((ptgrab != AlreadyGrabbed && ptgrab != GrabSuccess) ||
  344. (kbgrab != AlreadyGrabbed && kbgrab != GrabSuccess))
  345. break;
  346. usleep(100000);
  347. }
  348. /* we couldn't grab all input: fail out */
  349. if (ptgrab != GrabSuccess)
  350. fprintf(stderr, "slock: unable to grab mouse pointer for screen %d\n",
  351. screen);
  352. if (kbgrab != GrabSuccess)
  353. fprintf(stderr, "slock: unable to grab keyboard for screen %d\n",
  354. screen);
  355. return NULL;
  356. }
  357. static void
  358. usage(void)
  359. {
  360. die("usage: slock [-v] [-f] [-m message] [cmd [arg ...]]\n");
  361. }
  362. int
  363. main(int argc, char **argv) {
  364. struct xrandr rr;
  365. struct lock **locks;
  366. struct passwd *pwd;
  367. struct group *grp;
  368. uid_t duid;
  369. gid_t dgid;
  370. const char *hash;
  371. Display *dpy;
  372. int i, s, nlocks, nscreens;
  373. int count_fonts;
  374. char **font_names;
  375. ARGBEGIN {
  376. case 'v':
  377. fprintf(stderr, "slock-"VERSION"\n");
  378. return 0;
  379. case 'm':
  380. message = EARGF(usage());
  381. break;
  382. case 'f':
  383. if (!(dpy = XOpenDisplay(NULL)))
  384. die("slock: cannot open display\n");
  385. font_names = XListFonts(dpy, "*", 10000 /* list 10000 fonts*/, &count_fonts);
  386. for (i=0; i<count_fonts; i++) {
  387. fprintf(stderr, "%s\n", *(font_names+i));
  388. }
  389. return 0;
  390. default:
  391. usage();
  392. } ARGEND
  393. /* validate drop-user and -group */
  394. errno = 0;
  395. if (!(pwd = getpwnam(user)))
  396. die("slock: getpwnam %s: %s\n", user,
  397. errno ? strerror(errno) : "user entry not found");
  398. duid = pwd->pw_uid;
  399. errno = 0;
  400. if (!(grp = getgrnam(group)))
  401. die("slock: getgrnam %s: %s\n", group,
  402. errno ? strerror(errno) : "group entry not found");
  403. dgid = grp->gr_gid;
  404. #ifdef __linux__
  405. dontkillme();
  406. #endif
  407. hash = gethash();
  408. errno = 0;
  409. if (!crypt("", hash))
  410. die("slock: crypt: %s\n", strerror(errno));
  411. if (!(dpy = XOpenDisplay(NULL)))
  412. die("slock: cannot open display\n");
  413. /* drop privileges */
  414. if (setgroups(0, NULL) < 0)
  415. die("slock: setgroups: %s\n", strerror(errno));
  416. if (setgid(dgid) < 0)
  417. die("slock: setgid: %s\n", strerror(errno));
  418. if (setuid(duid) < 0)
  419. die("slock: setuid: %s\n", strerror(errno));
  420. /* check for Xrandr support */
  421. rr.active = XRRQueryExtension(dpy, &rr.evbase, &rr.errbase);
  422. /* get number of screens in display "dpy" and blank them */
  423. nscreens = ScreenCount(dpy);
  424. if (!(locks = calloc(nscreens, sizeof(struct lock *))))
  425. die("slock: out of memory\n");
  426. for (nlocks = 0, s = 0; s < nscreens; s++) {
  427. if ((locks[s] = lockscreen(dpy, &rr, s)) != NULL) {
  428. writemessage(dpy, locks[s]->win, s);
  429. nlocks++;
  430. } else {
  431. break;
  432. }
  433. }
  434. XSync(dpy, 0);
  435. /* did we manage to lock everything? */
  436. if (nlocks != nscreens)
  437. return 1;
  438. /* run post-lock command */
  439. if (argc > 0) {
  440. switch (fork()) {
  441. case -1:
  442. die("slock: fork failed: %s\n", strerror(errno));
  443. case 0:
  444. if (close(ConnectionNumber(dpy)) < 0)
  445. die("slock: close: %s\n", strerror(errno));
  446. execvp(argv[0], argv);
  447. fprintf(stderr, "slock: execvp %s: %s\n", argv[0], strerror(errno));
  448. _exit(1);
  449. }
  450. }
  451. /* everything is now blank. Wait for the correct password */
  452. readpw(dpy, &rr, locks, nscreens, hash);
  453. return 0;
  454. }