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