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