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.

877 lines
28 KiB

11 years ago
15 years ago
  1. /*
  2. * vim:ts=4:sw=4:expandtab
  3. *
  4. * © 2010-2013 Michael Stapelberg
  5. *
  6. * See LICENSE for licensing information
  7. *
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #include <unistd.h>
  13. #include <stdbool.h>
  14. #include <stdint.h>
  15. #include <xcb/xcb.h>
  16. #include <xcb/dpms.h>
  17. #include <err.h>
  18. #include <assert.h>
  19. #include <security/pam_appl.h>
  20. #include <X11/Xlib-xcb.h>
  21. #include <getopt.h>
  22. #include <string.h>
  23. #include <ev.h>
  24. #include <sys/mman.h>
  25. #include <X11/XKBlib.h>
  26. #include <X11/extensions/XKBfile.h>
  27. #include <xkbcommon/xkbcommon.h>
  28. #include <cairo.h>
  29. #include <cairo/cairo-xcb.h>
  30. #include "i3lock.h"
  31. #include "xcb.h"
  32. #include "cursors.h"
  33. #include "unlock_indicator.h"
  34. #include "xinerama.h"
  35. #define TSTAMP_N_SECS(n) (n * 1.0)
  36. #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
  37. #define START_TIMER(timer_obj, timeout, callback) \
  38. timer_obj = start_timer(timer_obj, timeout, callback)
  39. #define STOP_TIMER(timer_obj) \
  40. timer_obj = stop_timer(timer_obj)
  41. typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
  42. /* We need this for libxkbfile */
  43. static Display *display;
  44. char color[7] = "ffffff";
  45. int inactivity_timeout = 30;
  46. uint32_t last_resolution[2];
  47. xcb_window_t win;
  48. static xcb_cursor_t cursor;
  49. static pam_handle_t *pam_handle;
  50. int input_position = 0;
  51. /* Holds the password you enter (in UTF-8). */
  52. static char password[512];
  53. static bool beep = false;
  54. bool debug_mode = false;
  55. static bool dpms = false;
  56. bool unlock_indicator = true;
  57. static bool dont_fork = false;
  58. struct ev_loop *main_loop;
  59. static struct ev_timer *clear_pam_wrong_timeout;
  60. static struct ev_timer *clear_indicator_timeout;
  61. static struct ev_timer *dpms_timeout;
  62. static struct ev_timer *discard_passwd_timeout;
  63. extern unlock_state_t unlock_state;
  64. extern pam_state_t pam_state;
  65. static struct xkb_state *xkb_state;
  66. static struct xkb_context *xkb_context;
  67. static struct xkb_keymap *xkb_keymap;
  68. cairo_surface_t *img = NULL;
  69. bool tile = false;
  70. bool ignore_empty_password = false;
  71. /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
  72. #define isutf(c) (((c) & 0xC0) != 0x80)
  73. /*
  74. * Decrements i to point to the previous unicode glyph
  75. *
  76. */
  77. void u8_dec(char *s, int *i) {
  78. (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
  79. }
  80. static void turn_monitors_on(void) {
  81. if (dpms)
  82. dpms_set_mode(conn, XCB_DPMS_DPMS_MODE_ON);
  83. }
  84. static void turn_monitors_off(void) {
  85. if (dpms)
  86. dpms_set_mode(conn, XCB_DPMS_DPMS_MODE_OFF);
  87. }
  88. /*
  89. * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
  90. * Necessary so that we can properly let xkbcommon track the keyboard state and
  91. * translate keypresses to utf-8.
  92. *
  93. * Ideally, xkbcommon would ship something like this itself, but as of now
  94. * (version 0.2.0), it doesnt.
  95. *
  96. * TODO: Once xcb-xkb is enabled by default and released, we should port this
  97. * code to xcb-xkb. See also https://github.com/xkbcommon/libxkbcommon/issues/1
  98. *
  99. */
  100. static bool load_keymap(void) {
  101. bool ret = false;
  102. XkbFileInfo result;
  103. memset(&result, '\0', sizeof(result));
  104. result.xkb = XkbGetKeyboard(display, XkbAllMapComponentsMask, XkbUseCoreKbd);
  105. if (result.xkb == NULL) {
  106. fprintf(stderr, "[i3lock] XKB: XkbGetKeyboard failed\n");
  107. return false;
  108. }
  109. FILE *temp = tmpfile();
  110. if (temp == NULL) {
  111. fprintf(stderr, "[i3lock] could not create tempfile\n");
  112. return false;
  113. }
  114. bool ok = XkbWriteXKBKeymap(temp, &result, false, false, NULL, NULL);
  115. if (!ok) {
  116. fprintf(stderr, "[i3lock] XkbWriteXKBKeymap failed\n");
  117. goto out;
  118. }
  119. rewind(temp);
  120. if (xkb_context == NULL) {
  121. if ((xkb_context = xkb_context_new(0)) == NULL) {
  122. fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
  123. goto out;
  124. }
  125. }
  126. if (xkb_keymap != NULL)
  127. xkb_keymap_unref(xkb_keymap);
  128. if ((xkb_keymap = xkb_keymap_new_from_file(xkb_context, temp, XKB_KEYMAP_FORMAT_TEXT_V1, 0)) == NULL) {
  129. fprintf(stderr, "[i3lock] xkb_keymap_new_from_file failed\n");
  130. goto out;
  131. }
  132. struct xkb_state *new_state = xkb_state_new(xkb_keymap);
  133. if (new_state == NULL) {
  134. fprintf(stderr, "[i3lock] xkb_state_new failed\n");
  135. goto out;
  136. }
  137. /* Get the initial modifier state to be in sync with the X server.
  138. * See https://github.com/xkbcommon/libxkbcommon/issues/1 for why we ignore
  139. * the base and latched fields. */
  140. XkbStateRec state_rec;
  141. XkbGetState(display, XkbUseCoreKbd, &state_rec);
  142. xkb_state_update_mask(new_state,
  143. 0, 0, state_rec.locked_mods,
  144. 0, 0, state_rec.locked_group);
  145. if (xkb_state != NULL)
  146. xkb_state_unref(xkb_state);
  147. xkb_state = new_state;
  148. ret = true;
  149. out:
  150. XkbFreeKeyboard(result.xkb, XkbAllComponentsMask, true);
  151. fclose(temp);
  152. return ret;
  153. }
  154. /*
  155. * Clears the memory which stored the password to be a bit safer against
  156. * cold-boot attacks.
  157. *
  158. */
  159. static void clear_password_memory(void) {
  160. /* A volatile pointer to the password buffer to prevent the compiler from
  161. * optimizing this out. */
  162. volatile char *vpassword = password;
  163. for (int c = 0; c < sizeof(password); c++)
  164. /* We store a non-random pattern which consists of the (irrelevant)
  165. * index plus (!) the value of the beep variable. This prevents the
  166. * compiler from optimizing the calls away, since the value of 'beep'
  167. * is not known at compile-time. */
  168. vpassword[c] = c + (int)beep;
  169. }
  170. ev_timer* start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
  171. if (timer_obj) {
  172. ev_timer_stop(main_loop, timer_obj);
  173. ev_timer_set(timer_obj, timeout, 0.);
  174. ev_timer_start(main_loop, timer_obj);
  175. } else {
  176. /* When there is no memory, we just don’t have a timeout. We cannot
  177. * exit() here, since that would effectively unlock the screen. */
  178. timer_obj = calloc(sizeof(struct ev_timer), 1);
  179. if (timer_obj) {
  180. ev_timer_init(timer_obj, callback, timeout, 0.);
  181. ev_timer_start(main_loop, timer_obj);
  182. }
  183. }
  184. return timer_obj;
  185. }
  186. ev_timer* stop_timer(ev_timer *timer_obj) {
  187. if (timer_obj) {
  188. ev_timer_stop(main_loop, timer_obj);
  189. free(timer_obj);
  190. }
  191. return NULL;
  192. }
  193. /*
  194. * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccessful
  195. * authentication event.
  196. *
  197. */
  198. static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
  199. DEBUG("clearing pam wrong\n");
  200. pam_state = STATE_PAM_IDLE;
  201. unlock_state = STATE_STARTED;
  202. redraw_screen();
  203. /* Now free this timeout. */
  204. ev_timer_stop(main_loop, clear_pam_wrong_timeout);
  205. free(clear_pam_wrong_timeout);
  206. clear_pam_wrong_timeout = NULL;
  207. }
  208. static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
  209. clear_indicator();
  210. STOP_TIMER(clear_indicator_timeout);
  211. }
  212. static void clear_input(void) {
  213. input_position = 0;
  214. clear_password_memory();
  215. password[input_position] = '\0';
  216. /* Hide the unlock indicator after a bit if the password buffer is
  217. * empty. */
  218. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  219. unlock_state = STATE_BACKSPACE_ACTIVE;
  220. redraw_screen();
  221. unlock_state = STATE_KEY_PRESSED;
  222. }
  223. static void turn_off_monitors_cb(EV_P_ ev_timer *w, int revents) {
  224. if (input_position == 0)
  225. turn_monitors_off();
  226. STOP_TIMER(dpms_timeout);
  227. }
  228. static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
  229. clear_input();
  230. turn_monitors_off();
  231. STOP_TIMER(discard_passwd_timeout);
  232. }
  233. static void input_done(void) {
  234. if (clear_pam_wrong_timeout) {
  235. ev_timer_stop(main_loop, clear_pam_wrong_timeout);
  236. free(clear_pam_wrong_timeout);
  237. clear_pam_wrong_timeout = NULL;
  238. }
  239. pam_state = STATE_PAM_VERIFY;
  240. redraw_screen();
  241. if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
  242. DEBUG("successfully authenticated\n");
  243. clear_password_memory();
  244. /* Turn the screen on, as it may have been turned off
  245. * on release of the 'enter' key. */
  246. turn_monitors_on();
  247. exit(0);
  248. }
  249. if (debug_mode)
  250. fprintf(stderr, "Authentication failure\n");
  251. pam_state = STATE_PAM_WRONG;
  252. clear_input();
  253. redraw_screen();
  254. /* Clear this state after 2 seconds (unless the user enters another
  255. * password during that time). */
  256. ev_now_update(main_loop);
  257. if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
  258. ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
  259. ev_timer_start(main_loop, clear_pam_wrong_timeout);
  260. }
  261. /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
  262. * too early. */
  263. STOP_TIMER(clear_indicator_timeout);
  264. /* beep on authentication failure, if enabled */
  265. if (beep) {
  266. xcb_bell(conn, 100);
  267. xcb_flush(conn);
  268. }
  269. }
  270. /*
  271. * Called when the user releases a key. We need to leave the Mode_switch
  272. * state when the user releases the Mode_switch key.
  273. *
  274. */
  275. static void handle_key_release(xcb_key_release_event_t *event) {
  276. xkb_state_update_key(xkb_state, event->detail, XKB_KEY_UP);
  277. }
  278. static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
  279. redraw_screen();
  280. ev_timer_stop(main_loop, w);
  281. free(w);
  282. }
  283. /*
  284. * Handle key presses. Fixes state, then looks up the key symbol for the
  285. * given keycode, then looks up the key symbol (as UCS-2), converts it to
  286. * UTF-8 and stores it in the password array.
  287. *
  288. */
  289. static void handle_key_press(xcb_key_press_event_t *event) {
  290. xkb_keysym_t ksym;
  291. char buffer[128];
  292. int n;
  293. bool ctrl;
  294. ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
  295. ctrl = xkb_state_mod_name_is_active(xkb_state, "Control", XKB_STATE_MODS_DEPRESSED);
  296. xkb_state_update_key(xkb_state, event->detail, XKB_KEY_DOWN);
  297. /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
  298. memset(buffer, '\0', sizeof(buffer));
  299. n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
  300. switch (ksym) {
  301. case XKB_KEY_Return:
  302. case XKB_KEY_KP_Enter:
  303. case XKB_KEY_XF86ScreenSaver:
  304. if (ignore_empty_password && input_position == 0) {
  305. clear_input();
  306. return;
  307. }
  308. password[input_position] = '\0';
  309. unlock_state = STATE_KEY_PRESSED;
  310. redraw_screen();
  311. input_done();
  312. return;
  313. case XKB_KEY_u:
  314. if (ctrl) {
  315. DEBUG("C-u pressed\n");
  316. clear_input();
  317. return;
  318. }
  319. break;
  320. case XKB_KEY_Escape:
  321. clear_input();
  322. return;
  323. case XKB_KEY_BackSpace:
  324. if (input_position == 0)
  325. return;
  326. /* decrement input_position to point to the previous glyph */
  327. u8_dec(password, &input_position);
  328. password[input_position] = '\0';
  329. /* Hide the unlock indicator after a bit if the password buffer is
  330. * empty. */
  331. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  332. unlock_state = STATE_BACKSPACE_ACTIVE;
  333. redraw_screen();
  334. unlock_state = STATE_KEY_PRESSED;
  335. return;
  336. }
  337. if ((input_position + 8) >= sizeof(password))
  338. return;
  339. #if 0
  340. /* FIXME: handle all of these? */
  341. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  342. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  343. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  344. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  345. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  346. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  347. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  348. #endif
  349. if (n < 2)
  350. return;
  351. /* store it in the password array as UTF-8 */
  352. memcpy(password+input_position, buffer, n-1);
  353. input_position += n-1;
  354. DEBUG("current password = %.*s\n", input_position, password);
  355. unlock_state = STATE_KEY_ACTIVE;
  356. redraw_screen();
  357. unlock_state = STATE_KEY_PRESSED;
  358. struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
  359. if (timeout) {
  360. ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
  361. ev_timer_start(main_loop, timeout);
  362. }
  363. STOP_TIMER(clear_indicator_timeout);
  364. START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
  365. }
  366. /*
  367. * A visibility notify event will be received when the visibility (= can the
  368. * user view the complete window) changes, so for example when a popup overlays
  369. * some area of the i3lock window.
  370. *
  371. * In this case, we raise our window on top so that the popup (or whatever is
  372. * hiding us) gets hidden.
  373. *
  374. */
  375. static void handle_visibility_notify(xcb_connection_t *conn,
  376. xcb_visibility_notify_event_t *event) {
  377. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  378. uint32_t values[] = { XCB_STACK_MODE_ABOVE };
  379. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  380. xcb_flush(conn);
  381. }
  382. }
  383. /*
  384. * Called when the keyboard mapping changes. We update our symbols.
  385. *
  386. */
  387. static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
  388. /* We ignore errors — if the new keymap cannot be loaded it’s better if the
  389. * screen stays locked and the user intervenes by using killall i3lock. */
  390. (void)load_keymap();
  391. }
  392. /*
  393. * Called when the properties on the root window change, e.g. when the screen
  394. * resolution changes. If so we update the window to cover the whole screen
  395. * and also redraw the image, if any.
  396. *
  397. */
  398. void handle_screen_resize(void) {
  399. xcb_get_geometry_cookie_t geomc;
  400. xcb_get_geometry_reply_t *geom;
  401. geomc = xcb_get_geometry(conn, screen->root);
  402. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
  403. return;
  404. if (last_resolution[0] == geom->width &&
  405. last_resolution[1] == geom->height) {
  406. free(geom);
  407. return;
  408. }
  409. last_resolution[0] = geom->width;
  410. last_resolution[1] = geom->height;
  411. free(geom);
  412. redraw_screen();
  413. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  414. xcb_configure_window(conn, win, mask, last_resolution);
  415. xcb_flush(conn);
  416. xinerama_query_screens();
  417. redraw_screen();
  418. }
  419. /*
  420. * Callback function for PAM. We only react on password request callbacks.
  421. *
  422. */
  423. static int conv_callback(int num_msg, const struct pam_message **msg,
  424. struct pam_response **resp, void *appdata_ptr)
  425. {
  426. if (num_msg == 0)
  427. return 1;
  428. /* PAM expects an array of responses, one for each message */
  429. if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
  430. perror("calloc");
  431. return 1;
  432. }
  433. for (int c = 0; c < num_msg; c++) {
  434. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  435. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  436. continue;
  437. /* return code is currently not used but should be set to zero */
  438. resp[c]->resp_retcode = 0;
  439. if ((resp[c]->resp = strdup(password)) == NULL) {
  440. perror("strdup");
  441. return 1;
  442. }
  443. }
  444. return 0;
  445. }
  446. /*
  447. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  448. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  449. *
  450. */
  451. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  452. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  453. }
  454. /*
  455. * Flush before blocking (and waiting for new events)
  456. *
  457. */
  458. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  459. xcb_flush(conn);
  460. }
  461. /*
  462. * Instead of polling the X connection socket we leave this to
  463. * xcb_poll_for_event() which knows better than we can ever know.
  464. *
  465. */
  466. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  467. xcb_generic_event_t *event;
  468. while ((event = xcb_poll_for_event(conn)) != NULL) {
  469. if (event->response_type == 0) {
  470. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  471. if (debug_mode)
  472. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  473. error->sequence, error->error_code);
  474. free(event);
  475. continue;
  476. }
  477. /* Strip off the highest bit (set if the event is generated) */
  478. int type = (event->response_type & 0x7F);
  479. switch (type) {
  480. case XCB_KEY_PRESS:
  481. handle_key_press((xcb_key_press_event_t*)event);
  482. break;
  483. case XCB_KEY_RELEASE:
  484. handle_key_release((xcb_key_release_event_t*)event);
  485. /* If this was the backspace or escape key we are back at an
  486. * empty input, so turn off the screen if DPMS is enabled, but
  487. * only do that after some timeout: maybe user mistyped and
  488. * will type again right away */
  489. START_TIMER(dpms_timeout, TSTAMP_N_SECS(inactivity_timeout),
  490. turn_off_monitors_cb);
  491. break;
  492. case XCB_VISIBILITY_NOTIFY:
  493. handle_visibility_notify(conn, (xcb_visibility_notify_event_t*)event);
  494. break;
  495. case XCB_MAP_NOTIFY:
  496. if (!dont_fork) {
  497. /* After the first MapNotify, we never fork again. We don’t
  498. * expect to get another MapNotify, but better be sure */
  499. dont_fork = true;
  500. /* In the parent process, we exit */
  501. if (fork() != 0)
  502. exit(0);
  503. ev_loop_fork(EV_DEFAULT);
  504. }
  505. break;
  506. case XCB_MAPPING_NOTIFY:
  507. handle_mapping_notify((xcb_mapping_notify_event_t*)event);
  508. break;
  509. case XCB_CONFIGURE_NOTIFY:
  510. handle_screen_resize();
  511. break;
  512. }
  513. free(event);
  514. }
  515. }
  516. /*
  517. * This function is called from a fork()ed child and will raise the i3lock
  518. * window when the window is obscured, even when the main i3lock process is
  519. * blocked due to PAM.
  520. *
  521. */
  522. static void raise_loop(xcb_window_t window) {
  523. xcb_connection_t *conn;
  524. xcb_generic_event_t *event;
  525. int screens;
  526. if ((conn = xcb_connect(NULL, &screens)) == NULL ||
  527. xcb_connection_has_error(conn))
  528. errx(EXIT_FAILURE, "Cannot open display\n");
  529. /* We need to know about the window being obscured or getting destroyed. */
  530. xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
  531. (uint32_t[]){
  532. XCB_EVENT_MASK_VISIBILITY_CHANGE |
  533. XCB_EVENT_MASK_STRUCTURE_NOTIFY
  534. });
  535. xcb_flush(conn);
  536. DEBUG("Watching window 0x%08x\n", window);
  537. while ((event = xcb_wait_for_event(conn)) != NULL) {
  538. if (event->response_type == 0) {
  539. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  540. DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
  541. error->sequence, error->error_code);
  542. free(event);
  543. continue;
  544. }
  545. /* Strip off the highest bit (set if the event is generated) */
  546. int type = (event->response_type & 0x7F);
  547. DEBUG("Read event of type %d\n", type);
  548. switch (type) {
  549. case XCB_VISIBILITY_NOTIFY:
  550. handle_visibility_notify(conn, (xcb_visibility_notify_event_t*)event);
  551. break;
  552. case XCB_UNMAP_NOTIFY:
  553. DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t*)event)->window));
  554. if (((xcb_unmap_notify_event_t*)event)->window == window)
  555. exit(EXIT_SUCCESS);
  556. break;
  557. case XCB_DESTROY_NOTIFY:
  558. DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t*)event)->window));
  559. if (((xcb_destroy_notify_event_t*)event)->window == window)
  560. exit(EXIT_SUCCESS);
  561. break;
  562. default:
  563. DEBUG("Unhandled event type %d\n", type);
  564. break;
  565. }
  566. free(event);
  567. }
  568. }
  569. int main(int argc, char *argv[]) {
  570. char *username;
  571. char *image_path = NULL;
  572. int ret;
  573. struct pam_conv conv = {conv_callback, NULL};
  574. int curs_choice = CURS_NONE;
  575. int o;
  576. int optind = 0;
  577. struct option longopts[] = {
  578. {"version", no_argument, NULL, 'v'},
  579. {"nofork", no_argument, NULL, 'n'},
  580. {"beep", no_argument, NULL, 'b'},
  581. {"dpms", no_argument, NULL, 'd'},
  582. {"color", required_argument, NULL, 'c'},
  583. {"pointer", required_argument, NULL , 'p'},
  584. {"debug", no_argument, NULL, 0},
  585. {"help", no_argument, NULL, 'h'},
  586. {"no-unlock-indicator", no_argument, NULL, 'u'},
  587. {"image", required_argument, NULL, 'i'},
  588. {"tiling", no_argument, NULL, 't'},
  589. {"ignore-empty-password", no_argument, NULL, 'e'},
  590. {"inactivity-timeout", required_argument, NULL, 'I'},
  591. {NULL, no_argument, NULL, 0}
  592. };
  593. if ((username = getenv("USER")) == NULL)
  594. errx(EXIT_FAILURE, "USER environment variable not set, please set it.\n");
  595. char *optstring = "hvnbdc:p:ui:teI:";
  596. while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
  597. switch (o) {
  598. case 'v':
  599. errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
  600. case 'n':
  601. dont_fork = true;
  602. break;
  603. case 'b':
  604. beep = true;
  605. break;
  606. case 'd':
  607. dpms = true;
  608. break;
  609. case 'I': {
  610. int time = 0;
  611. if (sscanf(optarg, "%d", &time) != 1 || time < 0)
  612. errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
  613. inactivity_timeout = time;
  614. break;
  615. }
  616. case 'c': {
  617. char *arg = optarg;
  618. /* Skip # if present */
  619. if (arg[0] == '#')
  620. arg++;
  621. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  622. errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  623. break;
  624. }
  625. case 'u':
  626. unlock_indicator = false;
  627. break;
  628. case 'i':
  629. image_path = strdup(optarg);
  630. break;
  631. case 't':
  632. tile = true;
  633. break;
  634. case 'p':
  635. if (!strcmp(optarg, "win")) {
  636. curs_choice = CURS_WIN;
  637. } else if (!strcmp(optarg, "default")) {
  638. curs_choice = CURS_DEFAULT;
  639. } else {
  640. errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  641. }
  642. break;
  643. case 'e':
  644. ignore_empty_password = true;
  645. break;
  646. case 0:
  647. if (strcmp(longopts[optind].name, "debug") == 0)
  648. debug_mode = true;
  649. break;
  650. default:
  651. errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  652. " [-i image.png] [-t] [-e] [-I]"
  653. );
  654. }
  655. }
  656. /* We need (relatively) random numbers for highlighting a random part of
  657. * the unlock indicator upon keypresses. */
  658. srand(time(NULL));
  659. /* Initialize PAM */
  660. ret = pam_start("i3lock", username, &conv, &pam_handle);
  661. if (ret != PAM_SUCCESS)
  662. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  663. /* Using mlock() as non-super-user seems only possible in Linux. Users of other
  664. * operating systems should use encrypted swap/no swap (or remove the ifdef and
  665. * run i3lock as super-user). */
  666. #if defined(__linux__)
  667. /* Lock the area where we store the password in memory, we don’t want it to
  668. * be swapped to disk. Since Linux 2.6.9, this does not require any
  669. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  670. if (mlock(password, sizeof(password)) != 0)
  671. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  672. #endif
  673. /* Initialize connection to X11 */
  674. if ((display = XOpenDisplay(NULL)) == NULL)
  675. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  676. XSetEventQueueOwner(display, XCBOwnsEventQueue);
  677. conn = XGetXCBConnection(display);
  678. /* Double checking that connection is good and operatable with xcb */
  679. if (xcb_connection_has_error(conn))
  680. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  681. /* When we cannot initially load the keymap, we better exit */
  682. if (!load_keymap())
  683. errx(EXIT_FAILURE, "Could not load keymap");
  684. xinerama_init();
  685. xinerama_query_screens();
  686. /* if DPMS is enabled, check if the X server really supports it */
  687. if (dpms) {
  688. xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
  689. xcb_dpms_capable_reply_t *dpmsr;
  690. if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
  691. if (!dpmsr->capable) {
  692. if (debug_mode)
  693. fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
  694. dpms = false;
  695. }
  696. free(dpmsr);
  697. }
  698. }
  699. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  700. last_resolution[0] = screen->width_in_pixels;
  701. last_resolution[1] = screen->height_in_pixels;
  702. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  703. (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
  704. if (image_path) {
  705. /* Create a pixmap to render on, fill it with the background color */
  706. img = cairo_image_surface_create_from_png(image_path);
  707. /* In case loading failed, we just pretend no -i was specified. */
  708. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  709. fprintf(stderr, "Could not load image \"%s\": %s\n",
  710. image_path, cairo_status_to_string(cairo_surface_status(img)));
  711. img = NULL;
  712. }
  713. }
  714. /* Pixmap on which the image is rendered to (if any) */
  715. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  716. /* open the fullscreen window, already with the correct pixmap in place */
  717. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  718. xcb_free_pixmap(conn, bg_pixmap);
  719. pid_t pid = fork();
  720. /* The pid == -1 case is intentionally ignored here:
  721. * While the child process is useful for preventing other windows from
  722. * popping up while i3lock blocks, it is not critical. */
  723. if (pid == 0) {
  724. /* Child */
  725. close(xcb_get_file_descriptor(conn));
  726. raise_loop(win);
  727. exit(EXIT_SUCCESS);
  728. }
  729. cursor = create_cursor(conn, screen, win, curs_choice);
  730. grab_pointer_and_keyboard(conn, screen, cursor);
  731. /* Load the keymap again to sync the current modifier state. Since we first
  732. * loaded the keymap, there might have been changes, but starting from now,
  733. * we should get all key presses/releases due to having grabbed the
  734. * keyboard. */
  735. (void)load_keymap();
  736. turn_monitors_off();
  737. /* Initialize the libev event loop. */
  738. main_loop = EV_DEFAULT;
  739. if (main_loop == NULL)
  740. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  741. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  742. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  743. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  744. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  745. ev_io_start(main_loop, xcb_watcher);
  746. ev_check_init(xcb_check, xcb_check_cb);
  747. ev_check_start(main_loop, xcb_check);
  748. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  749. ev_prepare_start(main_loop, xcb_prepare);
  750. /* Invoke the event callback once to catch all the events which were
  751. * received up until now. ev will only pick up new events (when the X11
  752. * file descriptor becomes readable). */
  753. ev_invoke(main_loop, xcb_check, 0);
  754. ev_loop(main_loop, 0);
  755. }