2 * vim:ts=4:sw=4:expandtab
4 * © 2010 Michael Stapelberg
6 * See LICENSE for licensing information
14 #include <sys/types.h>
27 #include <security/pam_appl.h>
33 #include <xkbcommon/xkbcommon.h>
34 #include <xkbcommon/xkbcommon-compose.h>
35 #include <xkbcommon/xkbcommon-x11.h>
37 #include <cairo/cairo-xcb.h>
39 #include <strings.h> /* explicit_bzero(3) */
41 #include <xcb/xcb_aux.h>
42 #include <xcb/randr.h>
47 #include "unlock_indicator.h"
51 #define TSTAMP_N_SECS(n) (n * 1.0)
52 #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
53 #define START_TIMER(timer_obj, timeout, callback) \
54 timer_obj = start_timer(timer_obj, timeout, callback)
55 #define STOP_TIMER(timer_obj) \
56 timer_obj = stop_timer(timer_obj)
58 typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
59 static void input_done(void);
61 char color[7] = "ffffff";
62 uint32_t last_resolution[2];
64 static xcb_cursor_t cursor;
66 static pam_handle_t *pam_handle;
68 int input_position = 0;
69 /* Holds the password you enter (in UTF-8). */
70 static char password[512];
71 static bool beep = false;
72 bool debug_mode = false;
73 bool unlock_indicator = true;
74 char *modifier_string = NULL;
75 static bool dont_fork = false;
76 struct ev_loop *main_loop;
77 static struct ev_timer *clear_auth_wrong_timeout;
78 static struct ev_timer *clear_indicator_timeout;
79 static struct ev_timer *discard_passwd_timeout;
80 extern unlock_state_t unlock_state;
81 extern auth_state_t auth_state;
82 int failed_attempts = 0;
83 bool show_failed_attempts = false;
84 bool retry_verification = false;
86 static struct xkb_state *xkb_state;
87 static struct xkb_context *xkb_context;
88 static struct xkb_keymap *xkb_keymap;
89 static struct xkb_compose_table *xkb_compose_table;
90 static struct xkb_compose_state *xkb_compose_state;
91 static uint8_t xkb_base_event;
92 static uint8_t xkb_base_error;
93 static int randr_base = -1;
95 cairo_surface_t *img = NULL;
97 bool ignore_empty_password = false;
98 bool skip_repeated_empty_password = false;
100 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
101 #define isutf(c) (((c)&0xC0) != 0x80)
104 * Decrements i to point to the previous unicode glyph
107 void u8_dec(char *s, int *i) {
108 (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
112 * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
113 * Necessary so that we can properly let xkbcommon track the keyboard state and
114 * translate keypresses to utf-8.
117 static bool load_keymap(void) {
118 if (xkb_context == NULL) {
119 if ((xkb_context = xkb_context_new(0)) == NULL) {
120 fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
125 xkb_keymap_unref(xkb_keymap);
127 int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
128 DEBUG("device = %d\n", device_id);
129 if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
130 fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
134 struct xkb_state *new_state =
135 xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
136 if (new_state == NULL) {
137 fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
141 xkb_state_unref(xkb_state);
142 xkb_state = new_state;
148 * Loads the XKB compose table from the given locale.
151 static bool load_compose_table(const char *locale) {
152 xkb_compose_table_unref(xkb_compose_table);
154 if ((xkb_compose_table = xkb_compose_table_new_from_locale(xkb_context, locale, 0)) == NULL) {
155 fprintf(stderr, "[i3lock] xkb_compose_table_new_from_locale failed\n");
159 struct xkb_compose_state *new_compose_state = xkb_compose_state_new(xkb_compose_table, 0);
160 if (new_compose_state == NULL) {
161 fprintf(stderr, "[i3lock] xkb_compose_state_new failed\n");
165 xkb_compose_state_unref(xkb_compose_state);
166 xkb_compose_state = new_compose_state;
172 * Clears the memory which stored the password to be a bit safer against
176 static void clear_password_memory(void) {
178 /* Use explicit_bzero(3) which was explicitly designed not to be
179 * optimized out by the compiler. */
180 explicit_bzero(password, strlen(password));
182 /* A volatile pointer to the password buffer to prevent the compiler from
183 * optimizing this out. */
184 volatile char *vpassword = password;
185 for (size_t c = 0; c < sizeof(password); c++)
186 /* We store a non-random pattern which consists of the (irrelevant)
187 * index plus (!) the value of the beep variable. This prevents the
188 * compiler from optimizing the calls away, since the value of 'beep'
189 * is not known at compile-time. */
190 vpassword[c] = c + (int)beep;
194 ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
196 ev_timer_stop(main_loop, timer_obj);
197 ev_timer_set(timer_obj, timeout, 0.);
198 ev_timer_start(main_loop, timer_obj);
200 /* When there is no memory, we just don’t have a timeout. We cannot
201 * exit() here, since that would effectively unlock the screen. */
202 timer_obj = calloc(sizeof(struct ev_timer), 1);
204 ev_timer_init(timer_obj, callback, timeout, 0.);
205 ev_timer_start(main_loop, timer_obj);
211 ev_timer *stop_timer(ev_timer *timer_obj) {
213 ev_timer_stop(main_loop, timer_obj);
220 * Neccessary calls after ending input via enter or others
223 static void finish_input(void) {
224 password[input_position] = '\0';
225 unlock_state = STATE_KEY_PRESSED;
231 * Resets auth_state to STATE_AUTH_IDLE 2 seconds after an unsuccessful
232 * authentication event.
235 static void clear_auth_wrong(EV_P_ ev_timer *w, int revents) {
236 DEBUG("clearing auth wrong\n");
237 auth_state = STATE_AUTH_IDLE;
240 /* Clear modifier string. */
241 if (modifier_string != NULL) {
242 free(modifier_string);
243 modifier_string = NULL;
246 /* Now free this timeout. */
247 STOP_TIMER(clear_auth_wrong_timeout);
249 /* retry with input done during auth verification */
250 if (retry_verification) {
251 retry_verification = false;
256 static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
258 STOP_TIMER(clear_indicator_timeout);
261 static void clear_input(void) {
263 clear_password_memory();
264 password[input_position] = '\0';
267 static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
269 STOP_TIMER(discard_passwd_timeout);
272 static void input_done(void) {
273 STOP_TIMER(clear_auth_wrong_timeout);
274 auth_state = STATE_AUTH_VERIFY;
275 unlock_state = STATE_STARTED;
281 if (!(pw = getpwuid(getuid())))
282 errx(1, "unknown uid %u.", getuid());
284 if (auth_userokay(pw->pw_name, NULL, NULL, password) != 0) {
285 DEBUG("successfully authenticated\n");
286 clear_password_memory();
288 ev_break(EV_DEFAULT, EVBREAK_ALL);
292 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
293 DEBUG("successfully authenticated\n");
294 clear_password_memory();
296 /* PAM credentials should be refreshed, this will for example update any kerberos tickets.
297 * Related to credentials pam_end() needs to be called to cleanup any temporary
298 * credentials like kerberos /tmp/krb5cc_pam_* files which may of been left behind if the
299 * refresh of the credentials failed. */
300 pam_setcred(pam_handle, PAM_REFRESH_CRED);
301 pam_end(pam_handle, PAM_SUCCESS);
303 ev_break(EV_DEFAULT, EVBREAK_ALL);
309 fprintf(stderr, "Authentication failure\n");
311 /* Get state of Caps and Num lock modifiers, to be displayed in
312 * STATE_AUTH_WRONG state */
313 xkb_mod_index_t idx, num_mods;
314 const char *mod_name;
316 num_mods = xkb_keymap_num_mods(xkb_keymap);
318 for (idx = 0; idx < num_mods; idx++) {
319 if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
322 mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
323 if (mod_name == NULL)
326 /* Replace certain xkb names with nicer, human-readable ones. */
327 if (strcmp(mod_name, XKB_MOD_NAME_CAPS) == 0)
328 mod_name = "Caps Lock";
329 else if (strcmp(mod_name, XKB_MOD_NAME_ALT) == 0)
331 else if (strcmp(mod_name, XKB_MOD_NAME_NUM) == 0)
332 mod_name = "Num Lock";
333 else if (strcmp(mod_name, XKB_MOD_NAME_LOGO) == 0)
337 if (modifier_string == NULL) {
338 if (asprintf(&tmp, "%s", mod_name) != -1)
339 modifier_string = tmp;
340 } else if (asprintf(&tmp, "%s, %s", modifier_string, mod_name) != -1) {
341 free(modifier_string);
342 modifier_string = tmp;
346 auth_state = STATE_AUTH_WRONG;
347 failed_attempts += 1;
349 if (unlock_indicator)
352 /* Clear this state after 2 seconds (unless the user enters another
353 * password during that time). */
354 ev_now_update(main_loop);
355 START_TIMER(clear_auth_wrong_timeout, TSTAMP_N_SECS(2), clear_auth_wrong);
357 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
359 STOP_TIMER(clear_indicator_timeout);
361 /* beep on authentication failure, if enabled */
368 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
373 static bool skip_without_validation(void) {
374 if (input_position != 0)
377 if (skip_repeated_empty_password || ignore_empty_password)
384 * Handle key presses. Fixes state, then looks up the key symbol for the
385 * given keycode, then looks up the key symbol (as UCS-2), converts it to
386 * UTF-8 and stores it in the password array.
389 static void handle_key_press(xcb_key_press_event_t *event) {
394 bool composed = false;
396 ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
397 ctrl = xkb_state_mod_name_is_active(xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_DEPRESSED);
399 /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
400 memset(buffer, '\0', sizeof(buffer));
402 if (xkb_compose_state && xkb_compose_state_feed(xkb_compose_state, ksym) == XKB_COMPOSE_FEED_ACCEPTED) {
403 switch (xkb_compose_state_get_status(xkb_compose_state)) {
404 case XKB_COMPOSE_NOTHING:
406 case XKB_COMPOSE_COMPOSING:
408 case XKB_COMPOSE_COMPOSED:
409 /* xkb_compose_state_get_utf8 doesn't include the terminating byte in the return value
410 * as xkb_keysym_to_utf8 does. Adding one makes the variable n consistent. */
411 n = xkb_compose_state_get_utf8(xkb_compose_state, buffer, sizeof(buffer)) + 1;
412 ksym = xkb_compose_state_get_one_sym(xkb_compose_state);
415 case XKB_COMPOSE_CANCELLED:
416 xkb_compose_state_reset(xkb_compose_state);
422 n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
429 case XKB_KEY_KP_Enter:
430 case XKB_KEY_XF86ScreenSaver:
431 if ((ksym == XKB_KEY_j || ksym == XKB_KEY_m) && !ctrl)
434 if (auth_state == STATE_AUTH_WRONG) {
435 retry_verification = true;
439 if (skip_without_validation()) {
444 skip_repeated_empty_password = true;
447 skip_repeated_empty_password = false;
448 // A new password is being entered, but a previous one is pending.
449 // Discard the old one and clear the retry_verification flag.
450 if (retry_verification) {
451 retry_verification = false;
459 if ((ksym == XKB_KEY_u && ctrl) ||
460 ksym == XKB_KEY_Escape) {
461 DEBUG("C-u pressed\n");
463 /* Also hide the unlock indicator */
464 if (unlock_indicator)
471 case XKB_KEY_KP_Delete:
472 /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
473 * to move the cursor when entering a password. We need to eat this
474 * key press so that it won’t be treated as part of the password,
479 case XKB_KEY_BackSpace:
480 if (ksym == XKB_KEY_h && !ctrl)
483 if (input_position == 0) {
484 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
485 unlock_state = STATE_NOTHING_TO_DELETE;
490 /* decrement input_position to point to the previous glyph */
491 u8_dec(password, &input_position);
492 password[input_position] = '\0';
494 /* Hide the unlock indicator after a bit if the password buffer is
496 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
497 unlock_state = STATE_BACKSPACE_ACTIVE;
499 unlock_state = STATE_KEY_PRESSED;
503 if ((input_position + 8) >= (int)sizeof(password))
507 /* FIXME: handle all of these? */
508 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
509 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
510 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
511 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
512 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
513 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
514 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
520 /* store it in the password array as UTF-8 */
521 memcpy(password + input_position, buffer, n - 1);
522 input_position += n - 1;
523 DEBUG("current password = %.*s\n", input_position, password);
525 if (unlock_indicator) {
526 unlock_state = STATE_KEY_ACTIVE;
528 unlock_state = STATE_KEY_PRESSED;
530 struct ev_timer *timeout = NULL;
531 START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
532 STOP_TIMER(clear_indicator_timeout);
535 START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
539 * A visibility notify event will be received when the visibility (= can the
540 * user view the complete window) changes, so for example when a popup overlays
541 * some area of the i3lock window.
543 * In this case, we raise our window on top so that the popup (or whatever is
544 * hiding us) gets hidden.
547 static void handle_visibility_notify(xcb_connection_t *conn,
548 xcb_visibility_notify_event_t *event) {
549 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
550 uint32_t values[] = {XCB_STACK_MODE_ABOVE};
551 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
557 * Called when the keyboard mapping changes. We update our symbols.
559 * We ignore errors — if the new keymap cannot be loaded it’s better if the
560 * screen stays locked and the user intervenes by using killall i3lock.
563 static void process_xkb_event(xcb_generic_event_t *gevent) {
566 uint8_t response_type;
569 xcb_timestamp_t time;
572 xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
573 xcb_xkb_map_notify_event_t map_notify;
574 xcb_xkb_state_notify_event_t state_notify;
575 } *event = (union xkb_event *)gevent;
577 DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
579 if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
583 * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
584 * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
587 switch (event->any.xkbType) {
588 case XCB_XKB_NEW_KEYBOARD_NOTIFY:
589 if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
593 case XCB_XKB_MAP_NOTIFY:
597 case XCB_XKB_STATE_NOTIFY:
598 xkb_state_update_mask(xkb_state,
599 event->state_notify.baseMods,
600 event->state_notify.latchedMods,
601 event->state_notify.lockedMods,
602 event->state_notify.baseGroup,
603 event->state_notify.latchedGroup,
604 event->state_notify.lockedGroup);
610 * Called when the properties on the root window change, e.g. when the screen
611 * resolution changes. If so we update the window to cover the whole screen
612 * and also redraw the image, if any.
615 void handle_screen_resize(void) {
616 xcb_get_geometry_cookie_t geomc;
617 xcb_get_geometry_reply_t *geom;
618 geomc = xcb_get_geometry(conn, screen->root);
619 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
622 if (last_resolution[0] == geom->width &&
623 last_resolution[1] == geom->height) {
628 last_resolution[0] = geom->width;
629 last_resolution[1] = geom->height;
635 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
636 xcb_configure_window(conn, win, mask, last_resolution);
639 randr_query(screen->root);
643 static bool verify_png_image(const char *image_path) {
648 /* Check file exists and has correct PNG header */
649 FILE *png_file = fopen(image_path, "r");
650 if (png_file == NULL) {
651 fprintf(stderr, "Image file path \"%s\" cannot be opened: %s\n", image_path, strerror(errno));
654 unsigned char png_header[8];
655 memset(png_header, '\0', sizeof(png_header));
656 int bytes_read = fread(png_header, 1, sizeof(png_header), png_file);
658 if (bytes_read != sizeof(png_header)) {
659 fprintf(stderr, "Could not read PNG header from \"%s\"\n", image_path);
663 // Check PNG header according to the specification, available at:
664 // https://www.w3.org/TR/2003/REC-PNG-20031110/#5PNG-file-signature
665 static unsigned char PNG_REFERENCE_HEADER[8] = {137, 80, 78, 71, 13, 10, 26, 10};
666 if (memcmp(PNG_REFERENCE_HEADER, png_header, sizeof(png_header)) != 0) {
667 fprintf(stderr, "File \"%s\" does not start with a PNG header. i3lock currently only supports loading PNG files.\n", image_path);
675 * Callback function for PAM. We only react on password request callbacks.
678 static int conv_callback(int num_msg, const struct pam_message **msg,
679 struct pam_response **resp, void *appdata_ptr) {
683 /* PAM expects an array of responses, one for each message */
684 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
689 for (int c = 0; c < num_msg; c++) {
690 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
691 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
694 /* return code is currently not used but should be set to zero */
695 resp[c]->resp_retcode = 0;
696 if ((resp[c]->resp = strdup(password)) == NULL) {
707 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
708 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
711 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
712 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
716 * Flush before blocking (and waiting for new events)
719 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
724 * Try closing logind sleep lock fd passed over from xss-lock, in case we're
725 * being run from there.
728 static void maybe_close_sleep_lock_fd(void) {
729 const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
731 if (sleep_lock_fd && *sleep_lock_fd != 0) {
732 long int fd = strtol(sleep_lock_fd, &endptr, 10);
740 * Instead of polling the X connection socket we leave this to
741 * xcb_poll_for_event() which knows better than we can ever know.
744 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
745 xcb_generic_event_t *event;
747 if (xcb_connection_has_error(conn))
748 errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
750 while ((event = xcb_poll_for_event(conn)) != NULL) {
751 if (event->response_type == 0) {
752 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
754 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
755 error->sequence, error->error_code);
760 /* Strip off the highest bit (set if the event is generated) */
761 int type = (event->response_type & 0x7F);
765 handle_key_press((xcb_key_press_event_t *)event);
768 case XCB_VISIBILITY_NOTIFY:
769 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
773 maybe_close_sleep_lock_fd();
775 /* After the first MapNotify, we never fork again. We don’t
776 * expect to get another MapNotify, but better be sure… */
779 /* In the parent process, we exit */
783 ev_loop_fork(EV_DEFAULT);
787 case XCB_CONFIGURE_NOTIFY:
788 handle_screen_resize();
792 if (type == xkb_base_event) {
793 process_xkb_event(event);
795 if (randr_base > -1 &&
796 type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
797 randr_query(screen->root);
798 handle_screen_resize();
807 * This function is called from a fork()ed child and will raise the i3lock
808 * window when the window is obscured, even when the main i3lock process is
809 * blocked due to the authentication backend.
812 static void raise_loop(xcb_window_t window) {
813 xcb_connection_t *conn;
814 xcb_generic_event_t *event;
817 if (xcb_connection_has_error((conn = xcb_connect(NULL, &screens))) > 0)
818 errx(EXIT_FAILURE, "Cannot open display\n");
820 /* We need to know about the window being obscured or getting destroyed. */
821 xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
823 XCB_EVENT_MASK_VISIBILITY_CHANGE |
824 XCB_EVENT_MASK_STRUCTURE_NOTIFY});
827 DEBUG("Watching window 0x%08x\n", window);
828 while ((event = xcb_wait_for_event(conn)) != NULL) {
829 if (event->response_type == 0) {
830 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
831 DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
832 error->sequence, error->error_code);
836 /* Strip off the highest bit (set if the event is generated) */
837 int type = (event->response_type & 0x7F);
838 DEBUG("Read event of type %d\n", type);
840 case XCB_VISIBILITY_NOTIFY:
841 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
843 case XCB_UNMAP_NOTIFY:
844 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
845 if (((xcb_unmap_notify_event_t *)event)->window == window)
848 case XCB_DESTROY_NOTIFY:
849 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
850 if (((xcb_destroy_notify_event_t *)event)->window == window)
854 DEBUG("Unhandled event type %d\n", type);
861 int main(int argc, char *argv[]) {
864 char *image_path = NULL;
867 struct pam_conv conv = {conv_callback, NULL};
869 int curs_choice = CURS_NONE;
872 struct option longopts[] = {
873 {"version", no_argument, NULL, 'v'},
874 {"nofork", no_argument, NULL, 'n'},
875 {"beep", no_argument, NULL, 'b'},
876 {"dpms", no_argument, NULL, 'd'},
877 {"color", required_argument, NULL, 'c'},
878 {"pointer", required_argument, NULL, 'p'},
879 {"debug", no_argument, NULL, 0},
880 {"help", no_argument, NULL, 'h'},
881 {"no-unlock-indicator", no_argument, NULL, 'u'},
882 {"image", required_argument, NULL, 'i'},
883 {"tiling", no_argument, NULL, 't'},
884 {"ignore-empty-password", no_argument, NULL, 'e'},
885 {"inactivity-timeout", required_argument, NULL, 'I'},
886 {"show-failed-attempts", no_argument, NULL, 'f'},
887 {NULL, no_argument, NULL, 0}};
889 if ((pw = getpwuid(getuid())) == NULL)
890 err(EXIT_FAILURE, "getpwuid() failed");
891 if ((username = pw->pw_name) == NULL)
892 errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
894 char *optstring = "hvnbdc:p:ui:teI:f";
895 while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
898 errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
906 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
909 fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
915 /* Skip # if present */
919 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
920 errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
925 unlock_indicator = false;
928 image_path = strdup(optarg);
934 if (!strcmp(optarg, "win")) {
935 curs_choice = CURS_WIN;
936 } else if (!strcmp(optarg, "default")) {
937 curs_choice = CURS_DEFAULT;
939 errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
943 ignore_empty_password = true;
946 if (strcmp(longopts[longoptind].name, "debug") == 0)
950 show_failed_attempts = true;
953 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
954 " [-i image.png] [-t] [-e] [-I timeout] [-f]");
958 /* We need (relatively) random numbers for highlighting a random part of
959 * the unlock indicator upon keypresses. */
964 if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
965 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
967 if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
968 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
971 /* Using mlock() as non-super-user seems only possible in Linux.
972 * Users of other operating systems should use encrypted swap/no swap
973 * (or remove the ifdef and run i3lock as super-user).
974 * Alas, swap is encrypted by default on OpenBSD so swapping out
975 * is not necessarily an issue. */
976 #if defined(__linux__)
977 /* Lock the area where we store the password in memory, we don’t want it to
978 * be swapped to disk. Since Linux 2.6.9, this does not require any
979 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
980 if (mlock(password, sizeof(password)) != 0)
981 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
984 /* Double checking that connection is good and operatable with xcb */
986 if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
987 xcb_connection_has_error(conn))
988 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
990 if (xkb_x11_setup_xkb_extension(conn,
991 XKB_X11_MIN_MAJOR_XKB_VERSION,
992 XKB_X11_MIN_MINOR_XKB_VERSION,
997 &xkb_base_error) != 1)
998 errx(EXIT_FAILURE, "Could not setup XKB extension.");
1000 static const xcb_xkb_map_part_t required_map_parts =
1001 (XCB_XKB_MAP_PART_KEY_TYPES |
1002 XCB_XKB_MAP_PART_KEY_SYMS |
1003 XCB_XKB_MAP_PART_MODIFIER_MAP |
1004 XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
1005 XCB_XKB_MAP_PART_KEY_ACTIONS |
1006 XCB_XKB_MAP_PART_VIRTUAL_MODS |
1007 XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
1009 static const xcb_xkb_event_type_t required_events =
1010 (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
1011 XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
1012 XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
1014 xcb_xkb_select_events(
1016 xkb_x11_get_core_keyboard_device_id(conn),
1024 /* When we cannot initially load the keymap, we better exit */
1026 errx(EXIT_FAILURE, "Could not load keymap");
1028 const char *locale = getenv("LC_ALL");
1029 if (!locale || !*locale)
1030 locale = getenv("LC_CTYPE");
1031 if (!locale || !*locale)
1032 locale = getenv("LANG");
1033 if (!locale || !*locale) {
1035 fprintf(stderr, "Can't detect your locale, fallback to C\n");
1039 load_compose_table(locale);
1041 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
1045 randr_init(&randr_base, screen->root);
1046 randr_query(screen->root);
1048 last_resolution[0] = screen->width_in_pixels;
1049 last_resolution[1] = screen->height_in_pixels;
1051 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
1052 (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
1054 if (verify_png_image(image_path)) {
1055 /* Create a pixmap to render on, fill it with the background color */
1056 img = cairo_image_surface_create_from_png(image_path);
1057 /* In case loading failed, we just pretend no -i was specified. */
1058 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
1059 fprintf(stderr, "Could not load image \"%s\": %s\n",
1060 image_path, cairo_status_to_string(cairo_surface_status(img)));
1066 /* Pixmap on which the image is rendered to (if any) */
1067 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
1069 xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
1071 /* Open the fullscreen window, already with the correct pixmap in place */
1072 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
1073 xcb_free_pixmap(conn, bg_pixmap);
1075 cursor = create_cursor(conn, screen, win, curs_choice);
1077 /* Display the "locking…" message while trying to grab the pointer/keyboard. */
1078 auth_state = STATE_AUTH_LOCK;
1079 if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
1080 DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
1082 /* Set the focus to i3lock, possibly closing context menus which would
1083 * otherwise prevent us from grabbing keyboard/pointer.
1085 * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
1086 * works for managed windows, but i3lock uses an unmanaged window
1087 * (override_redirect=1). */
1088 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
1089 if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
1090 auth_state = STATE_I3LOCK_LOCK_FAILED;
1093 errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
1098 /* The pid == -1 case is intentionally ignored here:
1099 * While the child process is useful for preventing other windows from
1100 * popping up while i3lock blocks, it is not critical. */
1103 close(xcb_get_file_descriptor(conn));
1104 maybe_close_sleep_lock_fd();
1109 /* Load the keymap again to sync the current modifier state. Since we first
1110 * loaded the keymap, there might have been changes, but starting from now,
1111 * we should get all key presses/releases due to having grabbed the
1113 (void)load_keymap();
1115 /* Initialize the libev event loop. */
1116 main_loop = EV_DEFAULT;
1117 if (main_loop == NULL)
1118 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
1120 /* Explicitly call the screen redraw in case "locking…" message was displayed */
1121 auth_state = STATE_AUTH_IDLE;
1124 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1125 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1126 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1128 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1129 ev_io_start(main_loop, xcb_watcher);
1131 ev_check_init(xcb_check, xcb_check_cb);
1132 ev_check_start(main_loop, xcb_check);
1134 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1135 ev_prepare_start(main_loop, xcb_prepare);
1137 /* Invoke the event callback once to catch all the events which were
1138 * received up until now. ev will only pick up new events (when the X11
1139 * file descriptor becomes readable). */
1140 ev_invoke(main_loop, xcb_check, 0);
1141 ev_loop(main_loop, 0);
1143 if (stolen_focus == XCB_NONE) {
1147 DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
1148 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
1149 xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
1150 xcb_destroy_window(conn, win);
1151 set_focused_window(conn, screen->root, stolen_focus);