2 * vim:ts=4:sw=4:expandtab
4 * © 2010-2013 Michael Stapelberg
6 * See LICENSE for licensing information
19 #include <security/pam_appl.h>
20 #include <X11/Xlib-xcb.h>
26 #include <X11/XKBlib.h>
27 #include <X11/extensions/XKBfile.h>
28 #include <xkbcommon/xkbcommon.h>
30 #include <cairo/cairo-xcb.h>
35 #include "unlock_indicator.h"
38 /* We need this for libxkbfile */
39 static Display *display;
40 char color[7] = "ffffff";
41 uint32_t last_resolution[2];
43 static xcb_cursor_t cursor;
44 static pam_handle_t *pam_handle;
45 int input_position = 0;
46 /* Holds the password you enter (in UTF-8). */
47 static char password[512];
48 static bool beep = false;
49 bool debug_mode = false;
50 static bool dpms = false;
51 bool unlock_indicator = true;
52 static bool dont_fork = false;
53 struct ev_loop *main_loop;
54 static struct ev_timer *clear_pam_wrong_timeout;
55 extern unlock_state_t unlock_state;
56 extern pam_state_t pam_state;
58 static struct xkb_state *xkb_state;
59 static struct xkb_context *xkb_context;
60 static struct xkb_keymap *xkb_keymap;
62 cairo_surface_t *img = NULL;
64 bool ignore_empty_password = false;
66 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
67 #define isutf(c) (((c) & 0xC0) != 0x80)
70 * Decrements i to point to the previous unicode glyph
73 void u8_dec(char *s, int *i) {
74 (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
78 * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
79 * Necessary so that we can properly let xkbcommon track the keyboard state and
80 * translate keypresses to utf-8.
82 * Ideally, xkbcommon would ship something like this itself, but as of now
83 * (version 0.2.0), it doesn’t.
85 * TODO: Once xcb-xkb is enabled by default and released, we should port this
86 * code to xcb-xkb. See also https://github.com/xkbcommon/libxkbcommon/issues/1
89 static bool load_keymap(void) {
92 memset(&result, '\0', sizeof(result));
93 result.xkb = XkbGetKeyboard(display, XkbAllMapComponentsMask, XkbUseCoreKbd);
94 if (result.xkb == NULL) {
95 fprintf(stderr, "[i3lock] XKB: XkbGetKeyboard failed\n");
99 FILE *temp = tmpfile();
101 fprintf(stderr, "[i3lock] could not create tempfile\n");
105 bool ok = XkbWriteXKBKeymap(temp, &result, false, false, NULL, NULL);
107 fprintf(stderr, "[i3lock] XkbWriteXKBKeymap failed\n");
113 if (xkb_context == NULL) {
114 if ((xkb_context = xkb_context_new(0)) == NULL) {
115 fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
120 if (xkb_keymap != NULL)
121 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");
128 struct xkb_state *new_state = xkb_state_new(xkb_keymap);
129 if (new_state == NULL) {
130 fprintf(stderr, "[i3lock] xkb_state_new failed\n");
134 /* Get the initial modifier state to be in sync with the X server.
135 * See https://github.com/xkbcommon/libxkbcommon/issues/1 for why we ignore
136 * the base and latched fields. */
137 XkbStateRec state_rec;
138 XkbGetState(display, XkbUseCoreKbd, &state_rec);
140 xkb_state_update_mask(new_state,
141 0, 0, state_rec.locked_mods,
142 0, 0, state_rec.locked_group);
144 if (xkb_state != NULL)
145 xkb_state_unref(xkb_state);
146 xkb_state = new_state;
150 XkbFreeKeyboard(result.xkb, XkbAllComponentsMask, true);
156 * Clears the memory which stored the password to be a bit safer against
160 static void clear_password_memory(void) {
161 /* A volatile pointer to the password buffer to prevent the compiler from
162 * optimizing this out. */
163 volatile char *vpassword = password;
164 for (int c = 0; c < sizeof(password); c++)
165 /* We store a non-random pattern which consists of the (irrelevant)
166 * index plus (!) the value of the beep variable. This prevents the
167 * compiler from optimizing the calls away, since the value of 'beep'
168 * is not known at compile-time. */
169 vpassword[c] = c + (int)beep;
174 * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
175 * authentication event.
178 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
179 DEBUG("clearing pam wrong\n");
180 pam_state = STATE_PAM_IDLE;
181 unlock_state = STATE_STARTED;
184 /* Now free this timeout. */
185 ev_timer_stop(main_loop, clear_pam_wrong_timeout);
186 free(clear_pam_wrong_timeout);
187 clear_pam_wrong_timeout = NULL;
190 static void clear_input(void) {
192 clear_password_memory();
193 password[input_position] = '\0';
195 /* Hide the unlock indicator after a bit if the password buffer is
197 start_clear_indicator_timeout();
198 unlock_state = STATE_BACKSPACE_ACTIVE;
200 unlock_state = STATE_KEY_PRESSED;
203 static void auth_failed(void) {
205 fprintf(stderr, "Authentication failure\n");
207 pam_state = STATE_PAM_WRONG;
210 /* Clear this state after 2 seconds (unless the user enters another
211 * password during that time). */
212 ev_now_update(main_loop);
213 if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
214 ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
215 ev_timer_start(main_loop, clear_pam_wrong_timeout);
218 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
220 stop_clear_indicator_timeout();
222 /* beep on authentication failure, if enabled */
229 static void child_cb(EV_P_ ev_child *child_watcher, int revents) {
230 if (child_watcher->rstatus != 0) {
231 DEBUG("Authentication successfull\n");
232 clear_password_memory();
238 ev_child_stop(main_loop, child_watcher);
242 static void input_done(void) {
243 if (pam_state == STATE_PAM_VERIFY) {
247 if (clear_pam_wrong_timeout) {
248 ev_timer_stop(main_loop, clear_pam_wrong_timeout);
249 free(clear_pam_wrong_timeout);
250 clear_pam_wrong_timeout = NULL;
253 pam_state = STATE_PAM_VERIFY;
256 /* fork to unblock pam_authenticate */
259 exit(pam_authenticate(pam_handle, 0) == PAM_SUCCESS);
260 } else if (cpid > 0) {
262 struct ev_child *child_watcher = calloc(sizeof(struct ev_io), 1);
263 ev_child_init(child_watcher, child_cb, cpid, 0);
264 ev_child_set(child_watcher, cpid, 0);
265 ev_child_start(EV_DEFAULT_ child_watcher);
266 } else if (cpid < 0) {
267 DEBUG("Could not fork");
268 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
269 DEBUG("successfully authenticated\n");
270 clear_password_memory();
278 * Called when the user releases a key. We need to leave the Mode_switch
279 * state when the user releases the Mode_switch key.
282 static void handle_key_release(xcb_key_release_event_t *event) {
283 xkb_state_update_key(xkb_state, event->detail, XKB_KEY_UP);
286 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
289 ev_timer_stop(main_loop, w);
294 * Handle key presses. Fixes state, then looks up the key symbol for the
295 * given keycode, then looks up the key symbol (as UCS-2), converts it to
296 * UTF-8 and stores it in the password array.
299 static void handle_key_press(xcb_key_press_event_t *event) {
305 ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
306 ctrl = xkb_state_mod_name_is_active(xkb_state, "Control", XKB_STATE_MODS_DEPRESSED);
307 xkb_state_update_key(xkb_state, event->detail, XKB_KEY_DOWN);
309 /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
310 memset(buffer, '\0', sizeof(buffer));
311 n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
315 case XKB_KEY_KP_Enter:
316 case XKB_KEY_XF86ScreenSaver:
317 if (ignore_empty_password && input_position == 0) {
321 password[input_position] = '\0';
322 unlock_state = STATE_KEY_PRESSED;
329 DEBUG("C-u pressed\n");
339 case XKB_KEY_BackSpace:
340 if (input_position == 0)
343 /* decrement input_position to point to the previous glyph */
344 u8_dec(password, &input_position);
345 password[input_position] = '\0';
347 /* Hide the unlock indicator after a bit if the password buffer is
349 start_clear_indicator_timeout();
350 unlock_state = STATE_BACKSPACE_ACTIVE;
352 unlock_state = STATE_KEY_PRESSED;
356 if ((input_position + 8) >= sizeof(password))
360 /* FIXME: handle all of these? */
361 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
362 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
363 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
364 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
365 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
366 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
367 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
373 /* store it in the password array as UTF-8 */
374 memcpy(password+input_position, buffer, n-1);
375 input_position += n-1;
376 DEBUG("current password = %.*s\n", input_position, password);
378 unlock_state = STATE_KEY_ACTIVE;
380 unlock_state = STATE_KEY_PRESSED;
382 struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
384 ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
385 ev_timer_start(main_loop, timeout);
388 stop_clear_indicator_timeout();
392 * A visibility notify event will be received when the visibility (= can the
393 * user view the complete window) changes, so for example when a popup overlays
394 * some area of the i3lock window.
396 * In this case, we raise our window on top so that the popup (or whatever is
397 * hiding us) gets hidden.
400 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
401 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
402 uint32_t values[] = { XCB_STACK_MODE_ABOVE };
403 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
409 * Called when the keyboard mapping changes. We update our symbols.
412 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
413 /* We ignore errors — if the new keymap cannot be loaded it’s better if the
414 * screen stays locked and the user intervenes by using killall i3lock. */
419 * Called when the properties on the root window change, e.g. when the screen
420 * resolution changes. If so we update the window to cover the whole screen
421 * and also redraw the image, if any.
424 void handle_screen_resize(void) {
425 xcb_get_geometry_cookie_t geomc;
426 xcb_get_geometry_reply_t *geom;
427 geomc = xcb_get_geometry(conn, screen->root);
428 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
431 if (last_resolution[0] == geom->width &&
432 last_resolution[1] == geom->height) {
437 last_resolution[0] = geom->width;
438 last_resolution[1] = geom->height;
444 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
445 xcb_configure_window(conn, win, mask, last_resolution);
448 xinerama_query_screens();
453 * Callback function for PAM. We only react on password request callbacks.
456 static int conv_callback(int num_msg, const struct pam_message **msg,
457 struct pam_response **resp, void *appdata_ptr)
462 /* PAM expects an array of responses, one for each message */
463 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
468 for (int c = 0; c < num_msg; c++) {
469 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
470 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
473 /* return code is currently not used but should be set to zero */
474 resp[c]->resp_retcode = 0;
475 if ((resp[c]->resp = strdup(password)) == NULL) {
485 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
486 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
489 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
490 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
494 * Flush before blocking (and waiting for new events)
497 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
502 * Instead of polling the X connection socket we leave this to
503 * xcb_poll_for_event() which knows better than we can ever know.
506 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
507 xcb_generic_event_t *event;
509 while ((event = xcb_poll_for_event(conn)) != NULL) {
510 if (event->response_type == 0) {
511 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
513 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
514 error->sequence, error->error_code);
519 /* Strip off the highest bit (set if the event is generated) */
520 int type = (event->response_type & 0x7F);
523 handle_key_press((xcb_key_press_event_t*)event);
526 case XCB_KEY_RELEASE:
527 handle_key_release((xcb_key_release_event_t*)event);
529 /* If this was the backspace or escape key we are back at an
530 * empty input, so turn off the screen if DPMS is enabled */
531 if (dpms && input_position == 0)
532 dpms_turn_off_screen(conn);
536 case XCB_VISIBILITY_NOTIFY:
537 handle_visibility_notify((xcb_visibility_notify_event_t*)event);
542 /* After the first MapNotify, we never fork again. We don’t
543 * expect to get another MapNotify, but better be sure… */
546 /* In the parent process, we exit */
550 ev_loop_fork(EV_DEFAULT);
554 case XCB_MAPPING_NOTIFY:
555 handle_mapping_notify((xcb_mapping_notify_event_t*)event);
558 case XCB_CONFIGURE_NOTIFY:
559 handle_screen_resize();
567 int main(int argc, char *argv[]) {
569 char *image_path = NULL;
571 struct pam_conv conv = {conv_callback, NULL};
572 int curs_choice = CURS_NONE;
575 struct option longopts[] = {
576 {"version", no_argument, NULL, 'v'},
577 {"nofork", no_argument, NULL, 'n'},
578 {"beep", no_argument, NULL, 'b'},
579 {"dpms", no_argument, NULL, 'd'},
580 {"color", required_argument, NULL, 'c'},
581 {"pointer", required_argument, NULL , 'p'},
582 {"debug", no_argument, NULL, 0},
583 {"help", no_argument, NULL, 'h'},
584 {"no-unlock-indicator", no_argument, NULL, 'u'},
585 {"image", required_argument, NULL, 'i'},
586 {"tiling", no_argument, NULL, 't'},
587 {"ignore-empty-password", no_argument, NULL, 'e'},
588 {NULL, no_argument, NULL, 0}
591 if ((username = getenv("USER")) == NULL)
592 errx(1, "USER environment variable not set, please set it.\n");
594 while ((o = getopt_long(argc, argv, "hvnbdc:p:ui:te", longopts, &optind)) != -1) {
597 errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
610 /* Skip # if present */
614 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
615 errx(1, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
620 unlock_indicator = false;
623 image_path = strdup(optarg);
629 if (!strcmp(optarg, "win")) {
630 curs_choice = CURS_WIN;
631 } else if (!strcmp(optarg, "default")) {
632 curs_choice = CURS_DEFAULT;
634 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
638 ignore_empty_password = true;
641 if (strcmp(longopts[optind].name, "debug") == 0)
645 errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
646 " [-i image.png] [-t] [-e]"
651 /* We need (relatively) random numbers for highlighting a random part of
652 * the unlock indicator upon keypresses. */
656 ret = pam_start("i3lock", username, &conv, &pam_handle);
657 if (ret != PAM_SUCCESS)
658 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
660 /* Using mlock() as non-super-user seems only possible in Linux. Users of other
661 * operating systems should use encrypted swap/no swap (or remove the ifdef and
662 * run i3lock as super-user). */
663 #if defined(__linux__)
664 /* Lock the area where we store the password in memory, we don’t want it to
665 * be swapped to disk. Since Linux 2.6.9, this does not require any
666 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
667 if (mlock(password, sizeof(password)) != 0)
668 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
671 /* Initialize connection to X11 */
672 if ((display = XOpenDisplay(NULL)) == NULL)
673 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
674 XSetEventQueueOwner(display, XCBOwnsEventQueue);
675 conn = XGetXCBConnection(display);
677 /* Double checking that connection is good and operatable with xcb */
678 if (xcb_connection_has_error(conn))
679 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
681 /* When we cannot initially load the keymap, we better exit */
683 errx(EXIT_FAILURE, "Could not load keymap");
686 xinerama_query_screens();
688 /* if DPMS is enabled, check if the X server really supports it */
690 xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
691 xcb_dpms_capable_reply_t *dpmsr;
692 if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
693 if (!dpmsr->capable) {
695 fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
702 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
704 last_resolution[0] = screen->width_in_pixels;
705 last_resolution[1] = screen->height_in_pixels;
707 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
708 (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
711 /* Create a pixmap to render on, fill it with the background color */
712 img = cairo_image_surface_create_from_png(image_path);
713 /* In case loading failed, we just pretend no -i was specified. */
714 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
715 fprintf(stderr, "Could not load image \"%s\": %s\n",
716 image_path, cairo_status_to_string(cairo_surface_status(img)));
721 /* Pixmap on which the image is rendered to (if any) */
722 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
724 /* open the fullscreen window, already with the correct pixmap in place */
725 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
726 xcb_free_pixmap(conn, bg_pixmap);
728 cursor = create_cursor(conn, screen, win, curs_choice);
730 grab_pointer_and_keyboard(conn, screen, cursor);
731 /* Load the keymap again to sync the current modifier state. Since we first
732 * loaded the keymap, there might have been changes, but starting from now,
733 * we should get all key presses/releases due to having grabbed the
738 dpms_turn_off_screen(conn);
740 /* Initialize the libev event loop. */
741 main_loop = EV_DEFAULT;
742 if (main_loop == NULL)
743 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
745 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
746 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
747 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
749 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
750 ev_io_start(main_loop, xcb_watcher);
752 ev_check_init(xcb_check, xcb_check_cb);
753 ev_check_start(main_loop, xcb_check);
755 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
756 ev_prepare_start(main_loop, xcb_prepare);
758 /* Invoke the event callback once to catch all the events which were
759 * received up until now. ev will only pick up new events (when the X11
760 * file descriptor becomes readable). */
761 ev_invoke(main_loop, xcb_check, 0);
762 ev_loop(main_loop, 0);