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.

868 lines
27 KiB

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