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.

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