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>
43 #if defined(__linux__)
46 #include <sys/ioctl.h>
52 #include "unlock_indicator.h"
56 #define TSTAMP_N_SECS(n) (n * 1.0)
57 #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
58 #define START_TIMER(timer_obj, timeout, callback) \
59 timer_obj = start_timer(timer_obj, timeout, callback)
60 #define STOP_TIMER(timer_obj) \
61 timer_obj = stop_timer(timer_obj)
63 typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
64 static void input_done(void);
66 char color[7] = "ffffff";
67 uint32_t last_resolution[2];
69 static xcb_cursor_t cursor;
71 static pam_handle_t *pam_handle;
73 int input_position = 0;
74 /* Holds the password you enter (in UTF-8). */
75 static char password[512];
76 static bool beep = false;
77 bool debug_mode = false;
78 bool unlock_indicator = true;
79 char *modifier_string = NULL;
80 static bool dont_fork = false;
81 struct ev_loop *main_loop;
82 static struct ev_timer *clear_auth_wrong_timeout;
83 static struct ev_timer *clear_indicator_timeout;
84 static struct ev_timer *discard_passwd_timeout;
85 extern unlock_state_t unlock_state;
86 extern auth_state_t auth_state;
87 int failed_attempts = 0;
88 bool show_failed_attempts = false;
89 bool retry_verification = false;
91 static struct xkb_state *xkb_state;
92 static struct xkb_context *xkb_context;
93 static struct xkb_keymap *xkb_keymap;
94 static struct xkb_compose_table *xkb_compose_table;
95 static struct xkb_compose_state *xkb_compose_state;
96 static uint8_t xkb_base_event;
97 static uint8_t xkb_base_error;
98 static int randr_base = -1;
100 cairo_surface_t *img = NULL;
102 bool ignore_empty_password = false;
103 bool skip_repeated_empty_password = false;
105 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
106 #define isutf(c) (((c)&0xC0) != 0x80)
109 * Decrements i to point to the previous unicode glyph
112 void u8_dec(char *s, int *i) {
113 (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
117 * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
118 * Necessary so that we can properly let xkbcommon track the keyboard state and
119 * translate keypresses to utf-8.
122 static bool load_keymap(void) {
123 if (xkb_context == NULL) {
124 if ((xkb_context = xkb_context_new(0)) == NULL) {
125 fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
130 xkb_keymap_unref(xkb_keymap);
132 int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
133 DEBUG("device = %d\n", device_id);
134 if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
135 fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
139 struct xkb_state *new_state =
140 xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
141 if (new_state == NULL) {
142 fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
146 xkb_state_unref(xkb_state);
147 xkb_state = new_state;
153 * Loads the XKB compose table from the given locale.
156 static bool load_compose_table(const char *locale) {
157 xkb_compose_table_unref(xkb_compose_table);
159 if ((xkb_compose_table = xkb_compose_table_new_from_locale(xkb_context, locale, 0)) == NULL) {
160 fprintf(stderr, "[i3lock] xkb_compose_table_new_from_locale failed\n");
164 struct xkb_compose_state *new_compose_state = xkb_compose_state_new(xkb_compose_table, 0);
165 if (new_compose_state == NULL) {
166 fprintf(stderr, "[i3lock] xkb_compose_state_new failed\n");
170 xkb_compose_state_unref(xkb_compose_state);
171 xkb_compose_state = new_compose_state;
177 * Clears the memory which stored the password to be a bit safer against
181 static void clear_password_memory(void) {
183 /* Use explicit_bzero(3) which was explicitly designed not to be
184 * optimized out by the compiler. */
185 explicit_bzero(password, strlen(password));
187 /* A volatile pointer to the password buffer to prevent the compiler from
188 * optimizing this out. */
189 volatile char *vpassword = password;
190 for (size_t c = 0; c < sizeof(password); c++)
191 /* We store a non-random pattern which consists of the (irrelevant)
192 * index plus (!) the value of the beep variable. This prevents the
193 * compiler from optimizing the calls away, since the value of 'beep'
194 * is not known at compile-time. */
195 vpassword[c] = c + (int)beep;
199 ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
201 ev_timer_stop(main_loop, timer_obj);
202 ev_timer_set(timer_obj, timeout, 0.);
203 ev_timer_start(main_loop, timer_obj);
205 /* When there is no memory, we just don’t have a timeout. We cannot
206 * exit() here, since that would effectively unlock the screen. */
207 timer_obj = calloc(sizeof(struct ev_timer), 1);
209 ev_timer_init(timer_obj, callback, timeout, 0.);
210 ev_timer_start(main_loop, timer_obj);
216 ev_timer *stop_timer(ev_timer *timer_obj) {
218 ev_timer_stop(main_loop, timer_obj);
225 * Neccessary calls after ending input via enter or others
228 static void finish_input(void) {
229 password[input_position] = '\0';
230 unlock_state = STATE_KEY_PRESSED;
236 * Resets auth_state to STATE_AUTH_IDLE 2 seconds after an unsuccessful
237 * authentication event.
240 static void clear_auth_wrong(EV_P_ ev_timer *w, int revents) {
241 DEBUG("clearing auth wrong\n");
242 auth_state = STATE_AUTH_IDLE;
245 /* Clear modifier string. */
246 if (modifier_string != NULL) {
247 free(modifier_string);
248 modifier_string = NULL;
251 /* Now free this timeout. */
252 STOP_TIMER(clear_auth_wrong_timeout);
254 /* retry with input done during auth verification */
255 if (retry_verification) {
256 retry_verification = false;
261 static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
263 STOP_TIMER(clear_indicator_timeout);
266 static void clear_input(void) {
268 clear_password_memory();
269 password[input_position] = '\0';
272 static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
274 STOP_TIMER(discard_passwd_timeout);
277 static void input_done(void) {
278 STOP_TIMER(clear_auth_wrong_timeout);
279 auth_state = STATE_AUTH_VERIFY;
280 unlock_state = STATE_STARTED;
286 if (!(pw = getpwuid(getuid())))
287 errx(1, "unknown uid %u.", getuid());
289 if (auth_userokay(pw->pw_name, NULL, NULL, password) != 0) {
290 DEBUG("successfully authenticated\n");
291 clear_password_memory();
293 ev_break(EV_DEFAULT, EVBREAK_ALL);
297 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
298 DEBUG("successfully authenticated\n");
299 clear_password_memory();
301 /* PAM credentials should be refreshed, this will for example update any kerberos tickets.
302 * Related to credentials pam_end() needs to be called to cleanup any temporary
303 * credentials like kerberos /tmp/krb5cc_pam_* files which may of been left behind if the
304 * refresh of the credentials failed. */
305 pam_setcred(pam_handle, PAM_REFRESH_CRED);
306 pam_end(pam_handle, PAM_SUCCESS);
308 ev_break(EV_DEFAULT, EVBREAK_ALL);
314 fprintf(stderr, "Authentication failure\n");
316 /* Get state of Caps and Num lock modifiers, to be displayed in
317 * STATE_AUTH_WRONG state */
318 xkb_mod_index_t idx, num_mods;
319 const char *mod_name;
321 num_mods = xkb_keymap_num_mods(xkb_keymap);
323 for (idx = 0; idx < num_mods; idx++) {
324 if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
327 mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
328 if (mod_name == NULL)
331 /* Replace certain xkb names with nicer, human-readable ones. */
332 if (strcmp(mod_name, XKB_MOD_NAME_CAPS) == 0)
333 mod_name = "Caps Lock";
334 else if (strcmp(mod_name, XKB_MOD_NAME_ALT) == 0)
336 else if (strcmp(mod_name, XKB_MOD_NAME_NUM) == 0)
337 mod_name = "Num Lock";
338 else if (strcmp(mod_name, XKB_MOD_NAME_LOGO) == 0)
342 if (modifier_string == NULL) {
343 if (asprintf(&tmp, "%s", mod_name) != -1)
344 modifier_string = tmp;
345 } else if (asprintf(&tmp, "%s, %s", modifier_string, mod_name) != -1) {
346 free(modifier_string);
347 modifier_string = tmp;
351 auth_state = STATE_AUTH_WRONG;
352 failed_attempts += 1;
354 if (unlock_indicator)
357 /* Clear this state after 2 seconds (unless the user enters another
358 * password during that time). */
359 ev_now_update(main_loop);
360 START_TIMER(clear_auth_wrong_timeout, TSTAMP_N_SECS(2), clear_auth_wrong);
362 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
364 STOP_TIMER(clear_indicator_timeout);
366 /* beep on authentication failure, if enabled */
373 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
378 static bool skip_without_validation(void) {
379 if (input_position != 0)
382 if (skip_repeated_empty_password || ignore_empty_password)
389 * Handle key presses. Fixes state, then looks up the key symbol for the
390 * given keycode, then looks up the key symbol (as UCS-2), converts it to
391 * UTF-8 and stores it in the password array.
394 static void handle_key_press(xcb_key_press_event_t *event) {
399 bool composed = false;
401 ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
402 ctrl = xkb_state_mod_name_is_active(xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_DEPRESSED);
404 /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
405 memset(buffer, '\0', sizeof(buffer));
407 if (xkb_compose_state && xkb_compose_state_feed(xkb_compose_state, ksym) == XKB_COMPOSE_FEED_ACCEPTED) {
408 switch (xkb_compose_state_get_status(xkb_compose_state)) {
409 case XKB_COMPOSE_NOTHING:
411 case XKB_COMPOSE_COMPOSING:
413 case XKB_COMPOSE_COMPOSED:
414 /* xkb_compose_state_get_utf8 doesn't include the terminating byte in the return value
415 * as xkb_keysym_to_utf8 does. Adding one makes the variable n consistent. */
416 n = xkb_compose_state_get_utf8(xkb_compose_state, buffer, sizeof(buffer)) + 1;
417 ksym = xkb_compose_state_get_one_sym(xkb_compose_state);
420 case XKB_COMPOSE_CANCELLED:
421 xkb_compose_state_reset(xkb_compose_state);
427 n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
434 case XKB_KEY_KP_Enter:
435 case XKB_KEY_XF86ScreenSaver:
436 if ((ksym == XKB_KEY_j || ksym == XKB_KEY_m) && !ctrl)
439 if (auth_state == STATE_AUTH_WRONG) {
440 retry_verification = true;
444 if (skip_without_validation()) {
449 skip_repeated_empty_password = true;
452 skip_repeated_empty_password = false;
453 // A new password is being entered, but a previous one is pending.
454 // Discard the old one and clear the retry_verification flag.
455 if (retry_verification) {
456 retry_verification = false;
464 if ((ksym == XKB_KEY_u && ctrl) ||
465 ksym == XKB_KEY_Escape) {
466 DEBUG("C-u pressed\n");
468 /* Also hide the unlock indicator */
469 if (unlock_indicator)
476 case XKB_KEY_KP_Delete:
477 /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
478 * to move the cursor when entering a password. We need to eat this
479 * key press so that it won’t be treated as part of the password,
484 case XKB_KEY_BackSpace:
485 if (ksym == XKB_KEY_h && !ctrl)
488 if (input_position == 0) {
489 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
490 unlock_state = STATE_NOTHING_TO_DELETE;
495 /* decrement input_position to point to the previous glyph */
496 u8_dec(password, &input_position);
497 password[input_position] = '\0';
499 /* Hide the unlock indicator after a bit if the password buffer is
501 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
502 unlock_state = STATE_BACKSPACE_ACTIVE;
504 unlock_state = STATE_KEY_PRESSED;
508 if ((input_position + 8) >= (int)sizeof(password))
512 /* FIXME: handle all of these? */
513 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
514 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
515 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
516 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
517 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
518 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
519 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
525 /* store it in the password array as UTF-8 */
526 memcpy(password + input_position, buffer, n - 1);
527 input_position += n - 1;
528 DEBUG("current password = %.*s\n", input_position, password);
530 if (unlock_indicator) {
531 unlock_state = STATE_KEY_ACTIVE;
533 unlock_state = STATE_KEY_PRESSED;
535 struct ev_timer *timeout = NULL;
536 START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
537 STOP_TIMER(clear_indicator_timeout);
540 START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
544 * A visibility notify event will be received when the visibility (= can the
545 * user view the complete window) changes, so for example when a popup overlays
546 * some area of the i3lock window.
548 * In this case, we raise our window on top so that the popup (or whatever is
549 * hiding us) gets hidden.
552 static void handle_visibility_notify(xcb_connection_t *conn,
553 xcb_visibility_notify_event_t *event) {
554 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
555 uint32_t values[] = {XCB_STACK_MODE_ABOVE};
556 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
562 * Called when the keyboard mapping changes. We update our symbols.
564 * We ignore errors — if the new keymap cannot be loaded it’s better if the
565 * screen stays locked and the user intervenes by using killall i3lock.
568 static void process_xkb_event(xcb_generic_event_t *gevent) {
571 uint8_t response_type;
574 xcb_timestamp_t time;
577 xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
578 xcb_xkb_map_notify_event_t map_notify;
579 xcb_xkb_state_notify_event_t state_notify;
580 } *event = (union xkb_event *)gevent;
582 DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
584 if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
588 * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
589 * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
592 switch (event->any.xkbType) {
593 case XCB_XKB_NEW_KEYBOARD_NOTIFY:
594 if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
598 case XCB_XKB_MAP_NOTIFY:
602 case XCB_XKB_STATE_NOTIFY:
603 xkb_state_update_mask(xkb_state,
604 event->state_notify.baseMods,
605 event->state_notify.latchedMods,
606 event->state_notify.lockedMods,
607 event->state_notify.baseGroup,
608 event->state_notify.latchedGroup,
609 event->state_notify.lockedGroup);
615 * Called when the properties on the root window change, e.g. when the screen
616 * resolution changes. If so we update the window to cover the whole screen
617 * and also redraw the image, if any.
620 void handle_screen_resize(void) {
621 xcb_get_geometry_cookie_t geomc;
622 xcb_get_geometry_reply_t *geom;
623 geomc = xcb_get_geometry(conn, screen->root);
624 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
627 if (last_resolution[0] == geom->width &&
628 last_resolution[1] == geom->height) {
633 last_resolution[0] = geom->width;
634 last_resolution[1] = geom->height;
640 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
641 xcb_configure_window(conn, win, mask, last_resolution);
644 randr_query(screen->root);
648 static bool verify_png_image(const char *image_path) {
653 /* Check file exists and has correct PNG header */
654 FILE *png_file = fopen(image_path, "r");
655 if (png_file == NULL) {
656 fprintf(stderr, "Image file path \"%s\" cannot be opened: %s\n", image_path, strerror(errno));
659 unsigned char png_header[8];
660 memset(png_header, '\0', sizeof(png_header));
661 int bytes_read = fread(png_header, 1, sizeof(png_header), png_file);
663 if (bytes_read != sizeof(png_header)) {
664 fprintf(stderr, "Could not read PNG header from \"%s\"\n", image_path);
668 // Check PNG header according to the specification, available at:
669 // https://www.w3.org/TR/2003/REC-PNG-20031110/#5PNG-file-signature
670 static unsigned char PNG_REFERENCE_HEADER[8] = {137, 80, 78, 71, 13, 10, 26, 10};
671 if (memcmp(PNG_REFERENCE_HEADER, png_header, sizeof(png_header)) != 0) {
672 fprintf(stderr, "File \"%s\" does not start with a PNG header. i3lock currently only supports loading PNG files.\n", image_path);
680 * Callback function for PAM. We only react on password request callbacks.
683 static int conv_callback(int num_msg, const struct pam_message **msg,
684 struct pam_response **resp, void *appdata_ptr) {
688 /* PAM expects an array of responses, one for each message */
689 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
694 for (int c = 0; c < num_msg; c++) {
695 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
696 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
699 /* return code is currently not used but should be set to zero */
700 resp[c]->resp_retcode = 0;
701 if ((resp[c]->resp = strdup(password)) == NULL) {
712 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
713 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
716 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
717 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
721 * Flush before blocking (and waiting for new events)
724 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
729 * Try closing logind sleep lock fd passed over from xss-lock, in case we're
730 * being run from there.
733 static void maybe_close_sleep_lock_fd(void) {
734 const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
736 if (sleep_lock_fd && *sleep_lock_fd != 0) {
737 long int fd = strtol(sleep_lock_fd, &endptr, 10);
745 * Instead of polling the X connection socket we leave this to
746 * xcb_poll_for_event() which knows better than we can ever know.
749 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
750 xcb_generic_event_t *event;
752 if (xcb_connection_has_error(conn))
753 errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
755 while ((event = xcb_poll_for_event(conn)) != NULL) {
756 if (event->response_type == 0) {
757 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
759 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
760 error->sequence, error->error_code);
765 /* Strip off the highest bit (set if the event is generated) */
766 int type = (event->response_type & 0x7F);
770 handle_key_press((xcb_key_press_event_t *)event);
773 case XCB_VISIBILITY_NOTIFY:
774 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
778 maybe_close_sleep_lock_fd();
780 /* After the first MapNotify, we never fork again. We don’t
781 * expect to get another MapNotify, but better be sure… */
784 /* In the parent process, we exit */
788 ev_loop_fork(EV_DEFAULT);
792 case XCB_CONFIGURE_NOTIFY:
793 handle_screen_resize();
797 if (type == xkb_base_event) {
798 process_xkb_event(event);
800 if (randr_base > -1 &&
801 type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
802 randr_query(screen->root);
803 handle_screen_resize();
812 * This function is called from a fork()ed child and will raise the i3lock
813 * window when the window is obscured, even when the main i3lock process is
814 * blocked due to the authentication backend.
817 static void raise_loop(xcb_window_t window) {
818 xcb_connection_t *conn;
819 xcb_generic_event_t *event;
822 if (xcb_connection_has_error((conn = xcb_connect(NULL, &screens))) > 0)
823 errx(EXIT_FAILURE, "Cannot open display\n");
825 /* We need to know about the window being obscured or getting destroyed. */
826 xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
828 XCB_EVENT_MASK_VISIBILITY_CHANGE |
829 XCB_EVENT_MASK_STRUCTURE_NOTIFY});
832 DEBUG("Watching window 0x%08x\n", window);
833 while ((event = xcb_wait_for_event(conn)) != NULL) {
834 if (event->response_type == 0) {
835 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
836 DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
837 error->sequence, error->error_code);
841 /* Strip off the highest bit (set if the event is generated) */
842 int type = (event->response_type & 0x7F);
843 DEBUG("Read event of type %d\n", type);
845 case XCB_VISIBILITY_NOTIFY:
846 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
848 case XCB_UNMAP_NOTIFY:
849 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
850 if (((xcb_unmap_notify_event_t *)event)->window == window)
853 case XCB_DESTROY_NOTIFY:
854 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
855 if (((xcb_destroy_notify_event_t *)event)->window == window)
859 DEBUG("Unhandled event type %d\n", type);
866 int main(int argc, char *argv[]) {
869 char *image_path = NULL;
872 struct pam_conv conv = {conv_callback, NULL};
874 #if defined(__linux__)
875 bool lock_tty_switching = false;
879 int curs_choice = CURS_NONE;
882 struct option longopts[] = {
883 {"version", no_argument, NULL, 'v'},
884 {"nofork", no_argument, NULL, 'n'},
885 {"beep", no_argument, NULL, 'b'},
886 {"dpms", no_argument, NULL, 'd'},
887 {"color", required_argument, NULL, 'c'},
888 {"pointer", required_argument, NULL, 'p'},
889 {"debug", no_argument, NULL, 0},
890 {"help", no_argument, NULL, 'h'},
891 {"no-unlock-indicator", no_argument, NULL, 'u'},
892 {"image", required_argument, NULL, 'i'},
893 {"tiling", no_argument, NULL, 't'},
894 {"ignore-empty-password", no_argument, NULL, 'e'},
895 {"inactivity-timeout", required_argument, NULL, 'I'},
896 {"show-failed-attempts", no_argument, NULL, 'f'},
897 {"lock-console", no_argument, NULL, 'l'},
898 {NULL, no_argument, NULL, 0}};
900 if ((pw = getpwuid(getuid())) == NULL)
901 err(EXIT_FAILURE, "getpwuid() failed");
902 if ((username = pw->pw_name) == NULL)
903 errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
905 char *optstring = "hvnbdc:p:ui:teI:fl";
906 while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
909 errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
917 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
920 fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
926 /* Skip # if present */
930 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
931 errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
936 unlock_indicator = false;
939 image_path = strdup(optarg);
945 if (!strcmp(optarg, "win")) {
946 curs_choice = CURS_WIN;
947 } else if (!strcmp(optarg, "default")) {
948 curs_choice = CURS_DEFAULT;
950 errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
954 ignore_empty_password = true;
957 if (strcmp(longopts[longoptind].name, "debug") == 0)
961 show_failed_attempts = true;
964 #if defined(__linux__)
965 lock_tty_switching = true;
967 errx(EXIT_FAILURE, "TTY switch locking is only supported on Linux.");
971 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
972 " [-i image.png] [-t] [-e] [-I timeout] [-f] [-l]");
976 /* We need (relatively) random numbers for highlighting a random part of
977 * the unlock indicator upon keypresses. */
982 if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
983 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
985 if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
986 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
989 /* Using mlock() as non-super-user seems only possible in Linux.
990 * Users of other operating systems should use encrypted swap/no swap
991 * (or remove the ifdef and run i3lock as super-user).
992 * Alas, swap is encrypted by default on OpenBSD so swapping out
993 * is not necessarily an issue. */
994 #if defined(__linux__)
995 /* Lock the area where we store the password in memory, we don’t want it to
996 * be swapped to disk. Since Linux 2.6.9, this does not require any
997 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
998 if (mlock(password, sizeof(password)) != 0)
999 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
1002 /* Double checking that connection is good and operatable with xcb */
1004 if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
1005 xcb_connection_has_error(conn))
1006 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
1008 if (xkb_x11_setup_xkb_extension(conn,
1009 XKB_X11_MIN_MAJOR_XKB_VERSION,
1010 XKB_X11_MIN_MINOR_XKB_VERSION,
1015 &xkb_base_error) != 1)
1016 errx(EXIT_FAILURE, "Could not setup XKB extension.");
1018 static const xcb_xkb_map_part_t required_map_parts =
1019 (XCB_XKB_MAP_PART_KEY_TYPES |
1020 XCB_XKB_MAP_PART_KEY_SYMS |
1021 XCB_XKB_MAP_PART_MODIFIER_MAP |
1022 XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
1023 XCB_XKB_MAP_PART_KEY_ACTIONS |
1024 XCB_XKB_MAP_PART_VIRTUAL_MODS |
1025 XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
1027 static const xcb_xkb_event_type_t required_events =
1028 (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
1029 XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
1030 XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
1032 xcb_xkb_select_events(
1034 xkb_x11_get_core_keyboard_device_id(conn),
1042 /* When we cannot initially load the keymap, we better exit */
1044 errx(EXIT_FAILURE, "Could not load keymap");
1046 const char *locale = getenv("LC_ALL");
1047 if (!locale || !*locale)
1048 locale = getenv("LC_CTYPE");
1049 if (!locale || !*locale)
1050 locale = getenv("LANG");
1051 if (!locale || !*locale) {
1053 fprintf(stderr, "Can't detect your locale, fallback to C\n");
1057 load_compose_table(locale);
1059 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
1063 randr_init(&randr_base, screen->root);
1064 randr_query(screen->root);
1066 last_resolution[0] = screen->width_in_pixels;
1067 last_resolution[1] = screen->height_in_pixels;
1069 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
1070 (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
1072 if (verify_png_image(image_path)) {
1073 /* Create a pixmap to render on, fill it with the background color */
1074 img = cairo_image_surface_create_from_png(image_path);
1075 /* In case loading failed, we just pretend no -i was specified. */
1076 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
1077 fprintf(stderr, "Could not load image \"%s\": %s\n",
1078 image_path, cairo_status_to_string(cairo_surface_status(img)));
1084 /* Pixmap on which the image is rendered to (if any) */
1085 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
1087 xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
1089 /* Open the fullscreen window, already with the correct pixmap in place */
1090 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
1091 xcb_free_pixmap(conn, bg_pixmap);
1093 cursor = create_cursor(conn, screen, win, curs_choice);
1095 /* Display the "locking…" message while trying to grab the pointer/keyboard. */
1096 auth_state = STATE_AUTH_LOCK;
1097 if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
1098 DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
1100 /* Set the focus to i3lock, possibly closing context menus which would
1101 * otherwise prevent us from grabbing keyboard/pointer.
1103 * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
1104 * works for managed windows, but i3lock uses an unmanaged window
1105 * (override_redirect=1). */
1106 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
1107 if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
1108 auth_state = STATE_I3LOCK_LOCK_FAILED;
1111 errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
1116 /* The pid == -1 case is intentionally ignored here:
1117 * While the child process is useful for preventing other windows from
1118 * popping up while i3lock blocks, it is not critical. */
1121 close(xcb_get_file_descriptor(conn));
1122 maybe_close_sleep_lock_fd();
1127 /* Load the keymap again to sync the current modifier state. Since we first
1128 * loaded the keymap, there might have been changes, but starting from now,
1129 * we should get all key presses/releases due to having grabbed the
1131 (void)load_keymap();
1133 /* Initialize the libev event loop. */
1134 main_loop = EV_DEFAULT;
1135 if (main_loop == NULL)
1136 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
1138 #if defined(__linux__)
1140 /* Lock tty switching */
1141 if (lock_tty_switching) {
1142 if ((term = open("/dev/console", O_RDWR)) == -1) {
1143 perror("error locking TTY switching: opening console failed");
1146 if (term != -1 && (ioctl(term, VT_LOCKSWITCH)) == -1) {
1147 perror("error locking TTY switching: locking console failed");
1153 /* Explicitly call the screen redraw in case "locking…" message was displayed */
1154 auth_state = STATE_AUTH_IDLE;
1157 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1158 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1159 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1161 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1162 ev_io_start(main_loop, xcb_watcher);
1164 ev_check_init(xcb_check, xcb_check_cb);
1165 ev_check_start(main_loop, xcb_check);
1167 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1168 ev_prepare_start(main_loop, xcb_prepare);
1170 /* Invoke the event callback once to catch all the events which were
1171 * received up until now. ev will only pick up new events (when the X11
1172 * file descriptor becomes readable). */
1173 ev_invoke(main_loop, xcb_check, 0);
1174 ev_loop(main_loop, 0);
1176 if (stolen_focus == XCB_NONE) {
1180 #if defined(__linux__)
1181 /* Restore tty switching */
1182 if (lock_tty_switching) {
1183 if (term != -1 && (ioctl(term, VT_UNLOCKSWITCH)) == -1) {
1184 perror("error unlocking TTY switching: unlocking console failed");
1192 DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
1193 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
1194 xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
1195 xcb_destroy_window(conn, win);
1196 set_focused_window(conn, screen->root, stolen_focus);