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.

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