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.

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