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.

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