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.

1013 lines
33 KiB

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