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.

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