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.

333 lines
11 KiB

  1. /*
  2. * vim:ts=8:expandtab
  3. *
  4. * i3lock - an improved version of slock
  5. *
  6. * i3lock © 2009 Michael Stapelberg and contributors
  7. * slock © 2006-2008 Anselm R Garbe
  8. *
  9. * See file LICENSE for license information.
  10. *
  11. * Note that on any error (calloc is out of memory for example)
  12. * we do not do anything so that the user can fix the error by
  13. * himself (kill X to get more free memory or stop some other
  14. * program using SSH/console).
  15. *
  16. */
  17. #define _XOPEN_SOURCE 500
  18. #include <ctype.h>
  19. #include <stdarg.h>
  20. #include <stdlib.h>
  21. #include <stdio.h>
  22. #include <stdint.h>
  23. #include <string.h>
  24. #include <unistd.h>
  25. #include <sys/types.h>
  26. #include <X11/keysym.h>
  27. #include <X11/Xlib.h>
  28. #include <X11/Xutil.h>
  29. #include <X11/xpm.h>
  30. #include <X11/extensions/dpms.h>
  31. #include <stdbool.h>
  32. #include <getopt.h>
  33. #include <security/pam_appl.h>
  34. static char passwd[256];
  35. static void die(const char *errstr, ...) {
  36. va_list ap;
  37. va_start(ap, errstr);
  38. vfprintf(stderr, errstr, ap);
  39. va_end(ap);
  40. exit(EXIT_FAILURE);
  41. }
  42. /*
  43. * Returns the colorpixel to use for the given hex color (think of HTML).
  44. *
  45. * The hex_color may not start with #, for example FF00FF works.
  46. *
  47. * NOTE that get_colorpixel() does _NOT_ check the given color code for validity.
  48. * This has to be done by the caller.
  49. *
  50. */
  51. uint32_t get_colorpixel(char *hex) {
  52. char strgroups[3][3] = {{hex[0], hex[1], '\0'},
  53. {hex[2], hex[3], '\0'},
  54. {hex[4], hex[5], '\0'}};
  55. uint32_t rgb16[3] = {(strtol(strgroups[0], NULL, 16)),
  56. (strtol(strgroups[1], NULL, 16)),
  57. (strtol(strgroups[2], NULL, 16))};
  58. return (rgb16[0] << 16) + (rgb16[1] << 8) + rgb16[2];
  59. }
  60. /*
  61. * Check if given file can be opened => exists
  62. *
  63. */
  64. bool file_exists(const char *filename)
  65. {
  66. FILE * file = fopen(filename, "r");
  67. if(file)
  68. {
  69. fclose(file);
  70. return true;
  71. }
  72. return false;
  73. }
  74. /*
  75. * Puts the given XPM error code to stderr
  76. *
  77. */
  78. void print_xpm_error(int err)
  79. {
  80. switch (err) {
  81. case XpmColorError:
  82. fprintf(stderr, "XPM: Could not parse or alloc requested color\n");
  83. break;
  84. case XpmOpenFailed:
  85. fprintf(stderr, "XPM: Cannot open file\n");
  86. break;
  87. case XpmFileInvalid:
  88. fprintf(stderr, "XPM: invalid XPM file\n");
  89. break;
  90. case XpmNoMemory:
  91. fprintf(stderr, "XPM: Not enough memory\n");
  92. break;
  93. case XpmColorFailed:
  94. fprintf(stderr, "XPM: Color not found\n");
  95. break;
  96. }
  97. }
  98. /*
  99. * Callback function for PAM. We only react on password request callbacks.
  100. *
  101. */
  102. static int conv_callback(int num_msg, const struct pam_message **msg,
  103. struct pam_response **resp, void *appdata_ptr) {
  104. if (num_msg == 0)
  105. return 1;
  106. /* PAM expects an arry of responses, one for each message */
  107. if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
  108. perror("calloc");
  109. return 1;
  110. }
  111. for (int c = 0; c < num_msg; c++) {
  112. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  113. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  114. continue;
  115. /* return code is currently not used but should be set to zero */
  116. resp[c]->resp_retcode = 0;
  117. if ((resp[c]->resp = strdup(passwd)) == NULL) {
  118. perror("strdup");
  119. return 1;
  120. }
  121. }
  122. return 0;
  123. }
  124. int main(int argc, char *argv[]) {
  125. char curs[] = {0, 0, 0, 0, 0, 0, 0, 0};
  126. char buf[32];
  127. char *username;
  128. int num, screen;
  129. unsigned int len;
  130. bool running = true;
  131. /* By default, fork, don’t beep and don’t turn off monitor */
  132. bool dont_fork = false;
  133. bool beep = false;
  134. bool dpms = false;
  135. bool xpm_image = false;
  136. char xpm_image_path[256];
  137. char color[7] = "ffffff"; // white
  138. Cursor invisible;
  139. Display *dpy;
  140. KeySym ksym;
  141. Pixmap pmap;
  142. Window root, w;
  143. XColor black, dummy;
  144. XEvent ev;
  145. XSetWindowAttributes wa;
  146. pam_handle_t *handle;
  147. struct pam_conv conv = {conv_callback, NULL};
  148. char opt;
  149. int optind = 0;
  150. static struct option long_options[] = {
  151. {"version", no_argument, NULL, 'v'},
  152. {"nofork", no_argument, NULL, 'n'},
  153. {"beep", no_argument, NULL, 'b'},
  154. {"dpms", no_argument, NULL, 'd'},
  155. {"image", required_argument, NULL, 'i'},
  156. {"color", required_argument, NULL, 'c'},
  157. {NULL, no_argument, NULL, 0}
  158. };
  159. while ((opt = getopt_long(argc, argv, "vnbdi:c:", long_options, &optind)) != -1) {
  160. switch (opt) {
  161. case 'v':
  162. die("i3lock-"VERSION", © 2009 Michael Stapelberg\n"
  163. "based on slock, which is © 2006-2008 Anselm R Garbe\n");
  164. case 'n':
  165. dont_fork = true;
  166. break;
  167. case 'b':
  168. beep = true;
  169. break;
  170. case 'd':
  171. dpms = true;
  172. break;
  173. case 'i':
  174. strncpy(xpm_image_path, optarg, 255);
  175. xpm_image = true;
  176. break;
  177. case 'c':
  178. {
  179. char *arg = optarg;
  180. /* Skip # if present */
  181. if (arg[0] == '#')
  182. arg++;
  183. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  184. die("color is invalid, color must be given in 6-byte format: rrggbb\n");
  185. break;
  186. }
  187. default:
  188. die("i3lock: Unknown option. Syntax: i3lock [-v] [-n] [-b] [-d] [-i image.xpm] [-c color]\n");
  189. }
  190. }
  191. if ((username = getenv("USER")) == NULL)
  192. die("USER environment variable not set, please set it.\n");
  193. int ret = pam_start("i3lock", username, &conv, &handle);
  194. if (ret != PAM_SUCCESS)
  195. die("PAM: %s\n", pam_strerror(handle, ret));
  196. if(!(dpy = XOpenDisplay(0)))
  197. die("i3lock: cannot open display\n");
  198. screen = DefaultScreen(dpy);
  199. root = RootWindow(dpy, screen);
  200. if (!dont_fork) {
  201. if (fork() != 0)
  202. return 0;
  203. }
  204. /* init */
  205. wa.override_redirect = 1;
  206. wa.background_pixel = get_colorpixel(color);
  207. w = XCreateWindow(dpy, root, 0, 0, DisplayWidth(dpy, screen), DisplayHeight(dpy, screen),
  208. 0, DefaultDepth(dpy, screen), CopyFromParent,
  209. DefaultVisual(dpy, screen), CWOverrideRedirect | CWBackPixel, &wa);
  210. XAllocNamedColor(dpy, DefaultColormap(dpy, screen), "black", &black, &dummy);
  211. pmap = XCreateBitmapFromData(dpy, w, curs, 8, 8);
  212. invisible = XCreatePixmapCursor(dpy, pmap, pmap, &black, &black, 0, 0);
  213. XDefineCursor(dpy, w, invisible);
  214. XMapRaised(dpy, w);
  215. if(xpm_image && file_exists(xpm_image_path))
  216. {
  217. GC gc = XDefaultGC(dpy, 0);
  218. int depth = DefaultDepth(dpy, screen);
  219. int disp_width = DisplayWidth(dpy, screen);
  220. int disp_height = DisplayHeight(dpy, screen);
  221. Pixmap pix = XCreatePixmap(dpy, w, disp_width, disp_height, depth);
  222. int err = XpmReadFileToPixmap(dpy, w, xpm_image_path, &pix, 0, 0);
  223. if (err != 0) {
  224. print_xpm_error(err);
  225. return 1;
  226. }
  227. XCopyArea(dpy, pix, w, gc, 0, 0, disp_width, disp_height, 0, 0);
  228. }
  229. for(len = 1000; len; len--) {
  230. if(XGrabPointer(dpy, root, False, ButtonPressMask | ButtonReleaseMask,
  231. GrabModeAsync, GrabModeAsync, None, invisible, CurrentTime) == GrabSuccess)
  232. break;
  233. usleep(1000);
  234. }
  235. if((running = running && (len > 0))) {
  236. for(len = 1000; len; len--) {
  237. if(XGrabKeyboard(dpy, root, True, GrabModeAsync, GrabModeAsync, CurrentTime)
  238. == GrabSuccess)
  239. break;
  240. usleep(1000);
  241. }
  242. running = (len > 0);
  243. }
  244. len = 0;
  245. XSync(dpy, False);
  246. /* main event loop */
  247. while(running && !XNextEvent(dpy, &ev)) {
  248. if (len == 0 && dpms && DPMSCapable(dpy)) {
  249. DPMSEnable(dpy);
  250. DPMSForceLevel(dpy, DPMSModeOff);
  251. }
  252. if(ev.type != KeyPress)
  253. continue;
  254. buf[0] = 0;
  255. num = XLookupString(&ev.xkey, buf, sizeof buf, &ksym, 0);
  256. if(IsKeypadKey(ksym)) {
  257. if(ksym == XK_KP_Enter)
  258. ksym = XK_Return;
  259. else if(ksym >= XK_KP_0 && ksym <= XK_KP_9)
  260. ksym = (ksym - XK_KP_0) + XK_0;
  261. }
  262. if(IsFunctionKey(ksym) ||
  263. IsKeypadKey(ksym) ||
  264. IsMiscFunctionKey(ksym) ||
  265. IsPFKey(ksym) ||
  266. IsPrivateKeypadKey(ksym))
  267. continue;
  268. switch(ksym) {
  269. case XK_Return:
  270. passwd[len] = 0;
  271. if ((ret = pam_authenticate(handle, 0)) == PAM_SUCCESS)
  272. running = false;
  273. else {
  274. fprintf(stderr, "PAM: %s\n", pam_strerror(handle, ret));
  275. if (beep)
  276. XBell(dpy, 100);
  277. }
  278. len = 0;
  279. break;
  280. case XK_Escape:
  281. len = 0;
  282. break;
  283. case XK_BackSpace:
  284. if (len > 0)
  285. len--;
  286. break;
  287. default:
  288. if(num && !iscntrl((int) buf[0]) && (len + num < sizeof passwd)) {
  289. memcpy(passwd + len, buf, num);
  290. len += num;
  291. }
  292. break;
  293. }
  294. }
  295. XUngrabPointer(dpy, CurrentTime);
  296. XFreePixmap(dpy, pmap);
  297. XDestroyWindow(dpy, w);
  298. XCloseDisplay(dpy);
  299. return 0;
  300. }