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