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.

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