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