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