]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
Measure wall-clock time instead of CPU time for “locking” indicator. (#153)
[i3/i3lock] / i3lock.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2010 Michael Stapelberg
5  *
6  * See LICENSE for licensing information
7  *
8  */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <pwd.h>
12 #include <sys/types.h>
13 #include <string.h>
14 #include <unistd.h>
15 #include <stdbool.h>
16 #include <stdint.h>
17 #include <xcb/xcb.h>
18 #include <xcb/xkb.h>
19 #include <err.h>
20 #include <assert.h>
21 #ifdef __OpenBSD__
22 #include <bsd_auth.h>
23 #else
24 #include <security/pam_appl.h>
25 #endif
26 #include <getopt.h>
27 #include <string.h>
28 #include <ev.h>
29 #include <sys/mman.h>
30 #include <xkbcommon/xkbcommon.h>
31 #include <xkbcommon/xkbcommon-compose.h>
32 #include <xkbcommon/xkbcommon-x11.h>
33 #include <cairo.h>
34 #include <cairo/cairo-xcb.h>
35 #ifdef __OpenBSD__
36 #include <strings.h> /* explicit_bzero(3) */
37 #endif
38
39 #include "i3lock.h"
40 #include "xcb.h"
41 #include "cursors.h"
42 #include "unlock_indicator.h"
43 #include "xinerama.h"
44
45 #define TSTAMP_N_SECS(n) (n * 1.0)
46 #define TSTAMP_N_MINS(n) (60 * TSTAMP_N_SECS(n))
47 #define START_TIMER(timer_obj, timeout, callback) \
48     timer_obj = start_timer(timer_obj, timeout, callback)
49 #define STOP_TIMER(timer_obj) \
50     timer_obj = stop_timer(timer_obj)
51
52 typedef void (*ev_callback_t)(EV_P_ ev_timer *w, int revents);
53 static void input_done(void);
54
55 char color[7] = "ffffff";
56 uint32_t last_resolution[2];
57 xcb_window_t win;
58 static xcb_cursor_t cursor;
59 #ifndef __OpenBSD__
60 static pam_handle_t *pam_handle;
61 #endif
62 int input_position = 0;
63 /* Holds the password you enter (in UTF-8). */
64 static char password[512];
65 static bool beep = false;
66 bool debug_mode = false;
67 bool unlock_indicator = true;
68 char *modifier_string = NULL;
69 static bool dont_fork = false;
70 struct ev_loop *main_loop;
71 static struct ev_timer *clear_auth_wrong_timeout;
72 static struct ev_timer *clear_indicator_timeout;
73 static struct ev_timer *discard_passwd_timeout;
74 extern unlock_state_t unlock_state;
75 extern auth_state_t auth_state;
76 int failed_attempts = 0;
77 bool show_failed_attempts = false;
78 bool retry_verification = false;
79
80 static struct xkb_state *xkb_state;
81 static struct xkb_context *xkb_context;
82 static struct xkb_keymap *xkb_keymap;
83 static struct xkb_compose_table *xkb_compose_table;
84 static struct xkb_compose_state *xkb_compose_state;
85 static uint8_t xkb_base_event;
86 static uint8_t xkb_base_error;
87
88 cairo_surface_t *img = NULL;
89 bool tile = false;
90 bool ignore_empty_password = false;
91 bool skip_repeated_empty_password = false;
92
93 /* isutf, u8_dec © 2005 Jeff Bezanson, public domain */
94 #define isutf(c) (((c)&0xC0) != 0x80)
95
96 /*
97  * Decrements i to point to the previous unicode glyph
98  *
99  */
100 void u8_dec(char *s, int *i) {
101     (void)(isutf(s[--(*i)]) || isutf(s[--(*i)]) || isutf(s[--(*i)]) || --(*i));
102 }
103
104 /*
105  * Loads the XKB keymap from the X11 server and feeds it to xkbcommon.
106  * Necessary so that we can properly let xkbcommon track the keyboard state and
107  * translate keypresses to utf-8.
108  *
109  */
110 static bool load_keymap(void) {
111     if (xkb_context == NULL) {
112         if ((xkb_context = xkb_context_new(0)) == NULL) {
113             fprintf(stderr, "[i3lock] could not create xkbcommon context\n");
114             return false;
115         }
116     }
117
118     xkb_keymap_unref(xkb_keymap);
119
120     int32_t device_id = xkb_x11_get_core_keyboard_device_id(conn);
121     DEBUG("device = %d\n", device_id);
122     if ((xkb_keymap = xkb_x11_keymap_new_from_device(xkb_context, conn, device_id, 0)) == NULL) {
123         fprintf(stderr, "[i3lock] xkb_x11_keymap_new_from_device failed\n");
124         return false;
125     }
126
127     struct xkb_state *new_state =
128         xkb_x11_state_new_from_device(xkb_keymap, conn, device_id);
129     if (new_state == NULL) {
130         fprintf(stderr, "[i3lock] xkb_x11_state_new_from_device failed\n");
131         return false;
132     }
133
134     xkb_state_unref(xkb_state);
135     xkb_state = new_state;
136
137     return true;
138 }
139
140 /*
141  * Loads the XKB compose table from the given locale.
142  *
143  */
144 static bool load_compose_table(const char *locale) {
145     xkb_compose_table_unref(xkb_compose_table);
146
147     if ((xkb_compose_table = xkb_compose_table_new_from_locale(xkb_context, locale, 0)) == NULL) {
148         fprintf(stderr, "[i3lock] xkb_compose_table_new_from_locale failed\n");
149         return false;
150     }
151
152     struct xkb_compose_state *new_compose_state = xkb_compose_state_new(xkb_compose_table, 0);
153     if (new_compose_state == NULL) {
154         fprintf(stderr, "[i3lock] xkb_compose_state_new failed\n");
155         return false;
156     }
157
158     xkb_compose_state_unref(xkb_compose_state);
159     xkb_compose_state = new_compose_state;
160
161     return true;
162 }
163
164 /*
165  * Clears the memory which stored the password to be a bit safer against
166  * cold-boot attacks.
167  *
168  */
169 static void clear_password_memory(void) {
170 #ifdef __OpenBSD__
171     /* Use explicit_bzero(3) which was explicitly designed not to be
172      * optimized out by the compiler. */
173     explicit_bzero(password, strlen(password));
174 #else
175     /* A volatile pointer to the password buffer to prevent the compiler from
176      * optimizing this out. */
177     volatile char *vpassword = password;
178     for (int c = 0; c < sizeof(password); c++)
179         /* We store a non-random pattern which consists of the (irrelevant)
180          * index plus (!) the value of the beep variable. This prevents the
181          * compiler from optimizing the calls away, since the value of 'beep'
182          * is not known at compile-time. */
183         vpassword[c] = c + (int)beep;
184 #endif
185 }
186
187 ev_timer *start_timer(ev_timer *timer_obj, ev_tstamp timeout, ev_callback_t callback) {
188     if (timer_obj) {
189         ev_timer_stop(main_loop, timer_obj);
190         ev_timer_set(timer_obj, timeout, 0.);
191         ev_timer_start(main_loop, timer_obj);
192     } else {
193         /* When there is no memory, we just don’t have a timeout. We cannot
194          * exit() here, since that would effectively unlock the screen. */
195         timer_obj = calloc(sizeof(struct ev_timer), 1);
196         if (timer_obj) {
197             ev_timer_init(timer_obj, callback, timeout, 0.);
198             ev_timer_start(main_loop, timer_obj);
199         }
200     }
201     return timer_obj;
202 }
203
204 ev_timer *stop_timer(ev_timer *timer_obj) {
205     if (timer_obj) {
206         ev_timer_stop(main_loop, timer_obj);
207         free(timer_obj);
208     }
209     return NULL;
210 }
211
212 /*
213  * Neccessary calls after ending input via enter or others
214  *
215  */
216 static void finish_input(void) {
217     password[input_position] = '\0';
218     unlock_state = STATE_KEY_PRESSED;
219     redraw_screen();
220     input_done();
221 }
222
223 /*
224  * Resets auth_state to STATE_AUTH_IDLE 2 seconds after an unsuccessful
225  * authentication event.
226  *
227  */
228 static void clear_auth_wrong(EV_P_ ev_timer *w, int revents) {
229     DEBUG("clearing auth wrong\n");
230     auth_state = STATE_AUTH_IDLE;
231     redraw_screen();
232
233     /* Clear modifier string. */
234     if (modifier_string != NULL) {
235         free(modifier_string);
236         modifier_string = NULL;
237     }
238
239     /* Now free this timeout. */
240     STOP_TIMER(clear_auth_wrong_timeout);
241
242     /* retry with input done during auth verification */
243     if (retry_verification) {
244         retry_verification = false;
245         finish_input();
246     }
247 }
248
249 static void clear_indicator_cb(EV_P_ ev_timer *w, int revents) {
250     clear_indicator();
251     STOP_TIMER(clear_indicator_timeout);
252 }
253
254 static void clear_input(void) {
255     input_position = 0;
256     clear_password_memory();
257     password[input_position] = '\0';
258 }
259
260 static void discard_passwd_cb(EV_P_ ev_timer *w, int revents) {
261     clear_input();
262     STOP_TIMER(discard_passwd_timeout);
263 }
264
265 static void input_done(void) {
266     STOP_TIMER(clear_auth_wrong_timeout);
267     auth_state = STATE_AUTH_VERIFY;
268     unlock_state = STATE_STARTED;
269     redraw_screen();
270
271 #ifdef __OpenBSD__
272     struct passwd *pw;
273
274     if (!(pw = getpwuid(getuid())))
275         errx(1, "unknown uid %u.", getuid());
276
277     if (auth_userokay(pw->pw_name, NULL, NULL, password) != 0) {
278         DEBUG("successfully authenticated\n");
279         clear_password_memory();
280
281         exit(0);
282     }
283 #else
284     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
285         DEBUG("successfully authenticated\n");
286         clear_password_memory();
287
288         /* PAM credentials should be refreshed, this will for example update any kerberos tickets.
289          * Related to credentials pam_end() needs to be called to cleanup any temporary
290          * credentials like kerberos /tmp/krb5cc_pam_* files which may of been left behind if the
291          * refresh of the credentials failed. */
292         pam_setcred(pam_handle, PAM_REFRESH_CRED);
293         pam_end(pam_handle, PAM_SUCCESS);
294
295         exit(0);
296     }
297 #endif
298
299     if (debug_mode)
300         fprintf(stderr, "Authentication failure\n");
301
302     /* Get state of Caps and Num lock modifiers, to be displayed in
303      * STATE_AUTH_WRONG state */
304     xkb_mod_index_t idx, num_mods;
305     const char *mod_name;
306
307     num_mods = xkb_keymap_num_mods(xkb_keymap);
308
309     for (idx = 0; idx < num_mods; idx++) {
310         if (!xkb_state_mod_index_is_active(xkb_state, idx, XKB_STATE_MODS_EFFECTIVE))
311             continue;
312
313         mod_name = xkb_keymap_mod_get_name(xkb_keymap, idx);
314         if (mod_name == NULL)
315             continue;
316
317         /* Replace certain xkb names with nicer, human-readable ones. */
318         if (strcmp(mod_name, XKB_MOD_NAME_CAPS) == 0)
319             mod_name = "Caps Lock";
320         else if (strcmp(mod_name, XKB_MOD_NAME_ALT) == 0)
321             mod_name = "Alt";
322         else if (strcmp(mod_name, XKB_MOD_NAME_NUM) == 0)
323             mod_name = "Num Lock";
324         else if (strcmp(mod_name, XKB_MOD_NAME_LOGO) == 0)
325             mod_name = "Win";
326
327         char *tmp;
328         if (modifier_string == NULL) {
329             if (asprintf(&tmp, "%s", mod_name) != -1)
330                 modifier_string = tmp;
331         } else if (asprintf(&tmp, "%s, %s", modifier_string, mod_name) != -1) {
332             free(modifier_string);
333             modifier_string = tmp;
334         }
335     }
336
337     auth_state = STATE_AUTH_WRONG;
338     failed_attempts += 1;
339     clear_input();
340     if (unlock_indicator)
341         redraw_screen();
342
343     /* Clear this state after 2 seconds (unless the user enters another
344      * password during that time). */
345     ev_now_update(main_loop);
346     START_TIMER(clear_auth_wrong_timeout, TSTAMP_N_SECS(2), clear_auth_wrong);
347
348     /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
349      * too early. */
350     STOP_TIMER(clear_indicator_timeout);
351
352     /* beep on authentication failure, if enabled */
353     if (beep) {
354         xcb_bell(conn, 100);
355         xcb_flush(conn);
356     }
357 }
358
359 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
360     redraw_screen();
361     STOP_TIMER(w);
362 }
363
364 static bool skip_without_validation(void) {
365     if (input_position != 0)
366         return false;
367
368     if (skip_repeated_empty_password || ignore_empty_password)
369         return true;
370
371     return false;
372 }
373
374 /*
375  * Handle key presses. Fixes state, then looks up the key symbol for the
376  * given keycode, then looks up the key symbol (as UCS-2), converts it to
377  * UTF-8 and stores it in the password array.
378  *
379  */
380 static void handle_key_press(xcb_key_press_event_t *event) {
381     xkb_keysym_t ksym;
382     char buffer[128];
383     int n;
384     bool ctrl;
385     bool composed = false;
386
387     ksym = xkb_state_key_get_one_sym(xkb_state, event->detail);
388     ctrl = xkb_state_mod_name_is_active(xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_DEPRESSED);
389
390     /* The buffer will be null-terminated, so n >= 2 for 1 actual character. */
391     memset(buffer, '\0', sizeof(buffer));
392
393     if (xkb_compose_state && xkb_compose_state_feed(xkb_compose_state, ksym) == XKB_COMPOSE_FEED_ACCEPTED) {
394         switch (xkb_compose_state_get_status(xkb_compose_state)) {
395             case XKB_COMPOSE_NOTHING:
396                 break;
397             case XKB_COMPOSE_COMPOSING:
398                 return;
399             case XKB_COMPOSE_COMPOSED:
400                 /* xkb_compose_state_get_utf8 doesn't include the terminating byte in the return value
401              * as xkb_keysym_to_utf8 does. Adding one makes the variable n consistent. */
402                 n = xkb_compose_state_get_utf8(xkb_compose_state, buffer, sizeof(buffer)) + 1;
403                 ksym = xkb_compose_state_get_one_sym(xkb_compose_state);
404                 composed = true;
405                 break;
406             case XKB_COMPOSE_CANCELLED:
407                 xkb_compose_state_reset(xkb_compose_state);
408                 return;
409         }
410     }
411
412     if (!composed) {
413         n = xkb_keysym_to_utf8(ksym, buffer, sizeof(buffer));
414     }
415
416     switch (ksym) {
417         case XKB_KEY_j:
418         case XKB_KEY_m:
419         case XKB_KEY_Return:
420         case XKB_KEY_KP_Enter:
421         case XKB_KEY_XF86ScreenSaver:
422             if ((ksym == XKB_KEY_j || ksym == XKB_KEY_m) && !ctrl)
423                 break;
424
425             if (auth_state == STATE_AUTH_WRONG) {
426                 retry_verification = true;
427                 return;
428             }
429
430             if (skip_without_validation()) {
431                 clear_input();
432                 return;
433             }
434             finish_input();
435             skip_repeated_empty_password = true;
436             return;
437         default:
438             skip_repeated_empty_password = false;
439     }
440
441     switch (ksym) {
442         case XKB_KEY_u:
443         case XKB_KEY_Escape:
444             if ((ksym == XKB_KEY_u && ctrl) ||
445                 ksym == XKB_KEY_Escape) {
446                 DEBUG("C-u pressed\n");
447                 clear_input();
448                 /* Also hide the unlock indicator */
449                 if (unlock_indicator)
450                     clear_indicator();
451                 return;
452             }
453             break;
454
455         case XKB_KEY_Delete:
456         case XKB_KEY_KP_Delete:
457             /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
458              * to move the cursor when entering a password. We need to eat this
459              * key press so that it won’t be treated as part of the password,
460              * see issue #50. */
461             return;
462
463         case XKB_KEY_h:
464         case XKB_KEY_BackSpace:
465             if (ksym == XKB_KEY_h && !ctrl)
466                 break;
467
468             if (input_position == 0)
469                 return;
470
471             /* decrement input_position to point to the previous glyph */
472             u8_dec(password, &input_position);
473             password[input_position] = '\0';
474
475             /* Hide the unlock indicator after a bit if the password buffer is
476              * empty. */
477             START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
478             unlock_state = STATE_BACKSPACE_ACTIVE;
479             redraw_screen();
480             unlock_state = STATE_KEY_PRESSED;
481             return;
482     }
483
484     if ((input_position + 8) >= sizeof(password))
485         return;
486
487 #if 0
488     /* FIXME: handle all of these? */
489     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
490     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
491     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
492     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
493     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
494     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
495     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
496 #endif
497
498     if (n < 2)
499         return;
500
501     /* store it in the password array as UTF-8 */
502     memcpy(password + input_position, buffer, n - 1);
503     input_position += n - 1;
504     DEBUG("current password = %.*s\n", input_position, password);
505
506     if (unlock_indicator) {
507         unlock_state = STATE_KEY_ACTIVE;
508         redraw_screen();
509         unlock_state = STATE_KEY_PRESSED;
510
511         struct ev_timer *timeout = NULL;
512         START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
513         STOP_TIMER(clear_indicator_timeout);
514     }
515
516     START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
517 }
518
519 /*
520  * A visibility notify event will be received when the visibility (= can the
521  * user view the complete window) changes, so for example when a popup overlays
522  * some area of the i3lock window.
523  *
524  * In this case, we raise our window on top so that the popup (or whatever is
525  * hiding us) gets hidden.
526  *
527  */
528 static void handle_visibility_notify(xcb_connection_t *conn,
529                                      xcb_visibility_notify_event_t *event) {
530     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
531         uint32_t values[] = {XCB_STACK_MODE_ABOVE};
532         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
533         xcb_flush(conn);
534     }
535 }
536
537 /*
538  * Called when the keyboard mapping changes. We update our symbols.
539  *
540  * We ignore errors — if the new keymap cannot be loaded it’s better if the
541  * screen stays locked and the user intervenes by using killall i3lock.
542  *
543  */
544 static void process_xkb_event(xcb_generic_event_t *gevent) {
545     union xkb_event {
546         struct {
547             uint8_t response_type;
548             uint8_t xkbType;
549             uint16_t sequence;
550             xcb_timestamp_t time;
551             uint8_t deviceID;
552         } any;
553         xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
554         xcb_xkb_map_notify_event_t map_notify;
555         xcb_xkb_state_notify_event_t state_notify;
556     } *event = (union xkb_event *)gevent;
557
558     DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
559
560     if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
561         return;
562
563     /*
564      * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
565      * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
566      * recompilations.
567      */
568     switch (event->any.xkbType) {
569         case XCB_XKB_NEW_KEYBOARD_NOTIFY:
570             if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
571                 (void)load_keymap();
572             break;
573
574         case XCB_XKB_MAP_NOTIFY:
575             (void)load_keymap();
576             break;
577
578         case XCB_XKB_STATE_NOTIFY:
579             xkb_state_update_mask(xkb_state,
580                                   event->state_notify.baseMods,
581                                   event->state_notify.latchedMods,
582                                   event->state_notify.lockedMods,
583                                   event->state_notify.baseGroup,
584                                   event->state_notify.latchedGroup,
585                                   event->state_notify.lockedGroup);
586             break;
587     }
588 }
589
590 /*
591  * Called when the properties on the root window change, e.g. when the screen
592  * resolution changes. If so we update the window to cover the whole screen
593  * and also redraw the image, if any.
594  *
595  */
596 void handle_screen_resize(void) {
597     xcb_get_geometry_cookie_t geomc;
598     xcb_get_geometry_reply_t *geom;
599     geomc = xcb_get_geometry(conn, screen->root);
600     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
601         return;
602
603     if (last_resolution[0] == geom->width &&
604         last_resolution[1] == geom->height) {
605         free(geom);
606         return;
607     }
608
609     last_resolution[0] = geom->width;
610     last_resolution[1] = geom->height;
611
612     free(geom);
613
614     redraw_screen();
615
616     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
617     xcb_configure_window(conn, win, mask, last_resolution);
618     xcb_flush(conn);
619
620     xinerama_query_screens();
621     redraw_screen();
622 }
623
624 #ifndef __OpenBSD__
625 /*
626  * Callback function for PAM. We only react on password request callbacks.
627  *
628  */
629 static int conv_callback(int num_msg, const struct pam_message **msg,
630                          struct pam_response **resp, void *appdata_ptr) {
631     if (num_msg == 0)
632         return 1;
633
634     /* PAM expects an array of responses, one for each message */
635     if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
636         perror("calloc");
637         return 1;
638     }
639
640     for (int c = 0; c < num_msg; c++) {
641         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
642             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
643             continue;
644
645         /* return code is currently not used but should be set to zero */
646         resp[c]->resp_retcode = 0;
647         if ((resp[c]->resp = strdup(password)) == NULL) {
648             perror("strdup");
649             return 1;
650         }
651     }
652
653     return 0;
654 }
655 #endif
656
657 /*
658  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
659  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
660  *
661  */
662 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
663     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
664 }
665
666 /*
667  * Flush before blocking (and waiting for new events)
668  *
669  */
670 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
671     xcb_flush(conn);
672 }
673
674 /*
675  * Try closing logind sleep lock fd passed over from xss-lock, in case we're
676  * being run from there.
677  *
678  */
679 static void maybe_close_sleep_lock_fd(void) {
680     const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
681     char *endptr;
682     if (sleep_lock_fd && *sleep_lock_fd != 0) {
683         long int fd = strtol(sleep_lock_fd, &endptr, 10);
684         if (*endptr == 0) {
685             close(fd);
686         }
687     }
688 }
689
690 /*
691  * Instead of polling the X connection socket we leave this to
692  * xcb_poll_for_event() which knows better than we can ever know.
693  *
694  */
695 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
696     xcb_generic_event_t *event;
697
698     if (xcb_connection_has_error(conn))
699         errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
700
701     while ((event = xcb_poll_for_event(conn)) != NULL) {
702         if (event->response_type == 0) {
703             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
704             if (debug_mode)
705                 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
706                         error->sequence, error->error_code);
707             free(event);
708             continue;
709         }
710
711         /* Strip off the highest bit (set if the event is generated) */
712         int type = (event->response_type & 0x7F);
713
714         switch (type) {
715             case XCB_KEY_PRESS:
716                 handle_key_press((xcb_key_press_event_t *)event);
717                 break;
718
719             case XCB_VISIBILITY_NOTIFY:
720                 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
721                 break;
722
723             case XCB_MAP_NOTIFY:
724                 maybe_close_sleep_lock_fd();
725                 if (!dont_fork) {
726                     /* After the first MapNotify, we never fork again. We don’t
727                      * expect to get another MapNotify, but better be sure… */
728                     dont_fork = true;
729
730                     /* In the parent process, we exit */
731                     if (fork() != 0)
732                         exit(0);
733
734                     ev_loop_fork(EV_DEFAULT);
735                 }
736                 break;
737
738             case XCB_CONFIGURE_NOTIFY:
739                 handle_screen_resize();
740                 break;
741
742             default:
743                 if (type == xkb_base_event)
744                     process_xkb_event(event);
745         }
746
747         free(event);
748     }
749 }
750
751 /*
752  * This function is called from a fork()ed child and will raise the i3lock
753  * window when the window is obscured, even when the main i3lock process is
754  * blocked due to the authentication backend.
755  *
756  */
757 static void raise_loop(xcb_window_t window) {
758     xcb_connection_t *conn;
759     xcb_generic_event_t *event;
760     int screens;
761
762     if ((conn = xcb_connect(NULL, &screens)) == NULL ||
763         xcb_connection_has_error(conn))
764         errx(EXIT_FAILURE, "Cannot open display\n");
765
766     /* We need to know about the window being obscured or getting destroyed. */
767     xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
768                                  (uint32_t[]){
769                                      XCB_EVENT_MASK_VISIBILITY_CHANGE |
770                                      XCB_EVENT_MASK_STRUCTURE_NOTIFY});
771     xcb_flush(conn);
772
773     DEBUG("Watching window 0x%08x\n", window);
774     while ((event = xcb_wait_for_event(conn)) != NULL) {
775         if (event->response_type == 0) {
776             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
777             DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
778                   error->sequence, error->error_code);
779             free(event);
780             continue;
781         }
782         /* Strip off the highest bit (set if the event is generated) */
783         int type = (event->response_type & 0x7F);
784         DEBUG("Read event of type %d\n", type);
785         switch (type) {
786             case XCB_VISIBILITY_NOTIFY:
787                 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
788                 break;
789             case XCB_UNMAP_NOTIFY:
790                 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
791                 if (((xcb_unmap_notify_event_t *)event)->window == window)
792                     exit(EXIT_SUCCESS);
793                 break;
794             case XCB_DESTROY_NOTIFY:
795                 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
796                 if (((xcb_destroy_notify_event_t *)event)->window == window)
797                     exit(EXIT_SUCCESS);
798                 break;
799             default:
800                 DEBUG("Unhandled event type %d\n", type);
801                 break;
802         }
803         free(event);
804     }
805 }
806
807 int main(int argc, char *argv[]) {
808     struct passwd *pw;
809     char *username;
810     char *image_path = NULL;
811 #ifndef __OpenBSD__
812     int ret;
813     struct pam_conv conv = {conv_callback, NULL};
814 #endif
815     int curs_choice = CURS_NONE;
816     int o;
817     int longoptind = 0;
818     struct option longopts[] = {
819         {"version", no_argument, NULL, 'v'},
820         {"nofork", no_argument, NULL, 'n'},
821         {"beep", no_argument, NULL, 'b'},
822         {"dpms", no_argument, NULL, 'd'},
823         {"color", required_argument, NULL, 'c'},
824         {"pointer", required_argument, NULL, 'p'},
825         {"debug", no_argument, NULL, 0},
826         {"help", no_argument, NULL, 'h'},
827         {"no-unlock-indicator", no_argument, NULL, 'u'},
828         {"image", required_argument, NULL, 'i'},
829         {"tiling", no_argument, NULL, 't'},
830         {"ignore-empty-password", no_argument, NULL, 'e'},
831         {"inactivity-timeout", required_argument, NULL, 'I'},
832         {"show-failed-attempts", no_argument, NULL, 'f'},
833         {NULL, no_argument, NULL, 0}};
834
835     if ((pw = getpwuid(getuid())) == NULL)
836         err(EXIT_FAILURE, "getpwuid() failed");
837     if ((username = pw->pw_name) == NULL)
838         errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
839
840     char *optstring = "hvnbdc:p:ui:teI:f";
841     while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
842         switch (o) {
843             case 'v':
844                 errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg");
845             case 'n':
846                 dont_fork = true;
847                 break;
848             case 'b':
849                 beep = true;
850                 break;
851             case 'd':
852                 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
853                 break;
854             case 'I': {
855                 fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
856                 break;
857             }
858             case 'c': {
859                 char *arg = optarg;
860
861                 /* Skip # if present */
862                 if (arg[0] == '#')
863                     arg++;
864
865                 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
866                     errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
867
868                 break;
869             }
870             case 'u':
871                 unlock_indicator = false;
872                 break;
873             case 'i':
874                 image_path = strdup(optarg);
875                 break;
876             case 't':
877                 tile = true;
878                 break;
879             case 'p':
880                 if (!strcmp(optarg, "win")) {
881                     curs_choice = CURS_WIN;
882                 } else if (!strcmp(optarg, "default")) {
883                     curs_choice = CURS_DEFAULT;
884                 } else {
885                     errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
886                 }
887                 break;
888             case 'e':
889                 ignore_empty_password = true;
890                 break;
891             case 0:
892                 if (strcmp(longopts[longoptind].name, "debug") == 0)
893                     debug_mode = true;
894                 break;
895             case 'f':
896                 show_failed_attempts = true;
897                 break;
898             default:
899                 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
900                                    " [-i image.png] [-t] [-e] [-I timeout] [-f]");
901         }
902     }
903
904     /* We need (relatively) random numbers for highlighting a random part of
905      * the unlock indicator upon keypresses. */
906     srand(time(NULL));
907
908 #ifndef __OpenBSD__
909     /* Initialize PAM */
910     if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
911         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
912
913     if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
914         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
915 #endif
916
917 /* Using mlock() as non-super-user seems only possible in Linux.
918  * Users of other operating systems should use encrypted swap/no swap
919  * (or remove the ifdef and run i3lock as super-user).
920  * Alas, swap is encrypted by default on OpenBSD so swapping out
921  * is not necessarily an issue. */
922 #if defined(__linux__)
923     /* Lock the area where we store the password in memory, we don’t want it to
924      * be swapped to disk. Since Linux 2.6.9, this does not require any
925      * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
926     if (mlock(password, sizeof(password)) != 0)
927         err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
928 #endif
929
930     /* Double checking that connection is good and operatable with xcb */
931     int screennr;
932     if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
933         xcb_connection_has_error(conn))
934         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
935
936     if (xkb_x11_setup_xkb_extension(conn,
937                                     XKB_X11_MIN_MAJOR_XKB_VERSION,
938                                     XKB_X11_MIN_MINOR_XKB_VERSION,
939                                     0,
940                                     NULL,
941                                     NULL,
942                                     &xkb_base_event,
943                                     &xkb_base_error) != 1)
944         errx(EXIT_FAILURE, "Could not setup XKB extension.");
945
946     static const xcb_xkb_map_part_t required_map_parts =
947         (XCB_XKB_MAP_PART_KEY_TYPES |
948          XCB_XKB_MAP_PART_KEY_SYMS |
949          XCB_XKB_MAP_PART_MODIFIER_MAP |
950          XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
951          XCB_XKB_MAP_PART_KEY_ACTIONS |
952          XCB_XKB_MAP_PART_VIRTUAL_MODS |
953          XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
954
955     static const xcb_xkb_event_type_t required_events =
956         (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
957          XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
958          XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
959
960     xcb_xkb_select_events(
961         conn,
962         xkb_x11_get_core_keyboard_device_id(conn),
963         required_events,
964         0,
965         required_events,
966         required_map_parts,
967         required_map_parts,
968         0);
969
970     /* When we cannot initially load the keymap, we better exit */
971     if (!load_keymap())
972         errx(EXIT_FAILURE, "Could not load keymap");
973
974     const char *locale = getenv("LC_ALL");
975     if (!locale || !*locale)
976         locale = getenv("LC_CTYPE");
977     if (!locale || !*locale)
978         locale = getenv("LANG");
979     if (!locale || !*locale) {
980         if (debug_mode)
981             fprintf(stderr, "Can't detect your locale, fallback to C\n");
982         locale = "C";
983     }
984
985     load_compose_table(locale);
986
987     xinerama_init();
988     xinerama_query_screens();
989
990     screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
991
992     last_resolution[0] = screen->width_in_pixels;
993     last_resolution[1] = screen->height_in_pixels;
994
995     xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
996                                  (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
997
998     if (image_path) {
999         /* Create a pixmap to render on, fill it with the background color */
1000         img = cairo_image_surface_create_from_png(image_path);
1001         /* In case loading failed, we just pretend no -i was specified. */
1002         if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
1003             fprintf(stderr, "Could not load image \"%s\": %s\n",
1004                     image_path, cairo_status_to_string(cairo_surface_status(img)));
1005             img = NULL;
1006         }
1007         free(image_path);
1008     }
1009
1010     /* Pixmap on which the image is rendered to (if any) */
1011     xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
1012
1013     /* Open the fullscreen window, already with the correct pixmap in place */
1014     win = open_fullscreen_window(conn, screen, color, bg_pixmap);
1015     xcb_free_pixmap(conn, bg_pixmap);
1016
1017     cursor = create_cursor(conn, screen, win, curs_choice);
1018
1019     /* Display the "locking…" message while trying to grab the pointer/keyboard. */
1020     auth_state = STATE_AUTH_LOCK;
1021     grab_pointer_and_keyboard(conn, screen, cursor);
1022
1023     pid_t pid = fork();
1024     /* The pid == -1 case is intentionally ignored here:
1025      * While the child process is useful for preventing other windows from
1026      * popping up while i3lock blocks, it is not critical. */
1027     if (pid == 0) {
1028         /* Child */
1029         close(xcb_get_file_descriptor(conn));
1030         maybe_close_sleep_lock_fd();
1031         raise_loop(win);
1032         exit(EXIT_SUCCESS);
1033     }
1034
1035     /* Load the keymap again to sync the current modifier state. Since we first
1036      * loaded the keymap, there might have been changes, but starting from now,
1037      * we should get all key presses/releases due to having grabbed the
1038      * keyboard. */
1039     (void)load_keymap();
1040
1041     /* Initialize the libev event loop. */
1042     main_loop = EV_DEFAULT;
1043     if (main_loop == NULL)
1044         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
1045
1046     /* Explicitly call the screen redraw in case "locking…" message was displayed */
1047     auth_state = STATE_AUTH_IDLE;
1048     redraw_screen();
1049
1050     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1051     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1052     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1053
1054     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1055     ev_io_start(main_loop, xcb_watcher);
1056
1057     ev_check_init(xcb_check, xcb_check_cb);
1058     ev_check_start(main_loop, xcb_check);
1059
1060     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1061     ev_prepare_start(main_loop, xcb_prepare);
1062
1063     /* Invoke the event callback once to catch all the events which were
1064      * received up until now. ev will only pick up new events (when the X11
1065      * file descriptor becomes readable). */
1066     ev_invoke(main_loop, xcb_check, 0);
1067     ev_loop(main_loop, 0);
1068 }