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.

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