2 * vim:ts=4:sw=4:expandtab
4 * © 2010 Michael Stapelberg
6 * See LICENSE for licensing information
12 #include <sys/types.h>
21 #include <security/pam_appl.h>
26 #include <xkbcommon/xkbcommon.h>
27 #include <xkbcommon/xkbcommon-compose.h>
28 #include <xkbcommon/xkbcommon-x11.h>
30 #include <cairo/cairo-xcb.h>
35 #include "unlock_indicator.h"
38 #define TSTAMP_N_SECS(n) (n * 1.0)
39 #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
40 #define START_TIMER(timer_obj, timeout, callback) \
41 timer_obj = start_timer(timer_obj, timeout, callback)
42 #define STOP_TIMER(timer_obj) \
43 timer_obj = stop_timer(timer_obj)
45 typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
47 /* We need this for libxkbfile */
48 char color[7] = "ffffff";
49 int inactivity_timeout = 30;
50 uint32_t last_resolution[2];
52 static xcb_cursor_t cursor;
53 static pam_handle_t *pam_handle;
54 int input_position = 0;
55 /* Holds the password you enter (in UTF-8). */
56 static char password[512];
57 static bool beep = false;
58 bool debug_mode = false;
59 bool unlock_indicator = true;
60 char *modifier_string = NULL;
61 static bool dont_fork = false;
62 struct ev_loop *main_loop;
63 static struct ev_timer *clear_pam_wrong_timeout;
64 static struct ev_timer *clear_indicator_timeout;
65 static struct ev_timer *discard_passwd_timeout;
66 extern unlock_state_t unlock_state;
67 extern pam_state_t pam_state;
68 int failed_attempts = 0;
69 bool show_failed_attempts = false;
71 static struct xkb_state *xkb_state;
72 static struct xkb_context *xkb_context;
73 static struct xkb_keymap *xkb_keymap;
74 static struct xkb_compose_table *xkb_compose_table;
75 static struct xkb_compose_state *xkb_compose_state;
76 static uint8_t xkb_base_event;
77 static uint8_t xkb_base_error;
79 cairo_surface_t *img = NULL;
81 bool ignore_empty_password = false;
82 bool skip_repeated_empty_password = false;
84 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
85 #define isutf(c) (((c)&0xC0) != 0x80)
88 * Decrements i to point to the previous unicode glyph
91 void u8_dec(char *s, int *i) {
92 (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
96 * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
97 * Necessary so that we can properly let xkbcommon track the keyboard state and
98 * translate keypresses to utf-8.
101 static bool load_keymap(void) {
102 if (xkb_context == NULL) {
103 if ((xkb_context = xkb_context_new(0)) == NULL) {
104 fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
109 xkb_keymap_unref(xkb_keymap);
111 int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
112 DEBUG("device = %d\n", device_id);
113 if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
114 fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
118 struct xkb_state *new_state =
119 xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
120 if (new_state == NULL) {
121 fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
125 xkb_state_unref(xkb_state);
126 xkb_state = new_state;
132 * Loads the XKB compose table from the given locale.
135 static bool load_compose_table(const char *locale) {
136 xkb_compose_table_unref(xkb_compose_table);
138 if ((xkb_compose_table = xkb_compose_table_new_from_locale(xkb_context, locale, 0)) == NULL) {
139 fprintf(stderr, "[i3lock] xkb_compose_table_new_from_locale failed\n");
143 struct xkb_compose_state *new_compose_state = xkb_compose_state_new(xkb_compose_table, 0);
144 if (new_compose_state == NULL) {
145 fprintf(stderr, "[i3lock] xkb_compose_state_new failed\n");
149 xkb_compose_state_unref(xkb_compose_state);
150 xkb_compose_state = new_compose_state;
156 * Clears the memory which stored the password to be a bit safer against
160 static void clear_password_memory(void) {
161 /* A volatile pointer to the password buffer to prevent the compiler from
162 * optimizing this out. */
163 volatile char *vpassword = password;
164 for (int c = 0; c < sizeof(password); c++)
165 /* We store a non-random pattern which consists of the (irrelevant)
166 * index plus (!) the value of the beep variable. This prevents the
167 * compiler from optimizing the calls away, since the value of 'beep'
168 * is not known at compile-time. */
169 vpassword[c] = c + (int)beep;
172 ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
174 ev_timer_stop(main_loop, timer_obj);
175 ev_timer_set(timer_obj, timeout, 0.);
176 ev_timer_start(main_loop, timer_obj);
178 /* When there is no memory, we just don’t have a timeout. We cannot
179 * exit() here, since that would effectively unlock the screen. */
180 timer_obj = calloc(sizeof(struct ev_timer), 1);
182 ev_timer_init(timer_obj, callback, timeout, 0.);
183 ev_timer_start(main_loop, timer_obj);
189 ev_timer *stop_timer(ev_timer *timer_obj) {
191 ev_timer_stop(main_loop, timer_obj);
198 * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccessful
199 * authentication event.
202 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
203 DEBUG("clearing pam wrong\n");
204 pam_state = STATE_PAM_IDLE;
205 unlock_state = STATE_STARTED;
208 /* Clear modifier string. */
209 if (modifier_string != NULL) {
210 free(modifier_string);
211 modifier_string = NULL;
214 /* Now free this timeout. */
215 STOP_TIMER(clear_pam_wrong_timeout);
218 static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
220 STOP_TIMER(clear_indicator_timeout);
223 static void clear_input(void) {
225 clear_password_memory();
226 password[input_position] = '\0';
228 /* Hide the unlock indicator after a bit if the password buffer is
230 if (unlock_indicator) {
231 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
232 unlock_state = STATE_BACKSPACE_ACTIVE;
234 unlock_state = STATE_KEY_PRESSED;
238 static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
240 STOP_TIMER(discard_passwd_timeout);
243 static void input_done(void) {
244 STOP_TIMER(clear_pam_wrong_timeout);
245 pam_state = STATE_PAM_VERIFY;
248 if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
249 DEBUG("successfully authenticated\n");
250 clear_password_memory();
252 /* PAM credentials should be refreshed, this will for example update any kerberos tickets.
253 * Related to credentials pam_end() needs to be called to cleanup any temporary
254 * credentials like kerberos /tmp/krb5cc_pam_* files which may of been left behind if the
255 * refresh of the credentials failed. */
256 pam_setcred(pam_handle, PAM_REFRESH_CRED);
257 pam_end(pam_handle, PAM_SUCCESS);
263 fprintf(stderr, "Authentication failure\n");
265 /* Get state of Caps and Num lock modifiers, to be displayed in
266 * STATE_PAM_WRONG state */
267 xkb_mod_index_t idx, num_mods;
268 const char *mod_name;
270 num_mods = xkb_keymap_num_mods(xkb_keymap);
272 for (idx = 0; idx < num_mods; idx++) {
273 if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
276 mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
277 if (mod_name == NULL)
280 /* Replace certain xkb names with nicer, human-readable ones. */
281 if (strcmp(mod_name, XKB_MOD_NAME_CAPS) == 0)
282 mod_name = "Caps Lock";
283 else if (strcmp(mod_name, XKB_MOD_NAME_ALT) == 0)
285 else if (strcmp(mod_name, XKB_MOD_NAME_NUM) == 0)
286 mod_name = "Num Lock";
287 else if (strcmp(mod_name, XKB_MOD_NAME_LOGO) == 0)
291 if (modifier_string == NULL) {
292 if (asprintf(&tmp, "%s", mod_name) != -1)
293 modifier_string = tmp;
294 } else if (asprintf(&tmp, "%s, %s", modifier_string, mod_name) != -1) {
295 free(modifier_string);
296 modifier_string = tmp;
300 pam_state = STATE_PAM_WRONG;
301 failed_attempts += 1;
303 if (unlock_indicator)
306 /* Clear this state after 2 seconds (unless the user enters another
307 * password during that time). */
308 ev_now_update(main_loop);
309 START_TIMER(clear_pam_wrong_timeout, TSTAMP_N_SECS(2), clear_pam_wrong);
311 /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
313 STOP_TIMER(clear_indicator_timeout);
315 /* beep on authentication failure, if enabled */
322 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
327 static bool skip_without_validation(void) {
328 if (input_position != 0)
331 if (skip_repeated_empty_password || ignore_empty_password)
338 * Handle key presses. Fixes state, then looks up the key symbol for the
339 * given keycode, then looks up the key symbol (as UCS-2), converts it to
340 * UTF-8 and stores it in the password array.
343 static void handle_key_press(xcb_key_press_event_t *event) {
348 bool composed = false;
350 ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
351 ctrl = xkb_state_mod_name_is_active(xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_DEPRESSED);
353 /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
354 memset(buffer, '\0', sizeof(buffer));
356 if (xkb_compose_state && xkb_compose_state_feed(xkb_compose_state, ksym) == XKB_COMPOSE_FEED_ACCEPTED) {
357 switch (xkb_compose_state_get_status(xkb_compose_state)) {
358 case XKB_COMPOSE_NOTHING:
360 case XKB_COMPOSE_COMPOSING:
362 case XKB_COMPOSE_COMPOSED:
363 /* xkb_compose_state_get_utf8 doesn't include the terminating byte in the return value
364 * as xkb_keysym_to_utf8 does. Adding one makes the variable n consistent. */
365 n = xkb_compose_state_get_utf8(xkb_compose_state, buffer, sizeof(buffer)) + 1;
366 ksym = xkb_compose_state_get_one_sym(xkb_compose_state);
369 case XKB_COMPOSE_CANCELLED:
370 xkb_compose_state_reset(xkb_compose_state);
376 n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
381 case XKB_KEY_KP_Enter:
382 case XKB_KEY_XF86ScreenSaver:
383 if (pam_state == STATE_PAM_WRONG)
386 if (skip_without_validation()) {
390 password[input_position] = '\0';
391 unlock_state = STATE_KEY_PRESSED;
394 skip_repeated_empty_password = true;
397 skip_repeated_empty_password = false;
403 DEBUG("C-u pressed\n");
413 case XKB_KEY_BackSpace:
414 if (input_position == 0)
417 /* decrement input_position to point to the previous glyph */
418 u8_dec(password, &input_position);
419 password[input_position] = '\0';
421 /* Hide the unlock indicator after a bit if the password buffer is
423 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
424 unlock_state = STATE_BACKSPACE_ACTIVE;
426 unlock_state = STATE_KEY_PRESSED;
430 if ((input_position + 8) >= sizeof(password))
434 /* FIXME: handle all of these? */
435 printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
436 printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
437 printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
438 printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
439 printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
440 printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
441 printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
447 /* store it in the password array as UTF-8 */
448 memcpy(password + input_position, buffer, n - 1);
449 input_position += n - 1;
450 DEBUG("current password = %.*s\n", input_position, password);
452 if (unlock_indicator) {
453 unlock_state = STATE_KEY_ACTIVE;
455 unlock_state = STATE_KEY_PRESSED;
457 struct ev_timer *timeout = NULL;
458 START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
459 STOP_TIMER(clear_indicator_timeout);
462 START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
466 * A visibility notify event will be received when the visibility (= can the
467 * user view the complete window) changes, so for example when a popup overlays
468 * some area of the i3lock window.
470 * In this case, we raise our window on top so that the popup (or whatever is
471 * hiding us) gets hidden.
474 static void handle_visibility_notify(xcb_connection_t *conn,
475 xcb_visibility_notify_event_t *event) {
476 if (event->state != XCB_VISIBILITY_UNOBSCURED) {
477 uint32_t values[] = {XCB_STACK_MODE_ABOVE};
478 xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
484 * Called when the keyboard mapping changes. We update our symbols.
486 * We ignore errors — if the new keymap cannot be loaded it’s better if the
487 * screen stays locked and the user intervenes by using killall i3lock.
490 static void process_xkb_event(xcb_generic_event_t *gevent) {
493 uint8_t response_type;
496 xcb_timestamp_t time;
499 xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
500 xcb_xkb_map_notify_event_t map_notify;
501 xcb_xkb_state_notify_event_t state_notify;
502 } *event = (union xkb_event *)gevent;
504 DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
506 if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
510 * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
511 * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
514 switch (event->any.xkbType) {
515 case XCB_XKB_NEW_KEYBOARD_NOTIFY:
516 if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
520 case XCB_XKB_MAP_NOTIFY:
524 case XCB_XKB_STATE_NOTIFY:
525 xkb_state_update_mask(xkb_state,
526 event->state_notify.baseMods,
527 event->state_notify.latchedMods,
528 event->state_notify.lockedMods,
529 event->state_notify.baseGroup,
530 event->state_notify.latchedGroup,
531 event->state_notify.lockedGroup);
537 * Called when the properties on the root window change, e.g. when the screen
538 * resolution changes. If so we update the window to cover the whole screen
539 * and also redraw the image, if any.
542 void handle_screen_resize(void) {
543 xcb_get_geometry_cookie_t geomc;
544 xcb_get_geometry_reply_t *geom;
545 geomc = xcb_get_geometry(conn, screen->root);
546 if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
549 if (last_resolution[0] == geom->width &&
550 last_resolution[1] == geom->height) {
555 last_resolution[0] = geom->width;
556 last_resolution[1] = geom->height;
562 uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
563 xcb_configure_window(conn, win, mask, last_resolution);
566 xinerama_query_screens();
571 * Callback function for PAM. We only react on password request callbacks.
574 static int conv_callback(int num_msg, const struct pam_message **msg,
575 struct pam_response **resp, void *appdata_ptr) {
579 /* PAM expects an array of responses, one for each message */
580 if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
585 for (int c = 0; c < num_msg; c++) {
586 if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
587 msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
590 /* return code is currently not used but should be set to zero */
591 resp[c]->resp_retcode = 0;
592 if ((resp[c]->resp = strdup(password)) == NULL) {
602 * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
603 * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
606 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
607 /* empty, because xcb_prepare_cb and xcb_check_cb are used */
611 * Flush before blocking (and waiting for new events)
614 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
619 * Instead of polling the X connection socket we leave this to
620 * xcb_poll_for_event() which knows better than we can ever know.
623 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
624 xcb_generic_event_t *event;
626 if (xcb_connection_has_error(conn))
627 errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
629 while ((event = xcb_poll_for_event(conn)) != NULL) {
630 if (event->response_type == 0) {
631 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
633 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
634 error->sequence, error->error_code);
639 /* Strip off the highest bit (set if the event is generated) */
640 int type = (event->response_type & 0x7F);
644 handle_key_press((xcb_key_press_event_t *)event);
647 case XCB_VISIBILITY_NOTIFY:
648 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
653 /* After the first MapNotify, we never fork again. We don’t
654 * expect to get another MapNotify, but better be sure… */
657 /* In the parent process, we exit */
661 ev_loop_fork(EV_DEFAULT);
665 case XCB_CONFIGURE_NOTIFY:
666 handle_screen_resize();
670 if (type == xkb_base_event)
671 process_xkb_event(event);
679 * This function is called from a fork()ed child and will raise the i3lock
680 * window when the window is obscured, even when the main i3lock process is
681 * blocked due to PAM.
684 static void raise_loop(xcb_window_t window) {
685 xcb_connection_t *conn;
686 xcb_generic_event_t *event;
689 if ((conn = xcb_connect(NULL, &screens)) == NULL ||
690 xcb_connection_has_error(conn))
691 errx(EXIT_FAILURE, "Cannot open display\n");
693 /* We need to know about the window being obscured or getting destroyed. */
694 xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
696 XCB_EVENT_MASK_VISIBILITY_CHANGE |
697 XCB_EVENT_MASK_STRUCTURE_NOTIFY});
700 DEBUG("Watching window 0x%08x\n", window);
701 while ((event = xcb_wait_for_event(conn)) != NULL) {
702 if (event->response_type == 0) {
703 xcb_generic_error_t *error = (xcb_generic_error_t *)event;
704 DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
705 error->sequence, error->error_code);
709 /* Strip off the highest bit (set if the event is generated) */
710 int type = (event->response_type & 0x7F);
711 DEBUG("Read event of type %d\n", type);
713 case XCB_VISIBILITY_NOTIFY:
714 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
716 case XCB_UNMAP_NOTIFY:
717 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
718 if (((xcb_unmap_notify_event_t *)event)->window == window)
721 case XCB_DESTROY_NOTIFY:
722 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
723 if (((xcb_destroy_notify_event_t *)event)->window == window)
727 DEBUG("Unhandled event type %d\n", type);
734 int main(int argc, char *argv[]) {
737 char *image_path = NULL;
739 struct pam_conv conv = {conv_callback, NULL};
740 int curs_choice = CURS_NONE;
743 struct option longopts[] = {
744 {"version", no_argument, NULL, 'v'},
745 {"nofork", no_argument, NULL, 'n'},
746 {"beep", no_argument, NULL, 'b'},
747 {"dpms", no_argument, NULL, 'd'},
748 {"color", required_argument, NULL, 'c'},
749 {"pointer", required_argument, NULL, 'p'},
750 {"debug", no_argument, NULL, 0},
751 {"help", no_argument, NULL, 'h'},
752 {"no-unlock-indicator", no_argument, NULL, 'u'},
753 {"image", required_argument, NULL, 'i'},
754 {"tiling", no_argument, NULL, 't'},
755 {"ignore-empty-password", no_argument, NULL, 'e'},
756 {"inactivity-timeout", required_argument, NULL, 'I'},
757 {"show-failed-attempts", no_argument, NULL, 'f'},
758 {NULL, no_argument, NULL, 0}};
760 if ((pw = getpwuid(getuid())) == NULL)
761 err(EXIT_FAILURE, "getpwuid() failed");
762 if ((username = pw->pw_name) == NULL)
763 errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
765 char *optstring = "hvnbdc:p:ui:teI:f";
766 while ((o = getopt_long(argc, argv, optstring, longopts, &optind)) != -1) {
769 errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg");
777 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
781 if (sscanf(optarg, "%d", &time) != 1 || time < 0)
782 errx(EXIT_FAILURE, "invalid timeout, it must be a positive integer\n");
783 inactivity_timeout = time;
789 /* Skip # if present */
793 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
794 errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
799 unlock_indicator = false;
802 image_path = strdup(optarg);
808 if (!strcmp(optarg, "win")) {
809 curs_choice = CURS_WIN;
810 } else if (!strcmp(optarg, "default")) {
811 curs_choice = CURS_DEFAULT;
813 errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
817 ignore_empty_password = true;
820 if (strcmp(longopts[optind].name, "debug") == 0)
824 show_failed_attempts = true;
827 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
828 " [-i image.png] [-t] [-e] [-I timeout] [-f]");
832 /* We need (relatively) random numbers for highlighting a random part of
833 * the unlock indicator upon keypresses. */
837 if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
838 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
840 if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
841 errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
843 /* Using mlock() as non-super-user seems only possible in Linux. Users of other
844 * operating systems should use encrypted swap/no swap (or remove the ifdef and
845 * run i3lock as super-user). */
846 #if defined(__linux__)
847 /* Lock the area where we store the password in memory, we don’t want it to
848 * be swapped to disk. Since Linux 2.6.9, this does not require any
849 * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
850 if (mlock(password, sizeof(password)) != 0)
851 err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
854 /* Double checking that connection is good and operatable with xcb */
856 if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
857 xcb_connection_has_error(conn))
858 errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
860 if (xkb_x11_setup_xkb_extension(conn,
861 XKB_X11_MIN_MAJOR_XKB_VERSION,
862 XKB_X11_MIN_MINOR_XKB_VERSION,
867 &xkb_base_error) != 1)
868 errx(EXIT_FAILURE, "Could not setup XKB extension.");
870 static const xcb_xkb_map_part_t required_map_parts =
871 (XCB_XKB_MAP_PART_KEY_TYPES |
872 XCB_XKB_MAP_PART_KEY_SYMS |
873 XCB_XKB_MAP_PART_MODIFIER_MAP |
874 XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
875 XCB_XKB_MAP_PART_KEY_ACTIONS |
876 XCB_XKB_MAP_PART_VIRTUAL_MODS |
877 XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
879 static const xcb_xkb_event_type_t required_events =
880 (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
881 XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
882 XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
884 xcb_xkb_select_events(
886 xkb_x11_get_core_keyboard_device_id(conn),
894 /* When we cannot initially load the keymap, we better exit */
896 errx(EXIT_FAILURE, "Could not load keymap");
898 const char *locale = getenv("LC_ALL");
900 locale = getenv("LC_CTYPE");
902 locale = getenv("LANG");
905 fprintf(stderr, "Can't detect your locale, fallback to C\n");
909 load_compose_table(locale);
912 xinerama_query_screens();
914 screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
916 last_resolution[0] = screen->width_in_pixels;
917 last_resolution[1] = screen->height_in_pixels;
919 xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
920 (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
923 /* Create a pixmap to render on, fill it with the background color */
924 img = cairo_image_surface_create_from_png(image_path);
925 /* In case loading failed, we just pretend no -i was specified. */
926 if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
927 fprintf(stderr, "Could not load image \"%s\": %s\n",
928 image_path, cairo_status_to_string(cairo_surface_status(img)));
933 /* Pixmap on which the image is rendered to (if any) */
934 xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
936 /* open the fullscreen window, already with the correct pixmap in place */
937 win = open_fullscreen_window(conn, screen, color, bg_pixmap);
938 xcb_free_pixmap(conn, bg_pixmap);
941 /* The pid == -1 case is intentionally ignored here:
942 * While the child process is useful for preventing other windows from
943 * popping up while i3lock blocks, it is not critical. */
946 close(xcb_get_file_descriptor(conn));
951 cursor = create_cursor(conn, screen, win, curs_choice);
953 grab_pointer_and_keyboard(conn, screen, cursor);
954 /* Load the keymap again to sync the current modifier state. Since we first
955 * loaded the keymap, there might have been changes, but starting from now,
956 * we should get all key presses/releases due to having grabbed the
960 /* Initialize the libev event loop. */
961 main_loop = EV_DEFAULT;
962 if (main_loop == NULL)
963 errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
965 struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
966 struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
967 struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
969 ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
970 ev_io_start(main_loop, xcb_watcher);
972 ev_check_init(xcb_check, xcb_check_cb);
973 ev_check_start(main_loop, xcb_check);
975 ev_prepare_init(xcb_prepare, xcb_prepare_cb);
976 ev_prepare_start(main_loop, xcb_prepare);
978 /* Invoke the event callback once to catch all the events which were
979 * received up until now. ev will only pick up new events (when the X11
980 * file descriptor becomes readable). */
981 ev_invoke(main_loop, xcb_check, 0);
982 ev_loop(main_loop, 0);