987 lines
32 KiB

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