]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
13adc2b43838402d6975eb945cbb94f954c67bd4
[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     }
449
450     switch (ksym) {
451         case XKB_KEY_u:
452         case XKB_KEY_Escape:
453             if ((ksym == XKB_KEY_u && ctrl) ||
454                 ksym == XKB_KEY_Escape) {
455                 DEBUG("C-u pressed\n");
456                 clear_input();
457                 /* Also hide the unlock indicator */
458                 if (unlock_indicator)
459                     clear_indicator();
460                 return;
461             }
462             break;
463
464         case XKB_KEY_Delete:
465         case XKB_KEY_KP_Delete:
466             /* Deleting forward doesn’t make sense, as i3lock doesn’t allow you
467              * to move the cursor when entering a password. We need to eat this
468              * key press so that it won’t be treated as part of the password,
469              * see issue #50. */
470             return;
471
472         case XKB_KEY_h:
473         case XKB_KEY_BackSpace:
474             if (ksym == XKB_KEY_h && !ctrl)
475                 break;
476
477             if (input_position == 0) {
478                 START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
479                 unlock_state = STATE_NOTHING_TO_DELETE;
480                 redraw_screen();
481                 return;
482             }
483
484             /* decrement input_position to point to the previous glyph */
485             u8_dec(password, &input_position);
486             password[input_position] = '\0';
487
488             /* Hide the unlock indicator after a bit if the password buffer is
489              * empty. */
490             START_TIMER(clear_indicator_timeout, 1.0, clear_indicator_cb);
491             unlock_state = STATE_BACKSPACE_ACTIVE;
492             redraw_screen();
493             unlock_state = STATE_KEY_PRESSED;
494             return;
495     }
496
497     if ((input_position + 8) >= (int)sizeof(password))
498         return;
499
500 #if 0
501     /* FIXME: handle all of these? */
502     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
503     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
504     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
505     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
506     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
507     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
508     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
509 #endif
510
511     if (n < 2)
512         return;
513
514     /* store it in the password array as UTF-8 */
515     memcpy(password + input_position, buffer, n - 1);
516     input_position += n - 1;
517     DEBUG("current password = %.*s\n", input_position, password);
518
519     if (unlock_indicator) {
520         unlock_state = STATE_KEY_ACTIVE;
521         redraw_screen();
522         unlock_state = STATE_KEY_PRESSED;
523
524         struct ev_timer *timeout = NULL;
525         START_TIMER(timeout, TSTAMP_N_SECS(0.25), redraw_timeout);
526         STOP_TIMER(clear_indicator_timeout);
527     }
528
529     START_TIMER(discard_passwd_timeout, TSTAMP_N_MINS(3), discard_passwd_cb);
530 }
531
532 /*
533  * A visibility notify event will be received when the visibility (= can the
534  * user view the complete window) changes, so for example when a popup overlays
535  * some area of the i3lock window.
536  *
537  * In this case, we raise our window on top so that the popup (or whatever is
538  * hiding us) gets hidden.
539  *
540  */
541 static void handle_visibility_notify(xcb_connection_t *conn,
542                                      xcb_visibility_notify_event_t *event) {
543     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
544         uint32_t values[] = {XCB_STACK_MODE_ABOVE};
545         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
546         xcb_flush(conn);
547     }
548 }
549
550 /*
551  * Called when the keyboard mapping changes. We update our symbols.
552  *
553  * We ignore errors — if the new keymap cannot be loaded it’s better if the
554  * screen stays locked and the user intervenes by using killall i3lock.
555  *
556  */
557 static void process_xkb_event(xcb_generic_event_t *gevent) {
558     union xkb_event {
559         struct {
560             uint8_t response_type;
561             uint8_t xkbType;
562             uint16_t sequence;
563             xcb_timestamp_t time;
564             uint8_t deviceID;
565         } any;
566         xcb_xkb_new_keyboard_notify_event_t new_keyboard_notify;
567         xcb_xkb_map_notify_event_t map_notify;
568         xcb_xkb_state_notify_event_t state_notify;
569     } *event = (union xkb_event *)gevent;
570
571     DEBUG("process_xkb_event for device %d\n", event->any.deviceID);
572
573     if (event->any.deviceID != xkb_x11_get_core_keyboard_device_id(conn))
574         return;
575
576     /*
577      * XkbNewKkdNotify and XkbMapNotify together capture all sorts of keymap
578      * updates (e.g. xmodmap, xkbcomp, setxkbmap), with minimal redundent
579      * recompilations.
580      */
581     switch (event->any.xkbType) {
582         case XCB_XKB_NEW_KEYBOARD_NOTIFY:
583             if (event->new_keyboard_notify.changed & XCB_XKB_NKN_DETAIL_KEYCODES)
584                 (void)load_keymap();
585             break;
586
587         case XCB_XKB_MAP_NOTIFY:
588             (void)load_keymap();
589             break;
590
591         case XCB_XKB_STATE_NOTIFY:
592             xkb_state_update_mask(xkb_state,
593                                   event->state_notify.baseMods,
594                                   event->state_notify.latchedMods,
595                                   event->state_notify.lockedMods,
596                                   event->state_notify.baseGroup,
597                                   event->state_notify.latchedGroup,
598                                   event->state_notify.lockedGroup);
599             break;
600     }
601 }
602
603 /*
604  * Called when the properties on the root window change, e.g. when the screen
605  * resolution changes. If so we update the window to cover the whole screen
606  * and also redraw the image, if any.
607  *
608  */
609 void handle_screen_resize(void) {
610     xcb_get_geometry_cookie_t geomc;
611     xcb_get_geometry_reply_t *geom;
612     geomc = xcb_get_geometry(conn, screen->root);
613     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL)
614         return;
615
616     if (last_resolution[0] == geom->width &&
617         last_resolution[1] == geom->height) {
618         free(geom);
619         return;
620     }
621
622     last_resolution[0] = geom->width;
623     last_resolution[1] = geom->height;
624
625     free(geom);
626
627     redraw_screen();
628
629     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
630     xcb_configure_window(conn, win, mask, last_resolution);
631     xcb_flush(conn);
632
633     randr_query(screen->root);
634     redraw_screen();
635 }
636
637 static bool verify_png_image(const char *image_path) {
638     if (!image_path) {
639         return false;
640     }
641
642     /* Check file exists and has correct PNG header */
643     FILE *png_file = fopen(image_path, "r");
644     if (png_file == NULL) {
645         fprintf(stderr, "Image file path \"%s\" cannot be opened: %s\n", image_path, strerror(errno));
646         return false;
647     }
648     unsigned char png_header[8];
649     memset(png_header, '\0', sizeof(png_header));
650     int bytes_read = fread(png_header, 1, sizeof(png_header), png_file);
651     fclose(png_file);
652     if (bytes_read != sizeof(png_header)) {
653         fprintf(stderr, "Could not read PNG header from \"%s\"\n", image_path);
654         return false;
655     }
656
657     // Check PNG header according to the specification, available at:
658     // https://www.w3.org/TR/2003/REC-PNG-20031110/#5PNG-file-signature
659     static unsigned char PNG_REFERENCE_HEADER[8] = {137, 80, 78, 71, 13, 10, 26, 10};
660     if (memcmp(PNG_REFERENCE_HEADER, png_header, sizeof(png_header)) != 0) {
661         fprintf(stderr, "File \"%s\" does not start with a PNG header. i3lock currently only supports loading PNG files.\n", image_path);
662         return false;
663     }
664     return true;
665 }
666
667 #ifndef __OpenBSD__
668 /*
669  * Callback function for PAM. We only react on password request callbacks.
670  *
671  */
672 static int conv_callback(int num_msg, const struct pam_message **msg,
673                          struct pam_response **resp, void *appdata_ptr) {
674     if (num_msg == 0)
675         return 1;
676
677     /* PAM expects an array of responses, one for each message */
678     if ((*resp = calloc(num_msg, sizeof(struct pam_response))) == NULL) {
679         perror("calloc");
680         return 1;
681     }
682
683     for (int c = 0; c < num_msg; c++) {
684         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
685             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
686             continue;
687
688         /* return code is currently not used but should be set to zero */
689         resp[c]->resp_retcode = 0;
690         if ((resp[c]->resp = strdup(password)) == NULL) {
691             perror("strdup");
692             return 1;
693         }
694     }
695
696     return 0;
697 }
698 #endif
699
700 /*
701  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
702  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
703  *
704  */
705 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
706     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
707 }
708
709 /*
710  * Flush before blocking (and waiting for new events)
711  *
712  */
713 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
714     xcb_flush(conn);
715 }
716
717 /*
718  * Try closing logind sleep lock fd passed over from xss-lock, in case we're
719  * being run from there.
720  *
721  */
722 static void maybe_close_sleep_lock_fd(void) {
723     const char *sleep_lock_fd = getenv("XSS_SLEEP_LOCK_FD");
724     char *endptr;
725     if (sleep_lock_fd && *sleep_lock_fd != 0) {
726         long int fd = strtol(sleep_lock_fd, &endptr, 10);
727         if (*endptr == 0) {
728             close(fd);
729         }
730     }
731 }
732
733 /*
734  * Instead of polling the X connection socket we leave this to
735  * xcb_poll_for_event() which knows better than we can ever know.
736  *
737  */
738 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
739     xcb_generic_event_t *event;
740
741     if (xcb_connection_has_error(conn))
742         errx(EXIT_FAILURE, "X11 connection broke, did your server terminate?\n");
743
744     while ((event = xcb_poll_for_event(conn)) != NULL) {
745         if (event->response_type == 0) {
746             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
747             if (debug_mode)
748                 fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
749                         error->sequence, error->error_code);
750             free(event);
751             continue;
752         }
753
754         /* Strip off the highest bit (set if the event is generated) */
755         int type = (event->response_type & 0x7F);
756
757         switch (type) {
758             case XCB_KEY_PRESS:
759                 handle_key_press((xcb_key_press_event_t *)event);
760                 break;
761
762             case XCB_VISIBILITY_NOTIFY:
763                 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
764                 break;
765
766             case XCB_MAP_NOTIFY:
767                 maybe_close_sleep_lock_fd();
768                 if (!dont_fork) {
769                     /* After the first MapNotify, we never fork again. We don’t
770                      * expect to get another MapNotify, but better be sure… */
771                     dont_fork = true;
772
773                     /* In the parent process, we exit */
774                     if (fork() != 0)
775                         exit(0);
776
777                     ev_loop_fork(EV_DEFAULT);
778                 }
779                 break;
780
781             case XCB_CONFIGURE_NOTIFY:
782                 handle_screen_resize();
783                 break;
784
785             default:
786                 if (type == xkb_base_event) {
787                     process_xkb_event(event);
788                 }
789                 if (randr_base > -1 &&
790                     type == randr_base + XCB_RANDR_SCREEN_CHANGE_NOTIFY) {
791                     randr_query(screen->root);
792                     handle_screen_resize();
793                 }
794         }
795
796         free(event);
797     }
798 }
799
800 /*
801  * This function is called from a fork()ed child and will raise the i3lock
802  * window when the window is obscured, even when the main i3lock process is
803  * blocked due to the authentication backend.
804  *
805  */
806 static void raise_loop(xcb_window_t window) {
807     xcb_connection_t *conn;
808     xcb_generic_event_t *event;
809     int screens;
810
811     if (xcb_connection_has_error((conn = xcb_connect(NULL, &screens))) > 0)
812         errx(EXIT_FAILURE, "Cannot open display\n");
813
814     /* We need to know about the window being obscured or getting destroyed. */
815     xcb_change_window_attributes(conn, window, XCB_CW_EVENT_MASK,
816                                  (uint32_t[]){
817                                      XCB_EVENT_MASK_VISIBILITY_CHANGE |
818                                      XCB_EVENT_MASK_STRUCTURE_NOTIFY});
819     xcb_flush(conn);
820
821     DEBUG("Watching window 0x%08x\n", window);
822     while ((event = xcb_wait_for_event(conn)) != NULL) {
823         if (event->response_type == 0) {
824             xcb_generic_error_t *error = (xcb_generic_error_t *)event;
825             DEBUG("X11 Error received! sequence 0x%x, error_code = %d\n",
826                   error->sequence, error->error_code);
827             free(event);
828             continue;
829         }
830         /* Strip off the highest bit (set if the event is generated) */
831         int type = (event->response_type & 0x7F);
832         DEBUG("Read event of type %d\n", type);
833         switch (type) {
834             case XCB_VISIBILITY_NOTIFY:
835                 handle_visibility_notify(conn, (xcb_visibility_notify_event_t *)event);
836                 break;
837             case XCB_UNMAP_NOTIFY:
838                 DEBUG("UnmapNotify for 0x%08x\n", (((xcb_unmap_notify_event_t *)event)->window));
839                 if (((xcb_unmap_notify_event_t *)event)->window == window)
840                     exit(EXIT_SUCCESS);
841                 break;
842             case XCB_DESTROY_NOTIFY:
843                 DEBUG("DestroyNotify for 0x%08x\n", (((xcb_destroy_notify_event_t *)event)->window));
844                 if (((xcb_destroy_notify_event_t *)event)->window == window)
845                     exit(EXIT_SUCCESS);
846                 break;
847             default:
848                 DEBUG("Unhandled event type %d\n", type);
849                 break;
850         }
851         free(event);
852     }
853 }
854
855 int main(int argc, char *argv[]) {
856     struct passwd *pw;
857     char *username;
858     char *image_path = NULL;
859 #ifndef __OpenBSD__
860     int ret;
861     struct pam_conv conv = {conv_callback, NULL};
862 #endif
863     int curs_choice = CURS_NONE;
864     int o;
865     int longoptind = 0;
866     struct option longopts[] = {
867         {"version", no_argument, NULL, 'v'},
868         {"nofork", no_argument, NULL, 'n'},
869         {"beep", no_argument, NULL, 'b'},
870         {"dpms", no_argument, NULL, 'd'},
871         {"color", required_argument, NULL, 'c'},
872         {"pointer", required_argument, NULL, 'p'},
873         {"debug", no_argument, NULL, 0},
874         {"help", no_argument, NULL, 'h'},
875         {"no-unlock-indicator", no_argument, NULL, 'u'},
876         {"image", required_argument, NULL, 'i'},
877         {"tiling", no_argument, NULL, 't'},
878         {"ignore-empty-password", no_argument, NULL, 'e'},
879         {"inactivity-timeout", required_argument, NULL, 'I'},
880         {"show-failed-attempts", no_argument, NULL, 'f'},
881         {NULL, no_argument, NULL, 0}};
882
883     if ((pw = getpwuid(getuid())) == NULL)
884         err(EXIT_FAILURE, "getpwuid() failed");
885     if ((username = pw->pw_name) == NULL)
886         errx(EXIT_FAILURE, "pw->pw_name is NULL.\n");
887
888     char *optstring = "hvnbdc:p:ui:teI:f";
889     while ((o = getopt_long(argc, argv, optstring, longopts, &longoptind)) != -1) {
890         switch (o) {
891             case 'v':
892                 errx(EXIT_SUCCESS, "version " I3LOCK_VERSION " © 2010 Michael Stapelberg");
893             case 'n':
894                 dont_fork = true;
895                 break;
896             case 'b':
897                 beep = true;
898                 break;
899             case 'd':
900                 fprintf(stderr, "DPMS support has been removed from i3lock. Please see the manpage i3lock(1).\n");
901                 break;
902             case 'I': {
903                 fprintf(stderr, "Inactivity timeout only makes sense with DPMS, which was removed. Please see the manpage i3lock(1).\n");
904                 break;
905             }
906             case 'c': {
907                 char *arg = optarg;
908
909                 /* Skip # if present */
910                 if (arg[0] == '#')
911                     arg++;
912
913                 if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
914                     errx(EXIT_FAILURE, "color is invalid, it must be given in 3-byte hexadecimal format: rrggbb\n");
915
916                 break;
917             }
918             case 'u':
919                 unlock_indicator = false;
920                 break;
921             case 'i':
922                 image_path = strdup(optarg);
923                 break;
924             case 't':
925                 tile = true;
926                 break;
927             case 'p':
928                 if (!strcmp(optarg, "win")) {
929                     curs_choice = CURS_WIN;
930                 } else if (!strcmp(optarg, "default")) {
931                     curs_choice = CURS_DEFAULT;
932                 } else {
933                     errx(EXIT_FAILURE, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
934                 }
935                 break;
936             case 'e':
937                 ignore_empty_password = true;
938                 break;
939             case 0:
940                 if (strcmp(longopts[longoptind].name, "debug") == 0)
941                     debug_mode = true;
942                 break;
943             case 'f':
944                 show_failed_attempts = true;
945                 break;
946             default:
947                 errx(EXIT_FAILURE, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
948                                    " [-i image.png] [-t] [-e] [-I timeout] [-f]");
949         }
950     }
951
952     /* We need (relatively) random numbers for highlighting a random part of
953      * the unlock indicator upon keypresses. */
954     srand(time(NULL));
955
956 #ifndef __OpenBSD__
957     /* Initialize PAM */
958     if ((ret = pam_start("i3lock", username, &conv, &pam_handle)) != PAM_SUCCESS)
959         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
960
961     if ((ret = pam_set_item(pam_handle, PAM_TTY, getenv("DISPLAY"))) != PAM_SUCCESS)
962         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
963 #endif
964
965 /* Using mlock() as non-super-user seems only possible in Linux.
966  * Users of other operating systems should use encrypted swap/no swap
967  * (or remove the ifdef and run i3lock as super-user).
968  * Alas, swap is encrypted by default on OpenBSD so swapping out
969  * is not necessarily an issue. */
970 #if defined(__linux__)
971     /* Lock the area where we store the password in memory, we don’t want it to
972      * be swapped to disk. Since Linux 2.6.9, this does not require any
973      * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
974     if (mlock(password, sizeof(password)) != 0)
975         err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
976 #endif
977
978     /* Double checking that connection is good and operatable with xcb */
979     int screennr;
980     if ((conn = xcb_connect(NULL, &screennr)) == NULL ||
981         xcb_connection_has_error(conn))
982         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
983
984     if (xkb_x11_setup_xkb_extension(conn,
985                                     XKB_X11_MIN_MAJOR_XKB_VERSION,
986                                     XKB_X11_MIN_MINOR_XKB_VERSION,
987                                     0,
988                                     NULL,
989                                     NULL,
990                                     &xkb_base_event,
991                                     &xkb_base_error) != 1)
992         errx(EXIT_FAILURE, "Could not setup XKB extension.");
993
994     static const xcb_xkb_map_part_t required_map_parts =
995         (XCB_XKB_MAP_PART_KEY_TYPES |
996          XCB_XKB_MAP_PART_KEY_SYMS |
997          XCB_XKB_MAP_PART_MODIFIER_MAP |
998          XCB_XKB_MAP_PART_EXPLICIT_COMPONENTS |
999          XCB_XKB_MAP_PART_KEY_ACTIONS |
1000          XCB_XKB_MAP_PART_VIRTUAL_MODS |
1001          XCB_XKB_MAP_PART_VIRTUAL_MOD_MAP);
1002
1003     static const xcb_xkb_event_type_t required_events =
1004         (XCB_XKB_EVENT_TYPE_NEW_KEYBOARD_NOTIFY |
1005          XCB_XKB_EVENT_TYPE_MAP_NOTIFY |
1006          XCB_XKB_EVENT_TYPE_STATE_NOTIFY);
1007
1008     xcb_xkb_select_events(
1009         conn,
1010         xkb_x11_get_core_keyboard_device_id(conn),
1011         required_events,
1012         0,
1013         required_events,
1014         required_map_parts,
1015         required_map_parts,
1016         0);
1017
1018     /* When we cannot initially load the keymap, we better exit */
1019     if (!load_keymap())
1020         errx(EXIT_FAILURE, "Could not load keymap");
1021
1022     const char *locale = getenv("LC_ALL");
1023     if (!locale || !*locale)
1024         locale = getenv("LC_CTYPE");
1025     if (!locale || !*locale)
1026         locale = getenv("LANG");
1027     if (!locale || !*locale) {
1028         if (debug_mode)
1029             fprintf(stderr, "Can't detect your locale, fallback to C\n");
1030         locale = "C";
1031     }
1032
1033     load_compose_table(locale);
1034
1035     screen = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
1036
1037     init_dpi();
1038
1039     randr_init(&randr_base, screen->root);
1040     randr_query(screen->root);
1041
1042     last_resolution[0] = screen->width_in_pixels;
1043     last_resolution[1] = screen->height_in_pixels;
1044
1045     xcb_change_window_attributes(conn, screen->root, XCB_CW_EVENT_MASK,
1046                                  (uint32_t[]){XCB_EVENT_MASK_STRUCTURE_NOTIFY});
1047
1048     if (verify_png_image(image_path)) {
1049         /* Create a pixmap to render on, fill it with the background color */
1050         img = cairo_image_surface_create_from_png(image_path);
1051         /* In case loading failed, we just pretend no -i was specified. */
1052         if (cairo_surface_status(img) != CAIRO_STATUS_SUCCESS) {
1053             fprintf(stderr, "Could not load image \"%s\": %s\n",
1054                     image_path, cairo_status_to_string(cairo_surface_status(img)));
1055             img = NULL;
1056         }
1057     }
1058     free(image_path);
1059
1060     /* Pixmap on which the image is rendered to (if any) */
1061     xcb_pixmap_t bg_pixmap = draw_image(last_resolution);
1062
1063     xcb_window_t stolen_focus = find_focused_window(conn, screen->root);
1064
1065     /* Open the fullscreen window, already with the correct pixmap in place */
1066     win = open_fullscreen_window(conn, screen, color, bg_pixmap);
1067     xcb_free_pixmap(conn, bg_pixmap);
1068
1069     cursor = create_cursor(conn, screen, win, curs_choice);
1070
1071     /* Display the "locking…" message while trying to grab the pointer/keyboard. */
1072     auth_state = STATE_AUTH_LOCK;
1073     if (!grab_pointer_and_keyboard(conn, screen, cursor, 1000)) {
1074         DEBUG("stole focus from X11 window 0x%08x\n", stolen_focus);
1075
1076         /* Set the focus to i3lock, possibly closing context menus which would
1077          * otherwise prevent us from grabbing keyboard/pointer.
1078          *
1079          * We cannot use set_focused_window because _NET_ACTIVE_WINDOW only
1080          * works for managed windows, but i3lock uses an unmanaged window
1081          * (override_redirect=1). */
1082         xcb_set_input_focus(conn, XCB_INPUT_FOCUS_PARENT /* revert_to */, win, XCB_CURRENT_TIME);
1083         if (!grab_pointer_and_keyboard(conn, screen, cursor, 9000)) {
1084             auth_state = STATE_I3LOCK_LOCK_FAILED;
1085             redraw_screen();
1086             sleep(1);
1087             errx(EXIT_FAILURE, "Cannot grab pointer/keyboard");
1088         }
1089     }
1090
1091     pid_t pid = fork();
1092     /* The pid == -1 case is intentionally ignored here:
1093      * While the child process is useful for preventing other windows from
1094      * popping up while i3lock blocks, it is not critical. */
1095     if (pid == 0) {
1096         /* Child */
1097         close(xcb_get_file_descriptor(conn));
1098         maybe_close_sleep_lock_fd();
1099         raise_loop(win);
1100         exit(EXIT_SUCCESS);
1101     }
1102
1103     /* Load the keymap again to sync the current modifier state. Since we first
1104      * loaded the keymap, there might have been changes, but starting from now,
1105      * we should get all key presses/releases due to having grabbed the
1106      * keyboard. */
1107     (void)load_keymap();
1108
1109     /* Initialize the libev event loop. */
1110     main_loop = EV_DEFAULT;
1111     if (main_loop == NULL)
1112         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
1113
1114     /* Explicitly call the screen redraw in case "locking…" message was displayed */
1115     auth_state = STATE_AUTH_IDLE;
1116     redraw_screen();
1117
1118     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
1119     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
1120     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
1121
1122     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
1123     ev_io_start(main_loop, xcb_watcher);
1124
1125     ev_check_init(xcb_check, xcb_check_cb);
1126     ev_check_start(main_loop, xcb_check);
1127
1128     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
1129     ev_prepare_start(main_loop, xcb_prepare);
1130
1131     /* Invoke the event callback once to catch all the events which were
1132      * received up until now. ev will only pick up new events (when the X11
1133      * file descriptor becomes readable). */
1134     ev_invoke(main_loop, xcb_check, 0);
1135     ev_loop(main_loop, 0);
1136
1137     if (stolen_focus == XCB_NONE) {
1138         return 0;
1139     }
1140
1141     DEBUG("restoring focus to X11 window 0x%08x\n", stolen_focus);
1142     xcb_ungrab_pointer(conn, XCB_CURRENT_TIME);
1143     xcb_ungrab_keyboard(conn, XCB_CURRENT_TIME);
1144     xcb_destroy_window(conn, win);
1145     set_focused_window(conn, screen->root, stolen_focus);
1146     xcb_aux_sync(conn);
1147
1148     return 0;
1149 }