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.

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