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