2 * vim:ts=4:sw=4:expandtab
4 * © 2010-2012 Michael Stapelberg
6 * See LICENSE for licensing information
17 #include <xcb/xcb_keysyms.h>
20 #include <security/pam_appl.h>
21 /* FIXME: can we get rid of this header? */
22 #include <X11/keysym.h>
31 #include <cairo/cairo-xcb.h>
34 #include "keysym2ucs.h"
35 #include "ucs2_to_utf8.h"
38 #include "unlock_indicator.h"
40 char color[7] = "ffffff";
41 uint32_t last_resolution[2];
43 static xcb_cursor_t cursor;
44 static xcb_key_symbols_t *symbols;
45 static pam_handle_t *pam_handle;
46 int input_position = 0;
47 /* Holds the password you enter (in UTF-8). */
48 static char password[512];
49 static bool modeswitch_active = false;
50 static bool iso_level3_shift_active = false;
51 static bool iso_level5_shift_active = false;
52 static int numlockmask;
53 static bool beep = false;
54 static bool debug_mode = false;
55 static bool dpms = false;
56 bool unlock_indicator = true;
57 static bool dont_fork = false;
58 struct ev_loop *main_loop;
59 static struct ev_timer *clear_pam_wrong_timeout;
60 extern unlock_state_t unlock_state;
61 extern pam_state_t pam_state;
63 #define DEBUG(fmt, ...) do { \
65 printf("[i3lock-debug] " fmt, ##__VA_ARGS__); \
69 cairo_surface_t *img = NULL;
74 * Clears the memory which stored the password to be a bit safer against
78 static void clear_password_memory() {
79 /* A volatile pointer to the password buffer to prevent the compiler from
80 * optimizing this out. */
81 volatile char *vpassword = password;
82 for (int c = 0; c < sizeof(password); c++)
83 /* We store a non-random pattern which consists of the (irrelevant)
84 * index plus (!) the value of the beep variable. This prevents the
85 * compiler from optimizing the calls away, since the value of 'beep'
86 * is not known at compile-time. */
87 vpassword[c] = c + (int)beep;
92 * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
93 * authentication event.
96 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
97 DEBUG("clearing pam wrong\n");
98 pam_state = STATE_PAM_IDLE;
99 unlock_state = STATE_STARTED;
102 /* Now free this timeout. */
103 ev_timer_stop(main_loop, clear_pam_wrong_timeout);
104 free(clear_pam_wrong_timeout);
105 clear_pam_wrong_timeout = NULL;
108 static void input_done() {
109 if (input_position == 0)
112 if (clear_pam_wrong_timeout) {
113 ev_timer_stop(main_loop, clear_pam_wrong_timeout);
114 free(clear_pam_wrong_timeout);
115 clear_pam_wrong_timeout = NULL;
118 pam_state = STATE_PAM_VERIFY;
121 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
122 printf("successfully authenticated\n");
123 clear_password_memory();
127 fprintf(stderr, "Authentication failure\n");
129 pam_state = STATE_PAM_WRONG;
132 /* Clear this state after 2 seconds (unless the user enters another
133 * password during that time). */
134 ev_now_update(main_loop);
135 if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
136 ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
137 ev_timer_start(main_loop, clear_pam_wrong_timeout);
140 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
142 stop_clear_indicator_timeout();
144 /* beep on authentication failure, if enabled */
152 * Called when the user releases a key. We need to leave the Mode_switch
153 * state when the user releases the Mode_switch key.
156 static void handle_key_release(xcb_key_release_event_t *event) {
157 DEBUG("releasing key %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
158 event->detail, event->state, modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
160 /* We don’t care about the column here and just use the first symbol. Since
161 * we only check for Mode_switch and ISO_Level3_Shift, this *should* work.
162 * Also, if we would use the current column, we would look in the wrong
164 xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, 0);
165 if (sym == XK_Mode_switch) {
166 //printf("Mode switch disabled\n");
167 modeswitch_active = false;
168 } else if (sym == XK_ISO_Level3_Shift) {
169 iso_level3_shift_active = false;
170 } else if (sym == XK_ISO_Level5_Shift) {
171 iso_level5_shift_active = false;
173 DEBUG("release done. modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
174 modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
177 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
180 ev_timer_stop(main_loop, w);
185 * Handle key presses. Fixes state, then looks up the key symbol for the
186 * given keycode, then looks up the key symbol (as UCS-2), converts it to
187 * UTF-8 and stores it in the password array.
190 static void handle_key_press(xcb_key_press_event_t *event) {
191 DEBUG("keypress %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
192 event->detail, event->state, modeswitch_active, iso_level3_shift_active);
194 xcb_keysym_t sym0, sym1, sym;
195 /* For each keycode, there is a list of symbols. The list could look like this:
196 * $ xmodmap -pke | grep 'keycode 38'
197 * keycode 38 = a A adiaeresis Adiaeresis o O
198 * In non-X11 terminology, the symbols for the keycode 38 (the key labeled
199 * with "a" on my keyboard) are "a A ä Ä o O".
200 * Another form to display the same information is using xkbcomp:
201 * $ xkbcomp $DISPLAY /tmp/xkb.dump
202 * Then open /tmp/xkb.dump and search for '\<a\>' (in VIM regexp-language):
204 * symbols[Group1]= [ a, A, o, O ],
205 * symbols[Group2]= [ adiaeresis, Adiaeresis ]
207 * So there are two *groups*, one containing 'a A' and one containing 'ä
208 * Ä'. You can use Mode_switch to switch between these groups. You can use
209 * ISO_Level3_Shift to reach the 'o O' part of the first group (it’s the
210 * same group, just an even higher shift level).
212 * So, using the "logical" XKB information, the following lookup will be
215 * Neither Mode_switch nor ISO_Level3_Shift active: group 1, column 0 and 1
216 * Mode_switch active: group 2, column 0 and 1
217 * ISO_Level3_Shift active: group 1, column 2 and 3
219 * Using the column index which xcb_key_press_lookup_keysym uses (and
220 * xmodmap prints out), the following lookup will be performed:
222 * Neither Mode_switch nor ISO_Level3_Shift active: column 0 and 1
223 * Mode_switch active: column 2 and 3
224 * ISO_Level3_Shift active: column 4 and 5
227 if (modeswitch_active)
229 if (iso_level3_shift_active)
231 if (iso_level5_shift_active)
233 sym0 = xcb_key_press_lookup_keysym(symbols, event, base_column);
234 sym1 = xcb_key_press_lookup_keysym(symbols, event, base_column + 1);
237 DEBUG("Mode switch enabled\n");
238 modeswitch_active = true;
240 case XK_ISO_Level3_Shift:
241 DEBUG("ISO_Level3_Shift enabled\n");
242 iso_level3_shift_active = true;
244 case XK_ISO_Level5_Shift:
245 DEBUG("ISO_Level5_Shift enabled\n");
246 iso_level5_shift_active = true;
253 clear_password_memory();
254 password[input_position] = '\0';
258 if (input_position == 0)
261 /* decrement input_position to point to the previous glyph */
262 u8_dec(password, &input_position);
263 password[input_position] = '\0';
265 /* Clear this state after 2 seconds (unless the user enters another
266 * password during that time). */
267 start_clear_indicator_timeout();
268 unlock_state = STATE_BACKSPACE_ACTIVE;
270 unlock_state = STATE_KEY_PRESSED;
271 //printf("new input position = %d, new password = %s\n", input_position, password);
275 if ((input_position + 8) >= sizeof(password))
278 if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
279 /* this key was a keypad key */
280 if ((event->state & XCB_MOD_MASK_SHIFT))
284 if ((event->state & XCB_MOD_MASK_SHIFT))
290 /* FIXME: handle all of these? */
291 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
292 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
293 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
294 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
295 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
296 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
297 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
300 if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
303 DEBUG("resolved to keysym = %c (%d)\n", sym, sym);
305 /* convert the keysym to UCS */
306 uint16_t ucs = keysym2ucs(sym);
307 if ((int16_t)ucs == -1) {
308 fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
312 /* store the UCS in a string to convert it */
313 uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
314 DEBUG("input part = %s\n", inp);
316 /* store it in the password array as UTF-8 */
317 input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
318 password[input_position] = '\0';
319 DEBUG("current password = %s\n", password);
321 unlock_state = STATE_KEY_ACTIVE;
323 unlock_state = STATE_KEY_PRESSED;
325 struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
327 ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
328 ev_timer_start(main_loop, timeout);
331 stop_clear_indicator_timeout();
335 * A visibility notify event will be received when the visibility (= can the
336 * user view the complete window) changes, so for example when a popup overlays
337 * some area of the i3lock window.
339 * In this case, we raise our window on top so that the popup (or whatever is
340 * hiding us) gets hidden.
343 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
344 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
345 uint32_t values[] = { XCB_STACK_MODE_ABOVE };
346 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
352 * Called when the keyboard mapping changes. We update our symbols.
355 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
356 xcb_refresh_keyboard_mapping(symbols, event);
358 numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
362 * Called when the properties on the root window change, e.g. when the screen
363 * resolution changes. If so we update the window to cover the whole screen
364 * and also redraw the image, if any.
367 void handle_screen_resize() {
368 xcb_get_geometry_cookie_t geomc;
369 xcb_get_geometry_reply_t *geom;
370 geomc = xcb_get_geometry(conn, screen->root);
371 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
374 if (last_resolution[0] == geom->width &&
375 last_resolution[1] == geom->height) {
380 last_resolution[0] = geom->width;
381 last_resolution[1] = geom->height;
389 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
390 xcb_configure_window(conn, win, mask, last_resolution);
395 * Callback function for PAM. We only react on password request callbacks.
398 static int conv_callback(int num_msg, const struct pam_message **msg,
399 struct pam_response **resp, void *appdata_ptr)
404 /* PAM expects an array of responses, one for each message */
405 if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
410 for (int c = 0; c < num_msg; c++) {
411 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
412 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
415 /* return code is currently not used but should be set to zero */
416 resp[c]->resp_retcode = 0;
417 if ((resp[c]->resp = strdup(password)) == NULL) {
427 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
428 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
431 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
432 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
436 * Flush before blocking (and waiting for new events)
439 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
444 * Instead of polling the X connection socket we leave this to
445 * xcb_poll_for_event() which knows better than we can ever know.
448 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
449 xcb_generic_event_t *event;
451 while ((event = xcb_poll_for_event(conn)) != NULL) {
452 if (event->response_type == 0) {
453 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
454 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
455 error->sequence, error->error_code);
460 /* Strip off the highest bit (set if the event is generated) */
461 int type = (event->response_type & 0x7F);
464 handle_key_press((xcb_key_press_event_t*)event);
467 case XCB_KEY_RELEASE:
468 handle_key_release((xcb_key_release_event_t*)event);
470 /* If this was the backspace or escape key we are back at an
471 * empty input, so turn off the screen if DPMS is enabled */
472 if (dpms && input_position == 0)
473 dpms_turn_off_screen(conn);
477 case XCB_VISIBILITY_NOTIFY:
478 handle_visibility_notify((xcb_visibility_notify_event_t*)event);
483 /* After the first MapNotify, we never fork again. We don’t
484 * expect to get another MapNotify, but better be sure… */
487 /* In the parent process, we exit */
493 case XCB_MAPPING_NOTIFY:
494 handle_mapping_notify((xcb_mapping_notify_event_t*)event);
497 case XCB_CONFIGURE_NOTIFY:
498 handle_screen_resize();
506 int main(int argc, char *argv[]) {
509 char *image_path = NULL;
512 struct pam_conv conv = {conv_callback, NULL};
514 int curs_choice = CURS_NONE;
517 struct option longopts[] = {
518 {"version", no_argument, NULL, 'v'},
519 {"nofork", no_argument, NULL, 'n'},
520 {"beep", no_argument, NULL, 'b'},
521 {"dpms", no_argument, NULL, 'd'},
522 {"color", required_argument, NULL, 'c'},
523 {"pointer", required_argument, NULL , 'p'},
524 {"debug", no_argument, NULL, 0},
525 {"help", no_argument, NULL, 'h'},
526 {"no-unlock-indicator", no_argument, NULL, 'u'},
528 {"image", required_argument, NULL, 'i'},
529 {"tiling", no_argument, NULL, 't'},
531 {NULL, no_argument, NULL, 0}
534 if ((username = getenv("USER")) == NULL)
535 errx(1, "USER environment variable not set, please set it.\n");
537 while ((o = getopt_long(argc, argv, "hvnbdc:p:u"
541 , longopts, &optind)) != -1) {
544 errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
557 /* Skip # if present */
561 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
562 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
567 unlock_indicator = false;
571 image_path = strdup(optarg);
578 if (!strcmp(optarg, "win")) {
579 curs_choice = CURS_WIN;
580 } else if (!strcmp(optarg, "default")) {
581 curs_choice = CURS_DEFAULT;
583 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
587 if (strcmp(longopts[optind].name, "debug") == 0)
591 errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
593 " [-i image.png] [-t]"
595 " (compiled with NOLIBCAIRO)"
601 /* We need (relatively) random numbers for highlighting a random part of
602 * the unlock indicator upon keypresses. */
606 ret = pam_start("i3lock", username, &conv, &pam_handle);
607 if (ret != PAM_SUCCESS)
608 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
610 /* Lock the area where we store the password in memory, we don’t want it to
611 * be swapped to disk. Since Linux 2.6.9, this does not require any
612 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
613 if (mlock(password, sizeof(password)) != 0)
614 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
616 /* Initialize connection to X11 */
617 if ((conn = xcb_connect(NULL, &nscreen)) == NULL ||
618 xcb_connection_has_error(conn))
619 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
621 /* if DPMS is enabled, check if the X server really supports it */
623 xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
624 xcb_dpms_capable_reply_t *dpmsr;
625 if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
626 if (!dpmsr->capable) {
627 fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
634 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
636 last_resolution[0] = screen->width_in_pixels;
637 last_resolution[1] = screen->height_in_pixels;
642 /* Create a pixmap to render on, fill it with the background color */
643 img = cairo_image_surface_create_from_png(image_path);
647 /* Pixmap on which the image is rendered to (if any) */
648 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
650 /* open the fullscreen window, already with the correct pixmap in place */
651 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
652 xcb_free_pixmap(conn, bg_pixmap);
654 cursor = create_cursor(conn, screen, win, curs_choice);
656 grab_pointer_and_keyboard(conn, screen, cursor);
658 symbols = xcb_key_symbols_alloc(conn);
659 numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
662 dpms_turn_off_screen(conn);
664 /* Initialize the libev event loop. */
665 main_loop = EV_DEFAULT;
666 if (main_loop == NULL)
667 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
669 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
670 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
671 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
673 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
674 ev_io_start(main_loop, xcb_watcher);
676 ev_check_init(xcb_check, xcb_check_cb);
677 ev_check_start(main_loop, xcb_check);
679 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
680 ev_prepare_start(main_loop, xcb_prepare);
683 ev_loop(main_loop, 0);