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.

1205 lines
39 KiB

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