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.

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