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