Fix issue detected by static analysis tool
[platform/upstream/libxkbcommon.git] / tools / interactive-evdev.c
1 /*
2  * Copyright © 2012 Ran Benita <ran234@gmail.com>
3  *
4  * Permission is hereby granted, free of charge, to any person obtaining a
5  * copy of this software and associated documentation files (the "Software"),
6  * to deal in the Software without restriction, including without limitation
7  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8  * and/or sell copies of the Software, and to permit persons to whom the
9  * Software is furnished to do so, subject to the following conditions:
10  *
11  * The above copyright notice and this permission notice (including the next
12  * paragraph) shall be included in all copies or substantial portions of the
13  * Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
18  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
20  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
21  * DEALINGS IN THE SOFTWARE.
22  */
23
24 #include "config.h"
25
26 #include <assert.h>
27 #include <dirent.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <fnmatch.h>
31 #include <getopt.h>
32 #include <limits.h>
33 #include <locale.h>
34 #include <poll.h>
35 #include <signal.h>
36 #include <stdbool.h>
37 #include <stdio.h>
38 #include <stdlib.h>
39 #include <string.h>
40 #include <unistd.h>
41
42 #include <linux/input.h>
43
44 #include "xkbcommon/xkbcommon.h"
45
46 #include "tools-common.h"
47
48 struct keyboard {
49     char *path;
50     int fd;
51     struct xkb_state *state;
52     struct xkb_compose_state *compose_state;
53     struct keyboard *next;
54 };
55
56 static bool terminate;
57 static int evdev_offset = 8;
58 static bool report_state_changes;
59 static bool with_compose;
60 static enum xkb_consumed_mode consumed_mode = XKB_CONSUMED_MODE_XKB;
61
62 #ifdef ENABLE_PRIVATE_APIS
63 #define DEFAULT_PRINT_FIELDS (PRINT_ALL_FIELDS & ~PRINT_MODMAPS)
64 #else
65 #define DEFAULT_PRINT_FIELDS PRINT_ALL_FIELDS
66 #endif
67 print_state_fields_mask_t print_fields = DEFAULT_PRINT_FIELDS;
68
69 #define DEFAULT_INCLUDE_PATH_PLACEHOLDER "__defaults__"
70 #define NLONGS(n) (((n) + LONG_BIT - 1) / LONG_BIT)
71
72 static bool
73 evdev_bit_is_set(const unsigned long *array, int bit)
74 {
75     return array[bit / LONG_BIT] & (1LL << (bit % LONG_BIT));
76 }
77
78 /* Some heuristics to see if the device is a keyboard. */
79 static bool
80 is_keyboard(int fd)
81 {
82     int i;
83     unsigned long evbits[NLONGS(EV_CNT)] = { 0 };
84     unsigned long keybits[NLONGS(KEY_CNT)] = { 0 };
85
86     errno = 0;
87     ioctl(fd, EVIOCGBIT(0, sizeof(evbits)), evbits);
88     if (errno)
89         return false;
90
91     if (!evdev_bit_is_set(evbits, EV_KEY))
92         return false;
93
94     errno = 0;
95     ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(keybits)), keybits);
96     if (errno)
97         return false;
98
99     for (i = KEY_RESERVED; i <= KEY_MIN_INTERESTING; i++)
100         if (evdev_bit_is_set(keybits, i))
101             return true;
102
103     return false;
104 }
105
106 static int
107 keyboard_new(struct dirent *ent, struct xkb_keymap *keymap,
108              struct xkb_compose_table *compose_table, struct keyboard **out)
109 {
110     int ret;
111     char *path;
112     int fd;
113     struct xkb_state *state;
114     struct xkb_compose_state *compose_state = NULL;
115     struct keyboard *kbd;
116
117     ret = asprintf(&path, "/dev/input/%s", ent->d_name);
118     if (ret < 0)
119         return -ENOMEM;
120
121     fd = open(path, O_NONBLOCK | O_CLOEXEC | O_RDONLY);
122     if (fd < 0) {
123         ret = -errno;
124         goto err_path;
125     }
126
127     if (!is_keyboard(fd)) {
128         /* Dummy "skip this device" value. */
129         ret = -ENOTSUP;
130         goto err_fd;
131     }
132
133     state = xkb_state_new(keymap);
134     if (!state) {
135         fprintf(stderr, "Couldn't create xkb state for %s\n", path);
136         ret = -EFAULT;
137         goto err_fd;
138     }
139
140     if (with_compose) {
141         compose_state = xkb_compose_state_new(compose_table,
142                                               XKB_COMPOSE_STATE_NO_FLAGS);
143         if (!compose_state) {
144             fprintf(stderr, "Couldn't create compose state for %s\n", path);
145             ret = -EFAULT;
146             goto err_state;
147         }
148     }
149
150     kbd = calloc(1, sizeof(*kbd));
151     if (!kbd) {
152         ret = -ENOMEM;
153         goto err_compose_state;
154     }
155
156     kbd->path = path;
157     kbd->fd = fd;
158     kbd->state = state;
159     kbd->compose_state = compose_state;
160     *out = kbd;
161     return 0;
162
163 err_compose_state:
164     xkb_compose_state_unref(compose_state);
165 err_state:
166     xkb_state_unref(state);
167 err_fd:
168     close(fd);
169 err_path:
170     free(path);
171     return ret;
172 }
173
174 static void
175 keyboard_free(struct keyboard *kbd)
176 {
177     if (!kbd)
178         return;
179     if (kbd->fd >= 0)
180         close(kbd->fd);
181     free(kbd->path);
182     xkb_state_unref(kbd->state);
183     xkb_compose_state_unref(kbd->compose_state);
184     free(kbd);
185 }
186
187 static int
188 filter_device_name(const struct dirent *ent)
189 {
190     return !fnmatch("event*", ent->d_name, 0);
191 }
192
193 static struct keyboard *
194 get_keyboards(struct xkb_keymap *keymap,
195               struct xkb_compose_table *compose_table)
196 {
197     int ret, i, nents;
198     struct dirent **ents;
199     struct keyboard *kbds = NULL, *kbd = NULL;
200
201     nents = scandir("/dev/input", &ents, filter_device_name, alphasort);
202     if (nents < 0) {
203         fprintf(stderr, "Couldn't scan /dev/input: %s\n", strerror(errno));
204         return NULL;
205     }
206
207     for (i = 0; i < nents; i++) {
208         ret = keyboard_new(ents[i], keymap, compose_table, &kbd);
209         if (ret) {
210             if (ret == -EACCES) {
211                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. "
212                                 "You probably need root to run this.\n",
213                         ents[i]->d_name, strerror(-ret));
214                 break;
215             }
216             if (ret != -ENOTSUP) {
217                 fprintf(stderr, "Couldn't open /dev/input/%s: %s. Skipping.\n",
218                         ents[i]->d_name, strerror(-ret));
219             }
220             continue;
221         }
222
223         assert(kbd != NULL);
224         kbd->next = kbds;
225         kbds = kbd;
226     }
227
228     if (!kbds) {
229         fprintf(stderr, "Couldn't find any keyboards I can use! Quitting.\n");
230         goto err;
231     }
232
233 err:
234     for (i = 0; i < nents; i++)
235         free(ents[i]);
236     free(ents);
237     return kbds;
238 }
239
240 static void
241 free_keyboards(struct keyboard *kbds)
242 {
243     struct keyboard *next;
244
245     while (kbds) {
246         next = kbds->next;
247         keyboard_free(kbds);
248         kbds = next;
249     }
250 }
251
252 /* The meaning of the input_event 'value' field. */
253 enum {
254     KEY_STATE_RELEASE = 0,
255     KEY_STATE_PRESS = 1,
256     KEY_STATE_REPEAT = 2,
257 };
258
259 static void
260 process_event(struct keyboard *kbd, uint16_t type, uint16_t code, int32_t value)
261 {
262     xkb_keycode_t keycode;
263     struct xkb_keymap *keymap;
264     enum xkb_state_component changed;
265     enum xkb_compose_status status;
266
267     if (type != EV_KEY)
268         return;
269
270     keycode = evdev_offset + code;
271     keymap = xkb_state_get_keymap(kbd->state);
272
273     if (value == KEY_STATE_REPEAT && !xkb_keymap_key_repeats(keymap, keycode))
274         return;
275
276     if (with_compose && value != KEY_STATE_RELEASE) {
277         xkb_keysym_t keysym = xkb_state_key_get_one_sym(kbd->state, keycode);
278         xkb_compose_state_feed(kbd->compose_state, keysym);
279     }
280
281     if (value != KEY_STATE_RELEASE) {
282         tools_print_keycode_state(
283             kbd->state, kbd->compose_state, keycode,
284             consumed_mode, print_fields
285         );
286     }
287
288     if (with_compose) {
289         status = xkb_compose_state_get_status(kbd->compose_state);
290         if (status == XKB_COMPOSE_CANCELLED || status == XKB_COMPOSE_COMPOSED)
291             xkb_compose_state_reset(kbd->compose_state);
292     }
293
294     if (value == KEY_STATE_RELEASE)
295         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_UP);
296     else
297         changed = xkb_state_update_key(kbd->state, keycode, XKB_KEY_DOWN);
298
299     if (report_state_changes)
300         tools_print_state_changes(changed);
301 }
302
303 static int
304 read_keyboard(struct keyboard *kbd)
305 {
306     ssize_t len;
307     struct input_event evs[16];
308
309     /* No fancy error checking here. */
310     while ((len = read(kbd->fd, &evs, sizeof(evs))) > 0) {
311         const size_t nevs = len / sizeof(struct input_event);
312         for (size_t i = 0; i < nevs; i++)
313             process_event(kbd, evs[i].type, evs[i].code, evs[i].value);
314     }
315
316     if (len < 0 && errno != EWOULDBLOCK) {
317         fprintf(stderr, "Couldn't read %s: %s\n", kbd->path, strerror(errno));
318         return 1;
319     }
320
321     return 0;
322 }
323
324 static int
325 loop(struct keyboard *kbds)
326 {
327     int ret = -1;
328     struct keyboard *kbd;
329     nfds_t nfds, i;
330     struct pollfd *fds = NULL;
331
332     for (kbd = kbds, nfds = 0; kbd; kbd = kbd->next, nfds++) {}
333     fds = calloc(nfds, sizeof(*fds));
334     if (fds == NULL) {
335         fprintf(stderr, "Out of memory");
336         goto out;
337     }
338
339     for (i = 0, kbd = kbds; kbd; kbd = kbd->next, i++) {
340         fds[i].fd = kbd->fd;
341         fds[i].events = POLLIN;
342     }
343
344     while (!terminate) {
345         ret = poll(fds, nfds, -1);
346         if (ret < 0) {
347             if (errno == EINTR)
348                 continue;
349             fprintf(stderr, "Couldn't poll for events: %s\n",
350                     strerror(errno));
351             goto out;
352         }
353
354         for (i = 0, kbd = kbds; kbd; kbd = kbd->next, i++) {
355             if (fds[i].revents != 0) {
356                 ret = read_keyboard(kbd);
357                 if (ret) {
358                     goto out;
359                 }
360             }
361         }
362     }
363
364     ret = 0;
365 out:
366     free(fds);
367     return ret;
368 }
369
370 static void
371 sigintr_handler(int signum)
372 {
373     terminate = true;
374 }
375
376 static void
377 usage(FILE *fp, char *progname)
378 {
379         fprintf(fp, "Usage: %s [--include=<path>] [--include-defaults] "
380                 "[--rules=<rules>] [--model=<model>] [--layout=<layout>] "
381                 "[--variant=<variant>] [--options=<options>]\n",
382                 progname);
383         fprintf(fp, "      or: %s --keymap <path to keymap file>\n",
384                 progname);
385         fprintf(fp, "For both:\n"
386 #ifdef ENABLE_PRIVATE_APIS
387                         "          --print-modmaps (print real & virtual key modmaps)\n"
388 #endif
389                         "          --short (do not print layout nor Unicode keysym translation)\n"
390                         "          --report-state-changes (report changes to the state)\n"
391                         "          --enable-compose (enable Compose)\n"
392                         "          --consumed-mode={xkb|gtk} (select the consumed modifiers mode, default: xkb)\n"
393                         "          --without-x11-offset (don't add X11 keycode offset)\n"
394                     "Other:\n"
395                         "          --help (display this help and exit)\n"
396         );
397 }
398
399 int
400 main(int argc, char *argv[])
401 {
402     int ret = EXIT_FAILURE;
403     struct keyboard *kbds;
404     struct xkb_context *ctx = NULL;
405     struct xkb_keymap *keymap = NULL;
406     struct xkb_compose_table *compose_table = NULL;
407     const char *includes[64];
408     size_t num_includes = 0;
409     const char *rules = NULL;
410     const char *model = NULL;
411     const char *layout = NULL;
412     const char *variant = NULL;
413     const char *options = NULL;
414     const char *keymap_path = NULL;
415     const char *locale;
416     struct sigaction act;
417     enum options {
418         OPT_INCLUDE,
419         OPT_INCLUDE_DEFAULTS,
420         OPT_RULES,
421         OPT_MODEL,
422         OPT_LAYOUT,
423         OPT_VARIANT,
424         OPT_OPTION,
425         OPT_KEYMAP,
426         OPT_WITHOUT_X11_OFFSET,
427         OPT_CONSUMED_MODE,
428         OPT_COMPOSE,
429         OPT_SHORT,
430         OPT_REPORT_STATE,
431 #ifdef ENABLE_PRIVATE_APIS
432         OPT_PRINT_MODMAPS,
433 #endif
434     };
435     static struct option opts[] = {
436         {"help",                 no_argument,            0, 'h'},
437         {"include",              required_argument,      0, OPT_INCLUDE},
438         {"include-defaults",     no_argument,            0, OPT_INCLUDE_DEFAULTS},
439         {"rules",                required_argument,      0, OPT_RULES},
440         {"model",                required_argument,      0, OPT_MODEL},
441         {"layout",               required_argument,      0, OPT_LAYOUT},
442         {"variant",              required_argument,      0, OPT_VARIANT},
443         {"options",              required_argument,      0, OPT_OPTION},
444         {"keymap",               required_argument,      0, OPT_KEYMAP},
445         {"consumed-mode",        required_argument,      0, OPT_CONSUMED_MODE},
446         {"enable-compose",       no_argument,            0, OPT_COMPOSE},
447         {"short",                no_argument,            0, OPT_SHORT},
448         {"report-state-changes", no_argument,            0, OPT_REPORT_STATE},
449         {"without-x11-offset",   no_argument,            0, OPT_WITHOUT_X11_OFFSET},
450 #ifdef ENABLE_PRIVATE_APIS
451         {"print-modmaps",        no_argument,            0, OPT_PRINT_MODMAPS},
452 #endif
453         {0, 0, 0, 0},
454     };
455
456     setlocale(LC_ALL, "");
457
458     while (1) {
459         int opt;
460         int option_index = 0;
461
462         opt = getopt_long(argc, argv, "h", opts, &option_index);
463         if (opt == -1)
464             break;
465
466         switch (opt) {
467         case OPT_INCLUDE:
468             if (num_includes >= ARRAY_SIZE(includes)) {
469                 fprintf(stderr, "error: too many includes\n");
470                 exit(EXIT_INVALID_USAGE);
471             }
472             includes[num_includes++] = optarg;
473             break;
474         case OPT_INCLUDE_DEFAULTS:
475             if (num_includes >= ARRAY_SIZE(includes)) {
476                 fprintf(stderr, "error: too many includes\n");
477                 exit(EXIT_INVALID_USAGE);
478             }
479             includes[num_includes++] = DEFAULT_INCLUDE_PATH_PLACEHOLDER;
480             break;
481         case OPT_RULES:
482             rules = optarg;
483             break;
484         case OPT_MODEL:
485             model = optarg;
486             break;
487         case OPT_LAYOUT:
488             layout = optarg;
489             break;
490         case OPT_VARIANT:
491             variant = optarg;
492             break;
493         case OPT_OPTION:
494             options = optarg;
495             break;
496         case OPT_KEYMAP:
497             keymap_path = optarg;
498             break;
499         case OPT_WITHOUT_X11_OFFSET:
500             evdev_offset = 0;
501             break;
502         case OPT_REPORT_STATE:
503             report_state_changes = true;
504             break;
505         case OPT_COMPOSE:
506             with_compose = true;
507             break;
508         case OPT_SHORT:
509             print_fields &= ~PRINT_VERBOSE_FIELDS;
510             break;
511         case OPT_CONSUMED_MODE:
512             if (strcmp(optarg, "gtk") == 0) {
513                 consumed_mode = XKB_CONSUMED_MODE_GTK;
514             } else if (strcmp(optarg, "xkb") == 0) {
515                 consumed_mode = XKB_CONSUMED_MODE_XKB;
516             } else {
517                 fprintf(stderr, "error: invalid --consumed-mode \"%s\"\n", optarg);
518                 usage(stderr, argv[0]);
519                 return EXIT_INVALID_USAGE;
520             }
521             break;
522 #ifdef ENABLE_PRIVATE_APIS
523         case OPT_PRINT_MODMAPS:
524             print_fields |= PRINT_MODMAPS;
525             break;
526 #endif
527         case 'h':
528             usage(stdout, argv[0]);
529             return EXIT_SUCCESS;
530         case '?':
531             usage(stderr, argv[0]);
532             return EXIT_INVALID_USAGE;
533         }
534     }
535
536     ctx = xkb_context_new(XKB_CONTEXT_NO_DEFAULT_INCLUDES);
537     if (!ctx) {
538         fprintf(stderr, "Couldn't create xkb context\n");
539         goto out;
540     }
541
542     if (num_includes == 0)
543         includes[num_includes++] = DEFAULT_INCLUDE_PATH_PLACEHOLDER;
544
545     for (size_t i = 0; i < num_includes; i++) {
546         const char *include = includes[i];
547         if (strcmp(include, DEFAULT_INCLUDE_PATH_PLACEHOLDER) == 0)
548             xkb_context_include_path_append_default(ctx);
549         else
550             xkb_context_include_path_append(ctx, include);
551     }
552
553     if (keymap_path) {
554         FILE *file = fopen(keymap_path, "rb");
555         if (!file) {
556             fprintf(stderr, "Couldn't open '%s': %s\n",
557                     keymap_path, strerror(errno));
558             goto out;
559         }
560         keymap = xkb_keymap_new_from_file(ctx, file,
561                                           XKB_KEYMAP_FORMAT_TEXT_V1,
562                                           XKB_KEYMAP_COMPILE_NO_FLAGS);
563         fclose(file);
564     }
565     else {
566         struct xkb_rule_names rmlvo = {
567             .rules = (rules == NULL || rules[0] == '\0') ? NULL : rules,
568             .model = (model == NULL || model[0] == '\0') ? NULL : model,
569             .layout = (layout == NULL || layout[0] == '\0') ? NULL : layout,
570             .variant = (variant == NULL || variant[0] == '\0') ? NULL : variant,
571             .options = (options == NULL || options[0] == '\0') ? NULL : options
572         };
573
574         if (!rules && !model && !layout && !variant && !options)
575             keymap = xkb_keymap_new_from_names(ctx, NULL, 0);
576         else
577             keymap = xkb_keymap_new_from_names(ctx, &rmlvo, 0);
578
579         if (!keymap) {
580             fprintf(stderr,
581                     "Failed to compile RMLVO: '%s', '%s', '%s', '%s', '%s'\n",
582                     rules, model, layout, variant, options);
583             goto out;
584         }
585     }
586
587     if (!keymap) {
588         fprintf(stderr, "Couldn't create xkb keymap\n");
589         goto out;
590     }
591
592     if (with_compose) {
593         locale = setlocale(LC_CTYPE, NULL);
594         compose_table =
595             xkb_compose_table_new_from_locale(ctx, locale,
596                                               XKB_COMPOSE_COMPILE_NO_FLAGS);
597         if (!compose_table) {
598             fprintf(stderr, "Couldn't create compose from locale\n");
599             goto out;
600         }
601     }
602
603     kbds = get_keyboards(keymap, compose_table);
604     if (!kbds) {
605         goto out;
606     }
607
608 #ifdef ENABLE_PRIVATE_APIS
609     if (print_fields & PRINT_MODMAPS) {
610         print_keys_modmaps(keymap);
611         putchar('\n');
612         print_keymap_modmaps(keymap);
613         putchar('\n');
614     }
615 #endif
616
617     act.sa_handler = sigintr_handler;
618     sigemptyset(&act.sa_mask);
619     act.sa_flags = 0;
620     sigaction(SIGINT, &act, NULL);
621     sigaction(SIGTERM, &act, NULL);
622
623     tools_disable_stdin_echo();
624     ret = loop(kbds);
625     tools_enable_stdin_echo();
626
627     free_keyboards(kbds);
628 out:
629     xkb_compose_table_unref(compose_table);
630     xkb_keymap_unref(keymap);
631     xkb_context_unref(ctx);
632
633     return ret;
634 }