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.

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