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.

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