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.

915 lines
29 KiB

11 years ago
15 years ago
  1. /*
  2. * vim:ts=4:sw=4:expandtab
  3. *
  4. * © 2010-2013 Michael Stapelberg
  5. *
  6. * See LICENSE for licensing information
  7. *
  8. */
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <pwd.h>
  12. #include <sys/types.h>
  13. #include <string.h>
  14. #include <unistd.h>
  15. #include <stdbool.h>
  16. #include <stdint.h>
  17. #include <xcb/xcb.h>
  18. #include <xcb/xkb.h>
  19. #include <xcb/dpms.h>
  20. #include <err.h>
  21. #include <assert.h>
  22. #include <security/pam_appl.h>
  23. #include <getopt.h>
  24. #include <string.h>
  25. #include <ev.h>
  26. #include <sys/mman.h>
  27. #include <xkbcommon/xkbcommon.h>
  28. #include <xkbcommon/xkbcommon-x11.h>
  29. #include <cairo.h>
  30. #include <cairo/cairo-xcb.h>
  31. #include "i3lock.h"
  32. #include "xcb.h"
  33. #include "cursors.h"
  34. #include "unlock_indicator.h"
  35. #include "xinerama.h"
  36. #define TSTAMP_N_SECS(n) (n * 1.0)
  37. #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
  38. #define START_TIMER(timer_obj, timeout, callback) \
  39. timer_obj = start_timer(timer_obj, timeout, callback)
  40. #define STOP_TIMER(timer_obj) \
  41. timer_obj = stop_timer(timer_obj)
  42. typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
  43. /* We need this for libxkbfile */
  44. char color[7] = "ffffff";
  45. int inactivity_timeout = 30;
  46. uint32_t last_resolution[2];
  47. xcb_window_t win;
  48. static xcb_cursor_t cursor;
  49. static pam_handle_t *pam_handle;
  50. int input_position = 0;
  51. /* Holds the password you enter (in UTF-8). */
  52. static char password[512];
  53. static bool beep = false;
  54. bool debug_mode = false;
  55. static bool dpms = false;
  56. bool unlock_indicator = true;
  57. static bool dont_fork = false;
  58. struct ev_loop *main_loop;
  59. static struct ev_timer *clear_pam_wrong_timeout;
  60. static struct ev_timer *clear_indicator_timeout;
  61. static struct ev_timer *dpms_timeout;
  62. static struct ev_timer *discard_passwd_timeout;
  63. extern unlock_state_t unlock_state;
  64. extern pam_state_t pam_state;
  65. int failed_attempts = 0;
  66. bool show_failed_attempts = false;
  67. static struct xkb_state *xkb_state;
  68. static struct xkb_context *xkb_context;
  69. static struct xkb_keymap *xkb_keymap;
  70. static uint8_t xkb_base_event;
  71. static uint8_t xkb_base_error;
  72. cairo_surface_t *img = NULL;
  73. bool tile = false;
  74. bool ignore_empty_password = false;
  75. bool skip_repeated_empty_password = false;
  76. /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
  77. #define isutf(c) (((c) & 0xC0) != 0x80)
  78. /*
  79. * Decrements i to point to the previous unicode glyph
  80. *
  81. */
  82. void u8_dec(char *s, int *i) {
  83. (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
  84. }
  85. static void turn_monitors_on(void) {
  86. if (dpms)
  87. dpms_set_mode(conn, XCB_DPMS_DPMS_MODE_ON);
  88. }
  89. static void turn_monitors_off(void) {
  90. if (dpms)
  91. dpms_set_mode(conn, XCB_DPMS_DPMS_MODE_OFF);
  92. }
  93. /*
  94. * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
  95. * Necessary so that we can properly let xkbcommon track the keyboard state and
  96. * translate keypresses to utf-8.
  97. *
  98. */
  99. static bool load_keymap(void) {
  100. if (xkb_context == NULL) {
  101. if ((xkb_context = xkb_context_new(0)) == NULL) {
  102. fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
  103. return false;
  104. }
  105. }
  106. xkb_keymap_unref(xkb_keymap);
  107. int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
  108. DEBUG("device = %d\n", device_id);
  109. if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
  110. fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
  111. return false;
  112. }
  113. struct xkb_state *new_state =
  114. xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
  115. if (new_state == NULL) {
  116. fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
  117. return false;
  118. }
  119. xkb_state_unref(xkb_state);
  120. xkb_state = new_state;
  121. return true;
  122. }
  123. /*
  124. * Clears the memory which stored the password to be a bit safer against
  125. * cold-boot attacks.
  126. *
  127. */
  128. static void clear_password_memory(void) {
  129. /* A volatile pointer to the password buffer to prevent the compiler from
  130. * optimizing this out. */
  131. volatile char *vpassword = password;
  132. for (int c = 0; c < sizeof(password); c++)
  133. /* We store a non-random pattern which consists of the (irrelevant)
  134. * index plus (!) the value of the beep variable. This prevents the
  135. * compiler from optimizing the calls away, since the value of 'beep'
  136. * is not known at compile-time. */
  137. vpassword[c] = c + (int)beep;
  138. }
  139. ev_timer* start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
  140. if (timer_obj) {
  141. ev_timer_stop(main_loop, timer_obj);
  142. ev_timer_set(timer_obj, timeout, 0.);
  143. ev_timer_start(main_loop, timer_obj);
  144. } else {
  145. /* When there is no memory, we just don’t have a timeout. We cannot
  146. * exit() here, since that would effectively unlock the screen. */
  147. timer_obj = calloc(sizeof(struct ev_timer), 1);
  148. if (timer_obj) {
  149. ev_timer_init(timer_obj, callback, timeout, 0.);
  150. ev_timer_start(main_loop, timer_obj);
  151. }
  152. }
  153. return timer_obj;
  154. }
  155. ev_timer* stop_timer(ev_timer *timer_obj) {
  156. if (timer_obj) {
  157. ev_timer_stop(main_loop, timer_obj);
  158. free(timer_obj);
  159. }
  160. return NULL;
  161. }
  162. /*
  163. * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccessful
  164. * authentication event.
  165. *
  166. */
  167. static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
  168. DEBUG("clearing pam wrong\n");
  169. pam_state = STATE_PAM_IDLE;
  170. unlock_state = STATE_STARTED;
  171. redraw_screen();
  172. /* Now free this timeout. */
  173. STOP_TIMER(clear_pam_wrong_timeout);
  174. }
  175. static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
  176. clear_indicator();
  177. STOP_TIMER(clear_indicator_timeout);
  178. }
  179. static void clear_input(void) {
  180. input_position = 0;
  181. clear_password_memory();
  182. password[input_position] = '\0';
  183. /* Hide the unlock indicator after a bit if the password buffer is
  184. * empty. */
  185. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  186. unlock_state = STATE_BACKSPACE_ACTIVE;
  187. redraw_screen();
  188. unlock_state = STATE_KEY_PRESSED;
  189. }
  190. static void turn_off_monitors_cb(EV_P_ ev_timer *w, int revents) {
  191. if (input_position == 0)
  192. turn_monitors_off();
  193. STOP_TIMER(dpms_timeout);
  194. }
  195. static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
  196. clear_input();
  197. turn_monitors_off();
  198. STOP_TIMER(discard_passwd_timeout);
  199. }
  200. static void input_done(void) {
  201. STOP_TIMER(clear_pam_wrong_timeout);
  202. pam_state = STATE_PAM_VERIFY;
  203. redraw_screen();
  204. if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
  205. DEBUG("successfully authenticated\n");
  206. clear_password_memory();
  207. /* Turn the screen on, as it may have been turned off
  208. * on release of the 'enter' key. */
  209. turn_monitors_on();
  210. exit(0);
  211. }
  212. if (debug_mode)
  213. fprintf(stderr, "Authentication failure\n");
  214. pam_state = STATE_PAM_WRONG;
  215. failed_attempts += 1;
  216. clear_input();
  217. redraw_screen();
  218. /* Clear this state after 2 seconds (unless the user enters another
  219. * password during that time). */
  220. ev_now_update(main_loop);
  221. START_TIMER(clear_pam_wrong_timeout, TSTAMP_N_SECS(2), clear_pam_wrong);
  222. /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
  223. * too early. */
  224. STOP_TIMER(clear_indicator_timeout);
  225. /* beep on authentication failure, if enabled */
  226. if (beep) {
  227. xcb_bell(conn, 100);
  228. xcb_flush(conn);
  229. }
  230. }
  231. static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
  232. redraw_screen();
  233. STOP_TIMER(w);
  234. }
  235. static bool skip_without_validation(void) {
  236. if (input_position != 0)
  237. return false;
  238. if (skip_repeated_empty_password || ignore_empty_password)
  239. return true;
  240. return false;
  241. }
  242. /*
  243. * Handle key presses. Fixes state, then looks up the key symbol for the
  244. * given keycode, then looks up the key symbol (as UCS-2), converts it to
  245. * UTF-8 and stores it in the password array.
  246. *
  247. */
  248. static void handle_key_press(xcb_key_press_event_t *event) {
  249. xkb_keysym_t ksym;
  250. char buffer[128];
  251. int n;
  252. bool ctrl;
  253. ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
  254. ctrl = xkb_state_mod_name_is_active(xkb_state, "Control", XKB_STATE_MODS_DEPRESSED);
  255. /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
  256. memset(buffer, '\0', sizeof(buffer));
  257. n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
  258. switch (ksym) {
  259. case XKB_KEY_Return:
  260. case XKB_KEY_KP_Enter:
  261. case XKB_KEY_XF86ScreenSaver:
  262. if (pam_state == STATE_PAM_WRONG)
  263. return;
  264. if (skip_without_validation()) {
  265. clear_input();
  266. return;
  267. }
  268. password[input_position] = '\0';
  269. unlock_state = STATE_KEY_PRESSED;
  270. redraw_screen();
  271. input_done();
  272. skip_repeated_empty_password = true;
  273. return;
  274. default:
  275. skip_repeated_empty_password = false;
  276. }
  277. switch (ksym) {
  278. case XKB_KEY_u:
  279. if (ctrl) {
  280. DEBUG("C-u pressed\n");
  281. clear_input();
  282. return;
  283. }
  284. break;
  285. case XKB_KEY_Escape:
  286. clear_input();
  287. return;
  288. case XKB_KEY_BackSpace:
  289. if (input_position == 0)
  290. return;
  291. /* decrement input_position to point to the previous glyph */
  292. u8_dec(password, &input_position);
  293. password[input_position] = '\0';
  294. /* Hide the unlock indicator after a bit if the password buffer is
  295. * empty. */
  296. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  297. unlock_state = STATE_BACKSPACE_ACTIVE;
  298. redraw_screen();
  299. unlock_state = STATE_KEY_PRESSED;
  300. return;
  301. }
  302. if ((input_position + 8) >= sizeof(password))
  303. return;
  304. #if 0
  305. /* FIXME: handle all of these? */
  306. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  307. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  308. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  309. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  310. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  311. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  312. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  313. #endif
  314. if (n < 2)
  315. return;
  316. /* store it in the password array as UTF-8 */
  317. memcpy(password+input_position, buffer, n-1);
  318. input_position += n-1;
  319. DEBUG("current password = %.*s\n", input_position, password);
  320. unlock_state = STATE_KEY_ACTIVE;
  321. redraw_screen();
  322. unlock_state = STATE_KEY_PRESSED;
  323. struct ev_timer *timeout = NULL;
  324. START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
  325. STOP_TIMER(clear_indicator_timeout);
  326. START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
  327. }
  328. /*
  329. * A visibility notify event will be received when the visibility (= can the
  330. * user view the complete window) changes, so for example when a popup overlays
  331. * some area of the i3lock window.
  332. *
  333. * In this case, we raise our window on top so that the popup (or whatever is
  334. * hiding us) gets hidden.
  335. *
  336. */
  337. static void handle_visibility_notify(xcb_connection_t *conn,
  338. xcb_visibility_notify_event_t *event) {
  339. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  340. uint32_t values[] = { XCB_STACK_MODE_ABOVE };
  341. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  342. xcb_flush(conn);
  343. }
  344. }
  345. /*
  346. * Called when the keyboard mapping changes. We update our symbols.
  347. *
  348. * We ignore errors if the new keymap cannot be loaded its better if the
  349. * screen stays locked and the user intervenes by using killall i3lock.
  350. *
  351. */
  352. static void process_xkb_event(xcb_generic_event_t *gevent) {
  353. union xkb_event {
  354. struct {
  355. uint8_t response_type;
  356. uint8_t xkbType;
  357. uint16_t sequence;
  358. xcb_timestamp_t time;
  359. uint8_t deviceID;
  360. } any;
  361. xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
  362. xcb_xkb_map_notify_event_t map_notify;
  363. xcb_xkb_state_notify_event_t state_notify;
  364. } *event = (union xkb_event*)gevent;
  365. DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
  366. if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
  367. return;
  368. /*
  369. * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
  370. * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
  371. * recompilations.
  372. */
  373. switch (event->any.xkbType) {
  374. case XCB_XKB_NEW_KEYBOARD_NOTIFY:
  375. if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
  376. (void)load_keymap();
  377. break;
  378. case XCB_XKB_MAP_NOTIFY:
  379. (void)load_keymap();
  380. break;
  381. case XCB_XKB_STATE_NOTIFY:
  382. xkb_state_update_mask(xkb_state,
  383. event->state_notify.baseMods,
  384. event->state_notify.latchedMods,
  385. event->state_notify.lockedMods,
  386. event->state_notify.baseGroup,
  387. event->state_notify.latchedGroup,
  388. event->state_notify.lockedGroup);
  389. break;
  390. }
  391. }
  392. /*
  393. * Called when the properties on the root window change, e.g. when the screen
  394. * resolution changes. If so we update the window to cover the whole screen
  395. * and also redraw the image, if any.
  396. *
  397. */
  398. void handle_screen_resize(void) {
  399. xcb_get_geometry_cookie_t geomc;
  400. xcb_get_geometry_reply_t *geom;
  401. geomc = xcb_get_geometry(conn, screen->root);
  402. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
  403. return;
  404. if (last_resolution[0] == geom->width &&
  405. last_resolution[1] == geom->height) {
  406. free(geom);
  407. return;
  408. }
  409. last_resolution[0] = geom->width;
  410. last_resolution[1] = geom->height;
  411. free(geom);
  412. redraw_screen();
  413. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  414. xcb_configure_window(conn, win, mask, last_resolution);
  415. xcb_flush(conn);
  416. xinerama_query_screens();
  417. redraw_screen();
  418. }
  419. /*
  420. * Callback function for PAM. We only react on password request callbacks.
  421. *
  422. */
  423. static int conv_callback(int num_msg, const struct pam_message **msg,
  424. struct pam_response **resp, void *appdata_ptr)
  425. {
  426. if (num_msg == 0)
  427. return 1;
  428. /* PAM expects an array of responses, one for each message */
  429. if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
  430. perror("calloc");
  431. return 1;
  432. }
  433. for (int c = 0; c < num_msg; c++) {
  434. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  435. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  436. continue;
  437. /* return code is currently not used but should be set to zero */
  438. resp[c]->resp_retcode = 0;
  439. if ((resp[c]->resp = strdup(password)) == NULL) {
  440. perror("strdup");
  441. return 1;
  442. }
  443. }
  444. return 0;
  445. }
  446. /*
  447. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  448. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  449. *
  450. */
  451. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  452. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  453. }
  454. /*
  455. * Flush before blocking (and waiting for new events)
  456. *
  457. */
  458. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  459. xcb_flush(conn);
  460. }
  461. /*
  462. * Instead of polling the X connection socket we leave this to
  463. * xcb_poll_for_event() which knows better than we can ever know.
  464. *
  465. */
  466. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  467. xcb_generic_event_t *event;
  468. if (xcb_connection_has_error(conn))
  469. errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
  470. while ((event = xcb_poll_for_event(conn)) != NULL) {
  471. if (event->response_type == 0) {
  472. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  473. if (debug_mode)
  474. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  475. error->sequence, error->error_code);
  476. free(event);
  477. continue;
  478. }
  479. /* Strip off the highest bit (set if the event is generated) */
  480. int type = (event->response_type & 0x7F);
  481. switch (type) {
  482. case XCB_KEY_PRESS:
  483. handle_key_press((xcb_key_press_event_t*)event);
  484. break;
  485. case XCB_KEY_RELEASE:
  486. /* If this was the backspace or escape key we are back at an
  487. * empty input, so turn off the screen if DPMS is enabled, but
  488. * only do that after some timeout: maybe user mistyped and
  489. * will type again right away */
  490. START_TIMER(dpms_timeout, TSTAMP_N_SECS(inactivity_timeout),
  491. turn_off_monitors_cb);
  492. break;
  493. case XCB_VISIBILITY_NOTIFY:
  494. handle_visibility_notify(conn, (xcb_visibility_notify_event_t*)event);
  495. break;
  496. case XCB_MAP_NOTIFY:
  497. if (!dont_fork) {
  498. /* After the first MapNotify, we never fork again. We don’t
  499. * expect to get another MapNotify, but better be sure */
  500. dont_fork = true;
  501. /* In the parent process, we exit */
  502. if (fork() != 0)
  503. exit(0);
  504. ev_loop_fork(EV_DEFAULT);
  505. }
  506. break;
  507. case XCB_CONFIGURE_NOTIFY:
  508. handle_screen_resize();
  509. break;
  510. default:
  511. if (type == xkb_base_event)
  512. process_xkb_event(event);
  513. }
  514. free(event);
  515. }
  516. }
  517. /*
  518. * This function is called from a fork()ed child and will raise the i3lock
  519. * window when the window is obscured, even when the main i3lock process is
  520. * blocked due to PAM.
  521. *
  522. */
  523. static void raise_loop(xcb_window_t window) {
  524. xcb_connection_t *conn;
  525. xcb_generic_event_t *event;
  526. int screens;
  527. if ((conn = xcb_connect(NULL, &screens)) == NULL ||
  528. xcb_connection_has_error(conn))
  529. errx(EXIT_FAILURE, "Cannot open display\n");
  530. /* We need to know about the window being obscured or getting destroyed. */
  531. xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
  532. (uint32_t[]){
  533. XCB_EVENT_MASK_VISIBILITY_CHANGE |
  534. XCB_EVENT_MASK_STRUCTURE_NOTIFY
  535. });
  536. xcb_flush(conn);
  537. DEBUG("Watching window 0x%08x\n", window);
  538. while ((event = xcb_wait_for_event(conn)) != NULL) {
  539. if (event->response_type == 0) {
  540. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  541. DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
  542. error->sequence, error->error_code);
  543. free(event);
  544. continue;
  545. }
  546. /* Strip off the highest bit (set if the event is generated) */
  547. int type = (event->response_type & 0x7F);
  548. DEBUG("Read event of type %d\n", type);
  549. switch (type) {
  550. case XCB_VISIBILITY_NOTIFY:
  551. handle_visibility_notify(conn, (xcb_visibility_notify_event_t*)event);
  552. break;
  553. case XCB_UNMAP_NOTIFY:
  554. DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t*)event)->window));
  555. if (((xcb_unmap_notify_event_t*)event)->window == window)
  556. exit(EXIT_SUCCESS);
  557. break;
  558. case XCB_DESTROY_NOTIFY:
  559. DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t*)event)->window));
  560. if (((xcb_destroy_notify_event_t*)event)->window == window)
  561. exit(EXIT_SUCCESS);
  562. break;
  563. default:
  564. DEBUG("Unhandled event type %d\n", type);
  565. break;
  566. }
  567. free(event);
  568. }
  569. }
  570. int main(int argc, char *argv[]) {
  571. struct passwd *pw = getpwuid(getuid());
  572. char *username;
  573. char *image_path = NULL;
  574. int ret;
  575. struct pam_conv conv = {conv_callback, NULL};
  576. int curs_choice = CURS_NONE;
  577. int o;
  578. int optind = 0;
  579. struct option longopts[] = {
  580. {"version", no_argument, NULL, 'v'},
  581. {"nofork", no_argument, NULL, 'n'},
  582. {"beep", no_argument, NULL, 'b'},
  583. {"dpms", no_argument, NULL, 'd'},
  584. {"color", required_argument, NULL, 'c'},
  585. {"pointer", required_argument, NULL , 'p'},
  586. {"debug", no_argument, NULL, 0},
  587. {"help", no_argument, NULL, 'h'},
  588. {"no-unlock-indicator", no_argument, NULL, 'u'},
  589. {"image", required_argument, NULL, 'i'},
  590. {"tiling", no_argument, NULL, 't'},
  591. {"ignore-empty-password", no_argument, NULL, 'e'},
  592. {"inactivity-timeout", required_argument, NULL, 'I'},
  593. {"show-failed-attempts", no_argument, NULL, 'f'},
  594. {NULL, no_argument, NULL, 0}
  595. };
  596. if (pw == NULL)
  597. err(EXIT_FAILURE, "getpwuid() failed");
  598. if ((username = pw->pw_name) == NULL)
  599. errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
  600. char *optstring = "hvnbdc:p:ui:teI:f";
  601. while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
  602. switch (o) {
  603. case 'v':
  604. errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
  605. case 'n':
  606. dont_fork = true;
  607. break;
  608. case 'b':
  609. beep = true;
  610. break;
  611. case 'd':
  612. dpms = true;
  613. break;
  614. case 'I': {
  615. int time = 0;
  616. if (sscanf(optarg, "%d", &time) != 1 || time < 0)
  617. errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
  618. inactivity_timeout = time;
  619. break;
  620. }
  621. case 'c': {
  622. char *arg = optarg;
  623. /* Skip # if present */
  624. if (arg[0] == '#')
  625. arg++;
  626. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  627. errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  628. break;
  629. }
  630. case 'u':
  631. unlock_indicator = false;
  632. break;
  633. case 'i':
  634. image_path = strdup(optarg);
  635. break;
  636. case 't':
  637. tile = true;
  638. break;
  639. case 'p':
  640. if (!strcmp(optarg, "win")) {
  641. curs_choice = CURS_WIN;
  642. } else if (!strcmp(optarg, "default")) {
  643. curs_choice = CURS_DEFAULT;
  644. } else {
  645. errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  646. }
  647. break;
  648. case 'e':
  649. ignore_empty_password = true;
  650. break;
  651. case 0:
  652. if (strcmp(longopts[optind].name, "debug") == 0)
  653. debug_mode = true;
  654. break;
  655. case 'f':
  656. show_failed_attempts = true;
  657. break;
  658. default:
  659. errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  660. " [-i image.png] [-t] [-e] [-I] [-f]"
  661. );
  662. }
  663. }
  664. /* We need (relatively) random numbers for highlighting a random part of
  665. * the unlock indicator upon keypresses. */
  666. srand(time(NULL));
  667. /* Initialize PAM */
  668. ret = pam_start("i3lock", username, &conv, &pam_handle);
  669. if (ret != PAM_SUCCESS)
  670. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  671. /* Using mlock() as non-super-user seems only possible in Linux. Users of other
  672. * operating systems should use encrypted swap/no swap (or remove the ifdef and
  673. * run i3lock as super-user). */
  674. #if defined(__linux__)
  675. /* Lock the area where we store the password in memory, we don’t want it to
  676. * be swapped to disk. Since Linux 2.6.9, this does not require any
  677. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  678. if (mlock(password, sizeof(password)) != 0)
  679. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  680. #endif
  681. /* Double checking that connection is good and operatable with xcb */
  682. int screennr;
  683. if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
  684. xcb_connection_has_error(conn))
  685. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  686. if (xkb_x11_setup_xkb_extension(conn,
  687. XKB_X11_MIN_MAJOR_XKB_VERSION,
  688. XKB_X11_MIN_MINOR_XKB_VERSION,
  689. 0,
  690. NULL,
  691. NULL,
  692. &xkb_base_event,
  693. &xkb_base_error) != 1)
  694. errx(EXIT_FAILURE, "Could not setup XKB extension.");
  695. static const xcb_xkb_map_part_t required_map_parts =
  696. (XCB_XKB_MAP_PART_KEY_TYPES |
  697. XCB_XKB_MAP_PART_KEY_SYMS |
  698. XCB_XKB_MAP_PART_MODIFIER_MAP |
  699. XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
  700. XCB_XKB_MAP_PART_KEY_ACTIONS |
  701. XCB_XKB_MAP_PART_VIRTUAL_MODS |
  702. XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
  703. static const xcb_xkb_event_type_t required_events =
  704. (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
  705. XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
  706. XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
  707. xcb_xkb_select_events(
  708. conn,
  709. xkb_x11_get_core_keyboard_device_id(conn),
  710. required_events,
  711. 0,
  712. required_events,
  713. required_map_parts,
  714. required_map_parts,
  715. 0);
  716. /* When we cannot initially load the keymap, we better exit */
  717. if (!load_keymap())
  718. errx(EXIT_FAILURE, "Could not load keymap");
  719. xinerama_init();
  720. xinerama_query_screens();
  721. /* if DPMS is enabled, check if the X server really supports it */
  722. if (dpms) {
  723. xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
  724. xcb_dpms_capable_reply_t *dpmsr;
  725. if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
  726. if (!dpmsr->capable) {
  727. if (debug_mode)
  728. fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
  729. dpms = false;
  730. }
  731. free(dpmsr);
  732. }
  733. }
  734. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  735. last_resolution[0] = screen->width_in_pixels;
  736. last_resolution[1] = screen->height_in_pixels;
  737. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  738. (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
  739. if (image_path) {
  740. /* Create a pixmap to render on, fill it with the background color */
  741. img = cairo_image_surface_create_from_png(image_path);
  742. /* In case loading failed, we just pretend no -i was specified. */
  743. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  744. fprintf(stderr, "Could not load image \"%s\": %s\n",
  745. image_path, cairo_status_to_string(cairo_surface_status(img)));
  746. img = NULL;
  747. }
  748. }
  749. /* Pixmap on which the image is rendered to (if any) */
  750. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  751. /* open the fullscreen window, already with the correct pixmap in place */
  752. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  753. xcb_free_pixmap(conn, bg_pixmap);
  754. pid_t pid = fork();
  755. /* The pid == -1 case is intentionally ignored here:
  756. * While the child process is useful for preventing other windows from
  757. * popping up while i3lock blocks, it is not critical. */
  758. if (pid == 0) {
  759. /* Child */
  760. close(xcb_get_file_descriptor(conn));
  761. raise_loop(win);
  762. exit(EXIT_SUCCESS);
  763. }
  764. cursor = create_cursor(conn, screen, win, curs_choice);
  765. grab_pointer_and_keyboard(conn, screen, cursor);
  766. /* Load the keymap again to sync the current modifier state. Since we first
  767. * loaded the keymap, there might have been changes, but starting from now,
  768. * we should get all key presses/releases due to having grabbed the
  769. * keyboard. */
  770. (void)load_keymap();
  771. turn_monitors_off();
  772. /* Initialize the libev event loop. */
  773. main_loop = EV_DEFAULT;
  774. if (main_loop == NULL)
  775. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  776. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  777. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  778. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  779. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  780. ev_io_start(main_loop, xcb_watcher);
  781. ev_check_init(xcb_check, xcb_check_cb);
  782. ev_check_start(main_loop, xcb_check);
  783. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  784. ev_prepare_start(main_loop, xcb_prepare);
  785. /* Invoke the event callback once to catch all the events which were
  786. * received up until now. ev will only pick up new events (when the X11
  787. * file descriptor becomes readable). */
  788. ev_invoke(main_loop, xcb_check, 0);
  789. ev_loop(main_loop, 0);
  790. }