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