]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
Get rid of superfluous \n in --version
[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
26 #ifndef NOLIBCAIRO
27 #include <cairo.h>
28 #include <cairo/cairo-xcb.h>
29 #endif
30
31 #include "keysym2ucs.h"
32 #include "ucs2_to_utf8.h"
33 #include "xcb.h"
34 #include "cursors.h"
35
36 static xcb_connection_t *conn;
37 static xcb_cursor_t cursor;
38 static xcb_key_symbols_t *symbols;
39 static xcb_screen_t *scr;
40 static pam_handle_t *pam_handle;
41 static int input_position = 0;
42 /* holds the password you enter (in UTF-8) */
43 static char password[512];
44 static bool modeswitch_active = false;
45 static bool iso_level3_shift_active = false;
46 static int modeswitchmask;
47 static int numlockmask;
48 static bool beep = false;
49 static bool debug_mode = false;
50
51 #define DEBUG(fmt, ...) do { \
52     if (debug_mode) \
53         printf("[i3lock-debug] " fmt, ##__VA_ARGS__); \
54 } while (0)
55
56 #ifndef NOLIBCAIRO
57 static cairo_surface_t *img = NULL;
58 static bool tile = false;
59 #endif
60
61 /*
62  * Draws global image with fill color onto a pixmap with the given
63  * resolution and returns it.
64  *
65  */
66 xcb_pixmap_t draw_image(xcb_visualtype_t *vistype, u_int32_t* resolution, char* color) {
67     xcb_pixmap_t bg_pixmap = XCB_NONE;
68
69 #ifndef NOLIBCAIRO
70     if (!img)
71         return bg_pixmap;
72
73     bg_pixmap = create_bg_pixmap(conn, scr, resolution, color);
74     /* Initialize cairo */
75     cairo_surface_t *output;
76     output = cairo_xcb_surface_create(conn, bg_pixmap, vistype,
77              resolution[0], resolution[1]);
78     cairo_t *ctx = cairo_create(output);
79     if (!tile) {
80         cairo_set_source_surface(ctx, img, 0, 0);
81         cairo_paint(ctx);
82     } else {
83         /* create a pattern and fill a rectangle as big as the screen */
84         cairo_pattern_t *pattern;
85         pattern = cairo_pattern_create_for_surface(img);
86         cairo_set_source(ctx, pattern);
87         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
88         cairo_rectangle(ctx, 0, 0, resolution[0], resolution[1]);
89         cairo_fill(ctx);
90         cairo_pattern_destroy(pattern);
91     }
92     cairo_surface_destroy(output);
93     cairo_destroy(ctx);
94 #endif
95     return bg_pixmap;
96 }
97
98 static void input_done() {
99     if (input_position == 0)
100         return;
101
102     /* TODO: change cursor during authentication? */
103     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
104         printf("successfully authenticated\n");
105         exit(0);
106     }
107
108     fprintf(stderr, "Authentication failure\n");
109
110     /* beep on authentication failure, if enabled */
111     if (beep) {
112         xcb_bell(conn, 100);
113         xcb_flush(conn);
114     }
115 }
116
117 /*
118  * Called when the user releases a key. We need to leave the Mode_switch
119  * state when the user releases the Mode_switch key.
120  *
121  */
122 static void handle_key_release(xcb_key_release_event_t *event) {
123     DEBUG("releasing key %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
124           event->detail, event->state, modeswitch_active, iso_level3_shift_active);
125
126     /* We don’t care about the column here and just use the first symbol. Since
127      * we only check for Mode_switch and ISO_Level3_Shift, this *should* work.
128      * Also, if we would use the current column, we would look in the wrong
129      * place. */
130     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, 0);
131     if (sym == XK_Mode_switch) {
132         //printf("Mode switch disabled\n");
133         modeswitch_active = false;
134     } else if (sym == XK_ISO_Level3_Shift) {
135         iso_level3_shift_active = false;
136     }
137     DEBUG("release done. modeswitch_active = %d, iso_level3_shift_active = %d\n",
138           modeswitch_active, iso_level3_shift_active);
139 }
140
141 /*
142  * Handle key presses. Fixes state, then looks up the key symbol for the
143  * given keycode, then looks up the key symbol (as UCS-2), converts it to
144  * UTF-8 and stores it in the password array.
145  *
146  */
147 static void handle_key_press(xcb_key_press_event_t *event) {
148     DEBUG("keypress %d, state raw = %d, modeswitch_active = %d, iso_level3_shift_active = %d\n",
149           event->detail, event->state, modeswitch_active, iso_level3_shift_active);
150
151     xcb_keysym_t sym0, sym1, sym;
152     /* For each keycode, there is a list of symbols. The list could look like this:
153      * $ xmodmap -pke | grep 'keycode  38'
154      * keycode  38 = a A adiaeresis Adiaeresis o O
155      * In non-X11 terminology, the symbols for the keycode 38 (the key labeled
156      * with "a" on my keyboard) are "a A ä Ä o O".
157      * Another form to display the same information is using xkbcomp:
158      * $ xkbcomp $DISPLAY /tmp/xkb.dump
159      * Then open /tmp/xkb.dump and search for '\<a\>' (in VIM regexp-language):
160      *
161      * symbols[Group1]= [               a,               A,               o,               O ],
162      * symbols[Group2]= [      adiaeresis,      Adiaeresis ]
163      *
164      * So there are two *groups*, one containing 'a A' and one containing 'ä
165      * Ä'. You can use Mode_switch to switch between these groups. You can use
166      * ISO_Level3_Shift to reach the 'o O' part of the first group (it’s the
167      * same group, just an even higher shift level).
168      *
169      * So, using the "logical" XKB information, the following lookup will be
170      * performed:
171      *
172      * Neither Mode_switch nor ISO_Level3_Shift active: group 1, column 0 and 1
173      * Mode_switch active: group 2, column 0 and 1
174      * ISO_Level3_Shift active: group 1, column 2 and 3
175      *
176      * Using the column index which xcb_key_press_lookup_keysym uses (and
177      * xmodmap prints out), the following lookup will be performed:
178      *
179      * Neither Mode_switch nor ISO_Level3_Shift active: column 0 and 1
180      * Mode_switch active: column 2 and 3
181      * ISO_Level3_Shift active: column 4 and 5
182      */
183     int base_column = 0;
184     if (modeswitch_active)
185         base_column = 2;
186     if (iso_level3_shift_active)
187         base_column = 4;
188     sym0 = xcb_key_press_lookup_keysym(symbols, event, base_column);
189     sym1 = xcb_key_press_lookup_keysym(symbols, event, base_column + 1);
190     switch (sym0) {
191     case XK_Mode_switch:
192         DEBUG("Mode switch enabled\n");
193         modeswitch_active = true;
194         return;
195     case XK_ISO_Level3_Shift:
196         DEBUG("ISO_Level3_Shift enabled\n");
197         iso_level3_shift_active = true;
198         return;
199     case XK_Return:
200     case XK_KP_Enter:
201         input_done();
202     case XK_Escape:
203         input_position = 0;
204         password[input_position] = '\0';
205         return;
206
207     case XK_BackSpace:
208         if (input_position == 0)
209             return;
210
211         /* decrement input_position to point to the previous glyph */
212         u8_dec(password, &input_position);
213         password[input_position] = '\0';
214         //printf("new input position = %d, new password = %s\n", input_position, password);
215         return;
216     }
217
218     if ((input_position + 8) >= sizeof(password))
219         return;
220
221     if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
222         /* this key was a keypad key */
223         if ((event->state & XCB_MOD_MASK_SHIFT))
224             sym = sym0;
225         else sym = sym1;
226     } else {
227         if ((event->state & XCB_MOD_MASK_SHIFT))
228             sym = sym1;
229         else sym = sym0;
230     }
231
232 #if 0
233     /* FIXME: handle all of these? */
234     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
235     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
236     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
237     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
238     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
239     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
240     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
241 #endif
242
243     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
244         return;
245
246     DEBUG("resolved to keysym = %c (%d)\n", sym, sym);
247
248     /* convert the keysym to UCS */
249     uint16_t ucs = keysym2ucs(sym);
250     if ((int16_t)ucs == -1) {
251         fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
252         return;
253     }
254
255     /* store the UCS in a string to convert it */
256     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
257     DEBUG("input part = %s\n", inp);
258
259     /* store it in the password array as UTF-8 */
260     input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
261     password[input_position] = '\0';
262     DEBUG("current password = %s\n", password);
263 }
264
265 /*
266  * A visibility notify event will be received when the visibility (= can the
267  * user view the complete window) changes, so for example when a popup overlays
268  * some area of the i3lock window.
269  *
270  * In this case, we raise our window on top so that the popup (or whatever is
271  * hiding us) gets hidden.
272  *
273  */
274 static void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
275     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
276         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
277         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
278         xcb_flush(conn);
279     }
280 }
281
282 /*
283  * Called when the keyboard mapping changes. We update our symbols.
284  *
285  */
286 static void handle_mapping_notify(xcb_mapping_notify_event_t *event) {
287     xcb_refresh_keyboard_mapping(symbols, event);
288
289     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
290     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
291 }
292
293 /*
294  * Called when the properties on the root window change, e.g. when the screen
295  * resolution changes. If so we update the window to cover the whole screen
296  * and also redraw the image, if any.
297  *
298  */
299 void handle_screen_resize(xcb_visualtype_t *vistype, xcb_window_t win, uint32_t* last_resolution, char* color) {
300     xcb_get_geometry_cookie_t geomc;
301     xcb_get_geometry_reply_t *geom;
302     geomc = xcb_get_geometry(conn, scr->root);
303     if ((geom = xcb_get_geometry_reply(conn, geomc, 0)) == NULL) {
304       return;
305     }
306
307     if (last_resolution[0] == geom->width && last_resolution[1] == geom->height)
308       return;
309
310     last_resolution[0] = geom->width;
311     last_resolution[1] = geom->height;
312
313 #ifndef NOLIBCAIRO
314     if (img) {
315         xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution, color);
316         xcb_change_window_attributes(conn, win, XCB_CW_BACK_PIXMAP, (uint32_t[1]){ bg_pixmap });
317     }
318 #endif
319
320     uint32_t mask = XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT;
321     xcb_configure_window(conn, win, mask, last_resolution);
322     xcb_flush(conn);
323 }
324
325 /*
326  * Callback function for PAM. We only react on password request callbacks.
327  *
328  */
329 static int conv_callback(int num_msg, const struct pam_message **msg,
330                          struct pam_response **resp, void *appdata_ptr)
331 {
332     if (num_msg == 0)
333         return 1;
334
335     /* PAM expects an array of responses, one for each message */
336     if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
337         perror("calloc");
338         return 1;
339     }
340
341     for (int c = 0; c < num_msg; c++) {
342         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
343             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
344             continue;
345
346         /* return code is currently not used but should be set to zero */
347         resp[c]->resp_retcode = 0;
348         if ((resp[c]->resp = strdup(password)) == NULL) {
349             perror("strdup");
350             return 1;
351         }
352     }
353
354     return 0;
355 }
356
357 int main(int argc, char *argv[]) {
358     bool dont_fork = false;
359     bool dpms = false;
360     char color[7] = "ffffff";
361     char *username;
362 #ifndef NOLIBCAIRO
363     char *image_path = NULL;
364 #endif
365     int ret;
366     struct pam_conv conv = {conv_callback, NULL};
367     int screen;
368     xcb_visualtype_t *vistype;
369     xcb_generic_event_t *event;
370     xcb_window_t win;
371     int curs_choice = CURS_NONE;
372     char o;
373     int optind = 0;
374     struct option longopts[] = {
375         {"version", no_argument, NULL, 'v'},
376         {"nofork", no_argument, NULL, 'n'},
377         {"beep", no_argument, NULL, 'b'},
378         {"dpms", no_argument, NULL, 'd'},
379         {"color", required_argument, NULL, 'c'},
380         {"pointer", required_argument, NULL , 'p'},
381         {"debug", no_argument, NULL, 0},
382 #ifndef NOLIBCAIRO
383         {"image", required_argument, NULL, 'i'},
384         {"tiling", no_argument, NULL, 't'},
385 #endif
386         {NULL, no_argument, NULL, 0}
387     };
388
389     if ((username = getenv("USER")) == NULL)
390         errx(1, "USER environment variable not set, please set it.\n");
391
392     while ((o = getopt_long(argc, argv, "vnbdc:p:"
393 #ifndef NOLIBCAIRO
394         "i:t"
395 #endif
396         , longopts, &optind)) != -1) {
397         switch (o) {
398         case 'v':
399             errx(EXIT_SUCCESS, "version " VERSION " © 2010-2011 Michael Stapelberg");
400         case 'n':
401             dont_fork = true;
402             break;
403         case 'b':
404             beep = true;
405             break;
406         case 'd':
407             dpms = true;
408             break;
409         case 'c': {
410             char *arg = optarg;
411
412             /* Skip # if present */
413             if (arg[0] == '#')
414                 arg++;
415
416             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
417                 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
418
419             break;
420         }
421 #ifndef NOLIBCAIRO
422         case 'i':
423             image_path = strdup(optarg);
424             break;
425         case 't':
426             tile = true;
427             break;
428 #endif
429         case 'p':
430             if (!strcmp(optarg, "win")) {
431                 curs_choice = CURS_WIN;
432             } else if (!strcmp(optarg, "default")) {
433                 curs_choice = CURS_DEFAULT;
434             } else {
435                 errx(1, "i3lock: Invalid pointer type given. Expected one of \"win\" or \"default\".\n");
436             }
437             break;
438         case 0:
439             if (strcmp(longopts[optind].name, "debug") == 0)
440                 debug_mode = true;
441             break;
442         default:
443             errx(1, "i3lock: Unknown option. Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-p win|default]"
444 #ifndef NOLIBCAIRO
445             " [-i image.png] [-t]"
446 #else
447             " (compiled with NOLIBCAIRO)"
448 #endif
449             "\n");
450         }
451     }
452
453     /* Initialize PAM */
454     ret = pam_start("i3lock", username, &conv, &pam_handle);
455     if (ret != PAM_SUCCESS)
456         errx(EXIT_FAILURE, "PAM: %s\n", pam_strerror(pam_handle, ret));
457
458     /* Initialize connection to X11 */
459     if ((conn = xcb_connect(NULL, &screen)) == NULL ||
460         xcb_connection_has_error(conn))
461         errx(EXIT_FAILURE, "Could not connect to X11, maybe you need to set DISPLAY?");
462
463     if (!dont_fork) {
464         /* In the parent process, we exit */
465         if (fork() != 0)
466             return 0;
467     }
468
469     /* if DPMS is enabled, check if the X server really supports it */
470     if (dpms) {
471         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
472         xcb_dpms_capable_reply_t *dpmsr;
473         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL)) && !dpmsr->capable) {
474             fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
475             dpms = false;
476         }
477     }
478
479     scr = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
480     vistype = get_root_visual_type(scr);
481
482     uint32_t last_resolution[2] = {scr->width_in_pixels, scr->height_in_pixels};
483
484
485
486 #ifndef NOLIBCAIRO
487     if (image_path) {
488         /* Create a pixmap to render on, fill it with the background color */
489         img = cairo_image_surface_create_from_png(image_path);
490     }
491 #endif
492
493     /* Pixmap on which the image is rendered to (if any) */
494     xcb_pixmap_t bg_pixmap = draw_image(vistype, last_resolution, color);
495
496     /* open the fullscreen window, already with the correct pixmap in place */
497     win = open_fullscreen_window(conn, scr, color, bg_pixmap);
498
499     cursor = create_cursor(conn, scr, win, curs_choice);
500
501     grab_pointer_and_keyboard(conn, scr, cursor);
502
503     symbols = xcb_key_symbols_alloc(conn);
504     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
505     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
506
507     if (dpms)
508         dpms_turn_off_screen(conn);
509
510     while ((event = xcb_wait_for_event(conn))) {
511         if (event->response_type == 0)
512             errx(1, "XCB: Invalid event received");
513
514         /* Strip off the highest bit (set if the event is generated) */
515         int type = (event->response_type & 0x7F);
516
517         if (type == XCB_KEY_PRESS) {
518             handle_key_press((xcb_key_press_event_t*)event);
519             continue;
520         }
521
522         if (type == XCB_KEY_RELEASE) {
523             handle_key_release((xcb_key_release_event_t*)event);
524
525             /* If this was the backspace or escape key we are back at an
526              * empty input, so turn off the screen if DPMS is enabled */
527             if (dpms && input_position == 0)
528                 dpms_turn_off_screen(conn);
529
530             continue;
531         }
532
533         if (type == XCB_VISIBILITY_NOTIFY) {
534             handle_visibility_notify((xcb_visibility_notify_event_t*)event);
535             continue;
536         }
537
538         if (type == XCB_MAPPING_NOTIFY) {
539             handle_mapping_notify((xcb_mapping_notify_event_t*)event);
540             continue;
541         }
542
543         if (type == XCB_CONFIGURE_NOTIFY) {
544             handle_screen_resize(vistype, win, last_resolution, color);
545             continue;
546         }
547
548         printf("WARNING: unhandled event of type %d\n", type);
549     }
550
551     return 0;
552 }