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