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