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.

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