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