]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
a0560918a718cf4da0ec18c2683730a85cfb9b69
[i3/i3lock] / i3lock.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * © 2010-2011 Michael Stapelberg
5  *
6  * See LICENSE for licensing information
7  *
8  */
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <unistd.h>
13 #include <stdbool.h>
14 #include <stdint.h>
15 #include <xcb/xcb.h>
16 #include <xcb/dpms.h>
17 #include <xcb/xcb_keysyms.h>
18 #include <err.h>
19 #include <assert.h>
20 #include <security/pam_appl.h>
21 /* FIXME: can we get rid of this header? */
22 #include <X11/keysym.h>
23 #include <getopt.h>
24 #include <string.h>
25 #include <math.h>
26 #include <ev.h>
27 #include <sys/mman.h>
28
29
30 #ifndef NOLIBCAIRO
31 #include <cairo.h>
32 #include <cairo/cairo-xcb.h>
33 #endif
34
35 #include "keysym2ucs.h"
36 #include "ucs2_to_utf8.h"
37 #include "xcb.h"
38 #include "cursors.h"
39
40 #define BUTTON_RADIUS 90
41 #define BUTTON_SPACE (BUTTON_RADIUS + 5)
42 #define BUTTON_CENTER (BUTTON_RADIUS + 5)
43 #define BUTTON_DIAMETER (5 * BUTTON_SPACE)
44
45 static char color[7] = "ffffff";
46 static uint32_t last_resolution[2];
47 static xcb_connection_t *conn;
48 static xcb_window_t win;
49 static xcb_visualtype_t *vistype;
50 static xcb_cursor_t cursor;
51 static xcb_key_symbols_t *symbols;
52 static xcb_screen_t *scr;
53 static pam_handle_t *pam_handle;
54 static int input_position = 0;
55 /* Holds the password you enter (in UTF-8). */
56 static char password[512];
57 static bool modeswitch_active = false;
58 static bool iso_level3_shift_active = false;
59 static bool iso_level5_shift_active = false;
60 static int modeswitchmask;
61 static int numlockmask;
62 static bool beep = false;
63 static bool debug_mode = false;
64 static bool dpms = false;
65 static bool unlock_indicator = true;
66 static struct ev_loop *main_loop;
67 static struct ev_timer *clear_pam_wrong_timeout;
68 static struct ev_timer *clear_indicator_timeout;
69
70 static enum {
71     STATE_STARTED = 0,          /* default state */
72     STATE_KEY_PRESSED = 1,      /* key was pressed, show unlock indicator */
73     STATE_KEY_ACTIVE = 2,       /* a key was pressed recently, highlight part
74                                    of the unlock indicator. */
75     STATE_BACKSPACE_ACTIVE = 3  /* backspace was pressed recently, highlight
76                                    part of the unlock indicator in red. */
77 } unlock_state;
78
79 static enum {
80     STATE_PAM_IDLE = 0,         /* no PAM interaction at the moment */
81     STATE_PAM_VERIFY = 1,       /* currently verifying the password via PAM */
82     STATE_PAM_WRONG = 2         /* the password was wrong */
83 } pam_state;
84
85 #define DEBUG(fmt, ...) do { \
86     if (debug_mode) \
87         printf("[i3lock-debug] " fmt, ##__VA_ARGS__); \
88 } while (0)
89
90 #ifndef NOLIBCAIRO
91 static cairo_surface_t *img = NULL;
92 static bool tile = false;
93 #endif
94
95 /*
96  * Clears the memory which stored the password to be a bit safer against
97  * cold-boot attacks.
98  *
99  */
100 static void clear_password_memory() {
101     /* A volatile pointer to the password buffer to prevent the compiler from
102      * optimizing this out. */
103     volatile char *vpassword = password;
104     for (int c = 0; c < sizeof(password); c++)
105         /* We store a non-random pattern which consists of the (irrelevant)
106          * index plus (!) the value of the beep variable. This prevents the
107          * compiler from optimizing the calls away, since the value of 'beep'
108          * is not known at compile-time. */
109         vpassword[c] = c + (int)beep;
110 }
111
112 /*
113  * Draws global image with fill color onto a pixmap with the given
114  * resolution and returns it.
115  *
116  */
117 static xcb_pixmap_t draw_image(xcb_visualtype_t *vistype, u_int32_t* resolution) {
118     xcb_pixmap_t bg_pixmap = XCB_NONE;
119
120 #ifndef NOLIBCAIRO
121     bg_pixmap = create_bg_pixmap(conn, scr, resolution, color);
122     /* Initialize cairo */
123     cairo_surface_t *output;
124     output = cairo_xcb_surface_create(conn, bg_pixmap, vistype,
125              resolution[0], resolution[1]);
126     cairo_t *ctx = cairo_create(output);
127     if (img) {
128         if (!tile) {
129             cairo_set_source_surface(ctx, img, 0, 0);
130             cairo_paint(ctx);
131         } else {
132             /* create a pattern and fill a rectangle as big as the screen */
133             cairo_pattern_t *pattern;
134             pattern = cairo_pattern_create_for_surface(img);
135             cairo_set_source(ctx, pattern);
136             cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
137             cairo_rectangle(ctx, 0, 0, resolution[0], resolution[1]);
138             cairo_fill(ctx);
139             cairo_pattern_destroy(pattern);
140         }
141     }
142
143     if (unlock_state >= STATE_KEY_PRESSED && unlock_indicator) {
144         cairo_pattern_t *outer_pat = NULL;
145
146         outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
147         switch (pam_state) {
148             case STATE_PAM_VERIFY:
149                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 0, 250.0/255);
150                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 0, 250.0/255);
151                 break;
152             case STATE_PAM_WRONG:
153                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 255.0/250, 139.0/255, 0);
154                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 125.0/255, 51.0/255, 0);
155                 break;
156             case STATE_PAM_IDLE:
157                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 125.0/255, 0);
158                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 125.0/255, 0);
159                 break;
160         }
161
162         /* Draw a (centered) circle with transparent background. */
163         cairo_set_line_width(ctx, 10.0);
164         cairo_arc(ctx,
165                   (resolution[0] / 2) /* x */,
166                   (resolution[1] / 2) /* y */,
167                   BUTTON_RADIUS /* radius */,
168                   0 /* start */,
169                   2 * M_PI /* end */);
170
171         /* Use the appropriate color for the different PAM states
172          * (currently verifying, wrong password, or default) */
173         switch (pam_state) {
174             case STATE_PAM_VERIFY:
175                 cairo_set_source_rgba(ctx, 0, 114.0/255, 255.0/255, 0.75);
176                 break;
177             case STATE_PAM_WRONG:
178                 cairo_set_source_rgba(ctx, 250.0/255, 0, 0, 0.75);
179                 break;
180             default:
181                 cairo_set_source_rgba(ctx, 0, 0, 0, 0.75);
182                 break;
183         }
184         cairo_fill_preserve(ctx);
185         cairo_set_source(ctx, outer_pat);
186         cairo_stroke(ctx);
187
188         /* Draw an inner seperator line. */
189         cairo_set_source_rgb(ctx, 0, 0, 0);
190         cairo_set_line_width(ctx, 2.0);
191         cairo_arc(ctx,
192                   (resolution[0] / 2) /* x */,
193                   (resolution[1] / 2) /* y */,
194                   BUTTON_RADIUS - 5 /* radius */,
195                   0,
196                   2 * M_PI);
197         cairo_stroke(ctx);
198
199         cairo_set_line_width(ctx, 10.0);
200
201         /* Display a (centered) text of the current PAM state. */
202         char *text = NULL;
203         switch (pam_state) {
204             case STATE_PAM_VERIFY:
205                 text = "verifying…";
206                 break;
207             case STATE_PAM_WRONG:
208                 text = "wrong!";
209                 break;
210             default:
211                 break;
212         }
213
214         if (text) {
215             cairo_text_extents_t extents;
216             double x, y;
217
218             cairo_set_source_rgb(ctx, 0, 0, 0);
219             cairo_set_font_size(ctx, 28.0);
220
221             cairo_text_extents(ctx, text, &extents);
222             x = (resolution[0] / 2.0) - ((extents.width / 2) + extents.x_bearing);
223             y = (resolution[1] / 2.0) - ((extents.height / 2) + extents.y_bearing);
224
225             cairo_move_to(ctx, x, y);
226             cairo_show_text(ctx, text);
227             cairo_close_path(ctx);
228         }
229
230         /* After the user pressed any valid key or the backspace key, we
231          * highlight a random part of the unlock indicator to confirm this
232          * keypress. */
233         if (unlock_state == STATE_KEY_ACTIVE ||
234             unlock_state == STATE_BACKSPACE_ACTIVE) {
235             cairo_new_sub_path(ctx);
236             double highlight_start = (rand() % (int)(2 * M_PI * 100)) / 100.0;
237             DEBUG("Highlighting part %.2f\n", highlight_start);
238             cairo_arc(ctx, resolution[0] / 2 /* x */, resolution[1] / 2 /* y */,
239                       BUTTON_RADIUS /* radius */, highlight_start,
240                       highlight_start + (M_PI / 3.0));
241             if (unlock_state == STATE_KEY_ACTIVE) {
242                 /* For normal keys, we use a lighter green. */
243                 outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
244                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 139.0/255, 219.0/255, 0);
245                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 51.0/255, 219.0/255, 0);
246             } else {
247                 /* For backspace, we use red. */
248                 outer_pat = cairo_pattern_create_linear(0, 0, 0, BUTTON_DIAMETER);
249                 cairo_pattern_add_color_stop_rgb(outer_pat, 0, 219.0/255, 139.0/255, 0);
250                 cairo_pattern_add_color_stop_rgb(outer_pat, 1, 219.0/255, 51.0/255, 0);
251             }
252             cairo_set_source(ctx, outer_pat);
253             cairo_stroke(ctx);
254
255             /* Draw two little separators for the highlighted part of the
256              * unlock indicator. */
257             cairo_set_source_rgb(ctx, 0, 0, 0);
258             cairo_arc(ctx,
259                       (resolution[0] / 2) /* x */,
260                       (resolution[1] / 2) /* y */,
261                       BUTTON_RADIUS /* radius */,
262                       highlight_start /* start */,
263                       highlight_start + (M_PI / 128.0) /* end */);
264             cairo_stroke(ctx);
265             cairo_arc(ctx,
266                       (resolution[0] / 2) /* x */,
267                       (resolution[1] / 2) /* y */,
268                       BUTTON_RADIUS /* radius */,
269                       highlight_start + (M_PI / 3.0) /* start */,
270                       (highlight_start + (M_PI / 3.0)) + (M_PI / 128.0) /* end */);
271             cairo_stroke(ctx);
272         }
273     }
274
275     cairo_surface_destroy(output);
276     cairo_destroy(ctx);
277 #endif
278     return bg_pixmap;
279 }
280
281 /*
282  * Calls draw_image on a new pixmap and swaps that with the current pixmap
283  *
284  */
285 static void redraw_screen() {
286     xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
287     xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
288     /* XXX: Possible optimization: Only update the area in the middle of the
289      * screen instead of the whole screen. */
290     xcb_clear_area(conn, 0, win, 0, 0, scr->width_in_pixels, scr->height_in_pixels);
291     xcb_free_pixmap(conn, bg_pixmap);
292     xcb_flush(conn);
293 }
294
295 /*
296  * Resets pam_state to STATE_PAM_IDLE 2 seconds after an unsuccesful
297  * authentication event.
298  *
299  */
300 static void clear_pam_wrong(EV_P_ ev_timer *w, int revents) {
301     DEBUG("clearing pam wrong\n");
302     pam_state = STATE_PAM_IDLE;
303     unlock_state = STATE_STARTED;
304     redraw_screen();
305 }
306
307 /*
308  * Hides the unlock indicator completely when there is no content in the
309  * password buffer.
310  *
311  */
312 static void clear_indicator(EV_P_ ev_timer *w, int revents) {
313     if (input_position == 0) {
314         DEBUG("Clear indicator\n");
315         unlock_state = STATE_STARTED;
316     } else unlock_state = STATE_KEY_PRESSED;
317     redraw_screen();
318 }
319
320 /*
321  * (Re-)starts the clear_indicator timeout. Called after pressing backspace or
322  * after an unsuccessful authentication attempt.
323  *
324  */
325 static void start_clear_indicator_timeout() {
326     if (clear_indicator_timeout) {
327         ev_timer_stop(main_loop, clear_indicator_timeout);
328         ev_timer_set(clear_indicator_timeout, 1.0, 0.);
329         ev_timer_start(main_loop, clear_indicator_timeout);
330     } else {
331         clear_indicator_timeout = calloc(sizeof(struct ev_timer), 1);
332         ev_timer_init(clear_indicator_timeout, clear_indicator, 1.0, 0.);
333         ev_timer_start(main_loop, clear_indicator_timeout);
334     }
335 }
336
337 static void input_done() {
338     if (input_position == 0)
339         return;
340
341     if (clear_pam_wrong_timeout) {
342         ev_timer_stop(main_loop, clear_pam_wrong_timeout);
343         clear_pam_wrong_timeout = NULL;
344     }
345
346     pam_state = STATE_PAM_VERIFY;
347     redraw_screen();
348
349     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
350         printf("successfully authenticated\n");
351         clear_password_memory();
352         exit(0);
353     }
354
355     fprintf(stderr, "Authentication failure\n");
356
357     pam_state = STATE_PAM_WRONG;
358     redraw_screen();
359
360     /* Clear this state after 2 seconds (unless the user enters another
361      * password during that time). */
362     ev_now_update(main_loop);
363     clear_pam_wrong_timeout = calloc(sizeof(struct ev_timer), 1);
364     ev_timer_init(clear_pam_wrong_timeout, clear_pam_wrong, 2.0, 0.);
365     ev_timer_start(main_loop, clear_pam_wrong_timeout);
366
367     /* Cancel the clear_indicator_timeout, it would hide the unlock indicator
368      * too early. */
369     if (clear_indicator_timeout) {
370         ev_timer_stop(main_loop, clear_indicator_timeout);
371         clear_indicator_timeout = NULL;
372     }
373
374     /* beep on authentication failure, if enabled */
375     if (beep) {
376         xcb_bell(conn, 100);
377         xcb_flush(conn);
378     }
379 }
380
381 /*
382  * Called when the user releases a key. We need to leave the Mode_switch
383  * state when the user releases the Mode_switch key.
384  *
385  */
386 static void handle_key_release(xcb_key_release_event_t *event) {
387     DEBUG("releasing key %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
388           event->detail, event->state, modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
389
390     /* We don’t care about the column here and just use the first symbol. Since
391      * we only check for Mode_switch and ISO_Level3_Shift, this *should* work.
392      * Also, if we would use the current column, we would look in the wrong
393      * place. */
394     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, 0);
395     if (sym == XK_Mode_switch) {
396         //printf("Mode switch disabled\n");
397         modeswitch_active = false;
398     } else if (sym == XK_ISO_Level3_Shift) {
399         iso_level3_shift_active = false;
400     } else if (sym == XK_ISO_Level5_Shift) {
401         iso_level5_shift_active = false;
402     }
403     DEBUG("release done. modeswitch_active = %d, iso_level3_shift_active = %d, iso_level5_shift_active = %d\n",
404           modeswitch_active, iso_level3_shift_active, iso_level5_shift_active);
405 }
406
407 static void redraw_timeout(EV_P_ ev_timer *w, int revents) {
408     redraw_screen();
409 }
410
411 /*
412  * Handle key presses. Fixes state, then looks up the key symbol for the
413  * given keycode, then looks up the key symbol (as UCS-2), converts it to
414  * UTF-8 and stores it in the password array.
415  *
416  */
417 static void handle_key_press(xcb_key_press_event_t *event) {
418     DEBUG("keypress %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
419           event->detail, event->state, modeswitch_active, iso_level3_shift_active);
420
421     xcb_keysym_t sym0, sym1, sym;
422     /* For each keycode, there is a list of symbols. The list could look like this:
423      * $ xmodmap -pke | grep 'keycode  38'
424      * keycode  38 = a A adiaeresis Adiaeresis o O
425      * In non-X11 terminology, the symbols for the keycode 38 (the key labeled
426      * with "a" on my keyboard) are "a A ä Ä o O".
427      * Another form to display the same information is using xkbcomp:
428      * $ xkbcomp $DISPLAY /tmp/xkb.dump
429      * Then open /tmp/xkb.dump and search for '\<a\>' (in VIM regexp-language):
430      *
431      * symbols[Group1]= [               a,               A,               o,               O ],
432      * symbols[Group2]= [      adiaeresis,      Adiaeresis ]
433      *
434      * So there are two *groups*, one containing 'a A' and one containing 'ä
435      * Ä'. You can use Mode_switch to switch between these groups. You can use
436      * ISO_Level3_Shift to reach the 'o O' part of the first group (it’s the
437      * same group, just an even higher shift level).
438      *
439      * So, using the "logical" XKB information, the following lookup will be
440      * performed:
441      *
442      * Neither Mode_switch nor ISO_Level3_Shift active: group 1, column 0 and 1
443      * Mode_switch active: group 2, column 0 and 1
444      * ISO_Level3_Shift active: group 1, column 2 and 3
445      *
446      * Using the column index which xcb_key_press_lookup_keysym uses (and
447      * xmodmap prints out), the following lookup will be performed:
448      *
449      * Neither Mode_switch nor ISO_Level3_Shift active: column 0 and 1
450      * Mode_switch active: column 2 and 3
451      * ISO_Level3_Shift active: column 4 and 5
452      */
453     int base_column = 0;
454     if (modeswitch_active)
455         base_column = 2;
456     if (iso_level3_shift_active)
457         base_column = 4;
458     if (iso_level5_shift_active)
459         base_column = 6;
460     sym0 = xcb_key_press_lookup_keysym(symbols, event, base_column);
461     sym1 = xcb_key_press_lookup_keysym(symbols, event, base_column + 1);
462     switch (sym0) {
463     case XK_Mode_switch:
464         DEBUG("Mode switch enabled\n");
465         modeswitch_active = true;
466         return;
467     case XK_ISO_Level3_Shift:
468         DEBUG("ISO_Level3_Shift enabled\n");
469         iso_level3_shift_active = true;
470         return;
471     case XK_ISO_Level5_Shift:
472         DEBUG("ISO_Level5_Shift enabled\n");
473         iso_level5_shift_active = true;
474         return;
475     case XK_Return:
476     case XK_KP_Enter:
477         input_done();
478     case XK_Escape:
479         input_position = 0;
480         clear_password_memory();
481         password[input_position] = '\0';
482         return;
483
484     case XK_BackSpace:
485         if (input_position == 0)
486             return;
487
488         /* decrement input_position to point to the previous glyph */
489         u8_dec(password, &input_position);
490         password[input_position] = '\0';
491
492         /* Clear this state after 2 seconds (unless the user enters another
493          * password during that time). */
494         start_clear_indicator_timeout();
495         unlock_state = STATE_BACKSPACE_ACTIVE;
496         redraw_screen();
497         unlock_state = STATE_KEY_PRESSED;
498         //printf("new input position = %d, new password = %s\n", input_position, password);
499         return;
500     }
501
502     if ((input_position + 8) >= sizeof(password))
503         return;
504
505     if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
506         /* this key was a keypad key */
507         if ((event->state & XCB_MOD_MASK_SHIFT))
508             sym = sym0;
509         else sym = sym1;
510     } else {
511         if ((event->state & XCB_MOD_MASK_SHIFT))
512             sym = sym1;
513         else sym = sym0;
514     }
515
516 #if 0
517     /* FIXME: handle all of these? */
518     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
519     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
520     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
521     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
522     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
523     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
524     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
525 #endif
526
527     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
528         return;
529
530     DEBUG("resolved to keysym = %c (%d)\n", sym, sym);
531
532     /* convert the keysym to UCS */
533     uint16_t ucs = keysym2ucs(sym);
534     if ((int16_t)ucs == -1) {
535         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
536         return;
537     }
538
539     /* store the UCS in a string to convert it */
540     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
541     DEBUG("input part = %s\n", inp);
542
543     /* store it in the password array as UTF-8 */
544     input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
545     password[input_position] = '\0';
546     DEBUG("current password = %s\n", password);
547
548     unlock_state = STATE_KEY_ACTIVE;
549     redraw_screen();
550     unlock_state = STATE_KEY_PRESSED;
551
552     struct ev_timer *timeout = calloc(sizeof(struct ev_timer), 1);
553     ev_timer_init(timeout, redraw_timeout, 0.25, 0.);
554     ev_timer_start(main_loop, timeout);
555
556     if (clear_indicator_timeout) {
557         ev_timer_stop(main_loop, clear_indicator_timeout);
558         clear_indicator_timeout = NULL;
559     }
560 }
561
562 /*
563  * A visibility notify event will be received when the visibility (= can the
564  * user view the complete window) changes, so for example when a popup overlays
565  * some area of the i3lock window.
566  *
567  * In this case, we raise our window on top so that the popup (or whatever is
568  * hiding us) gets hidden.
569  *
570  */
571 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
572     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
573         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
574         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
575         xcb_flush(conn);
576     }
577 }
578
579 /*
580  * Called when the keyboard mapping changes. We update our symbols.
581  *
582  */
583 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
584     xcb_refresh_keyboard_mapping(symbols, event);
585
586     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
587     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
588 }
589
590 /*
591  * Called when the properties on the root window change, e.g. when the screen
592  * resolution changes. If so we update the window to cover the whole screen
593  * and also redraw the image, if any.
594  *
595  */
596 void handle_screen_resize(xcb_visualtype_t *vistype, xcb_window_t win, uint32_t* last_resolution) {
597     xcb_get_geometry_cookie_t geomc;
598     xcb_get_geometry_reply_t *geom;
599     geomc = xcb_get_geometry(conn, scr->root);
600     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL) {
601       return;
602     }
603
604     if (last_resolution[0] == geom->width && last_resolution[1] == geom->height)
605       return;
606
607     last_resolution[0] = geom->width;
608     last_resolution[1] = geom->height;
609
610 #ifndef NOLIBCAIRO
611     if (img) {
612         xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
613         xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
614         xcb_free_pixmap(conn, bg_pixmap);
615     }
616 #endif
617
618     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
619     xcb_configure_window(conn, win, mask, last_resolution);
620     xcb_flush(conn);
621 }
622
623 /*
624  * Callback function for PAM. We only react on password request callbacks.
625  *
626  */
627 static int conv_callback(int num_msg, const struct pam_message **msg,
628                          struct pam_response **resp, void *appdata_ptr)
629 {
630     if (num_msg == 0)
631         return 1;
632
633     /* PAM expects an array of responses, one for each message */
634     if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
635         perror("calloc");
636         return 1;
637     }
638
639     for (int c = 0; c < num_msg; c++) {
640         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
641             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
642             continue;
643
644         /* return code is currently not used but should be set to zero */
645         resp[c]->resp_retcode = 0;
646         if ((resp[c]->resp = strdup(password)) == NULL) {
647             perror("strdup");
648             return 1;
649         }
650     }
651
652     return 0;
653 }
654
655 /*
656  * This callback is only a dummy, see xcb_prepare_cb and xcb_check_cb.
657  * See also man libev(3): "ev_prepare" and "ev_check" - customise your event loop
658  *
659  */
660 static void xcb_got_event(EV_P_ struct ev_io *w, int revents) {
661     /* empty, because xcb_prepare_cb and xcb_check_cb are used */
662 }
663
664 /*
665  * Flush before blocking (and waiting for new events)
666  *
667  */
668 static void xcb_prepare_cb(EV_P_ ev_prepare *w, int revents) {
669     xcb_flush(conn);
670 }
671
672 /*
673  * Instead of polling the X connection socket we leave this to
674  * xcb_poll_for_event() which knows better than we can ever know.
675  *
676  */
677 static void xcb_check_cb(EV_P_ ev_check *w, int revents) {
678     xcb_generic_event_t *event;
679
680     while ((event = xcb_poll_for_event(conn)) != NULL) {
681         if (event->response_type == 0) {
682             xcb_generic_error_t *error = (xcb_generic_error_t*)event;
683             fprintf(stderr, "X11 Error received! sequence 0x%x, error_code = %d\n",
684                     error->sequence, error->error_code);
685             free(event);
686             continue;
687         }
688
689         /* Strip off the highest bit (set if the event is generated) */
690         int type = (event->response_type & 0x7F);
691
692         if (type == XCB_KEY_PRESS) {
693             handle_key_press((xcb_key_press_event_t*)event);
694             continue;
695         }
696
697         if (type == XCB_KEY_RELEASE) {
698             handle_key_release((xcb_key_release_event_t*)event);
699
700             /* If this was the backspace or escape key we are back at an
701              * empty input, so turn off the screen if DPMS is enabled */
702             if (dpms && input_position == 0)
703                 dpms_turn_off_screen(conn);
704
705             continue;
706         }
707
708         if (type == XCB_VISIBILITY_NOTIFY) {
709             handle_visibility_notify((xcb_visibility_notify_event_t*)event);
710             continue;
711         }
712
713         if (type == XCB_MAPPING_NOTIFY) {
714             handle_mapping_notify((xcb_mapping_notify_event_t*)event);
715             continue;
716         }
717
718         if (type == XCB_CONFIGURE_NOTIFY) {
719             handle_screen_resize(vistype, win, last_resolution);
720             continue;
721         }
722
723         printf("WARNING: unhandled event of type %d\n", type);
724
725         free(event);
726     }
727 }
728
729 int main(int argc, char *argv[]) {
730     bool dont_fork = false;
731     char *username;
732 #ifndef NOLIBCAIRO
733     char *image_path = NULL;
734 #endif
735     int ret;
736     struct pam_conv conv = {conv_callback, NULL};
737     int screen;
738     int curs_choice = CURS_NONE;
739     char o;
740     int optind = 0;
741     struct option longopts[] = {
742         {"version", no_argument, NULL, 'v'},
743         {"nofork", no_argument, NULL, 'n'},
744         {"beep", no_argument, NULL, 'b'},
745         {"dpms", no_argument, NULL, 'd'},
746         {"color", required_argument, NULL, 'c'},
747         {"pointer", required_argument, NULL , 'p'},
748         {"debug", no_argument, NULL, 0},
749         {"help", no_argument, NULL, 'h'},
750         {"no-unlock-indicator", no_argument, NULL, 'u'},
751 #ifndef NOLIBCAIRO
752         {"image", required_argument, NULL, 'i'},
753         {"tiling", no_argument, NULL, 't'},
754 #endif
755         {NULL, no_argument, NULL, 0}
756     };
757
758     if ((username = getenv("USER")) == NULL)
759         errx(1, "USER environment variable not set, please set it.\n");
760
761     while ((o = getopt_long(argc, argv, "hvnbdc:p:u"
762 #ifndef NOLIBCAIRO
763         "i:t"
764 #endif
765         , longopts, &optind)) != -1) {
766         switch (o) {
767         case 'v':
768             errx(EXIT_SUCCESS, "version " VERSION " © 2010-2011 Michael Stapelberg");
769         case 'n':
770             dont_fork = true;
771             break;
772         case 'b':
773             beep = true;
774             break;
775         case 'd':
776             dpms = true;
777             break;
778         case 'c': {
779             char *arg = optarg;
780
781             /* Skip # if present */
782             if (arg[0] == '#')
783                 arg++;
784
785             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
786                 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
787
788             break;
789         }
790         case 'u':
791             unlock_indicator = false;
792             break;
793 #ifndef NOLIBCAIRO
794         case 'i':
795             image_path = strdup(optarg);
796             break;
797         case 't':
798             tile = true;
799             break;
800 #endif
801         case 'p':
802             if (!strcmp(optarg, "win")) {
803                 curs_choice = CURS_WIN;
804             } else if (!strcmp(optarg, "default")) {
805                 curs_choice = CURS_DEFAULT;
806             } else {
807                 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
808             }
809             break;
810         case 0:
811             if (strcmp(longopts[optind].name, "debug") == 0)
812                 debug_mode = true;
813             break;
814         default:
815             errx(1, "Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-u] [-p win|default]"
816 #ifndef NOLIBCAIRO
817             " [-i image.png] [-t]"
818 #else
819             " (compiled with NOLIBCAIRO)"
820 #endif
821             );
822         }
823     }
824
825     /* We need (relatively) random numbers for highlighting a random part of
826      * the unlock indicator upon keypresses. */
827     srand(time(NULL));
828
829     /* Initialize PAM */
830     ret = pam_start("i3lock", username, &conv, &pam_handle);
831     if (ret != PAM_SUCCESS)
832         errx(EXIT_FAILURE, "PAM: %s", pam_strerror(pam_handle, ret));
833
834     /* Lock the area where we store the password in memory, we don’t want it to
835      * be swapped to disk. Since Linux 2.6.9, this does not require any
836      * privileges, just enough bytes in the RLIMIT_MEMLOCK limit. */
837     if (mlock(password, sizeof(password)) != 0)
838         err(EXIT_FAILURE, "Could not lock page in memory, check RLIMIT_MEMLOCK");
839
840     /* Initialize connection to X11 */
841     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
842         xcb_connection_has_error(conn))
843         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
844
845     if (!dont_fork) {
846         /* In the parent process, we exit */
847         if (fork() != 0)
848             return 0;
849     }
850
851     /* if DPMS is enabled, check if the X server really supports it */
852     if (dpms) {
853         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
854         xcb_dpms_capable_reply_t *dpmsr;
855         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL)) && !dpmsr->capable) {
856             fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
857             dpms = false;
858         }
859     }
860
861     scr = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
862     vistype = get_root_visual_type(scr);
863
864     last_resolution[0] = scr->width_in_pixels;
865     last_resolution[1] = scr->height_in_pixels;
866
867
868 #ifndef NOLIBCAIRO
869     if (image_path) {
870         /* Create a pixmap to render on, fill it with the background color */
871         img = cairo_image_surface_create_from_png(image_path);
872     }
873 #endif
874
875     /* Pixmap on which the image is rendered to (if any) */
876     xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution);
877
878     /* open the fullscreen window, already with the correct pixmap in place */
879     win = open_fullscreen_window(conn, scr, color, bg_pixmap);
880     xcb_free_pixmap(conn, bg_pixmap);
881
882     cursor = create_cursor(conn, scr, win, curs_choice);
883
884     grab_pointer_and_keyboard(conn, scr, cursor);
885
886     symbols = xcb_key_symbols_alloc(conn);
887     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
888     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
889
890     if (dpms)
891         dpms_turn_off_screen(conn);
892
893     /* Initialize the libev event loop. */
894     main_loop = EV_DEFAULT;
895     if (main_loop == NULL)
896         errx(EXIT_FAILURE, "Could not initialize libev. Bad LIBEV_FLAGS?\n");
897
898     struct ev_io *xcb_watcher = calloc(sizeof(struct ev_io), 1);
899     struct ev_check *xcb_check = calloc(sizeof(struct ev_check), 1);
900     struct ev_prepare *xcb_prepare = calloc(sizeof(struct ev_prepare), 1);
901
902     ev_io_init(xcb_watcher, xcb_got_event, xcb_get_file_descriptor(conn), EV_READ);
903     ev_io_start(main_loop, xcb_watcher);
904
905     ev_check_init(xcb_check, xcb_check_cb);
906     ev_check_start(main_loop, xcb_check);
907
908     ev_prepare_init(xcb_prepare, xcb_prepare_cb);
909     ev_prepare_start(main_loop, xcb_prepare);
910
911     xcb_flush(conn);
912     ev_loop(main_loop, 0);
913 }