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.

1048 lines
34 KiB

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