913 lines
30 KiB

15 years ago
  1. /*
  2. * vim:ts=4:sw=4:expandtab
  3. *
  4. * © 2010-2012 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 <xcb/xcb_keysyms.h>
  18. #include <err.h>
  19. #include <assert.h>
  20. #include <security/pam_appl.h>
  21. /* FIXME: can we get rid of this header? */
  22. #include <X11/keysym.h>
  23. #include <getopt.h>
  24. #include <string.h>
  25. #include <math.h>
  26. #include <ev.h>
  27. #include <sys/mman.h>
  28. #ifndef NOLIBCAIRO
  29. #include <cairo.h>
  30. #include <cairo/cairo-xcb.h>
  31. #endif
  32. #include "keysym2ucs.h"
  33. #include "ucs2_to_utf8.h"
  34. #include "xcb.h"
  35. #include "cursors.h"
  36. #define BUTTON_RADIUS 90
  37. #define BUTTON_SPACE (BUTTON_RADIUS + 5)
  38. #define BUTTON_CENTER (BUTTON_RADIUS + 5)
  39. #define BUTTON_DIAMETER (5 * BUTTON_SPACE)
  40. static char color[7] = "ffffff";
  41. static uint32_t last_resolution[2];
  42. static xcb_connection_t *conn;
  43. static xcb_window_t win;
  44. static xcb_visualtype_t *vistype;
  45. static xcb_cursor_t cursor;
  46. static xcb_key_symbols_t *symbols;
  47. static xcb_screen_t *scr;
  48. static pam_handle_t *pam_handle;
  49. static int input_position = 0;
  50. /* Holds the password you enter (in UTF-8). */
  51. static char password[512];
  52. static bool modeswitch_active = false;
  53. static bool iso_level3_shift_active = false;
  54. static bool iso_level5_shift_active = false;
  55. static int modeswitchmask;
  56. static int numlockmask;
  57. static bool beep = false;
  58. static bool debug_mode = false;
  59. static bool dpms = false;
  60. static bool unlock_indicator = true;
  61. static struct ev_loop *main_loop;
  62. static struct ev_timer *clear_pam_wrong_timeout;
  63. static struct ev_timer *clear_indicator_timeout;
  64. static enum {
  65. STATE_STARTED = 0, /* default state */
  66. STATE_KEY_PRESSED = 1, /* key was pressed, show unlock indicator */
  67. STATE_KEY_ACTIVE = 2, /* a key was pressed recently, highlight part
  68. of the unlock indicator. */
  69. STATE_BACKSPACE_ACTIVE = 3 /* backspace was pressed recently, highlight
  70. part of the unlock indicator in red. */
  71. } unlock_state;
  72. static enum {
  73. STATE_PAM_IDLE = 0, /* no PAM interaction at the moment */
  74. STATE_PAM_VERIFY = 1, /* currently verifying the password via PAM */
  75. STATE_PAM_WRONG = 2 /* the password was wrong */
  76. } pam_state;
  77. #define DEBUG(fmt, ...) do { \
  78. if (debug_mode) \
  79. printf("[i3lock-debug] " fmt, ##__VA_ARGS__); \
  80. } while (0)
  81. #ifndef NOLIBCAIRO
  82. static cairo_surface_t *img = NULL;
  83. static bool tile = false;
  84. #endif
  85. /*
  86. * Clears the memory which stored the password to be a bit safer against
  87. * cold-boot attacks.
  88. *
  89. */
  90. static void clear_password_memory() {
  91. /* A volatile pointer to the password buffer to prevent the compiler from
  92. * optimizing this out. */
  93. volatile char *vpassword = password;
  94. for (int c = 0; c < sizeof(password); c++)
  95. /* We store a non-random pattern which consists of the (irrelevant)
  96. * index plus (!) the value of the beep variable. This prevents the
  97. * compiler from optimizing the calls away, since the value of 'beep'
  98. * is not known at compile-time. */
  99. vpassword[c] = c + (int)beep;
  100. }
  101. /*
  102. * Draws global image with fill color onto a pixmap with the given
  103. * resolution and returns it.
  104. *
  105. */
  106. static xcb_pixmap_t draw_image(xcb_visualtype_t *vistype, u_int32_t* resolution) {
  107. xcb_pixmap_t bg_pixmap = XCB_NONE;
  108. #ifndef NOLIBCAIRO
  109. bg_pixmap = create_bg_pixmap(conn, scr, resolution, color);
  110. /* Initialize cairo */
  111. cairo_surface_t *output;
  112. output = cairo_xcb_surface_create(conn, bg_pixmap, vistype,
  113. resolution[0], resolution[1]);
  114. cairo_t *ctx = cairo_create(output);
  115. if (img) {
  116. if (!tile) {
  117. cairo_set_source_surface(ctx, img, 0, 0);
  118. cairo_paint(ctx);
  119. } else {
  120. /* create a pattern and fill a rectangle as big as the screen */
  121. cairo_pattern_t *pattern;
  122. pattern = cairo_pattern_create_for_surface(img);
  123. cairo_set_source(ctx, pattern);
  124. cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
  125. cairo_rectangle(ctx, 0, 0, resolution[0], resolution[1]);
  126. cairo_fill(ctx);
  127. cairo_pattern_destroy(pattern);
  128. }
  129. }
  130. if (unlock_state >= STATE_KEY_PRESSED && unlock_indicator) {
  131. cairo_pattern_t *outer_pat = NULL;
  132. outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
  133. switch (pam_state) {
  134. case STATE_PAM_VERIFY:
  135. cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 0, 250.0/255);
  136. cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 0, 250.0/255);
  137. break;
  138. case STATE_PAM_WRONG:
  139. cairo_pattern_add_color_stop_rgb(outer_pat, 0, 255.0/250, 139.0/255, 0);
  140. cairo_pattern_add_color_stop_rgb(outer_pat, 1, 125.0/255, 51.0/255, 0);
  141. break;
  142. case STATE_PAM_IDLE:
  143. cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 125.0/255, 0);
  144. cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 125.0/255, 0);
  145. break;
  146. }
  147. /* Draw a (centered) circle with transparent background. */
  148. cairo_set_line_width(ctx, 10.0);
  149. cairo_arc(ctx,
  150. (resolution[0] / 2) /* x */,
  151. (resolution[1] / 2) /* y */,
  152. BUTTON_RADIUS /* radius */,
  153. 0 /* start */,
  154. 2 * M_PI /* end */);
  155. /* Use the appropriate color for the different PAM states
  156. * (currently verifying, wrong password, or default) */
  157. switch (pam_state) {
  158. case STATE_PAM_VERIFY:
  159. cairo_set_source_rgba(ctx, 0, 114.0/255, 255.0/255, 0.75);
  160. break;
  161. case STATE_PAM_WRONG:
  162. cairo_set_source_rgba(ctx, 250.0/255, 0, 0, 0.75);
  163. break;
  164. default:
  165. cairo_set_source_rgba(ctx, 0, 0, 0, 0.75);
  166. break;
  167. }
  168. cairo_fill_preserve(ctx);
  169. cairo_set_source(ctx, outer_pat);
  170. cairo_stroke(ctx);
  171. /* Draw an inner seperator line. */
  172. cairo_set_source_rgb(ctx, 0, 0, 0);
  173. cairo_set_line_width(ctx, 2.0);
  174. cairo_arc(ctx,
  175. (resolution[0] / 2) /* x */,
  176. (resolution[1] / 2) /* y */,
  177. BUTTON_RADIUS - 5 /* radius */,
  178. 0,
  179. 2 * M_PI);
  180. cairo_stroke(ctx);
  181. cairo_set_line_width(ctx, 10.0);
  182. /* Display a (centered) text of the current PAM state. */
  183. char *text = NULL;
  184. switch (pam_state) {
  185. case STATE_PAM_VERIFY:
  186. text = "verifying…";
  187. break;
  188. case STATE_PAM_WRONG:
  189. text = "wrong!";
  190. break;
  191. default:
  192. break;
  193. }
  194. if (text) {
  195. cairo_text_extents_t extents;
  196. double x, y;
  197. cairo_set_source_rgb(ctx, 0, 0, 0);
  198. cairo_set_font_size(ctx, 28.0);
  199. cairo_text_extents(ctx, text, &extents);
  200. x = (resolution[0] / 2.0) - ((extents.width / 2) + extents.x_bearing);
  201. y = (resolution[1] / 2.0) - ((extents.height / 2) + extents.y_bearing);
  202. cairo_move_to(ctx, x, y);
  203. cairo_show_text(ctx, text);
  204. cairo_close_path(ctx);
  205. }
  206. /* After the user pressed any valid key or the backspace key, we
  207. * highlight a random part of the unlock indicator to confirm this
  208. * keypress. */
  209. if (unlock_state == STATE_KEY_ACTIVE ||
  210. unlock_state == STATE_BACKSPACE_ACTIVE) {
  211. cairo_new_sub_path(ctx);
  212. double highlight_start = (rand() % (int)(2 * M_PI * 100)) / 100.0;
  213. DEBUG("Highlighting part %.2f\n", highlight_start);
  214. cairo_arc(ctx, resolution[0] / 2 /* x */, resolution[1] / 2 /* y */,
  215. BUTTON_RADIUS /* radius */, highlight_start,
  216. highlight_start + (M_PI / 3.0));
  217. if (unlock_state == STATE_KEY_ACTIVE) {
  218. /* For normal keys, we use a lighter green. */
  219. outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
  220. cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 219.0/255, 0);
  221. cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 219.0/255, 0);
  222. } else {
  223. /* For backspace, we use red. */
  224. outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
  225. cairo_pattern_add_color_stop_rgb(outer_pat, 0, 219.0/255, 139.0/255, 0);
  226. cairo_pattern_add_color_stop_rgb(outer_pat, 1, 219.0/255, 51.0/255, 0);
  227. }
  228. cairo_set_source(ctx, outer_pat);
  229. cairo_stroke(ctx);
  230. /* Draw two little separators for the highlighted part of the
  231. * unlock indicator. */
  232. cairo_set_source_rgb(ctx, 0, 0, 0);
  233. cairo_arc(ctx,
  234. (resolution[0] / 2) /* x */,
  235. (resolution[1] / 2) /* y */,
  236. BUTTON_RADIUS /* radius */,
  237. highlight_start /* start */,
  238. highlight_start + (M_PI / 128.0) /* end */);
  239. cairo_stroke(ctx);
  240. cairo_arc(ctx,
  241. (resolution[0] / 2) /* x */,
  242. (resolution[1] / 2) /* y */,
  243. BUTTON_RADIUS /* radius */,
  244. highlight_start + (M_PI / 3.0) /* start */,
  245. (highlight_start + (M_PI / 3.0)) + (M_PI / 128.0) /* end */);
  246. cairo_stroke(ctx);
  247. }
  248. }
  249. cairo_surface_destroy(output);
  250. cairo_destroy(ctx);
  251. #endif
  252. return bg_pixmap;
  253. }
  254. /*
  255. * Calls draw_image on a new pixmap and swaps that with the current pixmap
  256. *
  257. */
  258. static void redraw_screen() {
  259. xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
  260. xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
  261. /* XXX: Possible optimization: Only update the area in the middle of the
  262. * screen instead of the whole screen. */
  263. xcb_clear_area(conn, 0, win, 0, 0, scr->width_in_pixels, scr->height_in_pixels);
  264. xcb_free_pixmap(conn, bg_pixmap);
  265. xcb_flush(conn);
  266. }
  267. /*
  268. * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
  269. * authentication event.
  270. *
  271. */
  272. static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
  273. DEBUG("clearing pam wrong\n");
  274. pam_state = STATE_PAM_IDLE;
  275. unlock_state = STATE_STARTED;
  276. redraw_screen();
  277. }
  278. /*
  279. * Hides the unlock indicator completely when there is no content in the
  280. * password buffer.
  281. *
  282. */
  283. static void clear_indicator(EV_P_ ev_timer *w, int revents) {
  284. if (input_position == 0) {
  285. DEBUG("Clear indicator\n");
  286. unlock_state = STATE_STARTED;
  287. } else unlock_state = STATE_KEY_PRESSED;
  288. redraw_screen();
  289. }
  290. /*
  291. * (Re-)starts the clear_indicator timeout. Called after pressing backspace or
  292. * after an unsuccessful authentication attempt.
  293. *
  294. */
  295. static void start_clear_indicator_timeout() {
  296. if (clear_indicator_timeout) {
  297. ev_timer_stop(main_loop, clear_indicator_timeout);
  298. ev_timer_set(clear_indicator_timeout, 1.0, 0.);
  299. ev_timer_start(main_loop, clear_indicator_timeout);
  300. } else {
  301. clear_indicator_timeout = calloc(sizeof(struct ev_timer), 1);
  302. ev_timer_init(clear_indicator_timeout, clear_indicator, 1.0, 0.);
  303. ev_timer_start(main_loop, clear_indicator_timeout);
  304. }
  305. }
  306. static void input_done() {
  307. if (input_position == 0)
  308. return;
  309. if (clear_pam_wrong_timeout) {
  310. ev_timer_stop(main_loop, clear_pam_wrong_timeout);
  311. clear_pam_wrong_timeout = NULL;
  312. }
  313. pam_state = STATE_PAM_VERIFY;
  314. redraw_screen();
  315. if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
  316. printf("successfully authenticated\n");
  317. clear_password_memory();
  318. exit(0);
  319. }
  320. fprintf(stderr, "Authentication failure\n");
  321. pam_state = STATE_PAM_WRONG;
  322. redraw_screen();
  323. /* Clear this state after 2 seconds (unless the user enters another
  324. * password during that time). */
  325. ev_now_update(main_loop);
  326. clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1);
  327. ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
  328. ev_timer_start(main_loop, clear_pam_wrong_timeout);
  329. /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
  330. * too early. */
  331. if (clear_indicator_timeout) {
  332. ev_timer_stop(main_loop, clear_indicator_timeout);
  333. clear_indicator_timeout = NULL;
  334. }
  335. /* beep on authentication failure, if enabled */
  336. if (beep) {
  337. xcb_bell(conn, 100);
  338. xcb_flush(conn);
  339. }
  340. }
  341. /*
  342. * Called when the user releases a key. We need to leave the Mode_switch
  343. * state when the user releases the Mode_switch key.
  344. *
  345. */
  346. static void handle_key_release(xcb_key_release_event_t *event) {
  347. DEBUG("releasing key %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
  348. event->detail, event->state, modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
  349. /* We don’t care about the column here and just use the first symbol. Since
  350. * we only check for Mode_switch and ISO_Level3_Shift, this *should* work.
  351. * Also, if we would use the current column, we would look in the wrong
  352. * place. */
  353. xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, 0);
  354. if (sym == XK_Mode_switch) {
  355. //printf("Mode switch disabled\n");
  356. modeswitch_active = false;
  357. } else if (sym == XK_ISO_Level3_Shift) {
  358. iso_level3_shift_active = false;
  359. } else if (sym == XK_ISO_Level5_Shift) {
  360. iso_level5_shift_active = false;
  361. }
  362. DEBUG("release done. modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
  363. modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
  364. }
  365. static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
  366. redraw_screen();
  367. }
  368. /*
  369. * Handle key presses. Fixes state, then looks up the key symbol for the
  370. * given keycode, then looks up the key symbol (as UCS-2), converts it to
  371. * UTF-8 and stores it in the password array.
  372. *
  373. */
  374. static void handle_key_press(xcb_key_press_event_t *event) {
  375. DEBUG("keypress %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
  376. event->detail, event->state, modeswitch_active, iso_level3_shift_active);
  377. xcb_keysym_t sym0, sym1, sym;
  378. /* For each keycode, there is a list of symbols. The list could look like this:
  379. * $ xmodmap -pke | grep 'keycode 38'
  380. * keycode 38 = a A adiaeresis Adiaeresis o O
  381. * In non-X11 terminology, the symbols for the keycode 38 (the key labeled
  382. * with "a" on my keyboard) are "a A ä Ä o O".
  383. * Another form to display the same information is using xkbcomp:
  384. * $ xkbcomp $DISPLAY /tmp/xkb.dump
  385. * Then open /tmp/xkb.dump and search for '\<a\>' (in VIM regexp-language):
  386. *
  387. * symbols[Group1]= [ a, A, o, O ],
  388. * symbols[Group2]= [ adiaeresis, Adiaeresis ]
  389. *
  390. * So there are two *groups*, one containing 'a A' and one containing 'ä
  391. * Ä'. You can use Mode_switch to switch between these groups. You can use
  392. * ISO_Level3_Shift to reach the 'o O' part of the first group (its the
  393. * same group, just an even higher shift level).
  394. *
  395. * So, using the "logical" XKB information, the following lookup will be
  396. * performed:
  397. *
  398. * Neither Mode_switch nor ISO_Level3_Shift active: group 1, column 0 and 1
  399. * Mode_switch active: group 2, column 0 and 1
  400. * ISO_Level3_Shift active: group 1, column 2 and 3
  401. *
  402. * Using the column index which xcb_key_press_lookup_keysym uses (and
  403. * xmodmap prints out), the following lookup will be performed:
  404. *
  405. * Neither Mode_switch nor ISO_Level3_Shift active: column 0 and 1
  406. * Mode_switch active: column 2 and 3
  407. * ISO_Level3_Shift active: column 4 and 5
  408. */
  409. int base_column = 0;
  410. if (modeswitch_active)
  411. base_column = 2;
  412. if (iso_level3_shift_active)
  413. base_column = 4;
  414. if (iso_level5_shift_active)
  415. base_column = 6;
  416. sym0 = xcb_key_press_lookup_keysym(symbols, event, base_column);
  417. sym1 = xcb_key_press_lookup_keysym(symbols, event, base_column + 1);
  418. switch (sym0) {
  419. case XK_Mode_switch:
  420. DEBUG("Mode switch enabled\n");
  421. modeswitch_active = true;
  422. return;
  423. case XK_ISO_Level3_Shift:
  424. DEBUG("ISO_Level3_Shift enabled\n");
  425. iso_level3_shift_active = true;
  426. return;
  427. case XK_ISO_Level5_Shift:
  428. DEBUG("ISO_Level5_Shift enabled\n");
  429. iso_level5_shift_active = true;
  430. return;
  431. case XK_Return:
  432. case XK_KP_Enter:
  433. input_done();
  434. case XK_Escape:
  435. input_position = 0;
  436. clear_password_memory();
  437. password[input_position] = '\0';
  438. return;
  439. case XK_BackSpace:
  440. if (input_position == 0)
  441. return;
  442. /* decrement input_position to point to the previous glyph */
  443. u8_dec(password, &input_position);
  444. password[input_position] = '\0';
  445. /* Clear this state after 2 seconds (unless the user enters another
  446. * password during that time). */
  447. start_clear_indicator_timeout();
  448. unlock_state = STATE_BACKSPACE_ACTIVE;
  449. redraw_screen();
  450. unlock_state = STATE_KEY_PRESSED;
  451. //printf("new input position = %d, new password = %s\n", input_position, password);
  452. return;
  453. }
  454. if ((input_position + 8) >= sizeof(password))
  455. return;
  456. if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
  457. /* this key was a keypad key */
  458. if ((event->state & XCB_MOD_MASK_SHIFT))
  459. sym = sym0;
  460. else sym = sym1;
  461. } else {
  462. if ((event->state & XCB_MOD_MASK_SHIFT))
  463. sym = sym1;
  464. else sym = sym0;
  465. }
  466. #if 0
  467. /* FIXME: handle all of these? */
  468. printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
  469. printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
  470. printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
  471. printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
  472. printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
  473. printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
  474. printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
  475. #endif
  476. if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
  477. return;
  478. DEBUG("resolved to keysym = %c (%d)\n", sym, sym);
  479. /* convert the keysym to UCS */
  480. uint16_t ucs = keysym2ucs(sym);
  481. if ((int16_t)ucs == -1) {
  482. fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
  483. return;
  484. }
  485. /* store the UCS in a string to convert it */
  486. uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
  487. DEBUG("input part = %s\n", inp);
  488. /* store it in the password array as UTF-8 */
  489. input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
  490. password[input_position] = '\0';
  491. DEBUG("current password = %s\n", password);
  492. unlock_state = STATE_KEY_ACTIVE;
  493. redraw_screen();
  494. unlock_state = STATE_KEY_PRESSED;
  495. struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
  496. ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
  497. ev_timer_start(main_loop, timeout);
  498. if (clear_indicator_timeout) {
  499. ev_timer_stop(main_loop, clear_indicator_timeout);
  500. clear_indicator_timeout = NULL;
  501. }
  502. }
  503. /*
  504. * A visibility notify event will be received when the visibility (= can the
  505. * user view the complete window) changes, so for example when a popup overlays
  506. * some area of the i3lock window.
  507. *
  508. * In this case, we raise our window on top so that the popup (or whatever is
  509. * hiding us) gets hidden.
  510. *
  511. */
  512. static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
  513. if (event->state != XCB_VISIBILITY_UNOBSCURED) {
  514. uint32_t values[] = { XCB_STACK_MODE_ABOVE };
  515. xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
  516. xcb_flush(conn);
  517. }
  518. }
  519. /*
  520. * Called when the keyboard mapping changes. We update our symbols.
  521. *
  522. */
  523. static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
  524. xcb_refresh_keyboard_mapping(symbols, event);
  525. modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
  526. numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
  527. }
  528. /*
  529. * Called when the properties on the root window change, e.g. when the screen
  530. * resolution changes. If so we update the window to cover the whole screen
  531. * and also redraw the image, if any.
  532. *
  533. */
  534. void handle_screen_resize(xcb_visualtype_t *vistype, xcb_window_t win, uint32_t* last_resolution) {
  535. xcb_get_geometry_cookie_t geomc;
  536. xcb_get_geometry_reply_t *geom;
  537. geomc = xcb_get_geometry(conn, scr->root);
  538. if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL) {
  539. return;
  540. }
  541. if (last_resolution[0] == geom->width && last_resolution[1] == geom->height)
  542. return;
  543. last_resolution[0] = geom->width;
  544. last_resolution[1] = geom->height;
  545. #ifndef NOLIBCAIRO
  546. if (img) {
  547. xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
  548. xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
  549. xcb_free_pixmap(conn, bg_pixmap);
  550. }
  551. #endif
  552. uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
  553. xcb_configure_window(conn, win, mask, last_resolution);
  554. xcb_flush(conn);
  555. }
  556. /*
  557. * Callback function for PAM. We only react on password request callbacks.
  558. *
  559. */
  560. static int conv_callback(int num_msg, const struct pam_message **msg,
  561. struct pam_response **resp, void *appdata_ptr)
  562. {
  563. if (num_msg == 0)
  564. return 1;
  565. /* PAM expects an array of responses, one for each message */
  566. if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
  567. perror("calloc");
  568. return 1;
  569. }
  570. for (int c = 0; c < num_msg; c++) {
  571. if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
  572. msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
  573. continue;
  574. /* return code is currently not used but should be set to zero */
  575. resp[c]->resp_retcode = 0;
  576. if ((resp[c]->resp = strdup(password)) == NULL) {
  577. perror("strdup");
  578. return 1;
  579. }
  580. }
  581. return 0;
  582. }
  583. /*
  584. * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
  585. * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
  586. *
  587. */
  588. static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
  589. /* empty, because xcb_prepare_cb and xcb_check_cb are used */
  590. }
  591. /*
  592. * Flush before blocking (and waiting for new events)
  593. *
  594. */
  595. static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
  596. xcb_flush(conn);
  597. }
  598. /*
  599. * Instead of polling the X connection socket we leave this to
  600. * xcb_poll_for_event() which knows better than we can ever know.
  601. *
  602. */
  603. static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
  604. xcb_generic_event_t *event;
  605. while ((event = xcb_poll_for_event(conn)) != NULL) {
  606. if (event->response_type == 0) {
  607. xcb_generic_error_t *error = (xcb_generic_error_t*)event;
  608. fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
  609. error->sequence, error->error_code);
  610. free(event);
  611. continue;
  612. }
  613. /* Strip off the highest bit (set if the event is generated) */
  614. int type = (event->response_type & 0x7F);
  615. if (type == XCB_KEY_PRESS) {
  616. handle_key_press((xcb_key_press_event_t*)event);
  617. continue;
  618. }
  619. if (type == XCB_KEY_RELEASE) {
  620. handle_key_release((xcb_key_release_event_t*)event);
  621. /* If this was the backspace or escape key we are back at an
  622. * empty input, so turn off the screen if DPMS is enabled */
  623. if (dpms && input_position == 0)
  624. dpms_turn_off_screen(conn);
  625. continue;
  626. }
  627. if (type == XCB_VISIBILITY_NOTIFY) {
  628. handle_visibility_notify((xcb_visibility_notify_event_t*)event);
  629. continue;
  630. }
  631. if (type == XCB_MAPPING_NOTIFY) {
  632. handle_mapping_notify((xcb_mapping_notify_event_t*)event);
  633. continue;
  634. }
  635. if (type == XCB_CONFIGURE_NOTIFY) {
  636. handle_screen_resize(vistype, win, last_resolution);
  637. continue;
  638. }
  639. printf("WARNING: unhandled event of type %d\n", type);
  640. free(event);
  641. }
  642. }
  643. int main(int argc, char *argv[]) {
  644. bool dont_fork = false;
  645. char *username;
  646. #ifndef NOLIBCAIRO
  647. char *image_path = NULL;
  648. #endif
  649. int ret;
  650. struct pam_conv conv = {conv_callback, NULL};
  651. int screen;
  652. int curs_choice = CURS_NONE;
  653. char o;
  654. int optind = 0;
  655. struct option longopts[] = {
  656. {"version", no_argument, NULL, 'v'},
  657. {"nofork", no_argument, NULL, 'n'},
  658. {"beep", no_argument, NULL, 'b'},
  659. {"dpms", no_argument, NULL, 'd'},
  660. {"color", required_argument, NULL, 'c'},
  661. {"pointer", required_argument, NULL , 'p'},
  662. {"debug", no_argument, NULL, 0},
  663. {"help", no_argument, NULL, 'h'},
  664. {"no-unlock-indicator", no_argument, NULL, 'u'},
  665. #ifndef NOLIBCAIRO
  666. {"image", required_argument, NULL, 'i'},
  667. {"tiling", no_argument, NULL, 't'},
  668. #endif
  669. {NULL, no_argument, NULL, 0}
  670. };
  671. if ((username = getenv("USER")) == NULL)
  672. errx(1, "USER environment variable not set, please set it.\n");
  673. while ((o = getopt_long(argc, argv, "hvnbdc:p:u"
  674. #ifndef NOLIBCAIRO
  675. "i:t"
  676. #endif
  677. , longopts, &optind)) != -1) {
  678. switch (o) {
  679. case 'v':
  680. errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
  681. case 'n':
  682. dont_fork = true;
  683. break;
  684. case 'b':
  685. beep = true;
  686. break;
  687. case 'd':
  688. dpms = true;
  689. break;
  690. case 'c': {
  691. char *arg = optarg;
  692. /* Skip # if present */
  693. if (arg[0] == '#')
  694. arg++;
  695. if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
  696. errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
  697. break;
  698. }
  699. case 'u':
  700. unlock_indicator = false;
  701. break;
  702. #ifndef NOLIBCAIRO
  703. case 'i':
  704. image_path = strdup(optarg);
  705. break;
  706. case 't':
  707. tile = true;
  708. break;
  709. #endif
  710. case 'p':
  711. if (!strcmp(optarg, "win")) {
  712. curs_choice = CURS_WIN;
  713. } else if (!strcmp(optarg, "default")) {
  714. curs_choice = CURS_DEFAULT;
  715. } else {
  716. errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
  717. }
  718. break;
  719. case 0:
  720. if (strcmp(longopts[optind].name, "debug") == 0)
  721. debug_mode = true;
  722. break;
  723. default:
  724. errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
  725. #ifndef NOLIBCAIRO
  726. " [-i image.png] [-t]"
  727. #else
  728. " (compiled with NOLIBCAIRO)"
  729. #endif
  730. );
  731. }
  732. }
  733. /* We need (relatively) random numbers for highlighting a random part of
  734. * the unlock indicator upon keypresses. */
  735. srand(time(NULL));
  736. /* Initialize PAM */
  737. ret = pam_start("i3lock", username, &conv, &pam_handle);
  738. if (ret != PAM_SUCCESS)
  739. errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
  740. /* Lock the area where we store the password in memory, we don’t want it to
  741. * be swapped to disk. Since Linux 2.6.9, this does not require any
  742. * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
  743. if (mlock(password, sizeof(password)) != 0)
  744. err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
  745. /* Initialize connection to X11 */
  746. if ((conn = xcb_connect(NULL, &screen)) == NULL ||
  747. xcb_connection_has_error(conn))
  748. errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
  749. if (!dont_fork) {
  750. /* In the parent process, we exit */
  751. if (fork() != 0)
  752. return 0;
  753. }
  754. /* if DPMS is enabled, check if the X server really supports it */
  755. if (dpms) {
  756. xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
  757. xcb_dpms_capable_reply_t *dpmsr;
  758. if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL)) && !dpmsr->capable) {
  759. fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
  760. dpms = false;
  761. }
  762. }
  763. scr = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
  764. vistype = get_root_visual_type(scr);
  765. last_resolution[0] = scr->width_in_pixels;
  766. last_resolution[1] = scr->height_in_pixels;
  767. #ifndef NOLIBCAIRO
  768. if (image_path) {
  769. /* Create a pixmap to render on, fill it with the background color */
  770. img = cairo_image_surface_create_from_png(image_path);
  771. }
  772. #endif
  773. /* Pixmap on which the image is rendered to (if any) */
  774. xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
  775. /* open the fullscreen window, already with the correct pixmap in place */
  776. win = open_fullscreen_window(conn, scr, color, bg_pixmap);
  777. xcb_free_pixmap(conn, bg_pixmap);
  778. cursor = create_cursor(conn, scr, win, curs_choice);
  779. grab_pointer_and_keyboard(conn, scr, cursor);
  780. symbols = xcb_key_symbols_alloc(conn);
  781. modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
  782. numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
  783. if (dpms)
  784. dpms_turn_off_screen(conn);
  785. /* Initialize the libev event loop. */
  786. main_loop = EV_DEFAULT;
  787. if (main_loop == NULL)
  788. errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
  789. struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
  790. struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
  791. struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
  792. ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
  793. ev_io_start(main_loop, xcb_watcher);
  794. ev_check_init(xcb_check, xcb_check_cb);
  795. ev_check_start(main_loop, xcb_check);
  796. ev_prepare_init(xcb_prepare, xcb_prepare_cb);
  797. ev_prepare_start(main_loop, xcb_prepare);
  798. xcb_flush(conn);
  799. ev_loop(main_loop, 0);
  800. }