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.

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