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.

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