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.

897 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. static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
  227. redraw_screen();
  228. STOP_TIMER(w);
  229. }
  230. static bool skip_without_validation(void) {
  231. if (input_position != 0)
  232. return false;
  233. if (skip_repeated_empty_password || ignore_empty_password)
  234. return true;
  235. return false;
  236. }
  237. /*
  238. * Handle key presses. Fixes state, then looks up the key symbol for the
  239. * given keycode, then looks up the key symbol (as UCS-2), converts it to
  240. * UTF-8 and stores it in the password array.
  241. *
  242. */
  243. static void handle_key_press(xcb_key_press_event_t *event) {
  244. xkb_keysym_t ksym;
  245. char buffer[128];
  246. int n;
  247. bool ctrl;
  248. ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
  249. ctrl = xkb_state_mod_name_is_active(xkb_state, "Control", XKB_STATE_MODS_DEPRESSED);
  250. /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
  251. memset(buffer, '\0', sizeof(buffer));
  252. n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
  253. switch (ksym) {
  254. case XKB_KEY_Return:
  255. case XKB_KEY_KP_Enter:
  256. case XKB_KEY_XF86ScreenSaver:
  257. if (skip_without_validation()) {
  258. clear_input();
  259. return;
  260. }
  261. password[input_position] = '\0';
  262. unlock_state = STATE_KEY_PRESSED;
  263. redraw_screen();
  264. input_done();
  265. skip_repeated_empty_password = true;
  266. return;
  267. default:
  268. skip_repeated_empty_password = false;
  269. }
  270. switch (ksym) {
  271. case XKB_KEY_u:
  272. if (ctrl) {
  273. DEBUG("C-u pressed\n");
  274. clear_input();
  275. return;
  276. }
  277. break;
  278. case XKB_KEY_Escape:
  279. clear_input();
  280. return;
  281. case XKB_KEY_BackSpace:
  282. if (input_position == 0)
  283. return;
  284. /* decrement input_position to point to the previous glyph */
  285. u8_dec(password, &input_position);
  286. password[input_position] = '\0';
  287. /* Hide the unlock indicator after a bit if the password buffer is
  288. * empty. */
  289. START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
  290. unlock_state = STATE_BACKSPACE_ACTIVE;
  291. redraw_screen();
  292. unlock_state = STATE_KEY_PRESSED;
  293. return;
  294. }
  295. if ((input_position + 8) >= sizeof(password))
  296. return;
  297. #if 0
  298. /* FIXME: handle all of these? */
  299. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  300. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  301. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  302. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  303. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  304. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  305. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  306. #endif
  307. if (n < 2)
  308. return;
  309. /* store it in the password array as UTF-8 */
  310. memcpy(password+input_position, buffer, n-1);
  311. input_position += n-1;
  312. DEBUG("current password = %.*s\n", input_position, password);
  313. unlock_state = STATE_KEY_ACTIVE;
  314. redraw_screen();
  315. unlock_state = STATE_KEY_PRESSED;
  316. struct ev_timer *timeout = NULL;
  317. START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
  318. STOP_TIMER(clear_indicator_timeout);
  319. START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
  320. }
  321. /*
  322. * A visibility notify event will be received when the visibility (= can the
  323. * user view the complete window) changes, so for example when a popup overlays
  324. * some area of the i3lock window.
  325. *
  326. * In this case, we raise our window on top so that the popup (or whatever is
  327. * hiding us) gets hidden.
  328. *
  329. */
  330. static void handle_visibility_notify(xcb_connection_t *conn,
  331. xcb_visibility_notify_event_t *event) {
  332. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  333. uint32_t values[] = { XCB_STACK_MODE_ABOVE };
  334. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  335. xcb_flush(conn);
  336. }
  337. }
  338. /*
  339. * Called when the keyboard mapping changes. We update our symbols.
  340. *
  341. * We ignore errors if the new keymap cannot be loaded its better if the
  342. * screen stays locked and the user intervenes by using killall i3lock.
  343. *
  344. */
  345. static void process_xkb_event(xcb_generic_event_t *gevent) {
  346. union xkb_event {
  347. struct {
  348. uint8_t response_type;
  349. uint8_t xkbType;
  350. uint16_t sequence;
  351. xcb_timestamp_t time;
  352. uint8_t deviceID;
  353. } any;
  354. xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
  355. xcb_xkb_map_notify_event_t map_notify;
  356. xcb_xkb_state_notify_event_t state_notify;
  357. } *event = (union xkb_event*)gevent;
  358. DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
  359. if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
  360. return;
  361. /*
  362. * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
  363. * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
  364. * recompilations.
  365. */
  366. switch (event->any.xkbType) {
  367. case XCB_XKB_NEW_KEYBOARD_NOTIFY:
  368. if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
  369. (void)load_keymap();
  370. break;
  371. case XCB_XKB_MAP_NOTIFY:
  372. (void)load_keymap();
  373. break;
  374. case XCB_XKB_STATE_NOTIFY:
  375. xkb_state_update_mask(xkb_state,
  376. event->state_notify.baseMods,
  377. event->state_notify.latchedMods,
  378. event->state_notify.lockedMods,
  379. event->state_notify.baseGroup,
  380. event->state_notify.latchedGroup,
  381. event->state_notify.lockedGroup);
  382. break;
  383. }
  384. }
  385. /*
  386. * Called when the properties on the root window change, e.g. when the screen
  387. * resolution changes. If so we update the window to cover the whole screen
  388. * and also redraw the image, if any.
  389. *
  390. */
  391. void handle_screen_resize(void) {
  392. xcb_get_geometry_cookie_t geomc;
  393. xcb_get_geometry_reply_t *geom;
  394. geomc = xcb_get_geometry(conn, screen->root);
  395. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
  396. return;
  397. if (last_resolution[0] == geom->width &&
  398. last_resolution[1] == geom->height) {
  399. free(geom);
  400. return;
  401. }
  402. last_resolution[0] = geom->width;
  403. last_resolution[1] = geom->height;
  404. free(geom);
  405. redraw_screen();
  406. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  407. xcb_configure_window(conn, win, mask, last_resolution);
  408. xcb_flush(conn);
  409. xinerama_query_screens();
  410. redraw_screen();
  411. }
  412. /*
  413. * Callback function for PAM. We only react on password request callbacks.
  414. *
  415. */
  416. static int conv_callback(int num_msg, const struct pam_message **msg,
  417. struct pam_response **resp, void *appdata_ptr)
  418. {
  419. if (num_msg == 0)
  420. return 1;
  421. /* PAM expects an array of responses, one for each message */
  422. if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
  423. perror("calloc");
  424. return 1;
  425. }
  426. for (int c = 0; c < num_msg; c++) {
  427. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  428. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  429. continue;
  430. /* return code is currently not used but should be set to zero */
  431. resp[c]->resp_retcode = 0;
  432. if ((resp[c]->resp = strdup(password)) == NULL) {
  433. perror("strdup");
  434. return 1;
  435. }
  436. }
  437. return 0;
  438. }
  439. /*
  440. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  441. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  442. *
  443. */
  444. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  445. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  446. }
  447. /*
  448. * Flush before blocking (and waiting for new events)
  449. *
  450. */
  451. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  452. xcb_flush(conn);
  453. }
  454. /*
  455. * Instead of polling the X connection socket we leave this to
  456. * xcb_poll_for_event() which knows better than we can ever know.
  457. *
  458. */
  459. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  460. xcb_generic_event_t *event;
  461. while ((event = xcb_poll_for_event(conn)) != NULL) {
  462. if (event->response_type == 0) {
  463. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  464. if (debug_mode)
  465. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  466. error->sequence, error->error_code);
  467. free(event);
  468. continue;
  469. }
  470. /* Strip off the highest bit (set if the event is generated) */
  471. int type = (event->response_type & 0x7F);
  472. switch (type) {
  473. case XCB_KEY_PRESS:
  474. handle_key_press((xcb_key_press_event_t*)event);
  475. break;
  476. case XCB_KEY_RELEASE:
  477. /* If this was the backspace or escape key we are back at an
  478. * empty input, so turn off the screen if DPMS is enabled, but
  479. * only do that after some timeout: maybe user mistyped and
  480. * will type again right away */
  481. START_TIMER(dpms_timeout, TSTAMP_N_SECS(inactivity_timeout),
  482. turn_off_monitors_cb);
  483. break;
  484. case XCB_VISIBILITY_NOTIFY:
  485. handle_visibility_notify(conn, (xcb_visibility_notify_event_t*)event);
  486. break;
  487. case XCB_MAP_NOTIFY:
  488. if (!dont_fork) {
  489. /* After the first MapNotify, we never fork again. We don’t
  490. * expect to get another MapNotify, but better be sure */
  491. dont_fork = true;
  492. /* In the parent process, we exit */
  493. if (fork() != 0)
  494. exit(0);
  495. ev_loop_fork(EV_DEFAULT);
  496. }
  497. break;
  498. case XCB_CONFIGURE_NOTIFY:
  499. handle_screen_resize();
  500. break;
  501. default:
  502. if (type == xkb_base_event)
  503. process_xkb_event(event);
  504. }
  505. free(event);
  506. }
  507. }
  508. /*
  509. * This function is called from a fork()ed child and will raise the i3lock
  510. * window when the window is obscured, even when the main i3lock process is
  511. * blocked due to PAM.
  512. *
  513. */
  514. static void raise_loop(xcb_window_t window) {
  515. xcb_connection_t *conn;
  516. xcb_generic_event_t *event;
  517. int screens;
  518. if ((conn = xcb_connect(NULL, &screens)) == NULL ||
  519. xcb_connection_has_error(conn))
  520. errx(EXIT_FAILURE, "Cannot open display\n");
  521. /* We need to know about the window being obscured or getting destroyed. */
  522. xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
  523. (uint32_t[]){
  524. XCB_EVENT_MASK_VISIBILITY_CHANGE |
  525. XCB_EVENT_MASK_STRUCTURE_NOTIFY
  526. });
  527. xcb_flush(conn);
  528. DEBUG("Watching window 0x%08x\n", window);
  529. while ((event = xcb_wait_for_event(conn)) != NULL) {
  530. if (event->response_type == 0) {
  531. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  532. DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
  533. error->sequence, error->error_code);
  534. free(event);
  535. continue;
  536. }
  537. /* Strip off the highest bit (set if the event is generated) */
  538. int type = (event->response_type & 0x7F);
  539. DEBUG("Read event of type %d\n", type);
  540. switch (type) {
  541. case XCB_VISIBILITY_NOTIFY:
  542. handle_visibility_notify(conn, (xcb_visibility_notify_event_t*)event);
  543. break;
  544. case XCB_UNMAP_NOTIFY:
  545. DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t*)event)->window));
  546. if (((xcb_unmap_notify_event_t*)event)->window == window)
  547. exit(EXIT_SUCCESS);
  548. break;
  549. case XCB_DESTROY_NOTIFY:
  550. DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t*)event)->window));
  551. if (((xcb_destroy_notify_event_t*)event)->window == window)
  552. exit(EXIT_SUCCESS);
  553. break;
  554. default:
  555. DEBUG("Unhandled event type %d\n", type);
  556. break;
  557. }
  558. free(event);
  559. }
  560. }
  561. int main(int argc, char *argv[]) {
  562. char *username;
  563. char *image_path = NULL;
  564. int ret;
  565. struct pam_conv conv = {conv_callback, NULL};
  566. int curs_choice = CURS_NONE;
  567. int o;
  568. int optind = 0;
  569. struct option longopts[] = {
  570. {"version", no_argument, NULL, 'v'},
  571. {"nofork", no_argument, NULL, 'n'},
  572. {"beep", no_argument, NULL, 'b'},
  573. {"dpms", no_argument, NULL, 'd'},
  574. {"color", required_argument, NULL, 'c'},
  575. {"pointer", required_argument, NULL , 'p'},
  576. {"debug", no_argument, NULL, 0},
  577. {"help", no_argument, NULL, 'h'},
  578. {"no-unlock-indicator", no_argument, NULL, 'u'},
  579. {"image", required_argument, NULL, 'i'},
  580. {"tiling", no_argument, NULL, 't'},
  581. {"ignore-empty-password", no_argument, NULL, 'e'},
  582. {"inactivity-timeout", required_argument, NULL, 'I'},
  583. {NULL, no_argument, NULL, 0}
  584. };
  585. if ((username = getenv("USER")) == NULL)
  586. errx(EXIT_FAILURE, "USER environment variable not set, please set it.\n");
  587. char *optstring = "hvnbdc:p:ui:teI:";
  588. while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
  589. switch (o) {
  590. case 'v':
  591. errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
  592. case 'n':
  593. dont_fork = true;
  594. break;
  595. case 'b':
  596. beep = true;
  597. break;
  598. case 'd':
  599. dpms = true;
  600. break;
  601. case 'I': {
  602. int time = 0;
  603. if (sscanf(optarg, "%d", &time) != 1 || time < 0)
  604. errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
  605. inactivity_timeout = time;
  606. break;
  607. }
  608. case 'c': {
  609. char *arg = optarg;
  610. /* Skip # if present */
  611. if (arg[0] == '#')
  612. arg++;
  613. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  614. errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
  615. break;
  616. }
  617. case 'u':
  618. unlock_indicator = false;
  619. break;
  620. case 'i':
  621. image_path = strdup(optarg);
  622. break;
  623. case 't':
  624. tile = true;
  625. break;
  626. case 'p':
  627. if (!strcmp(optarg, "win")) {
  628. curs_choice = CURS_WIN;
  629. } else if (!strcmp(optarg, "default")) {
  630. curs_choice = CURS_DEFAULT;
  631. } else {
  632. errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  633. }
  634. break;
  635. case 'e':
  636. ignore_empty_password = true;
  637. break;
  638. case 0:
  639. if (strcmp(longopts[optind].name, "debug") == 0)
  640. debug_mode = true;
  641. break;
  642. default:
  643. errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  644. " [-i image.png] [-t] [-e] [-I]"
  645. );
  646. }
  647. }
  648. /* We need (relatively) random numbers for highlighting a random part of
  649. * the unlock indicator upon keypresses. */
  650. srand(time(NULL));
  651. /* Initialize PAM */
  652. ret = pam_start("i3lock", username, &conv, &pam_handle);
  653. if (ret != PAM_SUCCESS)
  654. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  655. /* Using mlock() as non-super-user seems only possible in Linux. Users of other
  656. * operating systems should use encrypted swap/no swap (or remove the ifdef and
  657. * run i3lock as super-user). */
  658. #if defined(__linux__)
  659. /* Lock the area where we store the password in memory, we don’t want it to
  660. * be swapped to disk. Since Linux 2.6.9, this does not require any
  661. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  662. if (mlock(password, sizeof(password)) != 0)
  663. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  664. #endif
  665. /* Double checking that connection is good and operatable with xcb */
  666. int screennr;
  667. if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
  668. xcb_connection_has_error(conn))
  669. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  670. if (xkb_x11_setup_xkb_extension(conn,
  671. XKB_X11_MIN_MAJOR_XKB_VERSION,
  672. XKB_X11_MIN_MINOR_XKB_VERSION,
  673. 0,
  674. NULL,
  675. NULL,
  676. &xkb_base_event,
  677. &xkb_base_error) != 1)
  678. errx(EXIT_FAILURE, "Could not setup XKB extension.");
  679. static const xcb_xkb_map_part_t required_map_parts =
  680. (XCB_XKB_MAP_PART_KEY_TYPES |
  681. XCB_XKB_MAP_PART_KEY_SYMS |
  682. XCB_XKB_MAP_PART_MODIFIER_MAP |
  683. XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
  684. XCB_XKB_MAP_PART_KEY_ACTIONS |
  685. XCB_XKB_MAP_PART_VIRTUAL_MODS |
  686. XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
  687. static const xcb_xkb_event_type_t required_events =
  688. (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
  689. XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
  690. XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
  691. xcb_xkb_select_events(
  692. conn,
  693. xkb_x11_get_core_keyboard_device_id(conn),
  694. required_events,
  695. 0,
  696. required_events,
  697. required_map_parts,
  698. required_map_parts,
  699. 0);
  700. /* When we cannot initially load the keymap, we better exit */
  701. if (!load_keymap())
  702. errx(EXIT_FAILURE, "Could not load keymap");
  703. xinerama_init();
  704. xinerama_query_screens();
  705. /* if DPMS is enabled, check if the X server really supports it */
  706. if (dpms) {
  707. xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
  708. xcb_dpms_capable_reply_t *dpmsr;
  709. if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
  710. if (!dpmsr->capable) {
  711. if (debug_mode)
  712. fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
  713. dpms = false;
  714. }
  715. free(dpmsr);
  716. }
  717. }
  718. screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  719. last_resolution[0] = screen->width_in_pixels;
  720. last_resolution[1] = screen->height_in_pixels;
  721. xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
  722. (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
  723. if (image_path) {
  724. /* Create a pixmap to render on, fill it with the background color */
  725. img = cairo_image_surface_create_from_png(image_path);
  726. /* In case loading failed, we just pretend no -i was specified. */
  727. if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
  728. fprintf(stderr, "Could not load image \"%s\": %s\n",
  729. image_path, cairo_status_to_string(cairo_surface_status(img)));
  730. img = NULL;
  731. }
  732. }
  733. /* Pixmap on which the image is rendered to (if any) */
  734. xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
  735. /* open the fullscreen window, already with the correct pixmap in place */
  736. win = open_fullscreen_window(conn, screen, color, bg_pixmap);
  737. xcb_free_pixmap(conn, bg_pixmap);
  738. pid_t pid = fork();
  739. /* The pid == -1 case is intentionally ignored here:
  740. * While the child process is useful for preventing other windows from
  741. * popping up while i3lock blocks, it is not critical. */
  742. if (pid == 0) {
  743. /* Child */
  744. close(xcb_get_file_descriptor(conn));
  745. raise_loop(win);
  746. exit(EXIT_SUCCESS);
  747. }
  748. cursor = create_cursor(conn, screen, win, curs_choice);
  749. grab_pointer_and_keyboard(conn, screen, cursor);
  750. /* Load the keymap again to sync the current modifier state. Since we first
  751. * loaded the keymap, there might have been changes, but starting from now,
  752. * we should get all key presses/releases due to having grabbed the
  753. * keyboard. */
  754. (void)load_keymap();
  755. turn_monitors_off();
  756. /* Initialize the libev event loop. */
  757. main_loop = EV_DEFAULT;
  758. if (main_loop == NULL)
  759. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  760. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  761. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  762. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  763. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  764. ev_io_start(main_loop, xcb_watcher);
  765. ev_check_init(xcb_check, xcb_check_cb);
  766. ev_check_start(main_loop, xcb_check);
  767. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  768. ev_prepare_start(main_loop, xcb_prepare);
  769. /* Invoke the event callback once to catch all the events which were
  770. * received up until now. ev will only pick up new events (when the X11
  771. * file descriptor becomes readable). */
  772. ev_invoke(main_loop, xcb_check, 0);
  773. ev_loop(main_loop, 0);
  774. }