]> git.sur5r.net Git - i3/i3lock/blob - i3lock.c
198d334e43f2fc52d622e1d4be56620462046446
[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 <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_key_symbols_t *symbols;
38 static xcb_screen_t *scr;
39 static pam_handle_t *pam_handle;
40 static int input_position = 0;
41 /* holds the password you enter (in UTF-8) */
42 static char password[512];
43 static bool modeswitch_active = false;
44 static int modeswitchmask;
45 static int numlockmask;
46 static bool beep = false;
47
48 #ifndef NOLIBCAIRO
49 static cairo_surface_t *img = NULL;
50 static cairo_t *ctx = NULL;
51 static bool tile = false;
52 #endif
53
54 static void input_done() {
55     if (input_position == 0)
56         return;
57
58     /* TODO: change cursor during authentication? */
59     if (pam_authenticate(pam_handle, 0) == PAM_SUCCESS) {
60         printf("successfully authenticated\n");
61         exit(0);
62     }
63
64     /* beep on authentication failure, if enabled */
65     if (beep) {
66         xcb_bell(conn, 100);
67         xcb_flush(conn);
68     }
69 }
70
71 /*
72  * Called when we should draw the image (if any).
73  *
74  */
75 static void handle_expose_event() {
76 #ifndef NOLIBCAIRO
77     if (!ctx)
78         return;
79
80     if (tile) {
81         /* create a pattern and fill a rectangle as big as the screen */
82         cairo_pattern_t *pattern;
83         pattern = cairo_pattern_create_for_surface(img);
84         cairo_set_source(ctx, pattern);
85         cairo_pattern_set_extend(pattern, CAIRO_EXTEND_REPEAT);
86         cairo_rectangle(ctx, 0, 0, scr->width_in_pixels, scr->height_in_pixels);
87         cairo_fill(ctx);
88     } else {
89         /* otherwise, just paint the image */
90         cairo_paint(ctx);
91     }
92 #endif
93     xcb_flush(conn);
94 }
95
96 /*
97  * Called when the user releases a key. We need to leave the Mode_switch
98  * state when the user releases the Mode_switch key.
99  *
100  */
101 static void handle_key_release(xcb_key_release_event_t *event) {
102     //printf("releasing %d, state raw = %d\n", event->detail, event->state);
103
104     /* fix state */
105     event->state &= ~numlockmask;
106
107     xcb_keysym_t sym = xcb_key_press_lookup_keysym(symbols, event, event->state);
108     if (sym == XK_Mode_switch) {
109         //printf("Mode switch disabled\n");
110         modeswitch_active = false;
111     }
112 }
113
114 /*
115  * Handle key presses. Fixes state, then looks up the key symbol for the
116  * given keycode, then looks up the key symbol (as UCS-2), converts it to
117  * UTF-8 and stores it in the password array.
118  *
119  */
120 static void handle_key_press(xcb_key_press_event_t *event) {
121     //printf("keypress %d, state raw = %d\n", event->detail, event->state);
122
123     xcb_keysym_t sym0, sym1, sym;
124     if (modeswitch_active) {
125         sym0 = xcb_key_press_lookup_keysym(symbols, event, 4);
126         sym1 = xcb_key_press_lookup_keysym(symbols, event, 5);
127     } else {
128         sym0 = xcb_key_press_lookup_keysym(symbols, event, 0);
129         sym1 = xcb_key_press_lookup_keysym(symbols, event, 1);
130     }
131     switch (sym0) {
132     case XK_Mode_switch:
133         //printf("Mode switch enabled\n");
134         modeswitch_active = true;
135         return;
136
137     case XK_Return:
138         input_done();
139     case XK_Escape:
140         input_position = 0;
141         password[input_position] = '\0';
142         return;
143
144     case XK_BackSpace:
145         if (input_position == 0)
146             return;
147
148         /* decrement input_position to point to the previous glyph */
149         u8_dec(password, &input_position);
150         password[input_position] = '\0';
151         //printf("new input position = %d, new password = %s\n", input_position, password);
152         return;
153     }
154
155     if ((input_position + 8) >= sizeof(password))
156         return;
157
158     if ((event->state & numlockmask) && xcb_is_keypad_key(sym1)) {
159         /* this key was a keypad key */
160         if ((event->state & XCB_MOD_MASK_SHIFT))
161             sym = sym0;
162         else sym = sym1;
163     } else {
164         if ((event->state & XCB_MOD_MASK_SHIFT))
165             sym = sym1;
166         else sym = sym0;
167     }
168
169 #if 0
170     /* FIXME: handle all of these? */
171     printf("is_keypad_key = %d\n", xcb_is_keypad_key(sym));
172     printf("is_private_keypad_key = %d\n", xcb_is_private_keypad_key(sym));
173     printf("xcb_is_cursor_key = %d\n", xcb_is_cursor_key(sym));
174     printf("xcb_is_pf_key = %d\n", xcb_is_pf_key(sym));
175     printf("xcb_is_function_key = %d\n", xcb_is_function_key(sym));
176     printf("xcb_is_misc_function_key = %d\n", xcb_is_misc_function_key(sym));
177     printf("xcb_is_modifier_key = %d\n", xcb_is_modifier_key(sym));
178 #endif
179
180     if (xcb_is_modifier_key(sym) || xcb_is_cursor_key(sym))
181             return;
182
183     //printf("sym = %c (%d)\n", sym, sym);
184
185     /* convert the keysym to UCS */
186     uint16_t ucs = keysym2ucs(sym);
187     if ((int16_t)ucs == -1) {
188             fprintf(stderr, "Keysym could not be converted to UCS, skipping\n");
189             return;
190     }
191
192     /* store the UCS in a string to convert it */
193     uint8_t inp[3] = {(ucs & 0xFF00) >> 8, (ucs & 0xFF), 0};
194
195     /* store it in the password array as UTF-8 */
196     input_position += convert_ucs_to_utf8((char*)inp, password + input_position);
197     password[input_position] = '\0';
198     //printf("current password = %s\n", password);
199 }
200
201 /*
202  * A visibility notify event will be received when the visibility (= can the
203  * user view the complete window) changes, so for example when a popup overlays
204  * some area of the i3lock window.
205  *
206  * In this case, we raise our window on top so that the popup (or whatever is
207  * hiding us) gets hidden.
208  *
209  */
210 void handle_visibility_notify(xcb_visibility_notify_event_t *event) {
211     printf("visibility notify (window 0x%08x, state %d)\n", event->window, event->state);
212     if (event->state != XCB_VISIBILITY_UNOBSCURED) {
213         printf("window is obscured (not fully visible), raising\n");
214         uint32_t values[] = { XCB_STACK_MODE_ABOVE };
215         xcb_configure_window(conn, event->window, XCB_CONFIG_WINDOW_STACK_MODE, values);
216         xcb_flush(conn);
217     }
218 }
219
220 /*
221  * Callback function for PAM. We only react on password request callbacks.
222  *
223  */
224 static int conv_callback(int num_msg, const struct pam_message **msg,
225                          struct pam_response **resp, void *appdata_ptr)
226 {
227     if (num_msg == 0)
228         return 1;
229
230     /* PAM expects an array of responses, one for each message */
231     if ((*resp = calloc(num_msg, sizeof(struct pam_message))) == NULL) {
232         perror("calloc");
233         return 1;
234     }
235
236     for (int c = 0; c < num_msg; c++) {
237         if (msg[c]->msg_style != PAM_PROMPT_ECHO_OFF &&
238             msg[c]->msg_style != PAM_PROMPT_ECHO_ON)
239             continue;
240
241         /* return code is currently not used but should be set to zero */
242         resp[c]->resp_retcode = 0;
243         if ((resp[c]->resp = strdup(password)) == NULL) {
244             perror("strdup");
245             return 1;
246         }
247     }
248
249     return 0;
250 }
251
252 int main(int argc, char *argv[]) {
253     bool dont_fork = false;
254     bool dpms = false;
255     char color[7] = "ffffff";
256     char *username;
257 #ifndef NOLIBCAIRO
258     char *image_path = NULL;
259 #endif
260     int ret;
261     struct pam_conv conv = {conv_callback, NULL};
262     int screen;
263     xcb_visualtype_t *vistype;
264     xcb_generic_event_t *event;
265     xcb_window_t win;
266     xcb_cursor_t cursor;
267     int curs_choice = CURS_NONE;
268     char o;
269     int optind = 0;
270     struct option longopts[] = {
271         {"version", no_argument, NULL, 'v'},
272         {"nofork", no_argument, NULL, 'n'},
273         {"beep", no_argument, NULL, 'b'},
274         {"dpms", no_argument, NULL, 'd'},
275         {"color", required_argument, NULL, 'c'},
276         {"pointer", required_argument, NULL , 'p'},
277 #ifndef NOLIBCAIRO
278         {"image", required_argument, NULL, 'i'},
279         {"tiling", no_argument, NULL, 't'},
280 #endif
281         {NULL, no_argument, NULL, 0}
282     };
283
284     if ((username = getenv("USER")) == NULL)
285         errx(1, "USER environment variable not set, please set it.\n");
286
287     while ((o = getopt_long(argc, argv, "vnbdc:p:"
288 #ifndef NOLIBCAIRO
289         "i:t"
290 #endif
291         , longopts, &optind)) != -1) {
292         switch (o) {
293         case 'v':
294             errx(EXIT_SUCCESS, "version " VERSION " © 2010 Michael Stapelberg\n");
295         case 'n':
296             dont_fork = true;
297             break;
298         case 'b':
299             beep = true;
300             break;
301         case 'd':
302             dpms = true;
303             break;
304         case 'c': {
305             char *arg = optarg;
306
307             /* Skip # if present */
308             if (arg[0] == '#')
309                 arg++;
310
311             if (strlen(arg) != 6 || sscanf(arg, "%06[0-9a-fA-F]", color) != 1)
312                 errx(1, "color is invalid, color must be given in 6-byte format: rrggbb\n");
313
314             break;
315         }
316 #ifndef NOLIBCAIRO
317         case 'i':
318             image_path = strdup(optarg);
319             break;
320         case 't':
321             tile = true;
322             break;
323 #endif
324         case 'p':
325             if (!strcmp(optarg, "win")) {
326                 curs_choice = CURS_WIN;
327             }
328             if (!strcmp(optarg, "default")) {
329                 curs_choice = CURS_DEFAULT;
330             }
331             break;
332         default:
333             errx(1, "i3lock: Unknown option. Syntax: i3lock [-v] [-n] [-b] [-d] [-c color] [-p win|default]"
334 #ifndef NOLIBCAIRO
335             " [-i image.png] [-t]"
336 #else
337             " (compiled with NOLIBCAIRO)"
338 #endif
339             "\n");
340         }
341     }
342
343     /* Initialize PAM */
344     ret = pam_start("i3lock", username, &conv, &pam_handle);
345     if (ret != PAM_SUCCESS)
346         errx(EXIT_FAILURE, "PAM: %s\n", pam_strerror(pam_handle, ret));
347
348     /* Initialize connection to X11 */
349     if ((conn = xcb_connect(NULL, &screen)) == NULL)
350         err(EXIT_FAILURE, "xcb_connect()");
351
352     if (!dont_fork) {
353         /* In the parent process, we exit */
354         if (fork() != 0)
355             return 0;
356     }
357
358     /* if DPMS is enabled, check if the X server really supports it */
359     if (dpms) {
360         xcb_dpms_capable_cookie_t dpmsc = xcb_dpms_capable(conn);
361         xcb_dpms_capable_reply_t *dpmsr;
362         if ((dpmsr = xcb_dpms_capable_reply(conn, dpmsc, NULL)) && !dpmsr->capable) {
363             fprintf(stderr, "Disabling DPMS, X server not DPMS capable\n");
364             dpms = false;
365         }
366     }
367
368     scr = xcb_setup_roots_iterator(xcb_get_setup(conn)).data;
369     vistype = get_root_visual_type(scr);
370
371     /* open the fullscreen window and flush immediately afterwards so that X11
372      * can generate an expose event while we load the PNG file (so that we are
373      * ready to handle the expose event immediately afterwards) */
374     win = open_fullscreen_window(conn, scr, color);
375
376     cursor = create_cursor(conn, scr, win, curs_choice);
377
378     grab_pointer_and_keyboard(conn, scr, cursor);
379
380     symbols = xcb_key_symbols_alloc(conn);
381     modeswitchmask = get_mod_mask(conn, symbols, XK_Mode_switch);
382     numlockmask = get_mod_mask(conn, symbols, XK_Num_Lock);
383
384 #ifndef NOLIBCAIRO
385     if (image_path)
386         img = cairo_image_surface_create_from_png(image_path);
387
388     if (img) {
389         /* Initialize cairo */
390         cairo_surface_t *output;
391         output = cairo_xcb_surface_create(conn, win, vistype,
392                  scr->width_in_pixels, scr->height_in_pixels);
393         ctx = cairo_create(output);
394         if (!tile)
395             cairo_set_source_surface(ctx, img, 0, 0);
396
397         handle_expose_event();
398     }
399 #endif
400
401     if (dpms)
402         dpms_turn_off_screen(conn);
403
404     while ((event = xcb_wait_for_event(conn))) {
405         if (event->response_type == 0)
406             errx(1, "XCB: Invalid event received");
407
408         /* Strip off the highest bit (set if the event is generated) */
409         int type = (event->response_type & 0x7F);
410
411         if (type == XCB_EXPOSE) {
412             handle_expose_event();
413             continue;
414         }
415
416         if (type == XCB_KEY_PRESS) {
417             handle_key_press((xcb_key_press_event_t*)event);
418             continue;
419         }
420
421         if (type == XCB_KEY_RELEASE) {
422             handle_key_release((xcb_key_release_event_t*)event);
423
424             /* If this was the backspace or escape key we are back at an
425              * empty input, so turn off the screen if DPMS is enabled */
426             if (dpms && input_position == 0)
427                 dpms_turn_off_screen(conn);
428
429             continue;
430         }
431
432         if (type == XCB_VISIBILITY_NOTIFY) {
433             handle_visibility_notify((xcb_visibility_notify_event_t*)event);
434             continue;
435         }
436
437         printf("WARNING: unhandled event of type %d\n", type);
438     }
439
440     return 0;
441 }