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.

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