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.

1073 lines
34 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 "i3lock.h"
  39. #include "xcb.h"
  40. #include "cursors.h"
  41. #include "unlock_indicator.h"
  42. #include "xinerama.h"
  43. #define TSTAMP_N_SECS(n) (n * 1.0)
  44. #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
  45. #define START_TIMER(timer_obj, timeout, callback) \
  46. timer_obj = start_timer(timer_obj, timeout, callback)
  47. #define STOP_TIMER(timer_obj) \
  48. timer_obj = stop_timer(timer_obj)
  49. typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
  50. static void input_done(void);
  51. char color[7] = "ffffff";
  52. uint32_t last_resolution[2];
  53. xcb_window_t win;
  54. static xcb_cursor_t cursor;
  55. #ifndef __OpenBSD__
  56. static pam_handle_t *pam_handle;
  57. #endif
  58. int input_position = 0;
  59. /* Holds the password you enter (in UTF-8). */
  60. static char password[512];
  61. static bool beep = false;
  62. bool debug_mode = false;
  63. bool unlock_indicator = true;
  64. char *modifier_string = NULL;
  65. static bool dont_fork = false;
  66. struct ev_loop *main_loop;
  67. static struct ev_timer *clear_auth_wrong_timeout;
  68. static struct ev_timer *clear_indicator_timeout;
  69. static struct ev_timer *discard_passwd_timeout;
  70. extern unlock_state_t unlock_state;
  71. extern auth_state_t auth_state;
  72. int failed_attempts = 0;
  73. bool show_failed_attempts = false;
  74. bool retry_verification = false;
  75. static struct xkb_state *xkb_state;
  76. static struct xkb_context *xkb_context;
  77. static struct xkb_keymap *xkb_keymap;
  78. static struct xkb_compose_table *xkb_compose_table;
  79. static struct xkb_compose_state *xkb_compose_state;
  80. static uint8_t xkb_base_event;
  81. static uint8_t xkb_base_error;
  82. cairo_surface_t *img = NULL;
  83. bool tile = false;
  84. bool ignore_empty_password = false;
  85. bool skip_repeated_empty_password = false;
  86. /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
  87. #define isutf(c) (((c)&0xC0) != 0x80)
  88. /*
  89. * Decrements i to point to the previous unicode glyph
  90. *
  91. */
  92. void u8_dec(char *s, int *i) {
  93. (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
  94. }
  95. /*
  96. * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
  97. * Necessary so that we can properly let xkbcommon track the keyboard state and
  98. * translate keypresses to utf-8.
  99. *
  100. */
  101. static bool load_keymap(void) {
  102. if (xkb_context == NULL) {
  103. if ((xkb_context = xkb_context_new(0)) == NULL) {
  104. fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
  105. return false;
  106. }
  107. }
  108. xkb_keymap_unref(xkb_keymap);
  109. int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
  110. DEBUG("device = %d\n", device_id);
  111. if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
  112. fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
  113. return false;
  114. }
  115. struct xkb_state *new_state =
  116. xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
  117. if (new_state == NULL) {
  118. fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
  119. return false;
  120. }
  121. xkb_state_unref(xkb_state);
  122. xkb_state = new_state;
  123. return true;
  124. }
  125. /*
  126. * Loads the XKB compose table from the given locale.
  127. *
  128. */
  129. static bool load_compose_table(const char *locale) {
  130. xkb_compose_table_unref(xkb_compose_table);
  131. if ((xkb_compose_table = xkb_compose_table_new_from_locale(xkb_context, locale, 0)) == NULL) {
  132. fprintf(stderr, "[i3lock] xkb_compose_table_new_from_locale failed\n");
  133. return false;
  134. }
  135. struct xkb_compose_state *new_compose_state = xkb_compose_state_new(xkb_compose_table, 0);
  136. if (new_compose_state == NULL) {
  137. fprintf(stderr, "[i3lock] xkb_compose_state_new failed\n");
  138. return false;
  139. }
  140. xkb_compose_state_unref(xkb_compose_state);
  141. xkb_compose_state = new_compose_state;
  142. return true;
  143. }
  144. /*
  145. * Clears the memory which stored the password to be a bit safer against
  146. * cold-boot attacks.
  147. *
  148. */
  149. static void clear_password_memory(void) {
  150. #ifdef __OpenBSD__
  151. /* Use explicit_bzero(3) which was explicitly designed not to be
  152. * optimized out by the compiler. */
  153. explicit_bzero(password, strlen(password));
  154. #else
  155. /* A volatile pointer to the password buffer to prevent the compiler from
  156. * optimizing this out. */
  157. volatile char *vpassword = password;
  158. for (int c = 0; c < sizeof(password); c++)
  159. /* We store a non-random pattern which consists of the (irrelevant)
  160. * index plus (!) the value of the beep variable. This prevents the
  161. * compiler from optimizing the calls away, since the value of 'beep'
  162. * is not known at compile-time. */
  163. vpassword[c] = c + (int)beep;
  164. #endif
  165. }
  166. ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
  167. if (timer_obj) {
  168. ev_timer_stop(main_loop, timer_obj);
  169. ev_timer_set(timer_obj, timeout, 0.);
  170. ev_timer_start(main_loop, timer_obj);
  171. } else {
  172. /* When there is no memory, we just don’t have a timeout. We cannot
  173. * exit() here, since that would effectively unlock the screen. */
  174. timer_obj = calloc(sizeof(struct ev_timer), 1);
  175. if (timer_obj) {
  176. ev_timer_init(timer_obj, callback, timeout, 0.);
  177. ev_timer_start(main_loop, timer_obj);
  178. }
  179. }
  180. return timer_obj;
  181. }
  182. ev_timer *stop_timer(ev_timer *timer_obj) {
  183. if (timer_obj) {
  184. ev_timer_stop(main_loop, timer_obj);
  185. free(timer_obj);
  186. }
  187. return NULL;
  188. }
  189. /*
  190. * Neccessary calls after ending input via enter or others
  191. *
  192. */
  193. static void finish_input(void) {
  194. password[input_position] = '\0';
  195. unlock_state = STATE_KEY_PRESSED;
  196. redraw_screen();
  197. input_done();
  198. }
  199. /*
  200. * Resets auth_state to STATE_AUTH_IDLE 2 seconds after an unsuccessful
  201. * authentication event.
  202. *
  203. */
  204. static void clear_auth_wrong(EV_P_ ev_timer *w, int revents) {
  205. DEBUG("clearing auth wrong\n");
  206. auth_state = STATE_AUTH_IDLE;
  207. redraw_screen();
  208. /* Clear modifier string. */
  209. if (modifier_string != NULL) {
  210. free(modifier_string);
  211. modifier_string = NULL;
  212. }
  213. /* Now free this timeout. */
  214. STOP_TIMER(clear_auth_wrong_timeout);
  215. /* retry with input done during auth verification */
  216. if (retry_verification) {
  217. retry_verification = false;
  218. finish_input();
  219. }
  220. }
  221. static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
  222. clear_indicator();
  223. STOP_TIMER(clear_indicator_timeout);
  224. }
  225. static void clear_input(void) {
  226. input_position = 0;
  227. clear_password_memory();
  228. password[input_position] = '\0';
  229. }
  230. static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
  231. clear_input();
  232. STOP_TIMER(discard_passwd_timeout);
  233. }
  234. static void input_done(void) {
  235. STOP_TIMER(clear_auth_wrong_timeout);
  236. auth_state = STATE_AUTH_VERIFY;
  237. unlock_state = STATE_STARTED;
  238. redraw_screen();
  239. #ifdef __OpenBSD__
  240. struct passwd *pw;
  241. if (!(pw = getpwuid(getuid())))
  242. errx(1, "unknown uid %u.", getuid());
  243. if (auth_userokay(pw->pw_name, NULL, NULL, password) != 0) {
  244. DEBUG("successfully authenticated\n");
  245. clear_password_memory();
  246. exit(0);
  247. }
  248. #else
  249. if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
  250. DEBUG("successfully authenticated\n");
  251. clear_password_memory();
  252. /* PAM credentials should be refreshed, this will for example update any kerberos tickets.
  253. * Related to credentials pam_end() needs to be called to cleanup any temporary
  254. * credentials like kerberos /tmp/krb5cc_pam_* files which may of been left behind if the
  255. * refresh of the credentials failed. */
  256. pam_setcred(pam_handle, PAM_REFRESH_CRED);
  257. pam_end(pam_handle, PAM_SUCCESS);
  258. exit(0);
  259. }
  260. #endif
  261. if (debug_mode)
  262. fprintf(stderr, "Authentication failure\n");
  263. /* Get state of Caps and Num lock modifiers, to be displayed in
  264. * STATE_AUTH_WRONG state */
  265. xkb_mod_index_t idx, num_mods;
  266. const char *mod_name;
  267. num_mods = xkb_keymap_num_mods(xkb_keymap);
  268. for (idx = 0; idx < num_mods; idx++) {
  269. if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
  270. continue;
  271. mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
  272. if (mod_name == NULL)
  273. continue;
  274. /* Replace certain xkb names with nicer, human-readable ones. */
  275. if (strcmp(mod_name, XKB_MOD_NAME_CAPS) == 0)
  276. mod_name = "Caps Lock";
  277. else if (strcmp(mod_name, XKB_MOD_NAME_ALT) == 0)
  278. mod_name = "Alt";
  279. else if (strcmp(mod_name, XKB_MOD_NAME_NUM) == 0)
  280. mod_name = "Num Lock";
  281. else if (strcmp(mod_name, XKB_MOD_NAME_LOGO) == 0)
  282. mod_name = "Win";
  283. char *tmp;
  284. if (modifier_string == NULL) {
  285. if (asprintf(&tmp, "%s", mod_name) != -1)
  286. modifier_string = tmp;
  287. } else if (asprintf(&tmp, "%s, %s", modifier_string, mod_name) != -1) {
  288. free(modifier_string);
  289. modifier_string = tmp;
  290. }
  291. }
  292. auth_state = STATE_AUTH_WRONG;
  293. failed_attempts += 1;
  294. clear_input();
  295. if (unlock_indicator)
  296. redraw_screen();
  297. /* Clear this state after 2 seconds (unless the user enters another
  298. * password during that time). */
  299. ev_now_update(main_loop);
  300. START_TIMER(clear_auth_wrong_timeout, TSTAMP_N_SECS(2), clear_auth_wrong);
  301. /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
  302. * too early. */
  303. STOP_TIMER(clear_indicator_timeout);
  304. /* beep on authentication failure, if enabled */
  305. if (beep) {
  306. xcb_bell(conn, 100);
  307. xcb_flush(conn);
  308. }
  309. }
  310. static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
  311. redraw_screen();
  312. STOP_TIMER(w);
  313. }
  314. static bool skip_without_validation(void) {
  315. if (input_position != 0)
  316. return false;
  317. if (skip_repeated_empty_password || ignore_empty_password)
  318. return true;
  319. return false;
  320. }
  321. /*
  322. * Handle key presses. Fixes state, then looks up the key symbol for the
  323. * given keycode, then looks up the key symbol (as UCS-2), converts it to
  324. * UTF-8 and stores it in the password array.
  325. *
  326. */
  327. static void handle_key_press(xcb_key_press_event_t *event) {
  328. xkb_keysym_t ksym;
  329. char buffer[128];
  330. int n;
  331. bool ctrl;
  332. bool composed = false;
  333. ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
  334. ctrl = xkb_state_mod_name_is_active(xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_DEPRESSED);
  335. /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
  336. memset(buffer, '\0', sizeof(buffer));
  337. if (xkb_compose_state && xkb_compose_state_feed(xkb_compose_state, ksym) == XKB_COMPOSE_FEED_ACCEPTED) {
  338. switch (xkb_compose_state_get_status(xkb_compose_state)) {
  339. case XKB_COMPOSE_NOTHING:
  340. break;
  341. case XKB_COMPOSE_COMPOSING:
  342. return;
  343. case XKB_COMPOSE_COMPOSED:
  344. /* xkb_compose_state_get_utf8 doesn't include the terminating byte in the return value
  345. * as xkb_keysym_to_utf8 does. Adding one makes the variable n consistent. */
  346. n = xkb_compose_state_get_utf8(xkb_compose_state, buffer, sizeof(buffer)) + 1;
  347. ksym = xkb_compose_state_get_one_sym(xkb_compose_state);
  348. composed = true;
  349. break;
  350. case XKB_COMPOSE_CANCELLED:
  351. xkb_compose_state_reset(xkb_compose_state);
  352. return;
  353. }
  354. }
  355. if (!composed) {
  356. n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
  357. }
  358. switch (ksym) {
  359. case XKB_KEY_j:
  360. case XKB_KEY_m:
  361. case XKB_KEY_Return:
  362. case XKB_KEY_KP_Enter:
  363. case XKB_KEY_XF86ScreenSaver:
  364. if ((ksym == XKB_KEY_j || ksym == XKB_KEY_m) && !ctrl)
  365. break;
  366. if (auth_state == STATE_AUTH_WRONG) {
  367. retry_verification = true;
  368. return;
  369. }
  370. if (skip_without_validation()) {
  371. clear_input();
  372. return;
  373. }
  374. finish_input();
  375. skip_repeated_empty_password = true;
  376. return;
  377. default:
  378. skip_repeated_empty_password = false;
  379. }
  380. switch (ksym) {
  381. case XKB_KEY_u:
  382. case XKB_KEY_Escape:
  383. if ((ksym == XKB_KEY_u && ctrl) ||
  384. ksym == XKB_KEY_Escape) {
  385. DEBUG("C-u pressed\n");
  386. clear_input();
  387. /* Hide the unlock indicator after a bit if the password buffer is
  388. * empty. */
  389. if (unlock_indicator) {
  390. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  391. unlock_state = STATE_BACKSPACE_ACTIVE;
  392. redraw_screen();
  393. unlock_state = STATE_KEY_PRESSED;
  394. }
  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. xinerama_query_screens();
  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. free(event);
  646. }
  647. }
  648. /*
  649. * This function is called from a fork()ed child and will raise the i3lock
  650. * window when the window is obscured, even when the main i3lock process is
  651. * blocked due to the authentication backend.
  652. *
  653. */
  654. static void raise_loop(xcb_window_t window) {
  655. xcb_connection_t *conn;
  656. xcb_generic_event_t *event;
  657. int screens;
  658. if ((conn = xcb_connect(NULL, &screens)) == NULL ||
  659. xcb_connection_has_error(conn))
  660. errx(EXIT_FAILURE, "Cannot open display\n");
  661. /* We need to know about the window being obscured or getting destroyed. */
  662. xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
  663. (uint32_t[]){
  664. XCB_EVENT_MASK_VISIBILITY_CHANGE |
  665. XCB_EVENT_MASK_STRUCTURE_NOTIFY});
  666. xcb_flush(conn);
  667. DEBUG("Watching window 0x%08x\n", window);
  668. while ((event = xcb_wait_for_event(conn)) != NULL) {
  669. if (event->response_type == 0) {
  670. xcb_generic_error_t *error = (xcb_generic_error_t *)event;
  671. DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
  672. error->sequence, error->error_code);
  673. free(event);
  674. continue;
  675. }
  676. /* Strip off the highest bit (set if the event is generated) */
  677. int type = (event->response_type & 0x7F);
  678. DEBUG("Read event of type %d\n", type);
  679. switch (type) {
  680. case XCB_VISIBILITY_NOTIFY:
  681. handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
  682. break;
  683. case XCB_UNMAP_NOTIFY:
  684. DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
  685. if (((xcb_unmap_notify_event_t *)event)->window == window)
  686. exit(EXIT_SUCCESS);
  687. break;
  688. case XCB_DESTROY_NOTIFY:
  689. DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
  690. if (((xcb_destroy_notify_event_t *)event)->window == window)
  691. exit(EXIT_SUCCESS);
  692. break;
  693. default:
  694. DEBUG("Unhandled event type %d\n", type);
  695. break;
  696. }
  697. free(event);
  698. }
  699. }
  700. int main(int argc, char *argv[]) {
  701. struct passwd *pw;
  702. char *username;
  703. char *image_path = NULL;
  704. #ifndef __OpenBSD__
  705. int ret;
  706. struct pam_conv conv = {conv_callback, NULL};
  707. #endif
  708. int curs_choice = CURS_NONE;
  709. int o;
  710. int longoptind = 0;
  711. struct option longopts[] = {
  712. {"version", no_argument, NULL, 'v'},
  713. {"nofork", no_argument, NULL, 'n'},
  714. {"beep", no_argument, NULL, 'b'},
  715. {"dpms", no_argument, NULL, 'd'},
  716. {"color", required_argument, NULL, 'c'},
  717. {"pointer", required_argument, NULL, 'p'},
  718. {"debug", no_argument, NULL, 0},
  719. {"help", no_argument, NULL, 'h'},
  720. {"no-unlock-indicator", no_argument, NULL, 'u'},
  721. {"image", required_argument, NULL, 'i'},
  722. {"tiling", no_argument, NULL, 't'},
  723. {"ignore-empty-password", no_argument, NULL, 'e'},
  724. {"inactivity-timeout", required_argument, NULL, 'I'},
  725. {"show-failed-attempts", no_argument, NULL, 'f'},
  726. {NULL, no_argument, NULL, 0}};
  727. if ((pw = getpwuid(getuid())) == NULL)
  728. err(EXIT_FAILURE, "getpwuid() failed");
  729. if ((username = pw->pw_name) == NULL)
  730. errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
  731. char *optstring = "hvnbdc:p:ui:teI:f";
  732. while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
  733. switch (o) {
  734. case 'v':
  735. errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg");
  736. case 'n':
  737. dont_fork = true;
  738. break;
  739. case 'b':
  740. beep = true;
  741. break;
  742. case 'd':
  743. fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
  744. break;
  745. case 'I': {
  746. fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
  747. break;
  748. }
  749. case 'c': {
  750. char *arg = optarg;
  751. /* Skip # if present */
  752. if (arg[0] == '#')
  753. arg++;
  754. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  755. errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  756. break;
  757. }
  758. case 'u':
  759. unlock_indicator = false;
  760. break;
  761. case 'i':
  762. image_path = strdup(optarg);
  763. break;
  764. case 't':
  765. tile = true;
  766. break;
  767. case 'p':
  768. if (!strcmp(optarg, "win")) {
  769. curs_choice = CURS_WIN;
  770. } else if (!strcmp(optarg, "default")) {
  771. curs_choice = CURS_DEFAULT;
  772. } else {
  773. errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  774. }
  775. break;
  776. case 'e':
  777. ignore_empty_password = true;
  778. break;
  779. case 0:
  780. if (strcmp(longopts[longoptind].name, "debug") == 0)
  781. debug_mode = true;
  782. break;
  783. case 'f':
  784. show_failed_attempts = true;
  785. break;
  786. default:
  787. errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  788. " [-i image.png] [-t] [-e] [-I timeout] [-f]");
  789. }
  790. }
  791. /* We need (relatively) random numbers for highlighting a random part of
  792. * the unlock indicator upon keypresses. */
  793. srand(time(NULL));
  794. #ifndef __OpenBSD__
  795. /* Initialize PAM */
  796. if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
  797. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  798. if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
  799. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  800. #endif
  801. /* Using mlock() as non-super-user seems only possible in Linux.
  802. * Users of other operating systems should use encrypted swap/no swap
  803. * (or remove the ifdef and run i3lock as super-user).
  804. * Alas, swap is encrypted by default on OpenBSD so swapping out
  805. * is not necessarily an issue. */
  806. #if defined(__linux__)
  807. /* Lock the area where we store the password in memory, we don’t want it to
  808. * be swapped to disk. Since Linux 2.6.9, this does not require any
  809. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  810. if (mlock(password, sizeof(password)) != 0)
  811. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  812. #endif
  813. /* Double checking that connection is good and operatable with xcb */
  814. int screennr;
  815. if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
  816. xcb_connection_has_error(conn))
  817. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  818. if (xkb_x11_setup_xkb_extension(conn,
  819. XKB_X11_MIN_MAJOR_XKB_VERSION,
  820. XKB_X11_MIN_MINOR_XKB_VERSION,
  821. 0,
  822. NULL,
  823. NULL,
  824. &xkb_base_event,
  825. &xkb_base_error) != 1)
  826. errx(EXIT_FAILURE, "Could not setup XKB extension.");
  827. static const xcb_xkb_map_part_t required_map_parts =
  828. (XCB_XKB_MAP_PART_KEY_TYPES |
  829. XCB_XKB_MAP_PART_KEY_SYMS |
  830. XCB_XKB_MAP_PART_MODIFIER_MAP |
  831. XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
  832. XCB_XKB_MAP_PART_KEY_ACTIONS |
  833. XCB_XKB_MAP_PART_VIRTUAL_MODS |
  834. XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
  835. static const xcb_xkb_event_type_t required_events =
  836. (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
  837. XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
  838. XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
  839. xcb_xkb_select_events(
  840. conn,
  841. xkb_x11_get_core_keyboard_device_id(conn),
  842. required_events,
  843. 0,
  844. required_events,
  845. required_map_parts,
  846. required_map_parts,
  847. 0);
  848. /* When we cannot initially load the keymap, we better exit */
  849. if (!load_keymap())
  850. errx(EXIT_FAILURE, "Could not load keymap");
  851. const char *locale = getenv("LC_ALL");
  852. if (!locale || !*locale)
  853. locale = getenv("LC_CTYPE");
  854. if (!locale || !*locale)
  855. locale = getenv("LANG");
  856. if (!locale || !*locale) {
  857. if (debug_mode)
  858. fprintf(stderr, "Can't detect your locale, fallback to C\n");
  859. locale = "C";
  860. }
  861. load_compose_table(locale);
  862. xinerama_init();
  863. xinerama_query_screens();
  864. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  865. last_resolution[0] = screen->width_in_pixels;
  866. last_resolution[1] = screen->height_in_pixels;
  867. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  868. (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
  869. if (image_path) {
  870. /* Create a pixmap to render on, fill it with the background color */
  871. img = cairo_image_surface_create_from_png(image_path);
  872. /* In case loading failed, we just pretend no -i was specified. */
  873. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  874. fprintf(stderr, "Could not load image \"%s\": %s\n",
  875. image_path, cairo_status_to_string(cairo_surface_status(img)));
  876. img = NULL;
  877. }
  878. free(image_path);
  879. }
  880. /* Pixmap on which the image is rendered to (if any) */
  881. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  882. /* Open the fullscreen window, already with the correct pixmap in place */
  883. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  884. xcb_free_pixmap(conn, bg_pixmap);
  885. cursor = create_cursor(conn, screen, win, curs_choice);
  886. /* Display the "locking…" message while trying to grab the pointer/keyboard. */
  887. auth_state = STATE_AUTH_LOCK;
  888. grab_pointer_and_keyboard(conn, screen, cursor);
  889. pid_t pid = fork();
  890. /* The pid == -1 case is intentionally ignored here:
  891. * While the child process is useful for preventing other windows from
  892. * popping up while i3lock blocks, it is not critical. */
  893. if (pid == 0) {
  894. /* Child */
  895. close(xcb_get_file_descriptor(conn));
  896. maybe_close_sleep_lock_fd();
  897. raise_loop(win);
  898. exit(EXIT_SUCCESS);
  899. }
  900. /* Load the keymap again to sync the current modifier state. Since we first
  901. * loaded the keymap, there might have been changes, but starting from now,
  902. * we should get all key presses/releases due to having grabbed the
  903. * keyboard. */
  904. (void)load_keymap();
  905. /* Initialize the libev event loop. */
  906. main_loop = EV_DEFAULT;
  907. if (main_loop == NULL)
  908. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  909. /* Explicitly call the screen redraw in case "locking…" message was displayed */
  910. auth_state = STATE_AUTH_IDLE;
  911. redraw_screen();
  912. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  913. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  914. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  915. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  916. ev_io_start(main_loop, xcb_watcher);
  917. ev_check_init(xcb_check, xcb_check_cb);
  918. ev_check_start(main_loop, xcb_check);
  919. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  920. ev_prepare_start(main_loop, xcb_prepare);
  921. /* Invoke the event callback once to catch all the events which were
  922. * received up until now. ev will only pick up new events (when the X11
  923. * file descriptor becomes readable). */
  924. ev_invoke(main_loop, xcb_check, 0);
  925. ev_loop(main_loop, 0);
  926. }