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