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.

1155 lines
38 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. // A new password is being entered, but a previous one is pending.
  388. // Discard the old one and clear the retry_verification flag.
  389. if (retry_verification) {
  390. retry_verification = false;
  391. clear_input();
  392. }
  393. }
  394. switch (ksym) {
  395. case XKB_KEY_u:
  396. case XKB_KEY_Escape:
  397. if ((ksym == XKB_KEY_u && ctrl) ||
  398. ksym == XKB_KEY_Escape) {
  399. DEBUG("C-u pressed\n");
  400. clear_input();
  401. /* Also hide the unlock indicator */
  402. if (unlock_indicator)
  403. clear_indicator();
  404. return;
  405. }
  406. break;
  407. case XKB_KEY_Delete:
  408. case XKB_KEY_KP_Delete:
  409. /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
  410. * to move the cursor when entering a password. We need to eat this
  411. * key press so that it wont be treated as part of the password,
  412. * see issue #50. */
  413. return;
  414. case XKB_KEY_h:
  415. case XKB_KEY_BackSpace:
  416. if (ksym == XKB_KEY_h && !ctrl)
  417. break;
  418. if (input_position == 0) {
  419. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  420. unlock_state = STATE_NOTHING_TO_DELETE;
  421. redraw_screen();
  422. return;
  423. }
  424. /* decrement input_position to point to the previous glyph */
  425. u8_dec(password, &input_position);
  426. password[input_position] = '\0';
  427. /* Hide the unlock indicator after a bit if the password buffer is
  428. * empty. */
  429. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  430. unlock_state = STATE_BACKSPACE_ACTIVE;
  431. redraw_screen();
  432. unlock_state = STATE_KEY_PRESSED;
  433. return;
  434. }
  435. if ((input_position + 8) >= (int)sizeof(password))
  436. return;
  437. #if 0
  438. /* FIXME: handle all of these? */
  439. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  440. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  441. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  442. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  443. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  444. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  445. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  446. #endif
  447. if (n < 2)
  448. return;
  449. /* store it in the password array as UTF-8 */
  450. memcpy(password + input_position, buffer, n - 1);
  451. input_position += n - 1;
  452. DEBUG("current password = %.*s\n", input_position, password);
  453. if (unlock_indicator) {
  454. unlock_state = STATE_KEY_ACTIVE;
  455. redraw_screen();
  456. unlock_state = STATE_KEY_PRESSED;
  457. struct ev_timer *timeout = NULL;
  458. START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
  459. STOP_TIMER(clear_indicator_timeout);
  460. }
  461. START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
  462. }
  463. /*
  464. * A visibility notify event will be received when the visibility (= can the
  465. * user view the complete window) changes, so for example when a popup overlays
  466. * some area of the i3lock window.
  467. *
  468. * In this case, we raise our window on top so that the popup (or whatever is
  469. * hiding us) gets hidden.
  470. *
  471. */
  472. static void handle_visibility_notify(xcb_connection_t *conn,
  473. xcb_visibility_notify_event_t *event) {
  474. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  475. uint32_t values[] = {XCB_STACK_MODE_ABOVE};
  476. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  477. xcb_flush(conn);
  478. }
  479. }
  480. /*
  481. * Called when the keyboard mapping changes. We update our symbols.
  482. *
  483. * We ignore errors if the new keymap cannot be loaded its better if the
  484. * screen stays locked and the user intervenes by using killall i3lock.
  485. *
  486. */
  487. static void process_xkb_event(xcb_generic_event_t *gevent) {
  488. union xkb_event {
  489. struct {
  490. uint8_t response_type;
  491. uint8_t xkbType;
  492. uint16_t sequence;
  493. xcb_timestamp_t time;
  494. uint8_t deviceID;
  495. } any;
  496. xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
  497. xcb_xkb_map_notify_event_t map_notify;
  498. xcb_xkb_state_notify_event_t state_notify;
  499. } *event = (union xkb_event *)gevent;
  500. DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
  501. if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
  502. return;
  503. /*
  504. * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
  505. * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
  506. * recompilations.
  507. */
  508. switch (event->any.xkbType) {
  509. case XCB_XKB_NEW_KEYBOARD_NOTIFY:
  510. if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
  511. (void)load_keymap();
  512. break;
  513. case XCB_XKB_MAP_NOTIFY:
  514. (void)load_keymap();
  515. break;
  516. case XCB_XKB_STATE_NOTIFY:
  517. xkb_state_update_mask(xkb_state,
  518. event->state_notify.baseMods,
  519. event->state_notify.latchedMods,
  520. event->state_notify.lockedMods,
  521. event->state_notify.baseGroup,
  522. event->state_notify.latchedGroup,
  523. event->state_notify.lockedGroup);
  524. break;
  525. }
  526. }
  527. /*
  528. * Called when the properties on the root window change, e.g. when the screen
  529. * resolution changes. If so we update the window to cover the whole screen
  530. * and also redraw the image, if any.
  531. *
  532. */
  533. void handle_screen_resize(void) {
  534. xcb_get_geometry_cookie_t geomc;
  535. xcb_get_geometry_reply_t *geom;
  536. geomc = xcb_get_geometry(conn, screen->root);
  537. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
  538. return;
  539. if (last_resolution[0] == geom->width &&
  540. last_resolution[1] == geom->height) {
  541. free(geom);
  542. return;
  543. }
  544. last_resolution[0] = geom->width;
  545. last_resolution[1] = geom->height;
  546. free(geom);
  547. redraw_screen();
  548. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  549. xcb_configure_window(conn, win, mask, last_resolution);
  550. xcb_flush(conn);
  551. randr_query(screen->root);
  552. redraw_screen();
  553. }
  554. static bool verify_png_image(const char *image_path) {
  555. if (!image_path) {
  556. return false;
  557. }
  558. /* Check file exists and has correct PNG header */
  559. FILE *png_file = fopen(image_path, "r");
  560. if (png_file == NULL) {
  561. fprintf(stderr, "Image file path \"%s\" cannot be opened: %s\n", image_path, strerror(errno));
  562. return false;
  563. }
  564. unsigned char png_header[8];
  565. memset(png_header, '\0', sizeof(png_header));
  566. int bytes_read = fread(png_header, 1, sizeof(png_header), png_file);
  567. fclose(png_file);
  568. if (bytes_read != sizeof(png_header)) {
  569. fprintf(stderr, "Could not read PNG header from \"%s\"\n", image_path);
  570. return false;
  571. }
  572. // Check PNG header according to the specification, available at:
  573. // https://www.w3.org/TR/2003/REC-PNG-20031110/#5PNG-file-signature
  574. static unsigned char PNG_REFERENCE_HEADER[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  575. if (memcmp(PNG_REFERENCE_HEADER, png_header, sizeof(png_header)) != 0) {
  576. fprintf(stderr, "File \"%s\" does not start with a PNG header. i3lock currently only supports loading PNG files.\n", image_path);
  577. return false;
  578. }
  579. return true;
  580. }
  581. #ifndef __OpenBSD__
  582. /*
  583. * Callback function for PAM. We only react on password request callbacks.
  584. *
  585. */
  586. static int conv_callback(int num_msg, const struct pam_message **msg,
  587. struct pam_response **resp, void *appdata_ptr) {
  588. if (num_msg == 0)
  589. return 1;
  590. /* PAM expects an array of responses, one for each message */
  591. if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
  592. perror("calloc");
  593. return 1;
  594. }
  595. for (int c = 0; c < num_msg; c++) {
  596. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  597. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  598. continue;
  599. /* return code is currently not used but should be set to zero */
  600. resp[c]->resp_retcode = 0;
  601. if ((resp[c]->resp = strdup(password)) == NULL) {
  602. perror("strdup");
  603. return 1;
  604. }
  605. }
  606. return 0;
  607. }
  608. #endif
  609. /*
  610. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  611. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  612. *
  613. */
  614. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  615. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  616. }
  617. /*
  618. * Flush before blocking (and waiting for new events)
  619. *
  620. */
  621. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  622. xcb_flush(conn);
  623. }
  624. /*
  625. * Try closing logind sleep lock fd passed over from xss-lock, in case we're
  626. * being run from there.
  627. *
  628. */
  629. static void maybe_close_sleep_lock_fd(void) {
  630. const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
  631. char *endptr;
  632. if (sleep_lock_fd && *sleep_lock_fd != 0) {
  633. long int fd = strtol(sleep_lock_fd, &endptr, 10);
  634. if (*endptr == 0) {
  635. close(fd);
  636. }
  637. }
  638. }
  639. /*
  640. * Instead of polling the X connection socket we leave this to
  641. * xcb_poll_for_event() which knows better than we can ever know.
  642. *
  643. */
  644. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  645. xcb_generic_event_t *event;
  646. if (xcb_connection_has_error(conn))
  647. errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
  648. while ((event = xcb_poll_for_event(conn)) != NULL) {
  649. if (event->response_type == 0) {
  650. xcb_generic_error_t *error = (xcb_generic_error_t *)event;
  651. if (debug_mode)
  652. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  653. error->sequence, error->error_code);
  654. free(event);
  655. continue;
  656. }
  657. /* Strip off the highest bit (set if the event is generated) */
  658. int type = (event->response_type & 0x7F);
  659. switch (type) {
  660. case XCB_KEY_PRESS:
  661. handle_key_press((xcb_key_press_event_t *)event);
  662. break;
  663. case XCB_VISIBILITY_NOTIFY:
  664. handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
  665. break;
  666. case XCB_MAP_NOTIFY:
  667. maybe_close_sleep_lock_fd();
  668. if (!dont_fork) {
  669. /* After the first MapNotify, we never fork again. We don’t
  670. * expect to get another MapNotify, but better be sure */
  671. dont_fork = true;
  672. /* In the parent process, we exit */
  673. if (fork() != 0)
  674. exit(0);
  675. ev_loop_fork(EV_DEFAULT);
  676. }
  677. break;
  678. case XCB_CONFIGURE_NOTIFY:
  679. handle_screen_resize();
  680. break;
  681. default:
  682. if (type == xkb_base_event) {
  683. process_xkb_event(event);
  684. }
  685. if (randr_base > -1 &&
  686. type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
  687. randr_query(screen->root);
  688. handle_screen_resize();
  689. }
  690. }
  691. free(event);
  692. }
  693. }
  694. /*
  695. * This function is called from a fork()ed child and will raise the i3lock
  696. * window when the window is obscured, even when the main i3lock process is
  697. * blocked due to the authentication backend.
  698. *
  699. */
  700. static void raise_loop(xcb_window_t window) {
  701. xcb_connection_t *conn;
  702. xcb_generic_event_t *event;
  703. int screens;
  704. if (xcb_connection_has_error((conn = xcb_connect(NULL, &screens))) > 0)
  705. errx(EXIT_FAILURE, "Cannot open display\n");
  706. /* We need to know about the window being obscured or getting destroyed. */
  707. xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
  708. (uint32_t[]){
  709. XCB_EVENT_MASK_VISIBILITY_CHANGE |
  710. XCB_EVENT_MASK_STRUCTURE_NOTIFY});
  711. xcb_flush(conn);
  712. DEBUG("Watching window 0x%08x\n", window);
  713. while ((event = xcb_wait_for_event(conn)) != NULL) {
  714. if (event->response_type == 0) {
  715. xcb_generic_error_t *error = (xcb_generic_error_t *)event;
  716. DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
  717. error->sequence, error->error_code);
  718. free(event);
  719. continue;
  720. }
  721. /* Strip off the highest bit (set if the event is generated) */
  722. int type = (event->response_type & 0x7F);
  723. DEBUG("Read event of type %d\n", type);
  724. switch (type) {
  725. case XCB_VISIBILITY_NOTIFY:
  726. handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
  727. break;
  728. case XCB_UNMAP_NOTIFY:
  729. DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
  730. if (((xcb_unmap_notify_event_t *)event)->window == window)
  731. exit(EXIT_SUCCESS);
  732. break;
  733. case XCB_DESTROY_NOTIFY:
  734. DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
  735. if (((xcb_destroy_notify_event_t *)event)->window == window)
  736. exit(EXIT_SUCCESS);
  737. break;
  738. default:
  739. DEBUG("Unhandled event type %d\n", type);
  740. break;
  741. }
  742. free(event);
  743. }
  744. }
  745. int main(int argc, char *argv[]) {
  746. struct passwd *pw;
  747. char *username;
  748. char *image_path = NULL;
  749. #ifndef __OpenBSD__
  750. int ret;
  751. struct pam_conv conv = {conv_callback, NULL};
  752. #endif
  753. int curs_choice = CURS_NONE;
  754. int o;
  755. int longoptind = 0;
  756. struct option longopts[] = {
  757. {"version", no_argument, NULL, 'v'},
  758. {"nofork", no_argument, NULL, 'n'},
  759. {"beep", no_argument, NULL, 'b'},
  760. {"dpms", no_argument, NULL, 'd'},
  761. {"color", required_argument, NULL, 'c'},
  762. {"pointer", required_argument, NULL, 'p'},
  763. {"debug", no_argument, NULL, 0},
  764. {"help", no_argument, NULL, 'h'},
  765. {"no-unlock-indicator", no_argument, NULL, 'u'},
  766. {"image", required_argument, NULL, 'i'},
  767. {"tiling", no_argument, NULL, 't'},
  768. {"ignore-empty-password", no_argument, NULL, 'e'},
  769. {"inactivity-timeout", required_argument, NULL, 'I'},
  770. {"show-failed-attempts", no_argument, NULL, 'f'},
  771. {NULL, no_argument, NULL, 0}};
  772. if ((pw = getpwuid(getuid())) == NULL)
  773. err(EXIT_FAILURE, "getpwuid() failed");
  774. if ((username = pw->pw_name) == NULL)
  775. errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
  776. char *optstring = "hvnbdc:p:ui:teI:f";
  777. while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
  778. switch (o) {
  779. case 'v':
  780. errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
  781. case 'n':
  782. dont_fork = true;
  783. break;
  784. case 'b':
  785. beep = true;
  786. break;
  787. case 'd':
  788. fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
  789. break;
  790. case 'I': {
  791. fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
  792. break;
  793. }
  794. case 'c': {
  795. char *arg = optarg;
  796. /* Skip # if present */
  797. if (arg[0] == '#')
  798. arg++;
  799. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  800. errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  801. break;
  802. }
  803. case 'u':
  804. unlock_indicator = false;
  805. break;
  806. case 'i':
  807. image_path = strdup(optarg);
  808. break;
  809. case 't':
  810. tile = true;
  811. break;
  812. case 'p':
  813. if (!strcmp(optarg, "win")) {
  814. curs_choice = CURS_WIN;
  815. } else if (!strcmp(optarg, "default")) {
  816. curs_choice = CURS_DEFAULT;
  817. } else {
  818. errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  819. }
  820. break;
  821. case 'e':
  822. ignore_empty_password = true;
  823. break;
  824. case 0:
  825. if (strcmp(longopts[longoptind].name, "debug") == 0)
  826. debug_mode = true;
  827. break;
  828. case 'f':
  829. show_failed_attempts = true;
  830. break;
  831. default:
  832. errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  833. " [-i image.png] [-t] [-e] [-I timeout] [-f]");
  834. }
  835. }
  836. /* We need (relatively) random numbers for highlighting a random part of
  837. * the unlock indicator upon keypresses. */
  838. srand(time(NULL));
  839. #ifndef __OpenBSD__
  840. /* Initialize PAM */
  841. if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
  842. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  843. if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
  844. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  845. #endif
  846. /* Using mlock() as non-super-user seems only possible in Linux.
  847. * Users of other operating systems should use encrypted swap/no swap
  848. * (or remove the ifdef and run i3lock as super-user).
  849. * Alas, swap is encrypted by default on OpenBSD so swapping out
  850. * is not necessarily an issue. */
  851. #if defined(__linux__)
  852. /* Lock the area where we store the password in memory, we don’t want it to
  853. * be swapped to disk. Since Linux 2.6.9, this does not require any
  854. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  855. if (mlock(password, sizeof(password)) != 0)
  856. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  857. #endif
  858. /* Double checking that connection is good and operatable with xcb */
  859. int screennr;
  860. if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
  861. xcb_connection_has_error(conn))
  862. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  863. if (xkb_x11_setup_xkb_extension(conn,
  864. XKB_X11_MIN_MAJOR_XKB_VERSION,
  865. XKB_X11_MIN_MINOR_XKB_VERSION,
  866. 0,
  867. NULL,
  868. NULL,
  869. &xkb_base_event,
  870. &xkb_base_error) != 1)
  871. errx(EXIT_FAILURE, "Could not setup XKB extension.");
  872. static const xcb_xkb_map_part_t required_map_parts =
  873. (XCB_XKB_MAP_PART_KEY_TYPES |
  874. XCB_XKB_MAP_PART_KEY_SYMS |
  875. XCB_XKB_MAP_PART_MODIFIER_MAP |
  876. XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
  877. XCB_XKB_MAP_PART_KEY_ACTIONS |
  878. XCB_XKB_MAP_PART_VIRTUAL_MODS |
  879. XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
  880. static const xcb_xkb_event_type_t required_events =
  881. (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
  882. XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
  883. XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
  884. xcb_xkb_select_events(
  885. conn,
  886. xkb_x11_get_core_keyboard_device_id(conn),
  887. required_events,
  888. 0,
  889. required_events,
  890. required_map_parts,
  891. required_map_parts,
  892. 0);
  893. /* When we cannot initially load the keymap, we better exit */
  894. if (!load_keymap())
  895. errx(EXIT_FAILURE, "Could not load keymap");
  896. const char *locale = getenv("LC_ALL");
  897. if (!locale || !*locale)
  898. locale = getenv("LC_CTYPE");
  899. if (!locale || !*locale)
  900. locale = getenv("LANG");
  901. if (!locale || !*locale) {
  902. if (debug_mode)
  903. fprintf(stderr, "Can't detect your locale, fallback to C\n");
  904. locale = "C";
  905. }
  906. load_compose_table(locale);
  907. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  908. init_dpi();
  909. randr_init(&randr_base, screen->root);
  910. randr_query(screen->root);
  911. last_resolution[0] = screen->width_in_pixels;
  912. last_resolution[1] = screen->height_in_pixels;
  913. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  914. (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
  915. if (verify_png_image(image_path)) {
  916. /* Create a pixmap to render on, fill it with the background color */
  917. img = cairo_image_surface_create_from_png(image_path);
  918. /* In case loading failed, we just pretend no -i was specified. */
  919. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  920. fprintf(stderr, "Could not load image \"%s\": %s\n",
  921. image_path, cairo_status_to_string(cairo_surface_status(img)));
  922. img = NULL;
  923. }
  924. }
  925. free(image_path);
  926. /* Pixmap on which the image is rendered to (if any) */
  927. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  928. xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
  929. /* Open the fullscreen window, already with the correct pixmap in place */
  930. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  931. xcb_free_pixmap(conn, bg_pixmap);
  932. cursor = create_cursor(conn, screen, win, curs_choice);
  933. /* Display the "locking…" message while trying to grab the pointer/keyboard. */
  934. auth_state = STATE_AUTH_LOCK;
  935. if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
  936. DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
  937. /* Set the focus to i3lock, possibly closing context menus which would
  938. * otherwise prevent us from grabbing keyboard/pointer.
  939. *
  940. * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
  941. * works for managed windows, but i3lock uses an unmanaged window
  942. * (override_redirect=1). */
  943. xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
  944. if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
  945. auth_state = STATE_I3LOCK_LOCK_FAILED;
  946. redraw_screen();
  947. sleep(1);
  948. errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
  949. }
  950. }
  951. pid_t pid = fork();
  952. /* The pid == -1 case is intentionally ignored here:
  953. * While the child process is useful for preventing other windows from
  954. * popping up while i3lock blocks, it is not critical. */
  955. if (pid == 0) {
  956. /* Child */
  957. close(xcb_get_file_descriptor(conn));
  958. maybe_close_sleep_lock_fd();
  959. raise_loop(win);
  960. exit(EXIT_SUCCESS);
  961. }
  962. /* Load the keymap again to sync the current modifier state. Since we first
  963. * loaded the keymap, there might have been changes, but starting from now,
  964. * we should get all key presses/releases due to having grabbed the
  965. * keyboard. */
  966. (void)load_keymap();
  967. /* Initialize the libev event loop. */
  968. main_loop = EV_DEFAULT;
  969. if (main_loop == NULL)
  970. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  971. /* Explicitly call the screen redraw in case "locking…" message was displayed */
  972. auth_state = STATE_AUTH_IDLE;
  973. redraw_screen();
  974. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  975. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  976. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  977. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  978. ev_io_start(main_loop, xcb_watcher);
  979. ev_check_init(xcb_check, xcb_check_cb);
  980. ev_check_start(main_loop, xcb_check);
  981. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  982. ev_prepare_start(main_loop, xcb_prepare);
  983. /* Invoke the event callback once to catch all the events which were
  984. * received up until now. ev will only pick up new events (when the X11
  985. * file descriptor becomes readable). */
  986. ev_invoke(main_loop, xcb_check, 0);
  987. ev_loop(main_loop, 0);
  988. if (stolen_focus == XCB_NONE) {
  989. return 0;
  990. }
  991. DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
  992. xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
  993. xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
  994. xcb_destroy_window(conn, win);
  995. set_focused_window(conn, screen->root, stolen_focus);
  996. xcb_aux_sync(conn);
  997. return 0;
  998. }