2 * vim:ts=4:sw=4:expandtab
4 * © 2010 Michael Stapelberg
6 * See LICENSE for licensing information
12 #include <sys/types.h>
22 #include <security/pam_appl.h>
27 #include <xkbcommon/xkbcommon.h>
28 #include <xkbcommon/xkbcommon-compose.h>
29 #include <xkbcommon/xkbcommon-x11.h>
31 #include <cairo/cairo-xcb.h>
36 #include "unlock_indicator.h"
39 #define TSTAMP_N_SECS(n) (n * 1.0)
40 #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
41 #define START_TIMER(timer_obj, timeout, callback) \
42 timer_obj = start_timer(timer_obj, timeout, callback)
43 #define STOP_TIMER(timer_obj) \
44 timer_obj = stop_timer(timer_obj)
46 typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
48 /* We need this for libxkbfile */
49 char color[7] = "ffffff";
50 int inactivity_timeout = 30;
51 uint32_t last_resolution[2];
53 static xcb_cursor_t cursor;
54 static pam_handle_t *pam_handle;
55 int input_position = 0;
56 /* Holds the password you enter (in UTF-8). */
57 static char password[512];
58 static bool beep = false;
59 bool debug_mode = false;
60 static bool dpms = false;
61 bool unlock_indicator = true;
62 char *modifier_string = NULL;
63 static bool dont_fork = false;
64 struct ev_loop *main_loop;
65 static struct ev_timer *clear_pam_wrong_timeout;
66 static struct ev_timer *clear_indicator_timeout;
67 static struct ev_timer *dpms_timeout;
68 static struct ev_timer *discard_passwd_timeout;
69 extern unlock_state_t unlock_state;
70 extern pam_state_t pam_state;
71 int failed_attempts = 0;
72 bool show_failed_attempts = false;
74 static struct xkb_state *xkb_state;
75 static struct xkb_context *xkb_context;
76 static struct xkb_keymap *xkb_keymap;
77 static struct xkb_compose_table *xkb_compose_table;
78 static struct xkb_compose_state *xkb_compose_state;
79 static uint8_t xkb_base_event;
80 static uint8_t xkb_base_error;
82 cairo_surface_t *img = NULL;
84 bool ignore_empty_password = false;
85 bool skip_repeated_empty_password = false;
87 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
88 #define isutf(c) (((c)&0xC0) != 0x80)
91 * Decrements i to point to the previous unicode glyph
94 void u8_dec(char *s, int *i) {
95 (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
98 static void turn_monitors_on(void) {
100 dpms_set_mode(conn, XCB_DPMS_DPMS_MODE_ON);
103 static void turn_monitors_off(void) {
105 dpms_set_mode(conn, XCB_DPMS_DPMS_MODE_OFF);
109 * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
110 * Necessary so that we can properly let xkbcommon track the keyboard state and
111 * translate keypresses to utf-8.
114 static bool load_keymap(void) {
115 if (xkb_context == NULL) {
116 if ((xkb_context = xkb_context_new(0)) == NULL) {
117 fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
122 xkb_keymap_unref(xkb_keymap);
124 int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
125 DEBUG("device = %d\n", device_id);
126 if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
127 fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
131 struct xkb_state *new_state =
132 xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
133 if (new_state == NULL) {
134 fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
138 xkb_state_unref(xkb_state);
139 xkb_state = new_state;
145 * Loads the XKB compose table from the given locale.
148 static bool load_compose_table(const char *locale) {
149 xkb_compose_table_unref(xkb_compose_table);
151 if ((xkb_compose_table = xkb_compose_table_new_from_locale(xkb_context, locale, 0)) == NULL) {
152 fprintf(stderr, "[i3lock] xkb_compose_table_new_from_locale failed\n");
156 struct xkb_compose_state *new_compose_state = xkb_compose_state_new(xkb_compose_table, 0);
157 if (new_compose_state == NULL) {
158 fprintf(stderr, "[i3lock] xkb_compose_state_new failed\n");
162 xkb_compose_state_unref(xkb_compose_state);
163 xkb_compose_state = new_compose_state;
169 * Clears the memory which stored the password to be a bit safer against
173 static void clear_password_memory(void) {
174 /* A volatile pointer to the password buffer to prevent the compiler from
175 * optimizing this out. */
176 volatile char *vpassword = password;
177 for (int c = 0; c < sizeof(password); c++)
178 /* We store a non-random pattern which consists of the (irrelevant)
179 * index plus (!) the value of the beep variable. This prevents the
180 * compiler from optimizing the calls away, since the value of 'beep'
181 * is not known at compile-time. */
182 vpassword[c] = c + (int)beep;
185 ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
187 ev_timer_stop(main_loop, timer_obj);
188 ev_timer_set(timer_obj, timeout, 0.);
189 ev_timer_start(main_loop, timer_obj);
191 /* When there is no memory, we just don’t have a timeout. We cannot
192 * exit() here, since that would effectively unlock the screen. */
193 timer_obj = calloc(sizeof(struct ev_timer), 1);
195 ev_timer_init(timer_obj, callback, timeout, 0.);
196 ev_timer_start(main_loop, timer_obj);
202 ev_timer *stop_timer(ev_timer *timer_obj) {
204 ev_timer_stop(main_loop, timer_obj);
211 * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccessful
212 * authentication event.
215 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
216 DEBUG("clearing pam wrong\n");
217 pam_state = STATE_PAM_IDLE;
218 unlock_state = STATE_STARTED;
221 /* Clear modifier string. */
222 if (modifier_string != NULL) {
223 free(modifier_string);
224 modifier_string = NULL;
227 /* Now free this timeout. */
228 STOP_TIMER(clear_pam_wrong_timeout);
231 static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
233 STOP_TIMER(clear_indicator_timeout);
236 static void clear_input(void) {
238 clear_password_memory();
239 password[input_position] = '\0';
241 /* Hide the unlock indicator after a bit if the password buffer is
243 if (unlock_indicator) {
244 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
245 unlock_state = STATE_BACKSPACE_ACTIVE;
247 unlock_state = STATE_KEY_PRESSED;
251 static void turn_off_monitors_cb(EV_P_ ev_timer *w, int revents) {
252 if (input_position == 0)
255 STOP_TIMER(dpms_timeout);
258 static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
261 STOP_TIMER(discard_passwd_timeout);
264 static void input_done(void) {
265 STOP_TIMER(clear_pam_wrong_timeout);
266 pam_state = STATE_PAM_VERIFY;
269 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
270 DEBUG("successfully authenticated\n");
271 clear_password_memory();
272 /* Turn the screen on, as it may have been turned off
273 * on release of the 'enter' key. */
276 /* PAM credentials should be refreshed, this will for example update any kerberos tickets.
277 * Related to credentials pam_end() needs to be called to cleanup any temporary
278 * credentials like kerberos /tmp/krb5cc_pam_* files which may of been left behind if the
279 * refresh of the credentials failed. */
280 pam_setcred(pam_handle, PAM_REFRESH_CRED);
281 pam_end(pam_handle, PAM_SUCCESS);
287 fprintf(stderr, "Authentication failure\n");
289 /* Get state of Caps and Num lock modifiers, to be displayed in
290 * STATE_PAM_WRONG state */
291 xkb_mod_index_t idx, num_mods;
292 const char *mod_name;
294 num_mods = xkb_keymap_num_mods(xkb_keymap);
296 for (idx = 0; idx < num_mods; idx++) {
297 if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
300 mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
301 if (mod_name == NULL)
304 /* Replace certain xkb names with nicer, human-readable ones. */
305 if (strcmp(mod_name, XKB_MOD_NAME_CAPS) == 0)
306 mod_name = "Caps Lock";
307 else if (strcmp(mod_name, XKB_MOD_NAME_ALT) == 0)
309 else if (strcmp(mod_name, XKB_MOD_NAME_NUM) == 0)
310 mod_name = "Num Lock";
311 else if (strcmp(mod_name, XKB_MOD_NAME_LOGO) == 0)
315 if (modifier_string == NULL) {
316 if (asprintf(&tmp, "%s", mod_name) != -1)
317 modifier_string = tmp;
318 } else if (asprintf(&tmp, "%s, %s", modifier_string, mod_name) != -1) {
319 free(modifier_string);
320 modifier_string = tmp;
324 pam_state = STATE_PAM_WRONG;
325 failed_attempts += 1;
327 if (unlock_indicator)
330 /* Clear this state after 2 seconds (unless the user enters another
331 * password during that time). */
332 ev_now_update(main_loop);
333 START_TIMER(clear_pam_wrong_timeout, TSTAMP_N_SECS(2), clear_pam_wrong);
335 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
337 STOP_TIMER(clear_indicator_timeout);
339 /* beep on authentication failure, if enabled */
346 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
351 static bool skip_without_validation(void) {
352 if (input_position != 0)
355 if (skip_repeated_empty_password || ignore_empty_password)
362 * Handle key presses. Fixes state, then looks up the key symbol for the
363 * given keycode, then looks up the key symbol (as UCS-2), converts it to
364 * UTF-8 and stores it in the password array.
367 static void handle_key_press(xcb_key_press_event_t *event) {
372 bool composed = false;
374 ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
375 ctrl = xkb_state_mod_name_is_active(xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_DEPRESSED);
377 /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
378 memset(buffer, '\0', sizeof(buffer));
380 if (xkb_compose_state && xkb_compose_state_feed(xkb_compose_state, ksym) == XKB_COMPOSE_FEED_ACCEPTED) {
381 switch (xkb_compose_state_get_status(xkb_compose_state)) {
382 case XKB_COMPOSE_NOTHING:
384 case XKB_COMPOSE_COMPOSING:
386 case XKB_COMPOSE_COMPOSED:
387 /* xkb_compose_state_get_utf8 doesn't include the terminating byte in the return value
388 * as xkb_keysym_to_utf8 does. Adding one makes the variable n consistent. */
389 n = xkb_compose_state_get_utf8(xkb_compose_state, buffer, sizeof(buffer)) + 1;
390 ksym = xkb_compose_state_get_one_sym(xkb_compose_state);
393 case XKB_COMPOSE_CANCELLED:
394 xkb_compose_state_reset(xkb_compose_state);
400 n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
405 case XKB_KEY_KP_Enter:
406 case XKB_KEY_XF86ScreenSaver:
407 if (pam_state == STATE_PAM_WRONG)
410 if (skip_without_validation()) {
414 password[input_position] = '\0';
415 unlock_state = STATE_KEY_PRESSED;
418 skip_repeated_empty_password = true;
421 skip_repeated_empty_password = false;
427 DEBUG("C-u pressed\n");
437 case XKB_KEY_BackSpace:
438 if (input_position == 0)
441 /* decrement input_position to point to the previous glyph */
442 u8_dec(password, &input_position);
443 password[input_position] = '\0';
445 /* Hide the unlock indicator after a bit if the password buffer is
447 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
448 unlock_state = STATE_BACKSPACE_ACTIVE;
450 unlock_state = STATE_KEY_PRESSED;
454 if ((input_position + 8) >= sizeof(password))
458 /* FIXME: handle all of these? */
459 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
460 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
461 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
462 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
463 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
464 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
465 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
471 /* store it in the password array as UTF-8 */
472 memcpy(password + input_position, buffer, n - 1);
473 input_position += n - 1;
474 DEBUG("current password = %.*s\n", input_position, password);
476 if (unlock_indicator) {
477 unlock_state = STATE_KEY_ACTIVE;
479 unlock_state = STATE_KEY_PRESSED;
481 struct ev_timer *timeout = NULL;
482 START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
483 STOP_TIMER(clear_indicator_timeout);
486 START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
490 * A visibility notify event will be received when the visibility (= can the
491 * user view the complete window) changes, so for example when a popup overlays
492 * some area of the i3lock window.
494 * In this case, we raise our window on top so that the popup (or whatever is
495 * hiding us) gets hidden.
498 static void handle_visibility_notify(xcb_connection_t *conn,
499 xcb_visibility_notify_event_t *event) {
500 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
501 uint32_t values[] = {XCB_STACK_MODE_ABOVE};
502 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
508 * Called when the keyboard mapping changes. We update our symbols.
510 * We ignore errors — if the new keymap cannot be loaded it’s better if the
511 * screen stays locked and the user intervenes by using killall i3lock.
514 static void process_xkb_event(xcb_generic_event_t *gevent) {
517 uint8_t response_type;
520 xcb_timestamp_t time;
523 xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
524 xcb_xkb_map_notify_event_t map_notify;
525 xcb_xkb_state_notify_event_t state_notify;
526 } *event = (union xkb_event *)gevent;
528 DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
530 if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
534 * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
535 * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
538 switch (event->any.xkbType) {
539 case XCB_XKB_NEW_KEYBOARD_NOTIFY:
540 if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
544 case XCB_XKB_MAP_NOTIFY:
548 case XCB_XKB_STATE_NOTIFY:
549 xkb_state_update_mask(xkb_state,
550 event->state_notify.baseMods,
551 event->state_notify.latchedMods,
552 event->state_notify.lockedMods,
553 event->state_notify.baseGroup,
554 event->state_notify.latchedGroup,
555 event->state_notify.lockedGroup);
561 * Called when the properties on the root window change, e.g. when the screen
562 * resolution changes. If so we update the window to cover the whole screen
563 * and also redraw the image, if any.
566 void handle_screen_resize(void) {
567 xcb_get_geometry_cookie_t geomc;
568 xcb_get_geometry_reply_t *geom;
569 geomc = xcb_get_geometry(conn, screen->root);
570 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
573 if (last_resolution[0] == geom->width &&
574 last_resolution[1] == geom->height) {
579 last_resolution[0] = geom->width;
580 last_resolution[1] = geom->height;
586 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
587 xcb_configure_window(conn, win, mask, last_resolution);
590 xinerama_query_screens();
595 * Callback function for PAM. We only react on password request callbacks.
598 static int conv_callback(int num_msg, const struct pam_message **msg,
599 struct pam_response **resp, void *appdata_ptr) {
603 /* PAM expects an array of responses, one for each message */
604 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
609 for (int c = 0; c < num_msg; c++) {
610 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
611 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
614 /* return code is currently not used but should be set to zero */
615 resp[c]->resp_retcode = 0;
616 if ((resp[c]->resp = strdup(password)) == NULL) {
626 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
627 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
630 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
631 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
635 * Flush before blocking (and waiting for new events)
638 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
643 * Instead of polling the X connection socket we leave this to
644 * xcb_poll_for_event() which knows better than we can ever know.
647 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
648 xcb_generic_event_t *event;
650 if (xcb_connection_has_error(conn))
651 errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
653 while ((event = xcb_poll_for_event(conn)) != NULL) {
654 if (event->response_type == 0) {
655 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
657 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
658 error->sequence, error->error_code);
663 /* Strip off the highest bit (set if the event is generated) */
664 int type = (event->response_type & 0x7F);
668 handle_key_press((xcb_key_press_event_t *)event);
671 case XCB_KEY_RELEASE:
672 /* If this was the backspace or escape key we are back at an
673 * empty input, so turn off the screen if DPMS is enabled, but
674 * only do that after some timeout: maybe user mistyped and
675 * will type again right away */
676 START_TIMER(dpms_timeout, TSTAMP_N_SECS(inactivity_timeout),
677 turn_off_monitors_cb);
680 case XCB_VISIBILITY_NOTIFY:
681 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
686 /* After the first MapNotify, we never fork again. We don’t
687 * expect to get another MapNotify, but better be sure… */
690 /* In the parent process, we exit */
694 ev_loop_fork(EV_DEFAULT);
698 case XCB_CONFIGURE_NOTIFY:
699 handle_screen_resize();
703 if (type == xkb_base_event)
704 process_xkb_event(event);
712 * This function is called from a fork()ed child and will raise the i3lock
713 * window when the window is obscured, even when the main i3lock process is
714 * blocked due to PAM.
717 static void raise_loop(xcb_window_t window) {
718 xcb_connection_t *conn;
719 xcb_generic_event_t *event;
722 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
723 xcb_connection_has_error(conn))
724 errx(EXIT_FAILURE, "Cannot open display\n");
726 /* We need to know about the window being obscured or getting destroyed. */
727 xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
729 XCB_EVENT_MASK_VISIBILITY_CHANGE |
730 XCB_EVENT_MASK_STRUCTURE_NOTIFY});
733 DEBUG("Watching window 0x%08x\n", window);
734 while ((event = xcb_wait_for_event(conn)) != NULL) {
735 if (event->response_type == 0) {
736 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
737 DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
738 error->sequence, error->error_code);
742 /* Strip off the highest bit (set if the event is generated) */
743 int type = (event->response_type & 0x7F);
744 DEBUG("Read event of type %d\n", type);
746 case XCB_VISIBILITY_NOTIFY:
747 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
749 case XCB_UNMAP_NOTIFY:
750 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
751 if (((xcb_unmap_notify_event_t *)event)->window == window)
754 case XCB_DESTROY_NOTIFY:
755 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
756 if (((xcb_destroy_notify_event_t *)event)->window == window)
760 DEBUG("Unhandled event type %d\n", type);
767 int main(int argc, char *argv[]) {
770 char *image_path = NULL;
772 struct pam_conv conv = {conv_callback, NULL};
773 int curs_choice = CURS_NONE;
776 struct option longopts[] = {
777 {"version", no_argument, NULL, 'v'},
778 {"nofork", no_argument, NULL, 'n'},
779 {"beep", no_argument, NULL, 'b'},
780 {"dpms", no_argument, NULL, 'd'},
781 {"color", required_argument, NULL, 'c'},
782 {"pointer", required_argument, NULL, 'p'},
783 {"debug", no_argument, NULL, 0},
784 {"help", no_argument, NULL, 'h'},
785 {"no-unlock-indicator", no_argument, NULL, 'u'},
786 {"image", required_argument, NULL, 'i'},
787 {"tiling", no_argument, NULL, 't'},
788 {"ignore-empty-password", no_argument, NULL, 'e'},
789 {"inactivity-timeout", required_argument, NULL, 'I'},
790 {"show-failed-attempts", no_argument, NULL, 'f'},
791 {NULL, no_argument, NULL, 0}};
793 if ((pw = getpwuid(getuid())) == NULL)
794 err(EXIT_FAILURE, "getpwuid() failed");
795 if ((username = pw->pw_name) == NULL)
796 errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
798 char *optstring = "hvnbdc:p:ui:teI:f";
799 while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
802 errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg");
814 if (sscanf(optarg, "%d", &time) != 1 || time < 0)
815 errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
816 inactivity_timeout = time;
822 /* Skip # if present */
826 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
827 errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
832 unlock_indicator = false;
835 image_path = strdup(optarg);
841 if (!strcmp(optarg, "win")) {
842 curs_choice = CURS_WIN;
843 } else if (!strcmp(optarg, "default")) {
844 curs_choice = CURS_DEFAULT;
846 errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
850 ignore_empty_password = true;
853 if (strcmp(longopts[optind].name, "debug") == 0)
857 show_failed_attempts = true;
860 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
861 " [-i image.png] [-t] [-e] [-I timeout] [-f]");
865 /* We need (relatively) random numbers for highlighting a random part of
866 * the unlock indicator upon keypresses. */
870 ret = pam_start("i3lock", username, &conv, &pam_handle);
871 if (ret != PAM_SUCCESS)
872 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
874 /* Using mlock() as non-super-user seems only possible in Linux. Users of other
875 * operating systems should use encrypted swap/no swap (or remove the ifdef and
876 * run i3lock as super-user). */
877 #if defined(__linux__)
878 /* Lock the area where we store the password in memory, we don’t want it to
879 * be swapped to disk. Since Linux 2.6.9, this does not require any
880 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
881 if (mlock(password, sizeof(password)) != 0)
882 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
885 /* Double checking that connection is good and operatable with xcb */
887 if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
888 xcb_connection_has_error(conn))
889 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
891 if (xkb_x11_setup_xkb_extension(conn,
892 XKB_X11_MIN_MAJOR_XKB_VERSION,
893 XKB_X11_MIN_MINOR_XKB_VERSION,
898 &xkb_base_error) != 1)
899 errx(EXIT_FAILURE, "Could not setup XKB extension.");
901 static const xcb_xkb_map_part_t required_map_parts =
902 (XCB_XKB_MAP_PART_KEY_TYPES |
903 XCB_XKB_MAP_PART_KEY_SYMS |
904 XCB_XKB_MAP_PART_MODIFIER_MAP |
905 XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
906 XCB_XKB_MAP_PART_KEY_ACTIONS |
907 XCB_XKB_MAP_PART_VIRTUAL_MODS |
908 XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
910 static const xcb_xkb_event_type_t required_events =
911 (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
912 XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
913 XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
915 xcb_xkb_select_events(
917 xkb_x11_get_core_keyboard_device_id(conn),
925 /* When we cannot initially load the keymap, we better exit */
927 errx(EXIT_FAILURE, "Could not load keymap");
929 const char *locale = getenv("LC_ALL");
931 locale = getenv("LC_CTYPE");
933 locale = getenv("LANG");
936 fprintf(stderr, "Can't detect your locale, fallback to C\n");
940 load_compose_table(locale);
943 xinerama_query_screens();
945 /* if DPMS is enabled, check if the X server really supports it */
947 xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
948 xcb_dpms_capable_reply_t *dpmsr;
949 if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
950 if (!dpmsr->capable) {
952 fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
959 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
961 last_resolution[0] = screen->width_in_pixels;
962 last_resolution[1] = screen->height_in_pixels;
964 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
965 (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
968 /* Create a pixmap to render on, fill it with the background color */
969 img = cairo_image_surface_create_from_png(image_path);
970 /* In case loading failed, we just pretend no -i was specified. */
971 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
972 fprintf(stderr, "Could not load image \"%s\": %s\n",
973 image_path, cairo_status_to_string(cairo_surface_status(img)));
978 /* Pixmap on which the image is rendered to (if any) */
979 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
981 /* open the fullscreen window, already with the correct pixmap in place */
982 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
983 xcb_free_pixmap(conn, bg_pixmap);
986 /* The pid == -1 case is intentionally ignored here:
987 * While the child process is useful for preventing other windows from
988 * popping up while i3lock blocks, it is not critical. */
991 close(xcb_get_file_descriptor(conn));
996 cursor = create_cursor(conn, screen, win, curs_choice);
998 grab_pointer_and_keyboard(conn, screen, cursor);
999 /* Load the keymap again to sync the current modifier state. Since we first
1000 * loaded the keymap, there might have been changes, but starting from now,
1001 * we should get all key presses/releases due to having grabbed the
1003 (void)load_keymap();
1005 turn_monitors_off();
1007 /* Initialize the libev event loop. */
1008 main_loop = EV_DEFAULT;
1009 if (main_loop == NULL)
1010 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
1012 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1013 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1014 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1016 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1017 ev_io_start(main_loop, xcb_watcher);
1019 ev_check_init(xcb_check, xcb_check_cb);
1020 ev_check_start(main_loop, xcb_check);
1022 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1023 ev_prepare_start(main_loop, xcb_prepare);
1025 /* Invoke the event callback once to catch all the events which were
1026 * received up until now. ev will only pick up new events (when the X11
1027 * file descriptor becomes readable). */
1028 ev_invoke(main_loop, xcb_check, 0);
1029 ev_loop(main_loop, 0);