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.

1009 lines
33 KiB

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