2 * vim:ts=4:sw=4:expandtab
4 * © 2010-2012 Michael Stapelberg
6 * See LICENSE for licensing information
19 #include <security/pam_appl.h>
20 #include <X11/Xlib-xcb.h>
25 #include <X11/XKBlib.h>
26 #include <X11/extensions/XKBfile.h>
27 #include <xkbcommon/xkbcommon.h>
32 #include <cairo/cairo-xcb.h>
38 #include "unlock_indicator.h"
41 /* We need this for libxkbfile */
42 static Display *display;
43 char color[7] = "ffffff";
44 uint32_t last_resolution[2];
46 static xcb_cursor_t cursor;
47 static pam_handle_t *pam_handle;
48 int input_position = 0;
49 /* Holds the password you enter (in UTF-8). */
50 static char password[512];
51 static bool beep = false;
52 bool debug_mode = false;
53 static bool dpms = false;
54 bool unlock_indicator = true;
55 static bool dont_fork = false;
56 struct ev_loop *main_loop;
57 static struct ev_timer *clear_pam_wrong_timeout;
58 extern unlock_state_t unlock_state;
59 extern pam_state_t pam_state;
61 static struct xkb_state *xkb_state;
62 static struct xkb_context *xkb_context;
63 static struct xkb_keymap *xkb_keymap;
66 cairo_surface_t *img = NULL;
70 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
71 #define isutf(c) (((c) & 0xC0) != 0x80)
74 * Decrements i to point to the previous unicode glyph
77 void u8_dec(char *s, int *i) {
78 (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
82 * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
83 * Necessary so that we can properly let xkbcommon track the keyboard state and
84 * translate keypresses to utf-8.
86 * Ideally, xkbcommon would ship something like this itself, but as of now
87 * (version 0.2.0), it doesn’t.
90 static bool load_keymap(void) {
93 memset(&result, '\0', sizeof(result));
94 result.xkb = XkbGetKeyboard(display, XkbAllMapComponentsMask, XkbUseCoreKbd);
95 if (result.xkb == NULL) {
96 fprintf(stderr, "[i3lock] XKB: XkbGetKeyboard failed\n");
100 FILE *temp = tmpfile();
102 fprintf(stderr, "[i3lock] could not create tempfile\n");
106 bool ok = XkbWriteXKBKeymap(temp, &result, false, false, NULL, NULL);
108 fprintf(stderr, "[i3lock] XkbWriteXKBKeymap failed\n");
114 if (xkb_context == NULL) {
115 if ((xkb_context = xkb_context_new(0)) == NULL) {
116 fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
121 if (xkb_keymap != NULL)
122 xkb_keymap_unref(xkb_keymap);
124 if ((xkb_keymap = xkb_keymap_new_from_file(xkb_context, temp, XKB_KEYMAP_FORMAT_TEXT_V1, 0)) == NULL) {
125 fprintf(stderr, "[i3lock] xkb_keymap_new_from_file failed\n");
129 struct xkb_state *new_state = xkb_state_new(xkb_keymap);
130 if (new_state == NULL) {
131 fprintf(stderr, "[i3lock] xkb_state_new failed\n");
135 if (xkb_state != NULL)
136 xkb_state_unref(xkb_state);
137 xkb_state = new_state;
141 XkbFreeKeyboard(result.xkb, XkbAllComponentsMask, true);
147 * Clears the memory which stored the password to be a bit safer against
151 static void clear_password_memory(void) {
152 /* A volatile pointer to the password buffer to prevent the compiler from
153 * optimizing this out. */
154 volatile char *vpassword = password;
155 for (int c = 0; c < sizeof(password); c++)
156 /* We store a non-random pattern which consists of the (irrelevant)
157 * index plus (!) the value of the beep variable. This prevents the
158 * compiler from optimizing the calls away, since the value of 'beep'
159 * is not known at compile-time. */
160 vpassword[c] = c + (int)beep;
165 * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
166 * authentication event.
169 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
170 DEBUG("clearing pam wrong\n");
171 pam_state = STATE_PAM_IDLE;
172 unlock_state = STATE_STARTED;
175 /* Now free this timeout. */
176 ev_timer_stop(main_loop, clear_pam_wrong_timeout);
177 free(clear_pam_wrong_timeout);
178 clear_pam_wrong_timeout = NULL;
181 static void input_done(void) {
182 if (input_position == 0)
185 if (clear_pam_wrong_timeout) {
186 ev_timer_stop(main_loop, clear_pam_wrong_timeout);
187 free(clear_pam_wrong_timeout);
188 clear_pam_wrong_timeout = NULL;
191 pam_state = STATE_PAM_VERIFY;
194 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
195 DEBUG("successfully authenticated\n");
196 clear_password_memory();
201 fprintf(stderr, "Authentication failure\n");
203 pam_state = STATE_PAM_WRONG;
206 /* Clear this state after 2 seconds (unless the user enters another
207 * password during that time). */
208 ev_now_update(main_loop);
209 if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
210 ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
211 ev_timer_start(main_loop, clear_pam_wrong_timeout);
214 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
216 stop_clear_indicator_timeout();
218 /* beep on authentication failure, if enabled */
226 * Called when the user releases a key. We need to leave the Mode_switch
227 * state when the user releases the Mode_switch key.
230 static void handle_key_release(xcb_key_release_event_t *event) {
231 xkb_state_update_key(xkb_state, event->detail, XKB_KEY_UP);
234 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
237 ev_timer_stop(main_loop, w);
242 * Handle key presses. Fixes state, then looks up the key symbol for the
243 * given keycode, then looks up the key symbol (as UCS-2), converts it to
244 * UTF-8 and stores it in the password array.
247 static void handle_key_press(xcb_key_press_event_t *event) {
252 ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
253 xkb_state_update_key(xkb_state, event->detail, XKB_KEY_DOWN);
255 /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
256 memset(buffer, '\0', sizeof(buffer));
257 n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
261 case XKB_KEY_KP_Enter:
262 password[input_position] = '\0';
266 clear_password_memory();
267 password[input_position] = '\0';
269 /* Hide the unlock indicator after a bit if the password buffer is
271 start_clear_indicator_timeout();
272 unlock_state = STATE_BACKSPACE_ACTIVE;
274 unlock_state = STATE_KEY_PRESSED;
277 case XKB_KEY_BackSpace:
278 if (input_position == 0)
281 /* decrement input_position to point to the previous glyph */
282 u8_dec(password, &input_position);
283 password[input_position] = '\0';
285 /* Hide the unlock indicator after a bit if the password buffer is
287 start_clear_indicator_timeout();
288 unlock_state = STATE_BACKSPACE_ACTIVE;
290 unlock_state = STATE_KEY_PRESSED;
294 if ((input_position + 8) >= sizeof(password))
298 /* FIXME: handle all of these? */
299 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
300 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
301 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
302 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
303 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
304 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
305 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
311 /* store it in the password array as UTF-8 */
312 memcpy(password+input_position, buffer, n-1);
313 input_position += n-1;
314 DEBUG("current password = %s\n", password);
316 unlock_state = STATE_KEY_ACTIVE;
318 unlock_state = STATE_KEY_PRESSED;
320 struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
322 ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
323 ev_timer_start(main_loop, timeout);
326 stop_clear_indicator_timeout();
330 * A visibility notify event will be received when the visibility (= can the
331 * user view the complete window) changes, so for example when a popup overlays
332 * some area of the i3lock window.
334 * In this case, we raise our window on top so that the popup (or whatever is
335 * hiding us) gets hidden.
338 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
339 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
340 uint32_t values[] = { XCB_STACK_MODE_ABOVE };
341 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
347 * Called when the keyboard mapping changes. We update our symbols.
350 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
351 /* We ignore errors — if the new keymap cannot be loaded it’s better if the
352 * screen stays locked and the user intervenes by using killall i3lock. */
357 * Called when the properties on the root window change, e.g. when the screen
358 * resolution changes. If so we update the window to cover the whole screen
359 * and also redraw the image, if any.
362 void handle_screen_resize(void) {
363 xcb_get_geometry_cookie_t geomc;
364 xcb_get_geometry_reply_t *geom;
365 geomc = xcb_get_geometry(conn, screen->root);
366 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
369 if (last_resolution[0] == geom->width &&
370 last_resolution[1] == geom->height) {
375 last_resolution[0] = geom->width;
376 last_resolution[1] = geom->height;
384 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
385 xcb_configure_window(conn, win, mask, last_resolution);
388 xinerama_query_screens();
393 * Callback function for PAM. We only react on password request callbacks.
396 static int conv_callback(int num_msg, const struct pam_message **msg,
397 struct pam_response **resp, void *appdata_ptr)
402 /* PAM expects an array of responses, one for each message */
403 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
408 for (int c = 0; c < num_msg; c++) {
409 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
410 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
413 /* return code is currently not used but should be set to zero */
414 resp[c]->resp_retcode = 0;
415 if ((resp[c]->resp = strdup(password)) == NULL) {
425 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
426 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
429 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
430 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
434 * Flush before blocking (and waiting for new events)
437 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
442 * Instead of polling the X connection socket we leave this to
443 * xcb_poll_for_event() which knows better than we can ever know.
446 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
447 xcb_generic_event_t *event;
449 while ((event = xcb_poll_for_event(conn)) != NULL) {
450 if (event->response_type == 0) {
451 xcb_generic_error_t *error = (xcb_generic_error_t*)event;
453 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
454 error->sequence, error->error_code);
459 /* Strip off the highest bit (set if the event is generated) */
460 int type = (event->response_type & 0x7F);
463 handle_key_press((xcb_key_press_event_t*)event);
466 case XCB_KEY_RELEASE:
467 handle_key_release((xcb_key_release_event_t*)event);
469 /* If this was the backspace or escape key we are back at an
470 * empty input, so turn off the screen if DPMS is enabled */
471 if (dpms && input_position == 0)
472 dpms_turn_off_screen(conn);
476 case XCB_VISIBILITY_NOTIFY:
477 handle_visibility_notify((xcb_visibility_notify_event_t*)event);
482 /* After the first MapNotify, we never fork again. We don’t
483 * expect to get another MapNotify, but better be sure… */
486 /* In the parent process, we exit */
492 case XCB_MAPPING_NOTIFY:
493 handle_mapping_notify((xcb_mapping_notify_event_t*)event);
496 case XCB_CONFIGURE_NOTIFY:
497 handle_screen_resize();
505 int main(int argc, char *argv[]) {
508 char *image_path = NULL;
511 struct pam_conv conv = {conv_callback, NULL};
512 int curs_choice = CURS_NONE;
515 struct option longopts[] = {
516 {"version", no_argument, NULL, 'v'},
517 {"nofork", no_argument, NULL, 'n'},
518 {"beep", no_argument, NULL, 'b'},
519 {"dpms", no_argument, NULL, 'd'},
520 {"color", required_argument, NULL, 'c'},
521 {"pointer", required_argument, NULL , 'p'},
522 {"debug", no_argument, NULL, 0},
523 {"help", no_argument, NULL, 'h'},
524 {"no-unlock-indicator", no_argument, NULL, 'u'},
526 {"image", required_argument, NULL, 'i'},
527 {"tiling", no_argument, NULL, 't'},
529 {NULL, no_argument, NULL, 0}
532 if ((username = getenv("USER")) == NULL)
533 errx(1, "USER environment variable not set, please set it.\n");
535 while ((o = getopt_long(argc, argv, "hvnbdc:p:u"
539 , longopts, &optind)) != -1) {
542 errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
555 /* Skip # if present */
559 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
560 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
565 unlock_indicator = false;
569 image_path = strdup(optarg);
576 if (!strcmp(optarg, "win")) {
577 curs_choice = CURS_WIN;
578 } else if (!strcmp(optarg, "default")) {
579 curs_choice = CURS_DEFAULT;
581 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
585 if (strcmp(longopts[optind].name, "debug") == 0)
589 errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
591 " [-i image.png] [-t]"
593 " (compiled with NOLIBCAIRO)"
599 /* We need (relatively) random numbers for highlighting a random part of
600 * the unlock indicator upon keypresses. */
604 ret = pam_start("i3lock", username, &conv, &pam_handle);
605 if (ret != PAM_SUCCESS)
606 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
608 /* Using mlock() as non-super-user seems only possible in Linux. Users of other
609 * operating systems should use encrypted swap/no swap (or remove the ifdef and
610 * run i3lock as super-user). */
611 #if defined(__linux__)
612 /* Lock the area where we store the password in memory, we don’t want it to
613 * be swapped to disk. Since Linux 2.6.9, this does not require any
614 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
615 if (mlock(password, sizeof(password)) != 0)
616 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
619 /* Initialize connection to X11 */
620 if ((display = XOpenDisplay(NULL)) == NULL)
621 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
622 XSetEventQueueOwner(display, XCBOwnsEventQueue);
623 conn = XGetXCBConnection(display);
625 /* Double checking that connection is good and operatable with xcb */
626 if (xcb_connection_has_error(conn))
627 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
629 /* When we cannot initially load the keymap, we better exit */
631 errx(EXIT_FAILURE, "Could not load keymap");
634 xinerama_query_screens();
636 /* if DPMS is enabled, check if the X server really supports it */
638 xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
639 xcb_dpms_capable_reply_t *dpmsr;
640 if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
641 if (!dpmsr->capable) {
643 fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
650 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
652 last_resolution[0] = screen->width_in_pixels;
653 last_resolution[1] = screen->height_in_pixels;
655 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
656 (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
660 /* Create a pixmap to render on, fill it with the background color */
661 img = cairo_image_surface_create_from_png(image_path);
662 /* In case loading failed, we just pretend no -i was specified. */
663 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
664 fprintf(stderr, "Could not load image \"%s\": cairo surface status %d\n",
665 image_path, cairo_surface_status(img));
671 /* Pixmap on which the image is rendered to (if any) */
672 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
674 /* open the fullscreen window, already with the correct pixmap in place */
675 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
676 xcb_free_pixmap(conn, bg_pixmap);
678 cursor = create_cursor(conn, screen, win, curs_choice);
680 grab_pointer_and_keyboard(conn, screen, cursor);
683 dpms_turn_off_screen(conn);
685 /* Initialize the libev event loop. */
686 main_loop = EV_DEFAULT;
687 if (main_loop == NULL)
688 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
690 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
691 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
692 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
694 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
695 ev_io_start(main_loop, xcb_watcher);
697 ev_check_init(xcb_check, xcb_check_cb);
698 ev_check_start(main_loop, xcb_check);
700 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
701 ev_prepare_start(main_loop, xcb_prepare);
703 /* Invoke the event callback once to catch all the events which were
704 * received up until now. ev will only pick up new events (when the X11
705 * file descriptor becomes readable). */
706 ev_invoke(main_loop, xcb_check, 0);
707 ev_loop(main_loop, 0);