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.

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