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.

367 lines
12 KiB

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