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