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.

1116 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. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  412. unlock_state = STATE_NOTHING_TO_DELETE;
  413. redraw_screen();
  414. return;
  415. }
  416. /* decrement input_position to point to the previous glyph */
  417. u8_dec(password, &input_position);
  418. password[input_position] = '\0';
  419. /* Hide the unlock indicator after a bit if the password buffer is
  420. * empty. */
  421. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  422. unlock_state = STATE_BACKSPACE_ACTIVE;
  423. redraw_screen();
  424. unlock_state = STATE_KEY_PRESSED;
  425. return;
  426. }
  427. if ((input_position + 8) >= (int)sizeof(password))
  428. return;
  429. #if 0
  430. /* FIXME: handle all of these? */
  431. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  432. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  433. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  434. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  435. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  436. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  437. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  438. #endif
  439. if (n < 2)
  440. return;
  441. /* store it in the password array as UTF-8 */
  442. memcpy(password + input_position, buffer, n - 1);
  443. input_position += n - 1;
  444. DEBUG("current password = %.*s\n", input_position, password);
  445. if (unlock_indicator) {
  446. unlock_state = STATE_KEY_ACTIVE;
  447. redraw_screen();
  448. unlock_state = STATE_KEY_PRESSED;
  449. struct ev_timer *timeout = NULL;
  450. START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
  451. STOP_TIMER(clear_indicator_timeout);
  452. }
  453. START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
  454. }
  455. /*
  456. * A visibility notify event will be received when the visibility (= can the
  457. * user view the complete window) changes, so for example when a popup overlays
  458. * some area of the i3lock window.
  459. *
  460. * In this case, we raise our window on top so that the popup (or whatever is
  461. * hiding us) gets hidden.
  462. *
  463. */
  464. static void handle_visibility_notify(xcb_connection_t *conn,
  465. xcb_visibility_notify_event_t *event) {
  466. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  467. uint32_t values[] = {XCB_STACK_MODE_ABOVE};
  468. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  469. xcb_flush(conn);
  470. }
  471. }
  472. /*
  473. * Called when the keyboard mapping changes. We update our symbols.
  474. *
  475. * We ignore errors if the new keymap cannot be loaded its better if the
  476. * screen stays locked and the user intervenes by using killall i3lock.
  477. *
  478. */
  479. static void process_xkb_event(xcb_generic_event_t *gevent) {
  480. union xkb_event {
  481. struct {
  482. uint8_t response_type;
  483. uint8_t xkbType;
  484. uint16_t sequence;
  485. xcb_timestamp_t time;
  486. uint8_t deviceID;
  487. } any;
  488. xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
  489. xcb_xkb_map_notify_event_t map_notify;
  490. xcb_xkb_state_notify_event_t state_notify;
  491. } *event = (union xkb_event *)gevent;
  492. DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
  493. if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
  494. return;
  495. /*
  496. * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
  497. * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
  498. * recompilations.
  499. */
  500. switch (event->any.xkbType) {
  501. case XCB_XKB_NEW_KEYBOARD_NOTIFY:
  502. if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
  503. (void)load_keymap();
  504. break;
  505. case XCB_XKB_MAP_NOTIFY:
  506. (void)load_keymap();
  507. break;
  508. case XCB_XKB_STATE_NOTIFY:
  509. xkb_state_update_mask(xkb_state,
  510. event->state_notify.baseMods,
  511. event->state_notify.latchedMods,
  512. event->state_notify.lockedMods,
  513. event->state_notify.baseGroup,
  514. event->state_notify.latchedGroup,
  515. event->state_notify.lockedGroup);
  516. break;
  517. }
  518. }
  519. /*
  520. * Called when the properties on the root window change, e.g. when the screen
  521. * resolution changes. If so we update the window to cover the whole screen
  522. * and also redraw the image, if any.
  523. *
  524. */
  525. void handle_screen_resize(void) {
  526. xcb_get_geometry_cookie_t geomc;
  527. xcb_get_geometry_reply_t *geom;
  528. geomc = xcb_get_geometry(conn, screen->root);
  529. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
  530. return;
  531. if (last_resolution[0] == geom->width &&
  532. last_resolution[1] == geom->height) {
  533. free(geom);
  534. return;
  535. }
  536. last_resolution[0] = geom->width;
  537. last_resolution[1] = geom->height;
  538. free(geom);
  539. redraw_screen();
  540. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  541. xcb_configure_window(conn, win, mask, last_resolution);
  542. xcb_flush(conn);
  543. randr_query(screen->root);
  544. redraw_screen();
  545. }
  546. #ifndef __OpenBSD__
  547. /*
  548. * Callback function for PAM. We only react on password request callbacks.
  549. *
  550. */
  551. static int conv_callback(int num_msg, const struct pam_message **msg,
  552. struct pam_response **resp, void *appdata_ptr) {
  553. if (num_msg == 0)
  554. return 1;
  555. /* PAM expects an array of responses, one for each message */
  556. if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
  557. perror("calloc");
  558. return 1;
  559. }
  560. for (int c = 0; c < num_msg; c++) {
  561. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  562. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  563. continue;
  564. /* return code is currently not used but should be set to zero */
  565. resp[c]->resp_retcode = 0;
  566. if ((resp[c]->resp = strdup(password)) == NULL) {
  567. perror("strdup");
  568. return 1;
  569. }
  570. }
  571. return 0;
  572. }
  573. #endif
  574. /*
  575. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  576. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  577. *
  578. */
  579. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  580. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  581. }
  582. /*
  583. * Flush before blocking (and waiting for new events)
  584. *
  585. */
  586. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  587. xcb_flush(conn);
  588. }
  589. /*
  590. * Try closing logind sleep lock fd passed over from xss-lock, in case we're
  591. * being run from there.
  592. *
  593. */
  594. static void maybe_close_sleep_lock_fd(void) {
  595. const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
  596. char *endptr;
  597. if (sleep_lock_fd && *sleep_lock_fd != 0) {
  598. long int fd = strtol(sleep_lock_fd, &endptr, 10);
  599. if (*endptr == 0) {
  600. close(fd);
  601. }
  602. }
  603. }
  604. /*
  605. * Instead of polling the X connection socket we leave this to
  606. * xcb_poll_for_event() which knows better than we can ever know.
  607. *
  608. */
  609. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  610. xcb_generic_event_t *event;
  611. if (xcb_connection_has_error(conn))
  612. errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
  613. while ((event = xcb_poll_for_event(conn)) != NULL) {
  614. if (event->response_type == 0) {
  615. xcb_generic_error_t *error = (xcb_generic_error_t *)event;
  616. if (debug_mode)
  617. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  618. error->sequence, error->error_code);
  619. free(event);
  620. continue;
  621. }
  622. /* Strip off the highest bit (set if the event is generated) */
  623. int type = (event->response_type & 0x7F);
  624. switch (type) {
  625. case XCB_KEY_PRESS:
  626. handle_key_press((xcb_key_press_event_t *)event);
  627. break;
  628. case XCB_VISIBILITY_NOTIFY:
  629. handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
  630. break;
  631. case XCB_MAP_NOTIFY:
  632. maybe_close_sleep_lock_fd();
  633. if (!dont_fork) {
  634. /* After the first MapNotify, we never fork again. We don’t
  635. * expect to get another MapNotify, but better be sure */
  636. dont_fork = true;
  637. /* In the parent process, we exit */
  638. if (fork() != 0)
  639. exit(0);
  640. ev_loop_fork(EV_DEFAULT);
  641. }
  642. break;
  643. case XCB_CONFIGURE_NOTIFY:
  644. handle_screen_resize();
  645. break;
  646. default:
  647. if (type == xkb_base_event) {
  648. process_xkb_event(event);
  649. }
  650. if (randr_base > -1 &&
  651. type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
  652. randr_query(screen->root);
  653. handle_screen_resize();
  654. }
  655. }
  656. free(event);
  657. }
  658. }
  659. /*
  660. * This function is called from a fork()ed child and will raise the i3lock
  661. * window when the window is obscured, even when the main i3lock process is
  662. * blocked due to the authentication backend.
  663. *
  664. */
  665. static void raise_loop(xcb_window_t window) {
  666. xcb_connection_t *conn;
  667. xcb_generic_event_t *event;
  668. int screens;
  669. if ((conn = xcb_connect(NULL, &screens)) == NULL ||
  670. xcb_connection_has_error(conn))
  671. errx(EXIT_FAILURE, "Cannot open display\n");
  672. /* We need to know about the window being obscured or getting destroyed. */
  673. xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
  674. (uint32_t[]){
  675. XCB_EVENT_MASK_VISIBILITY_CHANGE |
  676. XCB_EVENT_MASK_STRUCTURE_NOTIFY});
  677. xcb_flush(conn);
  678. DEBUG("Watching window 0x%08x\n", window);
  679. while ((event = xcb_wait_for_event(conn)) != NULL) {
  680. if (event->response_type == 0) {
  681. xcb_generic_error_t *error = (xcb_generic_error_t *)event;
  682. DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
  683. error->sequence, error->error_code);
  684. free(event);
  685. continue;
  686. }
  687. /* Strip off the highest bit (set if the event is generated) */
  688. int type = (event->response_type & 0x7F);
  689. DEBUG("Read event of type %d\n", type);
  690. switch (type) {
  691. case XCB_VISIBILITY_NOTIFY:
  692. handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
  693. break;
  694. case XCB_UNMAP_NOTIFY:
  695. DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
  696. if (((xcb_unmap_notify_event_t *)event)->window == window)
  697. exit(EXIT_SUCCESS);
  698. break;
  699. case XCB_DESTROY_NOTIFY:
  700. DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
  701. if (((xcb_destroy_notify_event_t *)event)->window == window)
  702. exit(EXIT_SUCCESS);
  703. break;
  704. default:
  705. DEBUG("Unhandled event type %d\n", type);
  706. break;
  707. }
  708. free(event);
  709. }
  710. }
  711. int main(int argc, char *argv[]) {
  712. struct passwd *pw;
  713. char *username;
  714. char *image_path = NULL;
  715. #ifndef __OpenBSD__
  716. int ret;
  717. struct pam_conv conv = {conv_callback, NULL};
  718. #endif
  719. int curs_choice = CURS_NONE;
  720. int o;
  721. int longoptind = 0;
  722. struct option longopts[] = {
  723. {"version", no_argument, NULL, 'v'},
  724. {"nofork", no_argument, NULL, 'n'},
  725. {"beep", no_argument, NULL, 'b'},
  726. {"dpms", no_argument, NULL, 'd'},
  727. {"color", required_argument, NULL, 'c'},
  728. {"pointer", required_argument, NULL, 'p'},
  729. {"debug", no_argument, NULL, 0},
  730. {"help", no_argument, NULL, 'h'},
  731. {"no-unlock-indicator", no_argument, NULL, 'u'},
  732. {"image", required_argument, NULL, 'i'},
  733. {"tiling", no_argument, NULL, 't'},
  734. {"ignore-empty-password", no_argument, NULL, 'e'},
  735. {"inactivity-timeout", required_argument, NULL, 'I'},
  736. {"show-failed-attempts", no_argument, NULL, 'f'},
  737. {NULL, no_argument, NULL, 0}};
  738. if ((pw = getpwuid(getuid())) == NULL)
  739. err(EXIT_FAILURE, "getpwuid() failed");
  740. if ((username = pw->pw_name) == NULL)
  741. errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
  742. char *optstring = "hvnbdc:p:ui:teI:f";
  743. while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
  744. switch (o) {
  745. case 'v':
  746. errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
  747. case 'n':
  748. dont_fork = true;
  749. break;
  750. case 'b':
  751. beep = true;
  752. break;
  753. case 'd':
  754. fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
  755. break;
  756. case 'I': {
  757. fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
  758. break;
  759. }
  760. case 'c': {
  761. char *arg = optarg;
  762. /* Skip # if present */
  763. if (arg[0] == '#')
  764. arg++;
  765. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  766. errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  767. break;
  768. }
  769. case 'u':
  770. unlock_indicator = false;
  771. break;
  772. case 'i':
  773. image_path = strdup(optarg);
  774. break;
  775. case 't':
  776. tile = true;
  777. break;
  778. case 'p':
  779. if (!strcmp(optarg, "win")) {
  780. curs_choice = CURS_WIN;
  781. } else if (!strcmp(optarg, "default")) {
  782. curs_choice = CURS_DEFAULT;
  783. } else {
  784. errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  785. }
  786. break;
  787. case 'e':
  788. ignore_empty_password = true;
  789. break;
  790. case 0:
  791. if (strcmp(longopts[longoptind].name, "debug") == 0)
  792. debug_mode = true;
  793. break;
  794. case 'f':
  795. show_failed_attempts = true;
  796. break;
  797. default:
  798. errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  799. " [-i image.png] [-t] [-e] [-I timeout] [-f]");
  800. }
  801. }
  802. /* We need (relatively) random numbers for highlighting a random part of
  803. * the unlock indicator upon keypresses. */
  804. srand(time(NULL));
  805. #ifndef __OpenBSD__
  806. /* Initialize PAM */
  807. if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
  808. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  809. if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
  810. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  811. #endif
  812. /* Using mlock() as non-super-user seems only possible in Linux.
  813. * Users of other operating systems should use encrypted swap/no swap
  814. * (or remove the ifdef and run i3lock as super-user).
  815. * Alas, swap is encrypted by default on OpenBSD so swapping out
  816. * is not necessarily an issue. */
  817. #if defined(__linux__)
  818. /* Lock the area where we store the password in memory, we don’t want it to
  819. * be swapped to disk. Since Linux 2.6.9, this does not require any
  820. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  821. if (mlock(password, sizeof(password)) != 0)
  822. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  823. #endif
  824. /* Double checking that connection is good and operatable with xcb */
  825. int screennr;
  826. if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
  827. xcb_connection_has_error(conn))
  828. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  829. if (xkb_x11_setup_xkb_extension(conn,
  830. XKB_X11_MIN_MAJOR_XKB_VERSION,
  831. XKB_X11_MIN_MINOR_XKB_VERSION,
  832. 0,
  833. NULL,
  834. NULL,
  835. &xkb_base_event,
  836. &xkb_base_error) != 1)
  837. errx(EXIT_FAILURE, "Could not setup XKB extension.");
  838. static const xcb_xkb_map_part_t required_map_parts =
  839. (XCB_XKB_MAP_PART_KEY_TYPES |
  840. XCB_XKB_MAP_PART_KEY_SYMS |
  841. XCB_XKB_MAP_PART_MODIFIER_MAP |
  842. XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
  843. XCB_XKB_MAP_PART_KEY_ACTIONS |
  844. XCB_XKB_MAP_PART_VIRTUAL_MODS |
  845. XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
  846. static const xcb_xkb_event_type_t required_events =
  847. (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
  848. XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
  849. XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
  850. xcb_xkb_select_events(
  851. conn,
  852. xkb_x11_get_core_keyboard_device_id(conn),
  853. required_events,
  854. 0,
  855. required_events,
  856. required_map_parts,
  857. required_map_parts,
  858. 0);
  859. /* When we cannot initially load the keymap, we better exit */
  860. if (!load_keymap())
  861. errx(EXIT_FAILURE, "Could not load keymap");
  862. const char *locale = getenv("LC_ALL");
  863. if (!locale || !*locale)
  864. locale = getenv("LC_CTYPE");
  865. if (!locale || !*locale)
  866. locale = getenv("LANG");
  867. if (!locale || !*locale) {
  868. if (debug_mode)
  869. fprintf(stderr, "Can't detect your locale, fallback to C\n");
  870. locale = "C";
  871. }
  872. load_compose_table(locale);
  873. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  874. randr_init(&randr_base, screen->root);
  875. randr_query(screen->root);
  876. last_resolution[0] = screen->width_in_pixels;
  877. last_resolution[1] = screen->height_in_pixels;
  878. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  879. (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
  880. if (image_path) {
  881. /* Create a pixmap to render on, fill it with the background color */
  882. img = cairo_image_surface_create_from_png(image_path);
  883. /* In case loading failed, we just pretend no -i was specified. */
  884. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  885. fprintf(stderr, "Could not load image \"%s\": %s\n",
  886. image_path, cairo_status_to_string(cairo_surface_status(img)));
  887. img = NULL;
  888. }
  889. free(image_path);
  890. }
  891. /* Pixmap on which the image is rendered to (if any) */
  892. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  893. xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
  894. /* Open the fullscreen window, already with the correct pixmap in place */
  895. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  896. xcb_free_pixmap(conn, bg_pixmap);
  897. cursor = create_cursor(conn, screen, win, curs_choice);
  898. /* Display the "locking…" message while trying to grab the pointer/keyboard. */
  899. auth_state = STATE_AUTH_LOCK;
  900. if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
  901. DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
  902. /* Set the focus to i3lock, possibly closing context menus which would
  903. * otherwise prevent us from grabbing keyboard/pointer.
  904. *
  905. * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
  906. * works for managed windows, but i3lock uses an unmanaged window
  907. * (override_redirect=1). */
  908. xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
  909. if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
  910. auth_state = STATE_I3LOCK_LOCK_FAILED;
  911. redraw_screen();
  912. sleep(1);
  913. errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
  914. }
  915. }
  916. pid_t pid = fork();
  917. /* The pid == -1 case is intentionally ignored here:
  918. * While the child process is useful for preventing other windows from
  919. * popping up while i3lock blocks, it is not critical. */
  920. if (pid == 0) {
  921. /* Child */
  922. close(xcb_get_file_descriptor(conn));
  923. maybe_close_sleep_lock_fd();
  924. raise_loop(win);
  925. exit(EXIT_SUCCESS);
  926. }
  927. /* Load the keymap again to sync the current modifier state. Since we first
  928. * loaded the keymap, there might have been changes, but starting from now,
  929. * we should get all key presses/releases due to having grabbed the
  930. * keyboard. */
  931. (void)load_keymap();
  932. /* Initialize the libev event loop. */
  933. main_loop = EV_DEFAULT;
  934. if (main_loop == NULL)
  935. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  936. /* Explicitly call the screen redraw in case "locking…" message was displayed */
  937. auth_state = STATE_AUTH_IDLE;
  938. redraw_screen();
  939. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  940. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  941. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  942. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  943. ev_io_start(main_loop, xcb_watcher);
  944. ev_check_init(xcb_check, xcb_check_cb);
  945. ev_check_start(main_loop, xcb_check);
  946. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  947. ev_prepare_start(main_loop, xcb_prepare);
  948. /* Invoke the event callback once to catch all the events which were
  949. * received up until now. ev will only pick up new events (when the X11
  950. * file descriptor becomes readable). */
  951. ev_invoke(main_loop, xcb_check, 0);
  952. ev_loop(main_loop, 0);
  953. if (stolen_focus == XCB_NONE) {
  954. return 0;
  955. }
  956. DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
  957. xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
  958. xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
  959. xcb_destroy_window(conn, win);
  960. set_focused_window(conn, screen->root, stolen_focus);
  961. xcb_aux_sync(conn);
  962. return 0;
  963. }