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