1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2010 Michael Stapelberg
5  *
6  * See LICENSE for licensing information
7  *
8  */
9 #include <config.h>
10 
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <pwd.h>
14 #include <sys/types.h>
15 #include <string.h>
16 #include <unistd.h>
17 #include <stdbool.h>
18 #include <stdint.h>
19 #include <xcb/xcb.h>
20 #include <xcb/xkb.h>
21 #include <err.h>
22 #include <errno.h>
23 #include <assert.h>
24 #ifdef __OpenBSD__
25 #include <bsd_auth.h>
26 #else
27 #include <security/pam_appl.h>
28 #endif
29 #include <getopt.h>
30 #include <ev.h>
31 #include <sys/mman.h>
32 #include <xkbcommon/xkbcommon.h>
33 #include <xkbcommon/xkbcommon-compose.h>
34 #include <xkbcommon/xkbcommon-x11.h>
35 #include <cairo.h>
36 #include <cairo/cairo-xcb.h>
37 #ifdef HAVE_EXPLICIT_BZERO
38 #include <strings.h> /* explicit_bzero(3) */
39 #endif
40 #include <xcb/xcb_aux.h>
41 #include <xcb/randr.h>
42 
43 #include "i3lock.h"
44 #include "xcb.h"
45 #include "cursors.h"
46 #include "unlock_indicator.h"
47 #include "randr.h"
48 #include "dpi.h"
49 
50 #define TSTAMP_N_SECS(n) (n * 1.0)
51 #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
52 #define START_TIMER(timer_obj, timeout, callback) \
53     timer_obj = start_timer(timer_obj, timeout, callback)
54 #define STOP_TIMER(timer_obj) \
55     timer_obj = stop_timer(timer_obj)
56 
57 typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
58 static void input_done(void);
59 
60 char color[7] = "ffffff";
61 uint32_t last_resolution[2];
62 xcb_window_t win;
63 static xcb_cursor_t cursor;
64 #ifndef __OpenBSD__
65 static pam_handle_t *pam_handle;
66 static bool pam_cleanup;
67 #endif
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;
85 
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;
94 
95 cairo_surface_t *img = NULL;
96 bool tile = false;
97 bool ignore_empty_password = false;
98 bool skip_repeated_empty_password = false;
99 
100 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
101 #define isutf(c) (((c)&0xC0) != 0x80)
102 
103 /*
104  * Decrements i to point to the previous unicode glyph
105  *
106  */
u8_dec(char * s,int * i)107 static void u8_dec(char *s, int *i) {
108     (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
109 }
110 
111 /*
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.
115  *
116  */
load_keymap(void)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");
121             return false;
122         }
123     }
124 
125     xkb_keymap_unref(xkb_keymap);
126 
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");
131         return false;
132     }
133 
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");
138         return false;
139     }
140 
141     xkb_state_unref(xkb_state);
142     xkb_state = new_state;
143 
144     return true;
145 }
146 
147 /*
148  * Loads the XKB compose table from the given locale.
149  *
150  */
load_compose_table(const char * locale)151 static bool load_compose_table(const char *locale) {
152     xkb_compose_table_unref(xkb_compose_table);
153 
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");
156         return false;
157     }
158 
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");
162         return false;
163     }
164 
165     xkb_compose_state_unref(xkb_compose_state);
166     xkb_compose_state = new_compose_state;
167 
168     return true;
169 }
170 
171 /*
172  * Clears the memory which stored the password to be a bit safer against
173  * cold-boot attacks.
174  *
175  */
clear_password_memory(void)176 static void clear_password_memory(void) {
177 #ifdef HAVE_EXPLICIT_BZERO
178     /* Use explicit_bzero(3) which was explicitly designed not to be
179      * optimized out by the compiler. */
180     explicit_bzero(password, strlen(password));
181 #else
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;
191 #endif
192 }
193 
start_timer(ev_timer * timer_obj,ev_tstamp timeout,ev_callback_t callback)194 ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
195     if (timer_obj) {
196         ev_timer_stop(main_loop, timer_obj);
197         ev_timer_set(timer_obj, timeout, 0.);
198         ev_timer_start(main_loop, timer_obj);
199     } else {
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);
203         if (timer_obj) {
204             ev_timer_init(timer_obj, callback, timeout, 0.);
205             ev_timer_start(main_loop, timer_obj);
206         }
207     }
208     return timer_obj;
209 }
210 
stop_timer(ev_timer * timer_obj)211 ev_timer *stop_timer(ev_timer *timer_obj) {
212     if (timer_obj) {
213         ev_timer_stop(main_loop, timer_obj);
214         free(timer_obj);
215     }
216     return NULL;
217 }
218 
219 /*
220  * Neccessary calls after ending input via enter or others
221  *
222  */
finish_input(void)223 static void finish_input(void) {
224     password[input_position] = '\0';
225     unlock_state = STATE_KEY_PRESSED;
226     redraw_screen();
227     input_done();
228 }
229 
230 /*
231  * Resets auth_state to STATE_AUTH_IDLE 2 seconds after an unsuccessful
232  * authentication event.
233  *
234  */
clear_auth_wrong(EV_P_ ev_timer * w,int revents)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;
238     redraw_screen();
239 
240     /* Clear modifier string. */
241     if (modifier_string != NULL) {
242         free(modifier_string);
243         modifier_string = NULL;
244     }
245 
246     /* Now free this timeout. */
247     STOP_TIMER(clear_auth_wrong_timeout);
248 
249     /* retry with input done during auth verification */
250     if (retry_verification) {
251         retry_verification = false;
252         finish_input();
253     }
254 }
255 
clear_indicator_cb(EV_P_ ev_timer * w,int revents)256 static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
257     clear_indicator();
258     STOP_TIMER(clear_indicator_timeout);
259 }
260 
clear_input(void)261 static void clear_input(void) {
262     input_position = 0;
263     clear_password_memory();
264     password[input_position] = '\0';
265 }
266 
discard_passwd_cb(EV_P_ ev_timer * w,int revents)267 static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
268     clear_input();
269     STOP_TIMER(discard_passwd_timeout);
270 }
271 
input_done(void)272 static void input_done(void) {
273     STOP_TIMER(clear_auth_wrong_timeout);
274     auth_state = STATE_AUTH_VERIFY;
275     unlock_state = STATE_STARTED;
276     redraw_screen();
277 
278 #ifdef __OpenBSD__
279     struct passwd *pw;
280 
281     if (!(pw = getpwuid(getuid())))
282         errx(1, "unknown uid %u.", getuid());
283 
284     if (auth_userokay(pw->pw_name, NULL, NULL, password) != 0) {
285         DEBUG("successfully authenticated\n");
286         clear_password_memory();
287 
288         ev_break(EV_DEFAULT, EVBREAK_ALL);
289         return;
290     }
291 #else
292     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
293         DEBUG("successfully authenticated\n");
294         clear_password_memory();
295 
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_cleanup = true;
302 
303         ev_break(EV_DEFAULT, EVBREAK_ALL);
304         return;
305     }
306 #endif
307 
308     if (debug_mode)
309         fprintf(stderr, "Authentication failure\n");
310 
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;
315 
316     num_mods = xkb_keymap_num_mods(xkb_keymap);
317 
318     for (idx = 0; idx < num_mods; idx++) {
319         if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
320             continue;
321 
322         mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
323         if (mod_name == NULL)
324             continue;
325 
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)
330             mod_name = "Alt";
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)
334             mod_name = "Super";
335 
336         char *tmp;
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;
343         }
344     }
345 
346     auth_state = STATE_AUTH_WRONG;
347     failed_attempts += 1;
348     clear_input();
349     if (unlock_indicator)
350         redraw_screen();
351 
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);
356 
357     /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
358      * too early. */
359     STOP_TIMER(clear_indicator_timeout);
360 
361     /* beep on authentication failure, if enabled */
362     if (beep) {
363         xcb_bell(conn, 100);
364         xcb_flush(conn);
365     }
366 }
367 
redraw_timeout(EV_P_ ev_timer * w,int revents)368 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
369     redraw_screen();
370     STOP_TIMER(w);
371 }
372 
skip_without_validation(void)373 static bool skip_without_validation(void) {
374     if (input_position != 0)
375         return false;
376 
377     if (skip_repeated_empty_password || ignore_empty_password)
378         return true;
379 
380     return false;
381 }
382 
383 /*
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.
387  *
388  */
handle_key_press(xcb_key_press_event_t * event)389 static void handle_key_press(xcb_key_press_event_t *event) {
390     xkb_keysym_t ksym;
391     char buffer[128];
392     int n;
393     bool ctrl;
394     bool composed = false;
395 
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);
398 
399     /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
400     memset(buffer, '\0', sizeof(buffer));
401 
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:
405                 break;
406             case XKB_COMPOSE_COMPOSING:
407                 return;
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);
413                 composed = true;
414                 break;
415             case XKB_COMPOSE_CANCELLED:
416                 xkb_compose_state_reset(xkb_compose_state);
417                 return;
418         }
419     }
420 
421     if (!composed) {
422         n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
423     }
424 
425     switch (ksym) {
426         case XKB_KEY_j:
427         case XKB_KEY_m:
428         case XKB_KEY_Return:
429         case XKB_KEY_KP_Enter:
430         case XKB_KEY_XF86ScreenSaver:
431             if ((ksym == XKB_KEY_j || ksym == XKB_KEY_m) && !ctrl)
432                 break;
433 
434             if (auth_state == STATE_AUTH_WRONG) {
435                 retry_verification = true;
436                 return;
437             }
438 
439             if (skip_without_validation()) {
440                 clear_input();
441                 return;
442             }
443             finish_input();
444             skip_repeated_empty_password = true;
445             return;
446         default:
447             skip_repeated_empty_password = false;
448             // A new password is being entered, but a previous one is pending.
449             // Discard the old one and clear the retry_verification flag.
450             if (retry_verification) {
451                 retry_verification = false;
452                 clear_input();
453             }
454     }
455 
456     switch (ksym) {
457         case XKB_KEY_u:
458         case XKB_KEY_Escape:
459             if ((ksym == XKB_KEY_u && ctrl) ||
460                 ksym == XKB_KEY_Escape) {
461                 DEBUG("C-u pressed\n");
462                 clear_input();
463                 /* Also hide the unlock indicator */
464                 if (unlock_indicator)
465                     clear_indicator();
466                 return;
467             }
468             break;
469 
470         case XKB_KEY_Delete:
471         case XKB_KEY_KP_Delete:
472             /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
473              * to move the cursor when entering a password. We need to eat this
474              * key press so that it won’t be treated as part of the password,
475              * see issue #50. */
476             return;
477 
478         case XKB_KEY_h:
479         case XKB_KEY_BackSpace:
480             if (ksym == XKB_KEY_h && !ctrl)
481                 break;
482 
483             if (input_position == 0) {
484                 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
485                 unlock_state = STATE_NOTHING_TO_DELETE;
486                 redraw_screen();
487                 return;
488             }
489 
490             /* decrement input_position to point to the previous glyph */
491             u8_dec(password, &input_position);
492             password[input_position] = '\0';
493 
494             /* Hide the unlock indicator after a bit if the password buffer is
495              * empty. */
496             START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
497             unlock_state = STATE_BACKSPACE_ACTIVE;
498             redraw_screen();
499             unlock_state = STATE_KEY_PRESSED;
500             return;
501     }
502 
503     if ((input_position + 8) >= (int)sizeof(password))
504         return;
505 
506 #if 0
507     /* FIXME: handle all of these? */
508     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
509     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
510     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
511     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
512     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
513     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
514     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
515 #endif
516 
517     if (n < 2)
518         return;
519 
520     /* store it in the password array as UTF-8 */
521     memcpy(password + input_position, buffer, n - 1);
522     input_position += n - 1;
523     DEBUG("current password = %.*s\n", input_position, password);
524 
525     if (unlock_indicator) {
526         unlock_state = STATE_KEY_ACTIVE;
527         redraw_screen();
528         unlock_state = STATE_KEY_PRESSED;
529 
530         struct ev_timer *timeout = NULL;
531         START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
532         STOP_TIMER(clear_indicator_timeout);
533     }
534 
535     START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
536 }
537 
538 /*
539  * A visibility notify event will be received when the visibility (= can the
540  * user view the complete window) changes, so for example when a popup overlays
541  * some area of the i3lock window.
542  *
543  * In this case, we raise our window on top so that the popup (or whatever is
544  * hiding us) gets hidden.
545  *
546  */
handle_visibility_notify(xcb_connection_t * conn,xcb_visibility_notify_event_t * event)547 static void handle_visibility_notify(xcb_connection_t *conn,
548                                      xcb_visibility_notify_event_t *event) {
549     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
550         uint32_t values[] = {XCB_STACK_MODE_ABOVE};
551         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
552         xcb_flush(conn);
553     }
554 }
555 
556 /*
557  * Called when the keyboard mapping changes. We update our symbols.
558  *
559  * We ignore errors — if the new keymap cannot be loaded it’s better if the
560  * screen stays locked and the user intervenes by using killall i3lock.
561  *
562  */
process_xkb_event(xcb_generic_event_t * gevent)563 static void process_xkb_event(xcb_generic_event_t *gevent) {
564     union xkb_event {
565         struct {
566             uint8_t response_type;
567             uint8_t xkbType;
568             uint16_t sequence;
569             xcb_timestamp_t time;
570             uint8_t deviceID;
571         } any;
572         xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
573         xcb_xkb_map_notify_event_t map_notify;
574         xcb_xkb_state_notify_event_t state_notify;
575     } *event = (union xkb_event *)gevent;
576 
577     DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
578 
579     if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
580         return;
581 
582     /*
583      * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
584      * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
585      * recompilations.
586      */
587     switch (event->any.xkbType) {
588         case XCB_XKB_NEW_KEYBOARD_NOTIFY:
589             if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
590                 (void)load_keymap();
591             break;
592 
593         case XCB_XKB_MAP_NOTIFY:
594             (void)load_keymap();
595             break;
596 
597         case XCB_XKB_STATE_NOTIFY:
598             xkb_state_update_mask(xkb_state,
599                                   event->state_notify.baseMods,
600                                   event->state_notify.latchedMods,
601                                   event->state_notify.lockedMods,
602                                   event->state_notify.baseGroup,
603                                   event->state_notify.latchedGroup,
604                                   event->state_notify.lockedGroup);
605             break;
606     }
607 }
608 
609 /*
610  * Called when the properties on the root window change, e.g. when the screen
611  * resolution changes. If so we update the window to cover the whole screen
612  * and also redraw the image, if any.
613  *
614  */
handle_screen_resize(void)615 static void handle_screen_resize(void) {
616     xcb_get_geometry_cookie_t geomc;
617     xcb_get_geometry_reply_t *geom;
618     geomc = xcb_get_geometry(conn, screen->root);
619     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
620         return;
621 
622     if (last_resolution[0] == geom->width &&
623         last_resolution[1] == geom->height) {
624         free(geom);
625         return;
626     }
627 
628     last_resolution[0] = geom->width;
629     last_resolution[1] = geom->height;
630 
631     free(geom);
632 
633     redraw_screen();
634 
635     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
636     xcb_configure_window(conn, win, mask, last_resolution);
637     xcb_flush(conn);
638 
639     randr_query(screen->root);
640     redraw_screen();
641 }
642 
read_raw_image_native(uint32_t * dest,FILE * src,size_t width,size_t height,int pixstride)643 static ssize_t read_raw_image_native(uint32_t *dest, FILE *src, size_t width, size_t height, int pixstride) {
644     ssize_t count = 0;
645     for (size_t y = 0; y < height; y++) {
646         size_t n = fread(&dest[y * pixstride], 1, width * 4, src);
647         count += n;
648         if (n < (size_t)(width * 4))
649             break;
650     }
651 
652     return count;
653 }
654 
655 struct raw_pixel_format {
656     int bpp;
657     int red;
658     int green;
659     int blue;
660 };
661 
read_raw_image_fmt(uint32_t * dest,FILE * src,size_t width,size_t height,int pixstride,struct raw_pixel_format fmt)662 static ssize_t read_raw_image_fmt(uint32_t *dest, FILE *src, size_t width, size_t height, int pixstride,
663                                   struct raw_pixel_format fmt) {
664     unsigned char *buf = malloc(width * fmt.bpp);
665     if (buf == NULL)
666         return -1;
667 
668     ssize_t count = 0;
669     for (size_t y = 0; y < height; y++) {
670         size_t n = fread(buf, 1, width * fmt.bpp, src);
671         count += n;
672         if (n < (size_t)(width * fmt.bpp))
673             break;
674 
675         for (size_t x = 0; x < width; ++x) {
676             int idx = x * fmt.bpp;
677             dest[y * pixstride + x] = 0 |
678                                       (buf[idx + fmt.red]) << 16 |
679                                       (buf[idx + fmt.green]) << 8 |
680                                       (buf[idx + fmt.blue]);
681         }
682     }
683 
684     free(buf);
685     return count;
686 }
687 
688 // Pre-defind pixel formats (<bytes per pixel>, <red pixel>, <green pixel>, <blue pixel>)
689 static const struct raw_pixel_format raw_fmt_rgb = {3, 0, 1, 2};
690 static const struct raw_pixel_format raw_fmt_rgbx = {4, 0, 1, 2};
691 static const struct raw_pixel_format raw_fmt_xrgb = {4, 1, 2, 3};
692 static const struct raw_pixel_format raw_fmt_bgr = {3, 2, 1, 0};
693 static const struct raw_pixel_format raw_fmt_bgrx = {4, 2, 1, 0};
694 static const struct raw_pixel_format raw_fmt_xbgr = {4, 3, 2, 1};
695 
read_raw_image(const char * image_path,const char * image_raw_format)696 static cairo_surface_t *read_raw_image(const char *image_path, const char *image_raw_format) {
697     cairo_surface_t *img;
698 
699 #define RAW_PIXFMT_MAXLEN 6
700 #define STRINGIFY1(x) #x
701 #define STRINGIFY(x) STRINGIFY1(x)
702     /* Parse format as <width>x<height>:<pixfmt> */
703     char pixfmt[RAW_PIXFMT_MAXLEN + 1];
704     size_t w, h;
705     const char *fmt = "%zux%zu:%" STRINGIFY(RAW_PIXFMT_MAXLEN) "s";
706     if (sscanf(image_raw_format, fmt, &w, &h, pixfmt) != 3) {
707         fprintf(stderr, "Invalid image format: \"%s\"\n", image_raw_format);
708         return NULL;
709     }
710 #undef RAW_PIXFMT_MAXLEN
711 #undef STRINGIFY1
712 #undef STRINGIFY
713 
714     /* Create image surface */
715     img = cairo_image_surface_create(CAIRO_FORMAT_RGB24, w, h);
716     if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
717         fprintf(stderr, "Could not create surface: %s\n",
718                 cairo_status_to_string(cairo_surface_status(img)));
719         return NULL;
720     }
721     cairo_surface_flush(img);
722 
723     /* Use uint32_t* because cairo uses native endianness */
724     uint32_t *data = (uint32_t *)cairo_image_surface_get_data(img);
725     const int pixstride = cairo_image_surface_get_stride(img) / 4;
726 
727     FILE *f = fopen(image_path, "r");
728     if (f == NULL) {
729         fprintf(stderr, "Could not open image \"%s\": %s\n",
730                 image_path, strerror(errno));
731         cairo_surface_destroy(img);
732         return NULL;
733     }
734 
735     /* Read the image, respecting cairo's stride, according to the pixfmt */
736     ssize_t size, count;
737     if (strcmp(pixfmt, "native") == 0) {
738         /* If the pixfmt is 'native', just read each line directly into the buffer */
739         size = w * h * 4;
740         count = read_raw_image_native(data, f, w, h, pixstride);
741     } else {
742         const struct raw_pixel_format *fmt = NULL;
743 
744         if (strcmp(pixfmt, "rgb") == 0)
745             fmt = &raw_fmt_rgb;
746         else if (strcmp(pixfmt, "rgbx") == 0)
747             fmt = &raw_fmt_rgbx;
748         else if (strcmp(pixfmt, "xrgb") == 0)
749             fmt = &raw_fmt_xrgb;
750         else if (strcmp(pixfmt, "bgr") == 0)
751             fmt = &raw_fmt_bgr;
752         else if (strcmp(pixfmt, "bgrx") == 0)
753             fmt = &raw_fmt_bgrx;
754         else if (strcmp(pixfmt, "xbgr") == 0)
755             fmt = &raw_fmt_xbgr;
756 
757         if (fmt == NULL) {
758             fprintf(stderr, "Unknown raw pixel format: %s\n", pixfmt);
759             fclose(f);
760             cairo_surface_destroy(img);
761             return NULL;
762         }
763 
764         size = w * h * fmt->bpp;
765         count = read_raw_image_fmt(data, f, w, h, pixstride, *fmt);
766     }
767 
768     cairo_surface_mark_dirty(img);
769 
770     if (count < size) {
771         if (count < 0 || ferror(f)) {
772             fprintf(stderr, "Failed to read image \"%s\": %s\n",
773                     image_path, strerror(errno));
774             fclose(f);
775             cairo_surface_destroy(img);
776             return NULL;
777         } else {
778             /* Print a warning if the file contains less data than expected,
779              * but don't abort. It's useful to see how the image looks even if it's wrong. */
780             fprintf(stderr, "Warning: expected to read %zi bytes from \"%s\", read %zi\n",
781                     size, image_path, count);
782         }
783     }
784 
785     fclose(f);
786     return img;
787 }
788 
verify_png_image(const char * image_path)789 static bool verify_png_image(const char *image_path) {
790     if (!image_path) {
791         return false;
792     }
793 
794     /* Check file exists and has correct PNG header */
795     FILE *png_file = fopen(image_path, "r");
796     if (png_file == NULL) {
797         fprintf(stderr, "Image file path \"%s\" cannot be opened: %s\n", image_path, strerror(errno));
798         return false;
799     }
800     unsigned char png_header[8];
801     memset(png_header, '\0', sizeof(png_header));
802     int bytes_read = fread(png_header, 1, sizeof(png_header), png_file);
803     fclose(png_file);
804     if (bytes_read != sizeof(png_header)) {
805         fprintf(stderr, "Could not read PNG header from \"%s\"\n", image_path);
806         return false;
807     }
808 
809     // Check PNG header according to the specification, available at:
810     // https://www.w3.org/TR/2003/REC-PNG-20031110/#5PNG-file-signature
811     static unsigned char PNG_REFERENCE_HEADER[8] = {137, 80, 78, 71, 13, 10, 26, 10};
812     if (memcmp(PNG_REFERENCE_HEADER, png_header, sizeof(png_header)) != 0) {
813         fprintf(stderr, "File \"%s\" does not start with a PNG header. i3lock currently only supports loading PNG files.\n", image_path);
814         return false;
815     }
816     return true;
817 }
818 
819 #ifndef __OpenBSD__
820 /*
821  * Callback function for PAM. We only react on password request callbacks.
822  *
823  */
conv_callback(int num_msg,const struct pam_message ** msg,struct pam_response ** resp,void * appdata_ptr)824 static int conv_callback(int num_msg, const struct pam_message **msg,
825                          struct pam_response **resp, void *appdata_ptr) {
826     if (num_msg == 0)
827         return 1;
828 
829     /* PAM expects an array of responses, one for each message */
830     if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
831         perror("calloc");
832         return 1;
833     }
834 
835     for (int c = 0; c < num_msg; c++) {
836         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
837             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
838             continue;
839 
840         /* return code is currently not used but should be set to zero */
841         resp[c]->resp_retcode = 0;
842         if ((resp[c]->resp = strdup(password)) == NULL) {
843             perror("strdup");
844             return 1;
845         }
846     }
847 
848     return 0;
849 }
850 #endif
851 
852 /*
853  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
854  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
855  *
856  */
xcb_got_event(EV_P_ struct ev_io * w,int revents)857 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
858     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
859 }
860 
861 /*
862  * Flush before blocking (and waiting for new events)
863  *
864  */
xcb_prepare_cb(EV_P_ ev_prepare * w,int revents)865 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
866     xcb_flush(conn);
867 }
868 
869 /*
870  * Try closing logind sleep lock fd passed over from xss-lock, in case we're
871  * being run from there.
872  *
873  */
maybe_close_sleep_lock_fd(void)874 static void maybe_close_sleep_lock_fd(void) {
875     const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
876     char *endptr;
877     if (sleep_lock_fd && *sleep_lock_fd != 0) {
878         long int fd = strtol(sleep_lock_fd, &endptr, 10);
879         if (*endptr == 0) {
880             close(fd);
881         }
882     }
883 }
884 
885 /*
886  * Instead of polling the X connection socket we leave this to
887  * xcb_poll_for_event() which knows better than we can ever know.
888  *
889  */
xcb_check_cb(EV_P_ ev_check * w,int revents)890 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
891     xcb_generic_event_t *event;
892 
893     if (xcb_connection_has_error(conn))
894         errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?");
895 
896     while ((event = xcb_poll_for_event(conn)) != NULL) {
897         if (event->response_type == 0) {
898             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
899             if (debug_mode)
900                 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
901                         error->sequence, error->error_code);
902             free(event);
903             continue;
904         }
905 
906         /* Strip off the highest bit (set if the event is generated) */
907         int type = (event->response_type & 0x7F);
908 
909         switch (type) {
910             case XCB_KEY_PRESS:
911                 handle_key_press((xcb_key_press_event_t *)event);
912                 break;
913 
914             case XCB_VISIBILITY_NOTIFY:
915                 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
916                 break;
917 
918             case XCB_MAP_NOTIFY:
919                 maybe_close_sleep_lock_fd();
920                 if (!dont_fork) {
921                     /* After the first MapNotify, we never fork again. We don’t
922                      * expect to get another MapNotify, but better be sure… */
923                     dont_fork = true;
924 
925                     /* In the parent process, we exit */
926                     if (fork() != 0)
927                         exit(0);
928 
929                     ev_loop_fork(EV_DEFAULT);
930                 }
931                 break;
932 
933             case XCB_CONFIGURE_NOTIFY:
934                 handle_screen_resize();
935                 break;
936 
937             default:
938                 if (type == xkb_base_event) {
939                     process_xkb_event(event);
940                 }
941                 if (randr_base > -1 &&
942                     type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
943                     randr_query(screen->root);
944                     handle_screen_resize();
945                 }
946         }
947 
948         free(event);
949     }
950 }
951 
952 /*
953  * This function is called from a fork()ed child and will raise the i3lock
954  * window when the window is obscured, even when the main i3lock process is
955  * blocked due to the authentication backend.
956  *
957  */
raise_loop(xcb_window_t window)958 static void raise_loop(xcb_window_t window) {
959     xcb_connection_t *conn;
960     xcb_generic_event_t *event;
961     int screens;
962 
963     if (xcb_connection_has_error((conn = xcb_connect(NULL, &screens))) > 0)
964         errx(EXIT_FAILURE, "Cannot open display");
965 
966     /* We need to know about the window being obscured or getting destroyed. */
967     xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
968                                  (uint32_t[]){
969                                      XCB_EVENT_MASK_VISIBILITY_CHANGE |
970                                      XCB_EVENT_MASK_STRUCTURE_NOTIFY});
971     xcb_flush(conn);
972 
973     DEBUG("Watching window 0x%08x\n", window);
974     while ((event = xcb_wait_for_event(conn)) != NULL) {
975         if (event->response_type == 0) {
976             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
977             DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
978                   error->sequence, error->error_code);
979             free(event);
980             continue;
981         }
982         /* Strip off the highest bit (set if the event is generated) */
983         int type = (event->response_type & 0x7F);
984         DEBUG("Read event of type %d\n", type);
985         switch (type) {
986             case XCB_VISIBILITY_NOTIFY:
987                 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
988                 break;
989             case XCB_UNMAP_NOTIFY:
990                 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
991                 if (((xcb_unmap_notify_event_t *)event)->window == window)
992                     exit(EXIT_SUCCESS);
993                 break;
994             case XCB_DESTROY_NOTIFY:
995                 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
996                 if (((xcb_destroy_notify_event_t *)event)->window == window)
997                     exit(EXIT_SUCCESS);
998                 break;
999             default:
1000                 DEBUG("Unhandled event type %d\n", type);
1001                 break;
1002         }
1003         free(event);
1004     }
1005 }
1006 
main(int argc,char * argv[])1007 int main(int argc, char *argv[]) {
1008     struct passwd *pw;
1009     char *username;
1010     char *image_path = NULL;
1011     char *image_raw_format = NULL;
1012 #ifndef __OpenBSD__
1013     int ret;
1014     struct pam_conv conv = {conv_callback, NULL};
1015 #endif
1016     int curs_choice = CURS_NONE;
1017     int o;
1018     int longoptind = 0;
1019     struct option longopts[] = {
1020         {"version", no_argument, NULL, 'v'},
1021         {"nofork", no_argument, NULL, 'n'},
1022         {"beep", no_argument, NULL, 'b'},
1023         {"dpms", no_argument, NULL, 'd'},
1024         {"color", required_argument, NULL, 'c'},
1025         {"pointer", required_argument, NULL, 'p'},
1026         {"debug", no_argument, NULL, 0},
1027         {"help", no_argument, NULL, 'h'},
1028         {"no-unlock-indicator", no_argument, NULL, 'u'},
1029         {"image", required_argument, NULL, 'i'},
1030         {"raw", required_argument, NULL, 0},
1031         {"tiling", no_argument, NULL, 't'},
1032         {"ignore-empty-password", no_argument, NULL, 'e'},
1033         {"inactivity-timeout", required_argument, NULL, 'I'},
1034         {"show-failed-attempts", no_argument, NULL, 'f'},
1035         {NULL, no_argument, NULL, 0}};
1036 
1037     if ((pw = getpwuid(getuid())) == NULL)
1038         err(EXIT_FAILURE, "getpwuid() failed");
1039     if ((username = pw->pw_name) == NULL)
1040         errx(EXIT_FAILURE, "pw->pw_name is NULL.");
1041     if (getenv("WAYLAND_DISPLAY") != NULL)
1042         errx(EXIT_FAILURE, "i3lock is a program for X11 and does not work on Wayland. Try https://github.com/swaywm/swaylock instead");
1043 
1044     char *optstring = "hvnbdc:p:ui:teI:f";
1045     while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
1046         switch (o) {
1047             case 'v':
1048                 errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
1049             case 'n':
1050                 dont_fork = true;
1051                 break;
1052             case 'b':
1053                 beep = true;
1054                 break;
1055             case 'd':
1056                 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
1057                 break;
1058             case 'I': {
1059                 fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
1060                 break;
1061             }
1062             case 'c': {
1063                 char *arg = optarg;
1064 
1065                 /* Skip # if present */
1066                 if (arg[0] == '#')
1067                     arg++;
1068 
1069                 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
1070                     errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb");
1071 
1072                 break;
1073             }
1074             case 'u':
1075                 unlock_indicator = false;
1076                 break;
1077             case 'i':
1078                 image_path = strdup(optarg);
1079                 break;
1080             case 't':
1081                 tile = true;
1082                 break;
1083             case 'p':
1084                 if (!strcmp(optarg, "win")) {
1085                     curs_choice = CURS_WIN;
1086                 } else if (!strcmp(optarg, "default")) {
1087                     curs_choice = CURS_DEFAULT;
1088                 } else {
1089                     errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".");
1090                 }
1091                 break;
1092             case 'e':
1093                 ignore_empty_password = true;
1094                 break;
1095             case 0:
1096                 if (strcmp(longopts[longoptind].name, "debug") == 0)
1097                     debug_mode = true;
1098                 else if (strcmp(longopts[longoptind].name, "raw") == 0)
1099                     image_raw_format = strdup(optarg);
1100                 break;
1101             case 'f':
1102                 show_failed_attempts = true;
1103                 break;
1104             default:
1105                 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
1106                                    " [-i image.png] [-t] [-e] [-I timeout] [-f]");
1107         }
1108     }
1109 
1110     /* We need (relatively) random numbers for highlighting a random part of
1111      * the unlock indicator upon keypresses. */
1112     srand(time(NULL));
1113 
1114 #ifndef __OpenBSD__
1115     /* Initialize PAM */
1116     if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
1117         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
1118 
1119     if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
1120         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
1121 #endif
1122 
1123 /* Using mlock() as non-super-user seems only possible in Linux.
1124  * Users of other operating systems should use encrypted swap/no swap
1125  * (or remove the ifdef and run i3lock as super-user).
1126  * Alas, swap is encrypted by default on OpenBSD so swapping out
1127  * is not necessarily an issue. */
1128 #if defined(__linux__)
1129     /* Lock the area where we store the password in memory, we don’t want it to
1130      * be swapped to disk. Since Linux 2.6.9, this does not require any
1131      * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
1132     if (mlock(password, sizeof(password)) != 0)
1133         err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
1134 #endif
1135 
1136     /* Double checking that connection is good and operatable with xcb */
1137     int screennr;
1138     if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
1139         xcb_connection_has_error(conn))
1140         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
1141 
1142     if (xkb_x11_setup_xkb_extension(conn,
1143                                     XKB_X11_MIN_MAJOR_XKB_VERSION,
1144                                     XKB_X11_MIN_MINOR_XKB_VERSION,
1145                                     0,
1146                                     NULL,
1147                                     NULL,
1148                                     &xkb_base_event,
1149                                     &xkb_base_error) != 1)
1150         errx(EXIT_FAILURE, "Could not setup XKB extension.");
1151 
1152     static const xcb_xkb_map_part_t required_map_parts =
1153         (XCB_XKB_MAP_PART_KEY_TYPES |
1154          XCB_XKB_MAP_PART_KEY_SYMS |
1155          XCB_XKB_MAP_PART_MODIFIER_MAP |
1156          XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
1157          XCB_XKB_MAP_PART_KEY_ACTIONS |
1158          XCB_XKB_MAP_PART_VIRTUAL_MODS |
1159          XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
1160 
1161     static const xcb_xkb_event_type_t required_events =
1162         (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
1163          XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
1164          XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
1165 
1166     xcb_xkb_select_events(
1167         conn,
1168         xkb_x11_get_core_keyboard_device_id(conn),
1169         required_events,
1170         0,
1171         required_events,
1172         required_map_parts,
1173         required_map_parts,
1174         0);
1175 
1176     /* When we cannot initially load the keymap, we better exit */
1177     if (!load_keymap())
1178         errx(EXIT_FAILURE, "Could not load keymap");
1179 
1180     const char *locale = getenv("LC_ALL");
1181     if (!locale || !*locale)
1182         locale = getenv("LC_CTYPE");
1183     if (!locale || !*locale)
1184         locale = getenv("LANG");
1185     if (!locale || !*locale) {
1186         if (debug_mode)
1187             fprintf(stderr, "Can't detect your locale, fallback to C\n");
1188         locale = "C";
1189     }
1190 
1191     load_compose_table(locale);
1192 
1193     screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
1194 
1195     init_dpi();
1196 
1197     randr_init(&randr_base, screen->root);
1198     randr_query(screen->root);
1199 
1200     last_resolution[0] = screen->width_in_pixels;
1201     last_resolution[1] = screen->height_in_pixels;
1202 
1203     xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
1204                                  (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
1205 
1206     if (image_raw_format != NULL && image_path != NULL) {
1207         /* Read image. 'read_raw_image' returns NULL on error,
1208          * so we don't have to handle errors here. */
1209         img = read_raw_image(image_path, image_raw_format);
1210     } else if (verify_png_image(image_path)) {
1211         /* Create a pixmap to render on, fill it with the background color */
1212         img = cairo_image_surface_create_from_png(image_path);
1213         /* In case loading failed, we just pretend no -i was specified. */
1214         if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
1215             fprintf(stderr, "Could not load image \"%s\": %s\n",
1216                     image_path, cairo_status_to_string(cairo_surface_status(img)));
1217             img = NULL;
1218         }
1219     }
1220 
1221     free(image_path);
1222     free(image_raw_format);
1223 
1224     /* Pixmap on which the image is rendered to (if any) */
1225     xcb_pixmap_t bg_pixmap = create_bg_pixmap(conn, screen, last_resolution, color);
1226     draw_image(bg_pixmap, last_resolution);
1227 
1228     xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
1229 
1230     /* Open the fullscreen window, already with the correct pixmap in place */
1231     win = open_fullscreen_window(conn, screen, color, bg_pixmap);
1232     xcb_free_pixmap(conn, bg_pixmap);
1233 
1234     cursor = create_cursor(conn, screen, win, curs_choice);
1235 
1236     /* Display the "locking…" message while trying to grab the pointer/keyboard. */
1237     auth_state = STATE_AUTH_LOCK;
1238     if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
1239         DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
1240 
1241         /* Set the focus to i3lock, possibly closing context menus which would
1242          * otherwise prevent us from grabbing keyboard/pointer.
1243          *
1244          * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
1245          * works for managed windows, but i3lock uses an unmanaged window
1246          * (override_redirect=1). */
1247         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
1248         if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
1249             auth_state = STATE_I3LOCK_LOCK_FAILED;
1250             redraw_screen();
1251             sleep(1);
1252             errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
1253         }
1254     }
1255 
1256     pid_t pid = fork();
1257     /* The pid == -1 case is intentionally ignored here:
1258      * While the child process is useful for preventing other windows from
1259      * popping up while i3lock blocks, it is not critical. */
1260     if (pid == 0) {
1261         /* Child */
1262         close(xcb_get_file_descriptor(conn));
1263         maybe_close_sleep_lock_fd();
1264         raise_loop(win);
1265         exit(EXIT_SUCCESS);
1266     }
1267 
1268     /* Load the keymap again to sync the current modifier state. Since we first
1269      * loaded the keymap, there might have been changes, but starting from now,
1270      * we should get all key presses/releases due to having grabbed the
1271      * keyboard. */
1272     (void)load_keymap();
1273 
1274     /* Initialize the libev event loop. */
1275     main_loop = EV_DEFAULT;
1276     if (main_loop == NULL)
1277         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?");
1278 
1279     /* Explicitly call the screen redraw in case "locking…" message was displayed */
1280     auth_state = STATE_AUTH_IDLE;
1281     redraw_screen();
1282 
1283     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1284     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1285     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1286 
1287     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1288     ev_io_start(main_loop, xcb_watcher);
1289 
1290     ev_check_init(xcb_check, xcb_check_cb);
1291     ev_check_start(main_loop, xcb_check);
1292 
1293     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1294     ev_prepare_start(main_loop, xcb_prepare);
1295 
1296     /* Invoke the event callback once to catch all the events which were
1297      * received up until now. ev will only pick up new events (when the X11
1298      * file descriptor becomes readable). */
1299     ev_invoke(main_loop, xcb_check, 0);
1300     ev_loop(main_loop, 0);
1301 
1302 #ifndef __OpenBSD__
1303     if (pam_cleanup) {
1304         pam_end(pam_handle, PAM_SUCCESS);
1305     }
1306 #endif
1307 
1308     if (stolen_focus == XCB_NONE) {
1309         return 0;
1310     }
1311 
1312     DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
1313     xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
1314     xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
1315     xcb_destroy_window(conn, win);
1316     set_focused_window(conn, screen->root, stolen_focus);
1317     xcb_aux_sync(conn);
1318 
1319     return 0;
1320 }
1321