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.

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