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