893 lines
28 KiB

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