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