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.

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