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;
453 if ((ksym == XKB_KEY_u && ctrl) ||
454 ksym == XKB_KEY_Escape) {
455 DEBUG("C-u pressed\n");
457 /* Also hide the unlock indicator */
458 if (unlock_indicator)
465 case XKB_KEY_KP_Delete:
466 /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
467 * to move the cursor when entering a password. We need to eat this
468 * key press so that it won’t be treated as part of the password,
473 case XKB_KEY_BackSpace:
474 if (ksym == XKB_KEY_h && !ctrl)
477 if (input_position == 0) {
478 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
479 unlock_state = STATE_NOTHING_TO_DELETE;
484 /* decrement input_position to point to the previous glyph */
485 u8_dec(password, &input_position);
486 password[input_position] = '\0';
488 /* Hide the unlock indicator after a bit if the password buffer is
490 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
491 unlock_state = STATE_BACKSPACE_ACTIVE;
493 unlock_state = STATE_KEY_PRESSED;
497 if ((input_position + 8) >= (int)sizeof(password))
501 /* FIXME: handle all of these? */
502 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
503 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
504 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
505 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
506 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
507 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
508 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
514 /* store it in the password array as UTF-8 */
515 memcpy(password + input_position, buffer, n - 1);
516 input_position += n - 1;
517 DEBUG("current password = %.*s\n", input_position, password);
519 if (unlock_indicator) {
520 unlock_state = STATE_KEY_ACTIVE;
522 unlock_state = STATE_KEY_PRESSED;
524 struct ev_timer *timeout = NULL;
525 START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
526 STOP_TIMER(clear_indicator_timeout);
529 START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
533 * A visibility notify event will be received when the visibility (= can the
534 * user view the complete window) changes, so for example when a popup overlays
535 * some area of the i3lock window.
537 * In this case, we raise our window on top so that the popup (or whatever is
538 * hiding us) gets hidden.
541 static void handle_visibility_notify(xcb_connection_t *conn,
542 xcb_visibility_notify_event_t *event) {
543 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
544 uint32_t values[] = {XCB_STACK_MODE_ABOVE};
545 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
551 * Called when the keyboard mapping changes. We update our symbols.
553 * We ignore errors — if the new keymap cannot be loaded it’s better if the
554 * screen stays locked and the user intervenes by using killall i3lock.
557 static void process_xkb_event(xcb_generic_event_t *gevent) {
560 uint8_t response_type;
563 xcb_timestamp_t time;
566 xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
567 xcb_xkb_map_notify_event_t map_notify;
568 xcb_xkb_state_notify_event_t state_notify;
569 } *event = (union xkb_event *)gevent;
571 DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
573 if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
577 * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
578 * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
581 switch (event->any.xkbType) {
582 case XCB_XKB_NEW_KEYBOARD_NOTIFY:
583 if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
587 case XCB_XKB_MAP_NOTIFY:
591 case XCB_XKB_STATE_NOTIFY:
592 xkb_state_update_mask(xkb_state,
593 event->state_notify.baseMods,
594 event->state_notify.latchedMods,
595 event->state_notify.lockedMods,
596 event->state_notify.baseGroup,
597 event->state_notify.latchedGroup,
598 event->state_notify.lockedGroup);
604 * Called when the properties on the root window change, e.g. when the screen
605 * resolution changes. If so we update the window to cover the whole screen
606 * and also redraw the image, if any.
609 void handle_screen_resize(void) {
610 xcb_get_geometry_cookie_t geomc;
611 xcb_get_geometry_reply_t *geom;
612 geomc = xcb_get_geometry(conn, screen->root);
613 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
616 if (last_resolution[0] == geom->width &&
617 last_resolution[1] == geom->height) {
622 last_resolution[0] = geom->width;
623 last_resolution[1] = geom->height;
629 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
630 xcb_configure_window(conn, win, mask, last_resolution);
633 randr_query(screen->root);
637 static bool verify_png_image(const char *image_path) {
642 /* Check file exists and has correct PNG header */
643 FILE *png_file = fopen(image_path, "r");
644 if (png_file == NULL) {
645 fprintf(stderr, "Image file path \"%s\" cannot be opened: %s\n", image_path, strerror(errno));
648 unsigned char png_header[8];
649 memset(png_header, '\0', sizeof(png_header));
650 int bytes_read = fread(png_header, 1, sizeof(png_header), png_file);
652 if (bytes_read != sizeof(png_header)) {
653 fprintf(stderr, "Could not read PNG header from \"%s\"\n", image_path);
657 // Check PNG header according to the specification, available at:
658 // https://www.w3.org/TR/2003/REC-PNG-20031110/#5PNG-file-signature
659 static unsigned char PNG_REFERENCE_HEADER[8] = {137, 80, 78, 71, 13, 10, 26, 10};
660 if (memcmp(PNG_REFERENCE_HEADER, png_header, sizeof(png_header)) != 0) {
661 fprintf(stderr, "File \"%s\" does not start with a PNG header. i3lock currently only supports loading PNG files.\n", image_path);
669 * Callback function for PAM. We only react on password request callbacks.
672 static int conv_callback(int num_msg, const struct pam_message **msg,
673 struct pam_response **resp, void *appdata_ptr) {
677 /* PAM expects an array of responses, one for each message */
678 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
683 for (int c = 0; c < num_msg; c++) {
684 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
685 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
688 /* return code is currently not used but should be set to zero */
689 resp[c]->resp_retcode = 0;
690 if ((resp[c]->resp = strdup(password)) == NULL) {
701 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
702 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
705 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
706 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
710 * Flush before blocking (and waiting for new events)
713 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
718 * Try closing logind sleep lock fd passed over from xss-lock, in case we're
719 * being run from there.
722 static void maybe_close_sleep_lock_fd(void) {
723 const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
725 if (sleep_lock_fd && *sleep_lock_fd != 0) {
726 long int fd = strtol(sleep_lock_fd, &endptr, 10);
734 * Instead of polling the X connection socket we leave this to
735 * xcb_poll_for_event() which knows better than we can ever know.
738 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
739 xcb_generic_event_t *event;
741 if (xcb_connection_has_error(conn))
742 errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
744 while ((event = xcb_poll_for_event(conn)) != NULL) {
745 if (event->response_type == 0) {
746 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
748 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
749 error->sequence, error->error_code);
754 /* Strip off the highest bit (set if the event is generated) */
755 int type = (event->response_type & 0x7F);
759 handle_key_press((xcb_key_press_event_t *)event);
762 case XCB_VISIBILITY_NOTIFY:
763 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
767 maybe_close_sleep_lock_fd();
769 /* After the first MapNotify, we never fork again. We don’t
770 * expect to get another MapNotify, but better be sure… */
773 /* In the parent process, we exit */
777 ev_loop_fork(EV_DEFAULT);
781 case XCB_CONFIGURE_NOTIFY:
782 handle_screen_resize();
786 if (type == xkb_base_event) {
787 process_xkb_event(event);
789 if (randr_base > -1 &&
790 type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
791 randr_query(screen->root);
792 handle_screen_resize();
801 * This function is called from a fork()ed child and will raise the i3lock
802 * window when the window is obscured, even when the main i3lock process is
803 * blocked due to the authentication backend.
806 static void raise_loop(xcb_window_t window) {
807 xcb_connection_t *conn;
808 xcb_generic_event_t *event;
811 if (xcb_connection_has_error((conn = xcb_connect(NULL, &screens))) > 0)
812 errx(EXIT_FAILURE, "Cannot open display\n");
814 /* We need to know about the window being obscured or getting destroyed. */
815 xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
817 XCB_EVENT_MASK_VISIBILITY_CHANGE |
818 XCB_EVENT_MASK_STRUCTURE_NOTIFY});
821 DEBUG("Watching window 0x%08x\n", window);
822 while ((event = xcb_wait_for_event(conn)) != NULL) {
823 if (event->response_type == 0) {
824 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
825 DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
826 error->sequence, error->error_code);
830 /* Strip off the highest bit (set if the event is generated) */
831 int type = (event->response_type & 0x7F);
832 DEBUG("Read event of type %d\n", type);
834 case XCB_VISIBILITY_NOTIFY:
835 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
837 case XCB_UNMAP_NOTIFY:
838 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
839 if (((xcb_unmap_notify_event_t *)event)->window == window)
842 case XCB_DESTROY_NOTIFY:
843 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
844 if (((xcb_destroy_notify_event_t *)event)->window == window)
848 DEBUG("Unhandled event type %d\n", type);
855 int main(int argc, char *argv[]) {
858 char *image_path = NULL;
861 struct pam_conv conv = {conv_callback, NULL};
863 int curs_choice = CURS_NONE;
866 struct option longopts[] = {
867 {"version", no_argument, NULL, 'v'},
868 {"nofork", no_argument, NULL, 'n'},
869 {"beep", no_argument, NULL, 'b'},
870 {"dpms", no_argument, NULL, 'd'},
871 {"color", required_argument, NULL, 'c'},
872 {"pointer", required_argument, NULL, 'p'},
873 {"debug", no_argument, NULL, 0},
874 {"help", no_argument, NULL, 'h'},
875 {"no-unlock-indicator", no_argument, NULL, 'u'},
876 {"image", required_argument, NULL, 'i'},
877 {"tiling", no_argument, NULL, 't'},
878 {"ignore-empty-password", no_argument, NULL, 'e'},
879 {"inactivity-timeout", required_argument, NULL, 'I'},
880 {"show-failed-attempts", no_argument, NULL, 'f'},
881 {NULL, no_argument, NULL, 0}};
883 if ((pw = getpwuid(getuid())) == NULL)
884 err(EXIT_FAILURE, "getpwuid() failed");
885 if ((username = pw->pw_name) == NULL)
886 errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
888 char *optstring = "hvnbdc:p:ui:teI:f";
889 while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
892 errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
900 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
903 fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
909 /* Skip # if present */
913 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
914 errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
919 unlock_indicator = false;
922 image_path = strdup(optarg);
928 if (!strcmp(optarg, "win")) {
929 curs_choice = CURS_WIN;
930 } else if (!strcmp(optarg, "default")) {
931 curs_choice = CURS_DEFAULT;
933 errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
937 ignore_empty_password = true;
940 if (strcmp(longopts[longoptind].name, "debug") == 0)
944 show_failed_attempts = true;
947 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
948 " [-i image.png] [-t] [-e] [-I timeout] [-f]");
952 /* We need (relatively) random numbers for highlighting a random part of
953 * the unlock indicator upon keypresses. */
958 if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
959 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
961 if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
962 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
965 /* Using mlock() as non-super-user seems only possible in Linux.
966 * Users of other operating systems should use encrypted swap/no swap
967 * (or remove the ifdef and run i3lock as super-user).
968 * Alas, swap is encrypted by default on OpenBSD so swapping out
969 * is not necessarily an issue. */
970 #if defined(__linux__)
971 /* Lock the area where we store the password in memory, we don’t want it to
972 * be swapped to disk. Since Linux 2.6.9, this does not require any
973 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
974 if (mlock(password, sizeof(password)) != 0)
975 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
978 /* Double checking that connection is good and operatable with xcb */
980 if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
981 xcb_connection_has_error(conn))
982 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
984 if (xkb_x11_setup_xkb_extension(conn,
985 XKB_X11_MIN_MAJOR_XKB_VERSION,
986 XKB_X11_MIN_MINOR_XKB_VERSION,
991 &xkb_base_error) != 1)
992 errx(EXIT_FAILURE, "Could not setup XKB extension.");
994 static const xcb_xkb_map_part_t required_map_parts =
995 (XCB_XKB_MAP_PART_KEY_TYPES |
996 XCB_XKB_MAP_PART_KEY_SYMS |
997 XCB_XKB_MAP_PART_MODIFIER_MAP |
998 XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
999 XCB_XKB_MAP_PART_KEY_ACTIONS |
1000 XCB_XKB_MAP_PART_VIRTUAL_MODS |
1001 XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
1003 static const xcb_xkb_event_type_t required_events =
1004 (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
1005 XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
1006 XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
1008 xcb_xkb_select_events(
1010 xkb_x11_get_core_keyboard_device_id(conn),
1018 /* When we cannot initially load the keymap, we better exit */
1020 errx(EXIT_FAILURE, "Could not load keymap");
1022 const char *locale = getenv("LC_ALL");
1023 if (!locale || !*locale)
1024 locale = getenv("LC_CTYPE");
1025 if (!locale || !*locale)
1026 locale = getenv("LANG");
1027 if (!locale || !*locale) {
1029 fprintf(stderr, "Can't detect your locale, fallback to C\n");
1033 load_compose_table(locale);
1035 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
1039 randr_init(&randr_base, screen->root);
1040 randr_query(screen->root);
1042 last_resolution[0] = screen->width_in_pixels;
1043 last_resolution[1] = screen->height_in_pixels;
1045 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
1046 (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
1048 if (verify_png_image(image_path)) {
1049 /* Create a pixmap to render on, fill it with the background color */
1050 img = cairo_image_surface_create_from_png(image_path);
1051 /* In case loading failed, we just pretend no -i was specified. */
1052 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
1053 fprintf(stderr, "Could not load image \"%s\": %s\n",
1054 image_path, cairo_status_to_string(cairo_surface_status(img)));
1060 /* Pixmap on which the image is rendered to (if any) */
1061 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
1063 xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
1065 /* Open the fullscreen window, already with the correct pixmap in place */
1066 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
1067 xcb_free_pixmap(conn, bg_pixmap);
1069 cursor = create_cursor(conn, screen, win, curs_choice);
1071 /* Display the "locking…" message while trying to grab the pointer/keyboard. */
1072 auth_state = STATE_AUTH_LOCK;
1073 if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
1074 DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
1076 /* Set the focus to i3lock, possibly closing context menus which would
1077 * otherwise prevent us from grabbing keyboard/pointer.
1079 * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
1080 * works for managed windows, but i3lock uses an unmanaged window
1081 * (override_redirect=1). */
1082 xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
1083 if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
1084 auth_state = STATE_I3LOCK_LOCK_FAILED;
1087 errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
1092 /* The pid == -1 case is intentionally ignored here:
1093 * While the child process is useful for preventing other windows from
1094 * popping up while i3lock blocks, it is not critical. */
1097 close(xcb_get_file_descriptor(conn));
1098 maybe_close_sleep_lock_fd();
1103 /* Load the keymap again to sync the current modifier state. Since we first
1104 * loaded the keymap, there might have been changes, but starting from now,
1105 * we should get all key presses/releases due to having grabbed the
1107 (void)load_keymap();
1109 /* Initialize the libev event loop. */
1110 main_loop = EV_DEFAULT;
1111 if (main_loop == NULL)
1112 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
1114 /* Explicitly call the screen redraw in case "locking…" message was displayed */
1115 auth_state = STATE_AUTH_IDLE;
1118 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1119 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1120 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1122 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1123 ev_io_start(main_loop, xcb_watcher);
1125 ev_check_init(xcb_check, xcb_check_cb);
1126 ev_check_start(main_loop, xcb_check);
1128 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1129 ev_prepare_start(main_loop, xcb_prepare);
1131 /* Invoke the event callback once to catch all the events which were
1132 * received up until now. ev will only pick up new events (when the X11
1133 * file descriptor becomes readable). */
1134 ev_invoke(main_loop, xcb_check, 0);
1135 ev_loop(main_loop, 0);
1137 if (stolen_focus == XCB_NONE) {
1141 DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
1142 xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
1143 xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
1144 xcb_destroy_window(conn, win);
1145 set_focused_window(conn, screen->root, stolen_focus);