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.

848 lines
26 KiB

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