]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
Revert "Bug fix: Call clear_input() when the password is wrong."
[i3/i3lock] / i3lock.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2010-2013 Michael Stapelberg
5  *
6  * See LICENSE for licensing information
7  *
8  */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <stdbool.h>
14 #include <stdint.h>
15 #include <xcb/xcb.h>
16 #include <xcb/dpms.h>
17 #include <err.h>
18 #include <assert.h>
19 #include <security/pam_appl.h>
20 #include <X11/Xlib-xcb.h>
21 #include <getopt.h>
22 #include <string.h>
23 #include <ev.h>
24 #include <sys/mman.h>
25 #include <sys/wait.h>
26 #include <X11/XKBlib.h>
27 #include <X11/extensions/XKBfile.h>
28 #include <xkbcommon/xkbcommon.h>
29 #include <cairo.h>
30 #include <cairo/cairo-xcb.h>
31
32 #include "i3lock.h"
33 #include "xcb.h"
34 #include "cursors.h"
35 #include "unlock_indicator.h"
36 #include "xinerama.h"
37
38 /* We need this for libxkbfile */
39 static Display *display;
40 char color[7] = "ffffff";
41 uint32_t last_resolution[2];
42 xcb_window_t win;
43 static xcb_cursor_t cursor;
44 static pam_handle_t *pam_handle;
45 int input_position = 0;
46 /* Holds the password you enter (in UTF-8). */
47 static char password[512];
48 static bool beep = false;
49 bool debug_mode = false;
50 static bool dpms = false;
51 bool unlock_indicator = true;
52 static bool dont_fork = false;
53 struct ev_loop *main_loop;
54 static struct ev_timer *clear_pam_wrong_timeout;
55 extern unlock_state_t unlock_state;
56 extern pam_state_t pam_state;
57
58 static struct xkb_state *xkb_state;
59 static struct xkb_context *xkb_context;
60 static struct xkb_keymap *xkb_keymap;
61
62 cairo_surface_t *img = NULL;
63 bool tile = false;
64 bool ignore_empty_password = false;
65
66 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
67 #define isutf(c) (((c) & 0xC0) != 0x80)
68
69 /*
70  * Decrements i to point to the previous unicode glyph
71  *
72  */
73 void u8_dec(char *s, int *i) {
74     (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
75 }
76
77 /*
78  * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
79  * Necessary so that we can properly let xkbcommon track the keyboard state and
80  * translate keypresses to utf-8.
81  *
82  * Ideally, xkbcommon would ship something like this itself, but as of now
83  * (version 0.2.0), it doesn’t.
84  *
85  * TODO: Once xcb-xkb is enabled by default and released, we should port this
86  * code to xcb-xkb. See also https://github.com/xkbcommon/libxkbcommon/issues/1
87  *
88  */
89 static bool load_keymap(void) {
90     bool ret = false;
91     XkbFileInfo result;
92     memset(&result, '\0', sizeof(result));
93     result.xkb = XkbGetKeyboard(display, XkbAllMapComponentsMask, XkbUseCoreKbd);
94     if (result.xkb == NULL) {
95         fprintf(stderr, "[i3lock] XKB: XkbGetKeyboard failed\n");
96         return false;
97     }
98
99     FILE *temp = tmpfile();
100     if (temp == NULL) {
101         fprintf(stderr, "[i3lock] could not create tempfile\n");
102         return false;
103     }
104
105     bool ok = XkbWriteXKBKeymap(temp, &result, false, false, NULL, NULL);
106     if (!ok) {
107         fprintf(stderr, "[i3lock] XkbWriteXKBKeymap failed\n");
108         goto out;
109     }
110
111     rewind(temp);
112
113     if (xkb_context == NULL) {
114         if ((xkb_context = xkb_context_new(0)) == NULL) {
115             fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
116             goto out;
117         }
118     }
119
120     if (xkb_keymap != NULL)
121         xkb_keymap_unref(xkb_keymap);
122
123     if ((xkb_keymap = xkb_keymap_new_from_file(xkb_context, temp, XKB_KEYMAP_FORMAT_TEXT_V1, 0)) == NULL) {
124         fprintf(stderr, "[i3lock] xkb_keymap_new_from_file failed\n");
125         goto out;
126     }
127
128     struct xkb_state *new_state = xkb_state_new(xkb_keymap);
129     if (new_state == NULL) {
130         fprintf(stderr, "[i3lock] xkb_state_new failed\n");
131         goto out;
132     }
133
134     /* Get the initial modifier state to be in sync with the X server.
135      * See https://github.com/xkbcommon/libxkbcommon/issues/1 for why we ignore
136      * the base and latched fields. */
137     XkbStateRec state_rec;
138     XkbGetState(display, XkbUseCoreKbd, &state_rec);
139
140     xkb_state_update_mask(new_state,
141         0, 0, state_rec.locked_mods,
142         0, 0, state_rec.locked_group);
143
144     if (xkb_state != NULL)
145         xkb_state_unref(xkb_state);
146     xkb_state = new_state;
147
148     ret = true;
149 out:
150     XkbFreeKeyboard(result.xkb, XkbAllComponentsMask, true);
151     fclose(temp);
152     return ret;
153 }
154
155 /*
156  * Clears the memory which stored the password to be a bit safer against
157  * cold-boot attacks.
158  *
159  */
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;
170 }
171
172
173 /*
174  * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
175  * authentication event.
176  *
177  */
178 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
179     DEBUG("clearing pam wrong\n");
180     pam_state = STATE_PAM_IDLE;
181     unlock_state = STATE_STARTED;
182     redraw_screen();
183
184     /* Now free this timeout. */
185     ev_timer_stop(main_loop, clear_pam_wrong_timeout);
186     free(clear_pam_wrong_timeout);
187     clear_pam_wrong_timeout = NULL;
188 }
189
190 static void clear_input(void) {
191     input_position = 0;
192     clear_password_memory();
193     password[input_position] = '\0';
194
195     /* Hide the unlock indicator after a bit if the password buffer is
196      * empty. */
197     start_clear_indicator_timeout();
198     unlock_state = STATE_BACKSPACE_ACTIVE;
199     redraw_screen();
200     unlock_state = STATE_KEY_PRESSED;
201 }
202
203 static void auth_failed(void) {
204     if (debug_mode)
205         fprintf(stderr, "Authentication failure\n");
206
207     pam_state = STATE_PAM_WRONG;
208     redraw_screen();
209
210     /* Clear this state after 2 seconds (unless the user enters another
211      * password during that time). */
212     ev_now_update(main_loop);
213     if ((clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1))) {
214         ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
215         ev_timer_start(main_loop, clear_pam_wrong_timeout);
216     }
217
218     /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
219      * too early. */
220     stop_clear_indicator_timeout();
221
222     /* beep on authentication failure, if enabled */
223     if (beep) {
224         xcb_bell(conn, 100);
225         xcb_flush(conn);
226     }
227 }
228
229 static void child_cb(EV_P_ ev_child *child_watcher, int revents) {
230     if (child_watcher->rstatus != 0) {
231         DEBUG("Authentication successfull\n");
232         clear_password_memory();
233
234         exit(0);
235     } else {
236         auth_failed();
237     }
238     ev_child_stop(main_loop, child_watcher);
239     free(child_watcher);
240 }
241
242 static void input_done(void) {
243     if (pam_state == STATE_PAM_VERIFY) {
244         return;
245     }
246
247     if (clear_pam_wrong_timeout) {
248         ev_timer_stop(main_loop, clear_pam_wrong_timeout);
249         free(clear_pam_wrong_timeout);
250         clear_pam_wrong_timeout = NULL;
251     }
252
253     pam_state = STATE_PAM_VERIFY;
254     redraw_screen();
255
256     /* fork to unblock pam_authenticate */
257     pid_t cpid = fork();
258     if (cpid == 0) {
259         exit(pam_authenticate(pam_handle, 0) == PAM_SUCCESS);
260     } else if (cpid > 0) {
261         clear_input();
262         struct ev_child *child_watcher = calloc(sizeof(struct ev_io), 1);
263         ev_child_init(child_watcher, child_cb, cpid, 0);
264         ev_child_set(child_watcher, cpid, 0);
265         ev_child_start(EV_DEFAULT_ child_watcher);
266     } else if (cpid < 0) {
267         DEBUG("Could not fork");
268         if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
269             DEBUG("successfully authenticated\n");
270             clear_password_memory();
271             exit(0);
272         }
273         auth_failed();
274     }
275 }
276
277 /*
278  * Called when the user releases a key. We need to leave the Mode_switch
279  * state when the user releases the Mode_switch key.
280  *
281  */
282 static void handle_key_release(xcb_key_release_event_t *event) {
283     xkb_state_update_key(xkb_state, event->detail, XKB_KEY_UP);
284 }
285
286 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
287     redraw_screen();
288
289     ev_timer_stop(main_loop, w);
290     free(w);
291 }
292
293 /*
294  * Handle key presses. Fixes state, then looks up the key symbol for the
295  * given keycode, then looks up the key symbol (as UCS-2), converts it to
296  * UTF-8 and stores it in the password array.
297  *
298  */
299 static void handle_key_press(xcb_key_press_event_t *event) {
300     xkb_keysym_t ksym;
301     char buffer[128];
302     int n;
303     bool ctrl;
304
305     ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
306     ctrl = xkb_state_mod_name_is_active(xkb_state, "Control", XKB_STATE_MODS_DEPRESSED);
307     xkb_state_update_key(xkb_state, event->detail, XKB_KEY_DOWN);
308
309     /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
310     memset(buffer, '\0', sizeof(buffer));
311     n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
312
313     switch (ksym) {
314     case XKB_KEY_Return:
315     case XKB_KEY_KP_Enter:
316     case XKB_KEY_XF86ScreenSaver:
317         if (ignore_empty_password && input_position == 0) {
318             clear_input();
319             return;
320         }
321         password[input_position] = '\0';
322         unlock_state = STATE_KEY_PRESSED;
323         redraw_screen();
324         input_done();
325         return;
326
327     case XKB_KEY_u:
328         if (ctrl) {
329             DEBUG("C-u pressed\n");
330             clear_input();
331             return;
332         }
333         break;
334
335     case XKB_KEY_Escape:
336         clear_input();
337         return;
338
339     case XKB_KEY_BackSpace:
340         if (input_position == 0)
341             return;
342
343         /* decrement input_position to point to the previous glyph */
344         u8_dec(password, &input_position);
345         password[input_position] = '\0';
346
347         /* Hide the unlock indicator after a bit if the password buffer is
348          * empty. */
349         start_clear_indicator_timeout();
350         unlock_state = STATE_BACKSPACE_ACTIVE;
351         redraw_screen();
352         unlock_state = STATE_KEY_PRESSED;
353         return;
354     }
355
356     if ((input_position + 8) >= sizeof(password))
357         return;
358
359 #if 0
360     /* FIXME: handle all of these? */
361     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
362     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
363     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
364     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
365     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
366     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
367     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
368 #endif
369
370     if (n < 2)
371         return;
372
373     /* store it in the password array as UTF-8 */
374     memcpy(password+input_position, buffer, n-1);
375     input_position += n-1;
376     DEBUG("current password = %.*s\n", input_position, password);
377
378     unlock_state = STATE_KEY_ACTIVE;
379     redraw_screen();
380     unlock_state = STATE_KEY_PRESSED;
381
382     struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
383     if (timeout) {
384         ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
385         ev_timer_start(main_loop, timeout);
386     }
387
388     stop_clear_indicator_timeout();
389 }
390
391 /*
392  * A visibility notify event will be received when the visibility (= can the
393  * user view the complete window) changes, so for example when a popup overlays
394  * some area of the i3lock window.
395  *
396  * In this case, we raise our window on top so that the popup (or whatever is
397  * hiding us) gets hidden.
398  *
399  */
400 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
401     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
402         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
403         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
404         xcb_flush(conn);
405     }
406 }
407
408 /*
409  * Called when the keyboard mapping changes. We update our symbols.
410  *
411  */
412 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
413     /* We ignore errors — if the new keymap cannot be loaded it’s better if the
414      * screen stays locked and the user intervenes by using killall i3lock. */
415     (void)load_keymap();
416 }
417
418 /*
419  * Called when the properties on the root window change, e.g. when the screen
420  * resolution changes. If so we update the window to cover the whole screen
421  * and also redraw the image, if any.
422  *
423  */
424 void handle_screen_resize(void) {
425     xcb_get_geometry_cookie_t geomc;
426     xcb_get_geometry_reply_t *geom;
427     geomc = xcb_get_geometry(conn, screen->root);
428     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
429         return;
430
431     if (last_resolution[0] == geom->width &&
432         last_resolution[1] == geom->height) {
433         free(geom);
434         return;
435     }
436
437     last_resolution[0] = geom->width;
438     last_resolution[1] = geom->height;
439
440     free(geom);
441
442     redraw_screen();
443
444     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
445     xcb_configure_window(conn, win, mask, last_resolution);
446     xcb_flush(conn);
447
448     xinerama_query_screens();
449     redraw_screen();
450 }
451
452 /*
453  * Callback function for PAM. We only react on password request callbacks.
454  *
455  */
456 static int conv_callback(int num_msg, const struct pam_message **msg,
457                          struct pam_response **resp, void *appdata_ptr)
458 {
459     if (num_msg == 0)
460         return 1;
461
462     /* PAM expects an array of responses, one for each message */
463     if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
464         perror("calloc");
465         return 1;
466     }
467
468     for (int c = 0; c < num_msg; c++) {
469         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
470             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
471             continue;
472
473         /* return code is currently not used but should be set to zero */
474         resp[c]->resp_retcode = 0;
475         if ((resp[c]->resp = strdup(password)) == NULL) {
476             perror("strdup");
477             return 1;
478         }
479     }
480
481     return 0;
482 }
483
484 /*
485  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
486  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
487  *
488  */
489 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
490     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
491 }
492
493 /*
494  * Flush before blocking (and waiting for new events)
495  *
496  */
497 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
498     xcb_flush(conn);
499 }
500
501 /*
502  * Instead of polling the X connection socket we leave this to
503  * xcb_poll_for_event() which knows better than we can ever know.
504  *
505  */
506 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
507     xcb_generic_event_t *event;
508
509     while ((event = xcb_poll_for_event(conn)) != NULL) {
510         if (event->response_type == 0) {
511             xcb_generic_error_t *error = (xcb_generic_error_t*)event;
512             if (debug_mode)
513                 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
514                         error->sequence, error->error_code);
515             free(event);
516             continue;
517         }
518
519         /* Strip off the highest bit (set if the event is generated) */
520         int type = (event->response_type & 0x7F);
521         switch (type) {
522             case XCB_KEY_PRESS:
523                 handle_key_press((xcb_key_press_event_t*)event);
524                 break;
525
526             case XCB_KEY_RELEASE:
527                 handle_key_release((xcb_key_release_event_t*)event);
528
529                 /* If this was the backspace or escape key we are back at an
530                  * empty input, so turn off the screen if DPMS is enabled */
531                 if (dpms && input_position == 0)
532                     dpms_turn_off_screen(conn);
533
534                 break;
535
536             case XCB_VISIBILITY_NOTIFY:
537                 handle_visibility_notify((xcb_visibility_notify_event_t*)event);
538                 break;
539
540             case XCB_MAP_NOTIFY:
541                 if (!dont_fork) {
542                     /* After the first MapNotify, we never fork again. We don’t
543                      * expect to get another MapNotify, but better be sure… */
544                     dont_fork = true;
545
546                     /* In the parent process, we exit */
547                     if (fork() != 0)
548                         exit(0);
549
550                     ev_loop_fork(EV_DEFAULT);
551                 }
552                 break;
553
554             case XCB_MAPPING_NOTIFY:
555                 handle_mapping_notify((xcb_mapping_notify_event_t*)event);
556                 break;
557
558             case XCB_CONFIGURE_NOTIFY:
559                 handle_screen_resize();
560                 break;
561         }
562
563         free(event);
564     }
565 }
566
567 int main(int argc, char *argv[]) {
568     char *username;
569     char *image_path = NULL;
570     int ret;
571     struct pam_conv conv = {conv_callback, NULL};
572     int curs_choice = CURS_NONE;
573     int o;
574     int optind = 0;
575     struct option longopts[] = {
576         {"version", no_argument, NULL, 'v'},
577         {"nofork", no_argument, NULL, 'n'},
578         {"beep", no_argument, NULL, 'b'},
579         {"dpms", no_argument, NULL, 'd'},
580         {"color", required_argument, NULL, 'c'},
581         {"pointer", required_argument, NULL , 'p'},
582         {"debug", no_argument, NULL, 0},
583         {"help", no_argument, NULL, 'h'},
584         {"no-unlock-indicator", no_argument, NULL, 'u'},
585         {"image", required_argument, NULL, 'i'},
586         {"tiling", no_argument, NULL, 't'},
587         {"ignore-empty-password", no_argument, NULL, 'e'},
588         {NULL, no_argument, NULL, 0}
589     };
590
591     if ((username = getenv("USER")) == NULL)
592         errx(1, "USER environment variable not set, please set it.\n");
593
594     while ((o = getopt_long(argc, argv, "hvnbdc:p:ui:te", longopts, &optind)) != -1) {
595         switch (o) {
596         case 'v':
597             errx(EXIT_SUCCESS, "version " VERSION " © 2010-2012 Michael Stapelberg");
598         case 'n':
599             dont_fork = true;
600             break;
601         case 'b':
602             beep = true;
603             break;
604         case 'd':
605             dpms = true;
606             break;
607         case 'c': {
608             char *arg = optarg;
609
610             /* Skip # if present */
611             if (arg[0] == '#')
612                 arg++;
613
614             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
615                 errx(1, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
616
617             break;
618         }
619         case 'u':
620             unlock_indicator = false;
621             break;
622         case 'i':
623             image_path = strdup(optarg);
624             break;
625         case 't':
626             tile = true;
627             break;
628         case 'p':
629             if (!strcmp(optarg, "win")) {
630                 curs_choice = CURS_WIN;
631             } else if (!strcmp(optarg, "default")) {
632                 curs_choice = CURS_DEFAULT;
633             } else {
634                 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
635             }
636             break;
637         case 'e':
638             ignore_empty_password = true;
639             break;
640         case 0:
641             if (strcmp(longopts[optind].name, "debug") == 0)
642                 debug_mode = true;
643             break;
644         default:
645             errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
646             " [-i image.png] [-t] [-e]"
647             );
648         }
649     }
650
651     /* We need (relatively) random numbers for highlighting a random part of
652      * the unlock indicator upon keypresses. */
653     srand(time(NULL));
654
655     /* Initialize PAM */
656     ret = pam_start("i3lock", username, &conv, &pam_handle);
657     if (ret != PAM_SUCCESS)
658         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
659
660 /* Using mlock() as non-super-user seems only possible in Linux. Users of other
661  * operating systems should use encrypted swap/no swap (or remove the ifdef and
662  * run i3lock as super-user). */
663 #if defined(__linux__)
664     /* Lock the area where we store the password in memory, we don’t want it to
665      * be swapped to disk. Since Linux 2.6.9, this does not require any
666      * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
667     if (mlock(password, sizeof(password)) != 0)
668         err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
669 #endif
670
671     /* Initialize connection to X11 */
672     if ((display = XOpenDisplay(NULL)) == NULL)
673         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
674     XSetEventQueueOwner(display, XCBOwnsEventQueue);
675     conn = XGetXCBConnection(display);
676
677     /* Double checking that connection is good and operatable with xcb */
678     if (xcb_connection_has_error(conn))
679         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
680
681     /* When we cannot initially load the keymap, we better exit */
682     if (!load_keymap())
683         errx(EXIT_FAILURE, "Could not load keymap");
684
685     xinerama_init();
686     xinerama_query_screens();
687
688     /* if DPMS is enabled, check if the X server really supports it */
689     if (dpms) {
690         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
691         xcb_dpms_capable_reply_t *dpmsr;
692         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL))) {
693             if (!dpmsr->capable) {
694                 if (debug_mode)
695                     fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
696                 dpms = false;
697             }
698             free(dpmsr);
699         }
700     }
701
702     screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
703
704     last_resolution[0] = screen->width_in_pixels;
705     last_resolution[1] = screen->height_in_pixels;
706
707     xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
708             (uint32_t[]){ XCB_EVENT_MASK_STRUCTURE_NOTIFY });
709
710     if (image_path) {
711         /* Create a pixmap to render on, fill it with the background color */
712         img = cairo_image_surface_create_from_png(image_path);
713         /* In case loading failed, we just pretend no -i was specified. */
714         if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
715             fprintf(stderr, "Could not load image \"%s\": %s\n",
716                     image_path, cairo_status_to_string(cairo_surface_status(img)));
717             img = NULL;
718         }
719     }
720
721     /* Pixmap on which the image is rendered to (if any) */
722     xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
723
724     /* open the fullscreen window, already with the correct pixmap in place */
725     win = open_fullscreen_window(conn, screen, color, bg_pixmap);
726     xcb_free_pixmap(conn, bg_pixmap);
727
728     cursor = create_cursor(conn, screen, win, curs_choice);
729
730     grab_pointer_and_keyboard(conn, screen, cursor);
731     /* Load the keymap again to sync the current modifier state. Since we first
732      * loaded the keymap, there might have been changes, but starting from now,
733      * we should get all key presses/releases due to having grabbed the
734      * keyboard. */
735     (void)load_keymap();
736
737     if (dpms)
738         dpms_turn_off_screen(conn);
739
740     /* Initialize the libev event loop. */
741     main_loop = EV_DEFAULT;
742     if (main_loop == NULL)
743         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
744
745     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
746     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
747     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
748
749     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
750     ev_io_start(main_loop, xcb_watcher);
751
752     ev_check_init(xcb_check, xcb_check_cb);
753     ev_check_start(main_loop, xcb_check);
754
755     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
756     ev_prepare_start(main_loop, xcb_prepare);
757
758     /* Invoke the event callback once to catch all the events which were
759      * received up until now. ev will only pick up new events (when the X11
760      * file descriptor becomes readable). */
761     ev_invoke(main_loop, xcb_check, 0);
762     ev_loop(main_loop, 0);
763 }