• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: MIT
2 /*
3  * Copyright © 2013 Red Hat, Inc.
4  */
5 
6 #include "config.h"
7 #include <errno.h>
8 #include <limits.h>
9 #include <poll.h>
10 #include <stdarg.h>
11 #include <stdbool.h>
12 #include <stdint.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16 
17 #include "libevdev-int.h"
18 #include "libevdev-util.h"
19 #include "libevdev.h"
20 
21 #include "event-names.h"
22 
23 #define MAXEVENTS 64
24 
25 enum event_filter_status {
26 	EVENT_FILTER_NONE,	/**< Event untouched by filters */
27 	EVENT_FILTER_MODIFIED,	/**< Event was modified */
28 	EVENT_FILTER_DISCARD,	/**< Discard current event */
29 };
30 
31 /* Keeps a record of touches during SYN_DROPPED  */
32 enum touch_state {
33 	TOUCH_OFF,
34 	TOUCH_STARTED, /* Started during SYN_DROPPED */
35 	TOUCH_STOPPED, /* Stopped during SYN_DROPPED */
36 	TOUCH_ONGOING, /* Existed before, still have same tracking ID */
37 	TOUCH_CHANGED, /* Existed before but have new tracking ID now, so
38 			  stopped + started in that slot */
39 };
40 
41 struct slot_change_state {
42 	enum touch_state state;
43 	unsigned long axes[NLONGS(ABS_CNT)]; /* bitmask for updated axes */
44 };
45 
46 static int sync_mt_state(struct libevdev *dev,
47 			 struct slot_change_state changes_out[dev->num_slots]);
48 
49 static int
50 update_key_state(struct libevdev *dev, const struct input_event *e);
51 
52 static inline int*
slot_value(const struct libevdev * dev,int slot,int axis)53 slot_value(const struct libevdev *dev, int slot, int axis)
54 {
55 	if (unlikely(slot > dev->num_slots)) {
56 		log_bug(dev, "Slot %d exceeds number of slots (%d)\n", slot, dev->num_slots);
57 		slot = 0;
58 	}
59 	if (unlikely(axis < ABS_MT_MIN || axis > ABS_MT_MAX)) {
60 		log_bug(dev, "MT axis %d is outside the valid range [%d,%d]\n",
61 			axis, ABS_MT_MIN, ABS_MT_MAX);
62 		axis = ABS_MT_MIN;
63 	}
64 	return &dev->mt_slot_vals[slot * ABS_MT_CNT + axis - ABS_MT_MIN];
65 }
66 
67 static int
init_event_queue(struct libevdev * dev)68 init_event_queue(struct libevdev *dev)
69 {
70 	const int MIN_QUEUE_SIZE = 256;
71 	int nevents = 1; /* terminating SYN_REPORT */
72 	int nslots;
73 	unsigned int type, code;
74 
75 	/* count the number of axes, keys, etc. to get a better idea at how
76 	   many events per EV_SYN we could possibly get. That's the max we
77 	   may get during SYN_DROPPED too. Use double that, just so we have
78 	   room for events while syncing a device.
79 	 */
80 	for (type = EV_KEY; type < EV_MAX; type++) {
81 		int max = libevdev_event_type_get_max(type);
82 		for (code = 0; max > 0 && code < (unsigned int) max; code++) {
83 			if (libevdev_has_event_code(dev, type, code))
84 				nevents++;
85 		}
86 	}
87 
88 	nslots = libevdev_get_num_slots(dev);
89 	if (nslots > 1) {
90 		int num_mt_axes = 0;
91 
92 		for (code = ABS_MT_SLOT; code <= ABS_MAX; code++) {
93 			if (libevdev_has_event_code(dev, EV_ABS, code))
94 				num_mt_axes++;
95 		}
96 
97 		/* We already counted the first slot in the initial count */
98 		nevents += num_mt_axes * (nslots - 1);
99 	}
100 
101 	return queue_alloc(dev, max(MIN_QUEUE_SIZE, nevents * 2));
102 }
103 
104 static void
libevdev_dflt_log_func(enum libevdev_log_priority priority,void * data,const char * file,int line,const char * func,const char * format,va_list args)105 libevdev_dflt_log_func(enum libevdev_log_priority priority,
106 		       void *data,
107 		       const char *file, int line, const char *func,
108 		       const char *format, va_list args)
109 {
110 	const char *prefix;
111 	switch(priority) {
112 		case LIBEVDEV_LOG_ERROR: prefix = "libevdev error"; break;
113 		case LIBEVDEV_LOG_INFO: prefix = "libevdev info"; break;
114 		case LIBEVDEV_LOG_DEBUG:
115 					prefix = "libevdev debug";
116 					break;
117 		default:
118 					prefix = "libevdev INVALID LOG PRIORITY";
119 					break;
120 	}
121 	/* default logging format:
122 	   libevev error in libevdev_some_func: blah blah
123 	   libevev info in libevdev_some_func: blah blah
124 	   libevev debug in file.c:123:libevdev_some_func: blah blah
125 	 */
126 
127 	fprintf(stderr, "%s in ", prefix);
128 	if (priority == LIBEVDEV_LOG_DEBUG)
129 		fprintf(stderr, "%s:%d:", file, line);
130 	fprintf(stderr, "%s: ", func);
131 	vfprintf(stderr, format, args);
132 }
133 
134 static void
fix_invalid_absinfo(const struct libevdev * dev,int axis,struct input_absinfo * abs_info)135 fix_invalid_absinfo(const struct libevdev *dev,
136 		    int axis,
137 		    struct input_absinfo* abs_info)
138 {
139 	/*
140 	 * The reported absinfo for ABS_MT_TRACKING_ID is sometimes
141 	 * uninitialized for certain mtk-soc, due to init code mangling
142 	 * in the vendor kernel.
143 	 */
144 	if (axis == ABS_MT_TRACKING_ID &&
145 	    abs_info->maximum == abs_info->minimum) {
146 		abs_info->minimum = -1;
147 		abs_info->maximum = 0xFFFF;
148 		log_bug(dev,
149 			"Device \"%s\" has invalid ABS_MT_TRACKING_ID range",
150 			dev->name);
151 	}
152 }
153 
154 /*
155  * Global logging settings.
156  */
157 static struct logdata log_data = {
158 	.priority = LIBEVDEV_LOG_INFO,
159 	.global_handler = libevdev_dflt_log_func,
160 	.userdata = NULL,
161 };
162 
163 void
_libevdev_log_msg(const struct libevdev * dev,enum libevdev_log_priority priority,const char * file,int line,const char * func,const char * format,...)164 _libevdev_log_msg(const struct libevdev *dev,
165 		  enum libevdev_log_priority priority,
166 		  const char *file, int line, const char *func,
167 		  const char *format, ...)
168 {
169 	va_list args;
170 
171 	if (dev && dev->log.device_handler) {
172 		/**
173 		 * if both global handler and device handler are set
174 		 * we've set up the handlers wrong.  And that means we'll
175 		 * likely get the printf args wrong and cause all sorts of
176 		 * mayhem. Seppuku is called for.
177 		 */
178 		if (unlikely(dev->log.global_handler))
179 			abort();
180 
181 		if (priority > dev->log.priority)
182 			return;
183 	} else if (!log_data.global_handler || priority > log_data.priority) {
184 		return;
185 	} else if (unlikely(log_data.device_handler)) {
186 		abort(); /* Seppuku, see above */
187 	}
188 
189 	va_start(args, format);
190 	if (dev && dev->log.device_handler)
191 		dev->log.device_handler(dev, priority, dev->log.userdata, file, line, func, format, args);
192 	else
193 		log_data.global_handler(priority, log_data.userdata, file, line, func, format, args);
194 	va_end(args);
195 }
196 
197 static void
libevdev_reset(struct libevdev * dev)198 libevdev_reset(struct libevdev *dev)
199 {
200 	enum libevdev_log_priority pri = dev->log.priority;
201 	libevdev_device_log_func_t handler = dev->log.device_handler;
202 
203 	free(dev->name);
204 	free(dev->phys);
205 	free(dev->uniq);
206 	free(dev->mt_slot_vals);
207 	memset(dev, 0, sizeof(*dev));
208 	dev->fd = -1;
209 	dev->initialized = false;
210 	dev->num_slots = -1;
211 	dev->current_slot = -1;
212 	dev->grabbed = LIBEVDEV_UNGRAB;
213 	dev->sync_state = SYNC_NONE;
214 	dev->log.priority = pri;
215 	dev->log.device_handler = handler;
216 	libevdev_enable_event_type(dev, EV_SYN);
217 }
218 
219 LIBEVDEV_EXPORT struct libevdev*
libevdev_new(void)220 libevdev_new(void)
221 {
222 	struct libevdev *dev;
223 
224 	dev = calloc(1, sizeof(*dev));
225 	if (!dev)
226 		return NULL;
227 
228 	libevdev_reset(dev);
229 
230 	return dev;
231 }
232 
233 LIBEVDEV_EXPORT int
libevdev_new_from_fd(int fd,struct libevdev ** dev)234 libevdev_new_from_fd(int fd, struct libevdev **dev)
235 {
236 	struct libevdev *d;
237 	int rc;
238 
239 	d = libevdev_new();
240 	if (!d)
241 		return -ENOMEM;
242 
243 	rc = libevdev_set_fd(d, fd);
244 	if (rc < 0)
245 		libevdev_free(d);
246 	else
247 		*dev = d;
248 	return rc;
249 }
250 
251 LIBEVDEV_EXPORT void
libevdev_free(struct libevdev * dev)252 libevdev_free(struct libevdev *dev)
253 {
254 	if (!dev)
255 		return;
256 
257 	queue_free(dev);
258 	libevdev_reset(dev);
259 	free(dev);
260 }
261 
262 LIBEVDEV_EXPORT void
libevdev_set_log_function(libevdev_log_func_t logfunc,void * data)263 libevdev_set_log_function(libevdev_log_func_t logfunc, void *data)
264 {
265 	log_data.global_handler = logfunc;
266 	log_data.userdata = data;
267 }
268 
269 LIBEVDEV_EXPORT void
libevdev_set_log_priority(enum libevdev_log_priority priority)270 libevdev_set_log_priority(enum libevdev_log_priority priority)
271 {
272 	if (priority > LIBEVDEV_LOG_DEBUG)
273 		priority = LIBEVDEV_LOG_DEBUG;
274 	log_data.priority = priority;
275 }
276 
277 LIBEVDEV_EXPORT enum libevdev_log_priority
libevdev_get_log_priority(void)278 libevdev_get_log_priority(void)
279 {
280 	return log_data.priority;
281 }
282 
283 LIBEVDEV_EXPORT void
libevdev_set_device_log_function(struct libevdev * dev,libevdev_device_log_func_t logfunc,enum libevdev_log_priority priority,void * data)284 libevdev_set_device_log_function(struct libevdev *dev,
285 				 libevdev_device_log_func_t logfunc,
286 				 enum libevdev_log_priority priority,
287 				 void *data)
288 {
289 	if (!dev) {
290 		log_bug(NULL, "device must not be NULL\n");
291 		return;
292 	}
293 
294 	dev->log.priority = priority;
295 	dev->log.device_handler = logfunc;
296 	dev->log.userdata = data;
297 }
298 
299 enum libevdev_log_priority
_libevdev_log_priority(const struct libevdev * dev)300 _libevdev_log_priority(const struct libevdev *dev)
301 {
302 	if (dev && dev->log.device_handler)
303 		return dev->log.priority;
304 	return libevdev_get_log_priority();
305 }
306 
307 LIBEVDEV_EXPORT int
libevdev_change_fd(struct libevdev * dev,int fd)308 libevdev_change_fd(struct libevdev *dev, int fd)
309 {
310 	if (!dev->initialized) {
311 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
312 		return -1;
313 	}
314 	dev->fd = fd;
315 	dev->grabbed = LIBEVDEV_UNGRAB;
316 	return 0;
317 }
318 
319 static void
reset_tracking_ids(struct libevdev * dev)320 reset_tracking_ids(struct libevdev *dev)
321 {
322 	if (dev->num_slots == -1 ||
323 	    !libevdev_has_event_code(dev, EV_ABS, ABS_MT_TRACKING_ID))
324 		return;
325 
326 	for (int slot = 0; slot < dev->num_slots; slot++)
327 		libevdev_set_slot_value(dev, slot, ABS_MT_TRACKING_ID, -1);
328 }
329 
330 static inline void
free_slots(struct libevdev * dev)331 free_slots(struct libevdev *dev)
332 {
333 	dev->num_slots = -1;
334 	free(dev->mt_slot_vals);
335 	dev->mt_slot_vals = NULL;
336 }
337 
338 static int
init_slots(struct libevdev * dev)339 init_slots(struct libevdev *dev)
340 {
341 	const struct input_absinfo *abs_info;
342 	int rc = 0;
343 
344 	free(dev->mt_slot_vals);
345 	dev->mt_slot_vals = NULL;
346 
347 	/* devices with ABS_RESERVED aren't MT devices,
348 	   see the documentation for multitouch-related
349 	   functions for more details */
350 	if (libevdev_has_event_code(dev, EV_ABS, ABS_RESERVED) ||
351 	    !libevdev_has_event_code(dev, EV_ABS, ABS_MT_SLOT)) {
352 		if (dev->num_slots != -1) {
353 			free_slots(dev);
354 		}
355 		return rc;
356 	}
357 
358 	abs_info = libevdev_get_abs_info(dev, ABS_MT_SLOT);
359 
360 	free_slots(dev);
361 	dev->num_slots = abs_info->maximum + 1;
362 	dev->mt_slot_vals = calloc(dev->num_slots * ABS_MT_CNT, sizeof(int));
363 	if (!dev->mt_slot_vals) {
364 		rc = -ENOMEM;
365 		goto out;
366 	}
367 	dev->current_slot = abs_info->value;
368 
369 	reset_tracking_ids(dev);
370 out:
371 	return rc;
372 }
373 
374 LIBEVDEV_EXPORT int
libevdev_set_fd(struct libevdev * dev,int fd)375 libevdev_set_fd(struct libevdev* dev, int fd)
376 {
377 	int rc;
378 	int i;
379 	char buf[256];
380 
381 	if (dev->initialized) {
382 		log_bug(dev, "device already initialized.\n");
383 		return -EBADF;
384 	}
385 
386 	if (fd < 0) {
387 		return -EBADF;
388 	}
389 
390 	libevdev_reset(dev);
391 
392 	rc = ioctl(fd, EVIOCGBIT(0, sizeof(dev->bits)), dev->bits);
393 	if (rc < 0)
394 		goto out;
395 
396 	memset(buf, 0, sizeof(buf));
397 	rc = ioctl(fd, EVIOCGNAME(sizeof(buf) - 1), buf);
398 	if (rc < 0)
399 		goto out;
400 
401 	free(dev->name);
402 	dev->name = strdup(buf);
403 	if (!dev->name) {
404 		errno = ENOMEM;
405 		goto out;
406 	}
407 
408 	free(dev->phys);
409 	dev->phys = NULL;
410 	memset(buf, 0, sizeof(buf));
411 	rc = ioctl(fd, EVIOCGPHYS(sizeof(buf) - 1), buf);
412 	if (rc < 0) {
413 		/* uinput has no phys */
414 		if (errno != ENOENT)
415 			goto out;
416 	} else {
417 		dev->phys = strdup(buf);
418 		if (!dev->phys) {
419 			errno = ENOMEM;
420 			goto out;
421 		}
422 	}
423 
424 	free(dev->uniq);
425 	dev->uniq = NULL;
426 	memset(buf, 0, sizeof(buf));
427 	rc = ioctl(fd, EVIOCGUNIQ(sizeof(buf) - 1), buf);
428 	if (rc < 0) {
429 		if (errno != ENOENT)
430 			goto out;
431 	} else  {
432 		dev->uniq = strdup(buf);
433 		if (!dev->uniq) {
434 			errno = ENOMEM;
435 			goto out;
436 		}
437 	}
438 
439 	rc = ioctl(fd, EVIOCGID, &dev->ids);
440 	if (rc < 0)
441 		goto out;
442 
443 	rc = ioctl(fd, EVIOCGVERSION, &dev->driver_version);
444 	if (rc < 0)
445 		goto out;
446 
447 	/* Built on a kernel with props, running against a kernel without property
448 	   support. This should not be a fatal case, we'll be missing properties but other
449 	   than that everything is as expected.
450 	 */
451 	rc = ioctl(fd, EVIOCGPROP(sizeof(dev->props)), dev->props);
452 	if (rc < 0 && errno != EINVAL)
453 		goto out;
454 
455 	rc = ioctl(fd, EVIOCGBIT(EV_REL, sizeof(dev->rel_bits)), dev->rel_bits);
456 	if (rc < 0)
457 		goto out;
458 
459 	rc = ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(dev->abs_bits)), dev->abs_bits);
460 	if (rc < 0)
461 		goto out;
462 
463 	rc = ioctl(fd, EVIOCGBIT(EV_LED, sizeof(dev->led_bits)), dev->led_bits);
464 	if (rc < 0)
465 		goto out;
466 
467 	rc = ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(dev->key_bits)), dev->key_bits);
468 	if (rc < 0)
469 		goto out;
470 
471 	rc = ioctl(fd, EVIOCGBIT(EV_SW, sizeof(dev->sw_bits)), dev->sw_bits);
472 	if (rc < 0)
473 		goto out;
474 
475 	rc = ioctl(fd, EVIOCGBIT(EV_MSC, sizeof(dev->msc_bits)), dev->msc_bits);
476 	if (rc < 0)
477 		goto out;
478 
479 	rc = ioctl(fd, EVIOCGBIT(EV_FF, sizeof(dev->ff_bits)), dev->ff_bits);
480 	if (rc < 0)
481 		goto out;
482 
483 	rc = ioctl(fd, EVIOCGBIT(EV_SND, sizeof(dev->snd_bits)), dev->snd_bits);
484 	if (rc < 0)
485 		goto out;
486 
487 	rc = ioctl(fd, EVIOCGKEY(sizeof(dev->key_values)), dev->key_values);
488 	if (rc < 0)
489 		goto out;
490 
491 	rc = ioctl(fd, EVIOCGLED(sizeof(dev->led_values)), dev->led_values);
492 	if (rc < 0)
493 		goto out;
494 
495 	rc = ioctl(fd, EVIOCGSW(sizeof(dev->sw_values)), dev->sw_values);
496 	if (rc < 0)
497 		goto out;
498 
499 	/* rep is a special case, always set it to 1 for both values if EV_REP is set */
500 	if (bit_is_set(dev->bits, EV_REP)) {
501 		for (i = 0; i < REP_CNT; i++)
502 			set_bit(dev->rep_bits, i);
503 		rc = ioctl(fd, EVIOCGREP, dev->rep_values);
504 		if (rc < 0)
505 			goto out;
506 	}
507 
508 	for (i = ABS_X; i <= ABS_MAX; i++) {
509 		if (bit_is_set(dev->abs_bits, i)) {
510 			struct input_absinfo abs_info;
511 			rc = ioctl(fd, EVIOCGABS(i), &abs_info);
512 			if (rc < 0)
513 				goto out;
514 
515 			fix_invalid_absinfo(dev, i, &abs_info);
516 
517 			dev->abs_info[i] = abs_info;
518 		}
519 	}
520 
521 	dev->fd = fd;
522 
523 	rc = init_slots(dev);
524 	if (rc != 0)
525 		goto out;
526 
527 	if (dev->num_slots != -1) {
528 		struct slot_change_state unused[dev->num_slots];
529 		sync_mt_state(dev, unused);
530 	}
531 
532 	rc = init_event_queue(dev);
533 	if (rc < 0) {
534 		dev->fd = -1;
535 		return -rc;
536 	}
537 
538 	/* not copying key state because we won't know when we'll start to
539 	 * use this fd and key's are likely to change state by then.
540 	 * Same with the valuators, really, but they may not change.
541 	 */
542 
543 	dev->initialized = true;
544 out:
545 	if (rc)
546 		libevdev_reset(dev);
547 	return rc ? -errno : 0;
548 }
549 
550 LIBEVDEV_EXPORT int
libevdev_get_fd(const struct libevdev * dev)551 libevdev_get_fd(const struct libevdev* dev)
552 {
553 	return dev->fd;
554 }
555 
556 static int
sync_key_state(struct libevdev * dev)557 sync_key_state(struct libevdev *dev)
558 {
559 	int rc;
560 	int i;
561 	unsigned long keystate[NLONGS(KEY_CNT)] = {0};
562 
563 	rc = ioctl(dev->fd, EVIOCGKEY(sizeof(keystate)), keystate);
564 	if (rc < 0)
565 		goto out;
566 
567 	for (i = 0; i < KEY_CNT; i++) {
568 		int old, new;
569 		old = bit_is_set(dev->key_values, i);
570 		new = bit_is_set(keystate, i);
571 		if (old ^ new)
572 			queue_push_event(dev, EV_KEY, i, new ? 1 : 0);
573 	}
574 
575 	memcpy(dev->key_values, keystate, rc);
576 
577 	rc = 0;
578 out:
579 	return rc ? -errno : 0;
580 }
581 
582 static int
sync_sw_state(struct libevdev * dev)583 sync_sw_state(struct libevdev *dev)
584 {
585 	int rc;
586 	int i;
587 	unsigned long swstate[NLONGS(SW_CNT)] = {0};
588 
589 	rc = ioctl(dev->fd, EVIOCGSW(sizeof(swstate)), swstate);
590 	if (rc < 0)
591 		goto out;
592 
593 	for (i = 0; i < SW_CNT; i++) {
594 		int old, new;
595 		old = bit_is_set(dev->sw_values, i);
596 		new = bit_is_set(swstate, i);
597 		if (old ^ new)
598 			queue_push_event(dev, EV_SW, i, new ? 1 : 0);
599 	}
600 
601 	memcpy(dev->sw_values, swstate, rc);
602 
603 	rc = 0;
604 out:
605 	return rc ? -errno : 0;
606 }
607 
608 static int
sync_led_state(struct libevdev * dev)609 sync_led_state(struct libevdev *dev)
610 {
611 	int rc;
612 	int i;
613 	unsigned long ledstate[NLONGS(LED_CNT)] = {0};
614 
615 	rc = ioctl(dev->fd, EVIOCGLED(sizeof(ledstate)), ledstate);
616 	if (rc < 0)
617 		goto out;
618 
619 	for (i = 0; i < LED_CNT; i++) {
620 		int old, new;
621 		old = bit_is_set(dev->led_values, i);
622 		new = bit_is_set(ledstate, i);
623 		if (old ^ new) {
624 			queue_push_event(dev, EV_LED, i, new ? 1 : 0);
625 		}
626 	}
627 
628 	memcpy(dev->led_values, ledstate, rc);
629 
630 	rc = 0;
631 out:
632 	return rc ? -errno : 0;
633 }
634 static int
sync_abs_state(struct libevdev * dev)635 sync_abs_state(struct libevdev *dev)
636 {
637 	int rc;
638 	int i;
639 
640 	for (i = ABS_X; i < ABS_CNT; i++) {
641 		struct input_absinfo abs_info;
642 
643 		if (i >= ABS_MT_MIN && i <= ABS_MT_MAX)
644 			continue;
645 
646 		if (!bit_is_set(dev->abs_bits, i))
647 			continue;
648 
649 		rc = ioctl(dev->fd, EVIOCGABS(i), &abs_info);
650 		if (rc < 0)
651 			goto out;
652 
653 		if (dev->abs_info[i].value != abs_info.value) {
654 			queue_push_event(dev, EV_ABS, i, abs_info.value);
655 			dev->abs_info[i].value = abs_info.value;
656 		}
657 	}
658 
659 	rc = 0;
660 out:
661 	return rc ? -errno : 0;
662 }
663 
664 static int
sync_mt_state(struct libevdev * dev,struct slot_change_state changes_out[dev->num_slots])665 sync_mt_state(struct libevdev *dev,
666 	      struct slot_change_state changes_out[dev->num_slots])
667 {
668 #define MAX_SLOTS 256
669 	int rc = 0;
670 	struct slot_change_state changes[MAX_SLOTS] = {0};
671 	unsigned int nslots = min(MAX_SLOTS, dev->num_slots);
672 
673 	for (int axis = ABS_MT_MIN; axis <= ABS_MT_MAX; axis++) {
674 		/* EVIOCGMTSLOTS required format */
675 		struct mt_sync_state {
676 			uint32_t code;
677 			int32_t val[MAX_SLOTS];
678 		} mt_state;
679 
680 		if (axis == ABS_MT_SLOT ||
681 		    !libevdev_has_event_code(dev, EV_ABS, axis))
682 			continue;
683 
684 		mt_state.code = axis;
685 		rc = ioctl(dev->fd, EVIOCGMTSLOTS(sizeof(mt_state)), &mt_state);
686 		if (rc < 0)
687 			goto out;
688 
689 		for (unsigned int slot = 0; slot < nslots; slot++) {
690 			int val_before = *slot_value(dev, slot, axis),
691 			    val_after = mt_state.val[slot];
692 
693 			if (axis == ABS_MT_TRACKING_ID) {
694 				if (val_before == -1 && val_after != -1) {
695 					changes[slot].state = TOUCH_STARTED;
696 				} else if (val_before != -1 && val_after == -1) {
697 					changes[slot].state = TOUCH_STOPPED;
698 				} else if (val_before != -1 && val_after != -1 &&
699 					   val_before == val_after) {
700 					changes[slot].state = TOUCH_ONGOING;
701 				} else if (val_before != -1 && val_after != -1 &&
702 					   val_before != val_after) {
703 					changes[slot].state = TOUCH_CHANGED;
704 				} else {
705 					changes[slot].state = TOUCH_OFF;
706 				}
707 			}
708 
709 			if (val_before == val_after)
710 				continue;
711 
712 			*slot_value(dev, slot, axis) = val_after;
713 
714 			set_bit(changes[slot].axes, axis);
715 			/* note that this slot has updates */
716 			set_bit(changes[slot].axes, ABS_MT_SLOT);
717 		}
718 	}
719 
720 	if (dev->num_slots > MAX_SLOTS)
721 		memset(changes_out, 0, sizeof(*changes) * dev->num_slots);
722 
723 	memcpy(changes_out, changes, sizeof(*changes) * nslots);
724 out:
725 	return rc;
726 }
727 
728 static void
terminate_slots(struct libevdev * dev,const struct slot_change_state changes[dev->num_slots],int * last_reported_slot)729 terminate_slots(struct libevdev *dev,
730 		const struct slot_change_state changes[dev->num_slots],
731 		int *last_reported_slot)
732 {
733 	const unsigned int map[] = {BTN_TOOL_FINGER, BTN_TOOL_DOUBLETAP,
734 				    BTN_TOOL_TRIPLETAP, BTN_TOOL_QUADTAP,
735 				    BTN_TOOL_QUINTTAP};
736 	bool touches_stopped = false;
737 	int ntouches_before = 0, ntouches_after = 0;
738 
739 	/* For BTN_TOOL_* emulation, we need to know how many touches we had
740 	 * before and how many we have left once we terminate all the ones
741 	 * that changed and all the ones that stopped.
742 	 */
743 	for (int slot = 0; slot < dev->num_slots;  slot++) {
744 		switch(changes[slot].state) {
745 		case TOUCH_OFF:
746 			break;
747 		case TOUCH_CHANGED:
748 		case TOUCH_STOPPED:
749 			queue_push_event(dev, EV_ABS, ABS_MT_SLOT, slot);
750 			queue_push_event(dev, EV_ABS, ABS_MT_TRACKING_ID, -1);
751 
752 			*last_reported_slot = slot;
753 			touches_stopped = true;
754 			ntouches_before++;
755 			break;
756 		case TOUCH_ONGOING:
757 			ntouches_before++;
758 			ntouches_after++;
759 			break;
760 		case TOUCH_STARTED:
761 			break;
762 		}
763 	}
764 
765 	/* If any of the touches stopped, we need to split the sync state
766 	   into two frames - one with all the stopped touches, one with the
767 	   new touches starting (if any) */
768 	if (touches_stopped) {
769 		/* Send through the required BTN_TOOL_ 0 and 1 events for
770 		 * the previous and current number of fingers. And update
771 		 * our own key state accordingly, so that during the second
772 		 * sync event frame sync_key_state() sets everything correctly
773 		 * for the *real* number of touches.
774 		 */
775 		if (ntouches_before > 0 && ntouches_before <= 5) {
776 			struct input_event ev = {
777 				.type = EV_KEY,
778 				.code = map[ntouches_before - 1],
779 				.value = 0,
780 			};
781 			queue_push_event(dev, ev.type, ev.code, ev.value);
782 			update_key_state(dev, &ev);
783 		}
784 
785 		if (ntouches_after > 0 && ntouches_after <= 5) {
786 			struct input_event ev = {
787 				.type = EV_KEY,
788 				.code = map[ntouches_after - 1],
789 				.value = 1,
790 			};
791 			queue_push_event(dev, ev.type, ev.code, ev.value);
792 			update_key_state(dev, &ev);
793 		}
794 
795 		queue_push_event(dev, EV_SYN, SYN_REPORT, 0);
796 	}
797 }
798 
799 static int
push_mt_sync_events(struct libevdev * dev,const struct slot_change_state changes[dev->num_slots],int last_reported_slot)800 push_mt_sync_events(struct libevdev *dev,
801 		    const struct slot_change_state changes[dev->num_slots],
802 		    int last_reported_slot)
803 {
804 	struct input_absinfo abs_info;
805 	int rc;
806 
807 	for (int slot = 0; slot < dev->num_slots;  slot++) {
808 		/* stopped touches were already terminated in
809 		 * terminate_slots */
810 		if (changes[slot].state == TOUCH_STOPPED ||
811 		    !bit_is_set(changes[slot].axes, ABS_MT_SLOT))
812 			continue;
813 
814 		queue_push_event(dev, EV_ABS, ABS_MT_SLOT, slot);
815 		last_reported_slot = slot;
816 
817 		for (int axis = ABS_MT_MIN; axis <= ABS_MT_MAX; axis++) {
818 			if (axis == ABS_MT_SLOT ||
819 			    !libevdev_has_event_code(dev, EV_ABS, axis))
820 				continue;
821 
822 			if (bit_is_set(changes[slot].axes, axis))
823 				queue_push_event(dev, EV_ABS, axis,
824 						 *slot_value(dev, slot, axis));
825 		}
826 	}
827 
828 	/* add one last slot event to make sure the client is on the same
829 	   slot as the kernel */
830 
831 	rc = ioctl(dev->fd, EVIOCGABS(ABS_MT_SLOT), &abs_info);
832 	if (rc < 0)
833 		goto out;
834 
835 	dev->current_slot = abs_info.value;
836 
837 	if (dev->current_slot != last_reported_slot)
838 		queue_push_event(dev, EV_ABS, ABS_MT_SLOT, dev->current_slot);
839 
840 	rc = 0;
841 out:
842 	return rc ? -errno : 0;
843 }
844 
845 static int
read_more_events(struct libevdev * dev)846 read_more_events(struct libevdev *dev)
847 {
848 	int free_elem;
849 	int len;
850 	struct input_event *next;
851 
852 	free_elem = queue_num_free_elements(dev);
853 	if (free_elem <= 0)
854 		return 0;
855 
856 	next = queue_next_element(dev);
857 	len = read(dev->fd, next, free_elem * sizeof(struct input_event));
858 	if (len < 0)
859 		return -errno;
860 
861 	if (len > 0 && len % sizeof(struct input_event) != 0)
862 		return -EINVAL;
863 
864 	if (len > 0) {
865 		int nev = len/sizeof(struct input_event);
866 		queue_set_num_elements(dev, queue_num_elements(dev) + nev);
867 	}
868 
869 	return 0;
870 }
871 
872 static inline void
drain_events(struct libevdev * dev)873 drain_events(struct libevdev *dev)
874 {
875 	int rc;
876 	size_t nelem;
877 	int iterations = 0;
878 	const int max_iterations = 8; /* EVDEV_BUF_PACKETS in
879 					 kernel/drivers/input/evedev.c */
880 
881 	queue_shift_multiple(dev, queue_num_elements(dev), NULL);
882 
883 	do {
884 		rc = read_more_events(dev);
885 		if (rc == -EAGAIN)
886 			return;
887 
888 		if (rc < 0) {
889 			log_error(dev, "Failed to drain events before sync.\n");
890 			return;
891 		}
892 
893 		nelem = queue_num_elements(dev);
894 		queue_shift_multiple(dev, nelem, NULL);
895 	} while (iterations++ < max_iterations && nelem >= queue_size(dev));
896 
897 	/* Our buffer should be roughly the same or bigger than the kernel
898 	   buffer in most cases, so we usually don't expect to recurse. If
899 	   we do, make sure we stop after max_iterations and proceed with
900 	   what we have.  This could happen if events queue up faster than
901 	   we can drain them.
902 	 */
903 	if (iterations >= max_iterations)
904 		log_info(dev, "Unable to drain events, buffer size mismatch.\n");
905 }
906 
907 static int
sync_state(struct libevdev * dev)908 sync_state(struct libevdev *dev)
909 {
910 	int rc = 0;
911 	bool want_mt_sync = false;
912 	int last_reported_slot = 0;
913 	struct slot_change_state changes[dev->num_slots > 0 ? dev->num_slots : 1];
914 
915 	memset(changes, 0, sizeof(changes));
916 
917 	 /* see section "Discarding events before synchronizing" in
918 	  * libevdev/libevdev.h */
919 	drain_events(dev);
920 
921 	/* We generate one or two event frames during sync.
922 	 * The first one (if it exists) terminates all slots that have
923 	 * either terminated during SYN_DROPPED or changed their tracking
924 	 * ID.
925 	 *
926 	 * The second frame syncs everything up to the current state of the
927 	 * device - including re-starting those slots that have a changed
928 	 * tracking id.
929 	 */
930 	if (dev->num_slots > -1 &&
931 	    libevdev_has_event_code(dev, EV_ABS, ABS_MT_SLOT)) {
932 		want_mt_sync = true;
933 		rc = sync_mt_state(dev, changes);
934 		if (rc == 0)
935 			terminate_slots(dev, changes, &last_reported_slot);
936 		else
937 			want_mt_sync = false;
938 	}
939 
940 	if (libevdev_has_event_type(dev, EV_KEY))
941 		rc = sync_key_state(dev);
942 	if (libevdev_has_event_type(dev, EV_LED))
943 		rc = sync_led_state(dev);
944 	if (libevdev_has_event_type(dev, EV_SW))
945 		rc = sync_sw_state(dev);
946 	if (rc == 0 && libevdev_has_event_type(dev, EV_ABS))
947 		rc = sync_abs_state(dev);
948 	if (rc == 0 && want_mt_sync)
949 		push_mt_sync_events(dev, changes, last_reported_slot);
950 
951 	dev->queue_nsync = queue_num_elements(dev);
952 
953 	if (dev->queue_nsync > 0) {
954 		queue_push_event(dev, EV_SYN, SYN_REPORT, 0);
955 		dev->queue_nsync++;
956 	}
957 
958 	return rc;
959 }
960 
961 static int
update_key_state(struct libevdev * dev,const struct input_event * e)962 update_key_state(struct libevdev *dev, const struct input_event *e)
963 {
964 	if (!libevdev_has_event_type(dev, EV_KEY))
965 		return 1;
966 
967 	if (e->code > KEY_MAX)
968 		return 1;
969 
970 	set_bit_state(dev->key_values, e->code, e->value != 0);
971 
972 	return 0;
973 }
974 
975 static int
update_mt_state(struct libevdev * dev,const struct input_event * e)976 update_mt_state(struct libevdev *dev, const struct input_event *e)
977 {
978 	if (e->code == ABS_MT_SLOT && dev->num_slots > -1) {
979 		int i;
980 		dev->current_slot = e->value;
981 		/* sync abs_info with the current slot values */
982 		for (i = ABS_MT_SLOT + 1; i <= ABS_MT_MAX; i++) {
983 			if (libevdev_has_event_code(dev, EV_ABS, i))
984 				dev->abs_info[i].value = *slot_value(dev, dev->current_slot, i);
985 		}
986 
987 		return 0;
988 	}
989 
990 	if (dev->current_slot == -1)
991 		return 1;
992 
993 	*slot_value(dev, dev->current_slot, e->code) = e->value;
994 
995 	return 0;
996 }
997 
998 static int
update_abs_state(struct libevdev * dev,const struct input_event * e)999 update_abs_state(struct libevdev *dev, const struct input_event *e)
1000 {
1001 	if (!libevdev_has_event_type(dev, EV_ABS))
1002 		return 1;
1003 
1004 	if (e->code > ABS_MAX)
1005 		return 1;
1006 
1007 	if (e->code >= ABS_MT_MIN && e->code <= ABS_MT_MAX)
1008 		update_mt_state(dev, e);
1009 
1010 	dev->abs_info[e->code].value = e->value;
1011 
1012 	return 0;
1013 }
1014 
1015 static int
update_led_state(struct libevdev * dev,const struct input_event * e)1016 update_led_state(struct libevdev *dev, const struct input_event *e)
1017 {
1018 	if (!libevdev_has_event_type(dev, EV_LED))
1019 		return 1;
1020 
1021 	if (e->code > LED_MAX)
1022 		return 1;
1023 
1024 	set_bit_state(dev->led_values, e->code, e->value != 0);
1025 
1026 	return 0;
1027 }
1028 
1029 static int
update_sw_state(struct libevdev * dev,const struct input_event * e)1030 update_sw_state(struct libevdev *dev, const struct input_event *e)
1031 {
1032 	if (!libevdev_has_event_type(dev, EV_SW))
1033 		return 1;
1034 
1035 	if (e->code > SW_MAX)
1036 		return 1;
1037 
1038 	set_bit_state(dev->sw_values, e->code, e->value != 0);
1039 
1040 	return 0;
1041 }
1042 
1043 static int
update_state(struct libevdev * dev,const struct input_event * e)1044 update_state(struct libevdev *dev, const struct input_event *e)
1045 {
1046 	int rc = 0;
1047 
1048 	switch(e->type) {
1049 		case EV_SYN:
1050 		case EV_REL:
1051 			break;
1052 		case EV_KEY:
1053 			rc = update_key_state(dev, e);
1054 			break;
1055 		case EV_ABS:
1056 			rc = update_abs_state(dev, e);
1057 			break;
1058 		case EV_LED:
1059 			rc = update_led_state(dev, e);
1060 			break;
1061 		case EV_SW:
1062 			rc = update_sw_state(dev, e);
1063 			break;
1064 	}
1065 
1066 	dev->last_event_time.tv_sec = e->input_event_sec;
1067 	dev->last_event_time.tv_usec = e->input_event_usec;
1068 
1069 	return rc;
1070 }
1071 
1072 /**
1073  * Sanitize/modify events where needed.
1074  */
1075 static inline enum event_filter_status
sanitize_event(const struct libevdev * dev,struct input_event * ev,enum SyncState sync_state)1076 sanitize_event(const struct libevdev *dev,
1077 	       struct input_event *ev,
1078 	       enum SyncState sync_state)
1079 {
1080 	if (!libevdev_has_event_code(dev, ev->type, ev->code))
1081 		return EVENT_FILTER_DISCARD;
1082 
1083 	if (unlikely(dev->num_slots > -1 &&
1084 		     libevdev_event_is_code(ev, EV_ABS, ABS_MT_SLOT) &&
1085 		     (ev->value < 0 || ev->value >= dev->num_slots))) {
1086 		log_bug(dev, "Device \"%s\" received an invalid slot index %d."
1087 				"Capping to announced max slot number %d.\n",
1088 				dev->name, ev->value, dev->num_slots - 1);
1089 		ev->value = dev->num_slots - 1;
1090 		return EVENT_FILTER_MODIFIED;
1091 
1092 	/* Drop any invalid tracking IDs, they are only supposed to go from
1093 	   N to -1 or from -1 to N. Never from -1 to -1, or N to M. Very
1094 	   unlikely to ever happen from a real device.
1095 	   */
1096 	}
1097 
1098 	if (unlikely(sync_state == SYNC_NONE &&
1099 			    dev->num_slots > -1 &&
1100 			    libevdev_event_is_code(ev, EV_ABS, ABS_MT_TRACKING_ID) &&
1101 			    ((ev->value == -1 &&
1102 			     *slot_value(dev, dev->current_slot, ABS_MT_TRACKING_ID) == -1) ||
1103 			     (ev->value != -1 &&
1104 			     *slot_value(dev, dev->current_slot, ABS_MT_TRACKING_ID) != -1)))) {
1105 		log_bug(dev, "Device \"%s\" received a double tracking ID %d in slot %d.\n",
1106 			dev->name, ev->value, dev->current_slot);
1107 		return EVENT_FILTER_DISCARD;
1108 	}
1109 
1110 	return EVENT_FILTER_NONE;
1111 }
1112 
1113 LIBEVDEV_EXPORT int
libevdev_next_event(struct libevdev * dev,unsigned int flags,struct input_event * ev)1114 libevdev_next_event(struct libevdev *dev, unsigned int flags, struct input_event *ev)
1115 {
1116 	int rc = LIBEVDEV_READ_STATUS_SUCCESS;
1117 	enum event_filter_status filter_status;
1118 	const unsigned int valid_flags = LIBEVDEV_READ_FLAG_NORMAL |
1119 					 LIBEVDEV_READ_FLAG_SYNC |
1120 					 LIBEVDEV_READ_FLAG_FORCE_SYNC |
1121 					 LIBEVDEV_READ_FLAG_BLOCKING;
1122 
1123 	if (!dev->initialized) {
1124 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
1125 		return -EBADF;
1126 	}
1127 
1128 	if (dev->fd < 0)
1129 		return -EBADF;
1130 
1131 	if ((flags & valid_flags) == 0) {
1132 		log_bug(dev, "invalid flags %#x.\n", flags);
1133 		return -EINVAL;
1134 	}
1135 
1136 	if (flags & LIBEVDEV_READ_FLAG_SYNC) {
1137 		if (dev->sync_state == SYNC_NEEDED) {
1138 			rc = sync_state(dev);
1139 			if (rc != 0)
1140 				return rc;
1141 			dev->sync_state = SYNC_IN_PROGRESS;
1142 		}
1143 
1144 		if (dev->queue_nsync == 0) {
1145 			dev->sync_state = SYNC_NONE;
1146 			return -EAGAIN;
1147 		}
1148 
1149 	} else if (dev->sync_state != SYNC_NONE) {
1150 		struct input_event e;
1151 
1152 		/* call update_state for all events here, otherwise the library has the wrong view
1153 		   of the device too */
1154 		while (queue_shift(dev, &e) == 0) {
1155 			dev->queue_nsync--;
1156 			if (sanitize_event(dev, &e, dev->sync_state) != EVENT_FILTER_DISCARD)
1157 				update_state(dev, &e);
1158 		}
1159 
1160 		dev->sync_state = SYNC_NONE;
1161 	}
1162 
1163 	/* Always read in some more events. Best case this smoothes over a potential SYN_DROPPED,
1164 	   worst case we don't read fast enough and end up with SYN_DROPPED anyway.
1165 
1166 	   Except if the fd is in blocking mode and we still have events from the last read, don't
1167 	   read in any more.
1168 	 */
1169 	do {
1170 		if (queue_num_elements(dev) == 0) {
1171 			rc = read_more_events(dev);
1172 			if (rc < 0 && rc != -EAGAIN)
1173 				goto out;
1174 		}
1175 
1176 		if (flags & LIBEVDEV_READ_FLAG_FORCE_SYNC) {
1177 			dev->sync_state = SYNC_NEEDED;
1178 			rc = LIBEVDEV_READ_STATUS_SYNC;
1179 			goto out;
1180 		}
1181 
1182 		if (queue_shift(dev, ev) != 0)
1183 			return -EAGAIN;
1184 
1185 		filter_status = sanitize_event(dev, ev, dev->sync_state);
1186 		if (filter_status != EVENT_FILTER_DISCARD)
1187 			update_state(dev, ev);
1188 
1189 	/* if we disabled a code, get the next event instead */
1190 	} while(filter_status == EVENT_FILTER_DISCARD ||
1191 		!libevdev_has_event_code(dev, ev->type, ev->code));
1192 
1193 	rc = LIBEVDEV_READ_STATUS_SUCCESS;
1194 	if (ev->type == EV_SYN && ev->code == SYN_DROPPED) {
1195 		dev->sync_state = SYNC_NEEDED;
1196 		rc = LIBEVDEV_READ_STATUS_SYNC;
1197 	}
1198 
1199 	if (flags & LIBEVDEV_READ_FLAG_SYNC && dev->queue_nsync > 0) {
1200 		dev->queue_nsync--;
1201 		rc = LIBEVDEV_READ_STATUS_SYNC;
1202 		if (dev->queue_nsync == 0)
1203 			dev->sync_state = SYNC_NONE;
1204 	}
1205 
1206 out:
1207 	return rc;
1208 }
1209 
1210 LIBEVDEV_EXPORT int
libevdev_has_event_pending(struct libevdev * dev)1211 libevdev_has_event_pending(struct libevdev *dev)
1212 {
1213 	struct pollfd fds = { dev->fd, POLLIN, 0 };
1214 	int rc;
1215 
1216 	if (!dev->initialized) {
1217 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
1218 		return -EBADF;
1219 	}
1220 
1221 	if (dev->fd < 0)
1222 		return -EBADF;
1223 
1224 	if (queue_num_elements(dev) != 0)
1225 		return 1;
1226 
1227 	rc = poll(&fds, 1, 0);
1228 	return (rc >= 0) ? rc : -errno;
1229 }
1230 
1231 LIBEVDEV_EXPORT const char *
libevdev_get_name(const struct libevdev * dev)1232 libevdev_get_name(const struct libevdev *dev)
1233 {
1234 	return dev->name ? dev->name : "";
1235 }
1236 
1237 LIBEVDEV_EXPORT const char *
libevdev_get_phys(const struct libevdev * dev)1238 libevdev_get_phys(const struct libevdev *dev)
1239 {
1240 	return dev->phys;
1241 }
1242 
1243 LIBEVDEV_EXPORT const char *
libevdev_get_uniq(const struct libevdev * dev)1244 libevdev_get_uniq(const struct libevdev *dev)
1245 {
1246 	return dev->uniq;
1247 }
1248 
1249 #define STRING_SETTER(field) \
1250 LIBEVDEV_EXPORT void libevdev_set_##field(struct libevdev *dev, const char *field) \
1251 { \
1252 	if (field == NULL) \
1253 		return; \
1254 	free(dev->field); \
1255 	dev->field = strdup(field); \
1256 }
1257 
1258 STRING_SETTER(name)
STRING_SETTER(phys)1259 STRING_SETTER(phys)
1260 STRING_SETTER(uniq)
1261 
1262 #define PRODUCT_GETTER(name) \
1263 LIBEVDEV_EXPORT int libevdev_get_id_##name(const struct libevdev *dev) \
1264 { \
1265 	return dev->ids.name; \
1266 }
1267 
1268 PRODUCT_GETTER(product)
1269 PRODUCT_GETTER(vendor)
1270 PRODUCT_GETTER(bustype)
1271 PRODUCT_GETTER(version)
1272 
1273 #define PRODUCT_SETTER(field) \
1274 LIBEVDEV_EXPORT void libevdev_set_id_##field(struct libevdev *dev, int field) \
1275 { \
1276 	dev->ids.field = field;\
1277 }
1278 
1279 PRODUCT_SETTER(product)
1280 PRODUCT_SETTER(vendor)
1281 PRODUCT_SETTER(bustype)
1282 PRODUCT_SETTER(version)
1283 
1284 LIBEVDEV_EXPORT int
1285 libevdev_get_driver_version(const struct libevdev *dev)
1286 {
1287 	return dev->driver_version;
1288 }
1289 
1290 LIBEVDEV_EXPORT int
libevdev_has_property(const struct libevdev * dev,unsigned int prop)1291 libevdev_has_property(const struct libevdev *dev, unsigned int prop)
1292 {
1293 	return (prop <= INPUT_PROP_MAX) && bit_is_set(dev->props, prop);
1294 }
1295 
1296 LIBEVDEV_EXPORT int
libevdev_enable_property(struct libevdev * dev,unsigned int prop)1297 libevdev_enable_property(struct libevdev *dev, unsigned int prop)
1298 {
1299 	if (prop > INPUT_PROP_MAX)
1300 		return -1;
1301 
1302 	set_bit(dev->props, prop);
1303 	return 0;
1304 }
1305 
1306 LIBEVDEV_EXPORT int
libevdev_disable_property(struct libevdev * dev,unsigned int prop)1307 libevdev_disable_property(struct libevdev *dev, unsigned int prop)
1308 {
1309 	if (prop > INPUT_PROP_MAX)
1310 		return -1;
1311 
1312 	clear_bit(dev->props, prop);
1313 	return 0;
1314 }
1315 
1316 LIBEVDEV_EXPORT int
libevdev_has_event_type(const struct libevdev * dev,unsigned int type)1317 libevdev_has_event_type(const struct libevdev *dev, unsigned int type)
1318 {
1319 	return type == EV_SYN ||(type <= EV_MAX && bit_is_set(dev->bits, type));
1320 }
1321 
1322 LIBEVDEV_EXPORT int
libevdev_has_event_code(const struct libevdev * dev,unsigned int type,unsigned int code)1323 libevdev_has_event_code(const struct libevdev *dev, unsigned int type, unsigned int code)
1324 {
1325 	const unsigned long *mask = NULL;
1326 	int max;
1327 
1328 	if (!libevdev_has_event_type(dev, type))
1329 		return 0;
1330 
1331 	if (type == EV_SYN)
1332 		return 1;
1333 
1334 	max = type_to_mask_const(dev, type, &mask);
1335 
1336 	if (max == -1 || code > (unsigned int)max)
1337 		return 0;
1338 
1339 	return bit_is_set(mask, code);
1340 }
1341 
1342 LIBEVDEV_EXPORT int
libevdev_get_event_value(const struct libevdev * dev,unsigned int type,unsigned int code)1343 libevdev_get_event_value(const struct libevdev *dev, unsigned int type, unsigned int code)
1344 {
1345 	int value = 0;
1346 
1347 	if (!libevdev_has_event_type(dev, type) || !libevdev_has_event_code(dev, type, code))
1348 		return 0;
1349 
1350 	switch (type) {
1351 		case EV_ABS: value = dev->abs_info[code].value; break;
1352 		case EV_KEY: value = bit_is_set(dev->key_values, code); break;
1353 		case EV_LED: value = bit_is_set(dev->led_values, code); break;
1354 		case EV_SW: value = bit_is_set(dev->sw_values, code); break;
1355 		case EV_REP:
1356 			    switch(code) {
1357 				    case REP_DELAY:
1358 					    libevdev_get_repeat(dev, &value, NULL);
1359 					    break;
1360 				    case REP_PERIOD:
1361 					    libevdev_get_repeat(dev, NULL, &value);
1362 					    break;
1363 				    default:
1364 					    value = 0;
1365 					    break;
1366 			    }
1367 			    break;
1368 		default:
1369 			value = 0;
1370 			break;
1371 	}
1372 
1373 	return value;
1374 }
1375 
1376 LIBEVDEV_EXPORT int
libevdev_set_event_value(struct libevdev * dev,unsigned int type,unsigned int code,int value)1377 libevdev_set_event_value(struct libevdev *dev, unsigned int type, unsigned int code, int value)
1378 {
1379 	int rc = 0;
1380 	struct input_event e;
1381 
1382 	if (!libevdev_has_event_type(dev, type) || !libevdev_has_event_code(dev, type, code))
1383 		return -1;
1384 
1385 	e.type = type;
1386 	e.code = code;
1387 	e.value = value;
1388 
1389 	if (sanitize_event(dev, &e, SYNC_NONE) != EVENT_FILTER_NONE)
1390 		return -1;
1391 
1392 	switch(type) {
1393 		case EV_ABS: rc = update_abs_state(dev, &e); break;
1394 		case EV_KEY: rc = update_key_state(dev, &e); break;
1395 		case EV_LED: rc = update_led_state(dev, &e); break;
1396 		case EV_SW: rc = update_sw_state(dev, &e); break;
1397 		default:
1398 			     rc = -1;
1399 			     break;
1400 	}
1401 
1402 	return rc;
1403 }
1404 
1405 LIBEVDEV_EXPORT int
libevdev_fetch_event_value(const struct libevdev * dev,unsigned int type,unsigned int code,int * value)1406 libevdev_fetch_event_value(const struct libevdev *dev, unsigned int type, unsigned int code, int *value)
1407 {
1408 	if (libevdev_has_event_type(dev, type) &&
1409 	    libevdev_has_event_code(dev, type, code)) {
1410 		*value = libevdev_get_event_value(dev, type, code);
1411 		return 1;
1412 	}
1413 
1414 	return 0;
1415 }
1416 
1417 LIBEVDEV_EXPORT int
libevdev_get_slot_value(const struct libevdev * dev,unsigned int slot,unsigned int code)1418 libevdev_get_slot_value(const struct libevdev *dev, unsigned int slot, unsigned int code)
1419 {
1420 	if (!libevdev_has_event_type(dev, EV_ABS) || !libevdev_has_event_code(dev, EV_ABS, code))
1421 		return 0;
1422 
1423 	if (dev->num_slots < 0 || slot >= (unsigned int)dev->num_slots)
1424 		return 0;
1425 
1426 	if (code > ABS_MT_MAX || code < ABS_MT_MIN)
1427 		return 0;
1428 
1429 	return *slot_value(dev, slot, code);
1430 }
1431 
1432 LIBEVDEV_EXPORT int
libevdev_set_slot_value(struct libevdev * dev,unsigned int slot,unsigned int code,int value)1433 libevdev_set_slot_value(struct libevdev *dev, unsigned int slot, unsigned int code, int value)
1434 {
1435 	if (!libevdev_has_event_type(dev, EV_ABS) || !libevdev_has_event_code(dev, EV_ABS, code))
1436 		return -1;
1437 
1438 	if (dev->num_slots == -1 || slot >= (unsigned int)dev->num_slots)
1439 		return -1;
1440 
1441 	if (code > ABS_MT_MAX || code < ABS_MT_MIN)
1442 		return -1;
1443 
1444 	if (code == ABS_MT_SLOT) {
1445 		if (value < 0 || value >= libevdev_get_num_slots(dev))
1446 			return -1;
1447 		dev->current_slot = value;
1448 	}
1449 
1450 	*slot_value(dev, slot, code) = value;
1451 
1452 	return 0;
1453 }
1454 
1455 LIBEVDEV_EXPORT int
libevdev_fetch_slot_value(const struct libevdev * dev,unsigned int slot,unsigned int code,int * value)1456 libevdev_fetch_slot_value(const struct libevdev *dev, unsigned int slot, unsigned int code, int *value)
1457 {
1458 	if (libevdev_has_event_type(dev, EV_ABS) &&
1459 	    libevdev_has_event_code(dev, EV_ABS, code) &&
1460 	    dev->num_slots >= 0 &&
1461 	    slot < (unsigned int)dev->num_slots) {
1462 		*value = libevdev_get_slot_value(dev, slot, code);
1463 		return 1;
1464 	}
1465 
1466 	return 0;
1467 }
1468 
1469 LIBEVDEV_EXPORT int
libevdev_get_num_slots(const struct libevdev * dev)1470 libevdev_get_num_slots(const struct libevdev *dev)
1471 {
1472 	return dev->num_slots;
1473 }
1474 
1475 LIBEVDEV_EXPORT int
libevdev_get_current_slot(const struct libevdev * dev)1476 libevdev_get_current_slot(const struct libevdev *dev)
1477 {
1478 	return dev->current_slot;
1479 }
1480 
1481 LIBEVDEV_EXPORT const struct input_absinfo*
libevdev_get_abs_info(const struct libevdev * dev,unsigned int code)1482 libevdev_get_abs_info(const struct libevdev *dev, unsigned int code)
1483 {
1484 	if (!libevdev_has_event_type(dev, EV_ABS) ||
1485 	    !libevdev_has_event_code(dev, EV_ABS, code))
1486 		return NULL;
1487 
1488 	return &dev->abs_info[code];
1489 }
1490 
1491 #define ABS_GETTER(name) \
1492 LIBEVDEV_EXPORT int libevdev_get_abs_##name(const struct libevdev *dev, unsigned int code) \
1493 { \
1494 	const struct input_absinfo *absinfo = libevdev_get_abs_info(dev, code); \
1495 	return absinfo ? absinfo->name : 0; \
1496 }
1497 
1498 ABS_GETTER(maximum)
ABS_GETTER(minimum)1499 ABS_GETTER(minimum)
1500 ABS_GETTER(fuzz)
1501 ABS_GETTER(flat)
1502 ABS_GETTER(resolution)
1503 
1504 #define ABS_SETTER(field) \
1505 LIBEVDEV_EXPORT void libevdev_set_abs_##field(struct libevdev *dev, unsigned int code, int val) \
1506 { \
1507 	if (!libevdev_has_event_code(dev, EV_ABS, code)) \
1508 		return; \
1509 	dev->abs_info[code].field = val; \
1510 }
1511 
1512 ABS_SETTER(maximum)
1513 ABS_SETTER(minimum)
1514 ABS_SETTER(fuzz)
1515 ABS_SETTER(flat)
1516 ABS_SETTER(resolution)
1517 
1518 LIBEVDEV_EXPORT void
1519 libevdev_set_abs_info(struct libevdev *dev, unsigned int code, const struct input_absinfo *abs)
1520 {
1521 	if (!libevdev_has_event_code(dev, EV_ABS, code))
1522 		return;
1523 
1524 	dev->abs_info[code] = *abs;
1525 }
1526 
1527 LIBEVDEV_EXPORT int
libevdev_enable_event_type(struct libevdev * dev,unsigned int type)1528 libevdev_enable_event_type(struct libevdev *dev, unsigned int type)
1529 {
1530 	int max;
1531 
1532 	if (type > EV_MAX)
1533 		return -1;
1534 
1535 	if (libevdev_has_event_type(dev, type))
1536 		return 0;
1537 
1538 	max = libevdev_event_type_get_max(type);
1539 	if (max == -1)
1540 		return -1;
1541 
1542 	set_bit(dev->bits, type);
1543 
1544 	if (type == EV_REP) {
1545 		int delay = 0, period = 0;
1546 		libevdev_enable_event_code(dev, EV_REP, REP_DELAY, &delay);
1547 		libevdev_enable_event_code(dev, EV_REP, REP_PERIOD, &period);
1548 	}
1549 	return 0;
1550 }
1551 
1552 LIBEVDEV_EXPORT int
libevdev_disable_event_type(struct libevdev * dev,unsigned int type)1553 libevdev_disable_event_type(struct libevdev *dev, unsigned int type)
1554 {
1555 	int max;
1556 
1557 	if (type > EV_MAX || type == EV_SYN)
1558 		return -1;
1559 
1560 	max = libevdev_event_type_get_max(type);
1561 	if (max == -1)
1562 		return -1;
1563 
1564 	clear_bit(dev->bits, type);
1565 
1566 	return 0;
1567 }
1568 
1569 LIBEVDEV_EXPORT int
libevdev_enable_event_code(struct libevdev * dev,unsigned int type,unsigned int code,const void * data)1570 libevdev_enable_event_code(struct libevdev *dev, unsigned int type,
1571 			   unsigned int code, const void *data)
1572 {
1573 	unsigned int max;
1574 	unsigned long *mask = NULL;
1575 
1576 	if (libevdev_enable_event_type(dev, type))
1577 		return -1;
1578 
1579 	switch(type) {
1580 		case EV_SYN:
1581 			return 0;
1582 		case EV_ABS:
1583 		case EV_REP:
1584 			if (data == NULL)
1585 				return -1;
1586 			break;
1587 		default:
1588 			if (data != NULL)
1589 				return -1;
1590 			break;
1591 	}
1592 
1593 	max = type_to_mask(dev, type, &mask);
1594 
1595 	if (code > max || (int)max == -1)
1596 		return -1;
1597 
1598 	set_bit(mask, code);
1599 
1600 	if (type == EV_ABS) {
1601 		const struct input_absinfo *abs = data;
1602 		dev->abs_info[code] = *abs;
1603 		if (code == ABS_MT_SLOT) {
1604 			if (init_slots(dev) != 0)
1605 				return -1;
1606 		} else if (code == ABS_MT_TRACKING_ID) {
1607 			reset_tracking_ids(dev);
1608 		}
1609 	} else if (type == EV_REP) {
1610 		const int *value = data;
1611 		dev->rep_values[code] = *value;
1612 	}
1613 
1614 	return 0;
1615 }
1616 
1617 LIBEVDEV_EXPORT int
libevdev_disable_event_code(struct libevdev * dev,unsigned int type,unsigned int code)1618 libevdev_disable_event_code(struct libevdev *dev, unsigned int type, unsigned int code)
1619 {
1620 	unsigned int max;
1621 	unsigned long *mask = NULL;
1622 
1623 	if (type > EV_MAX || type == EV_SYN)
1624 		return -1;
1625 
1626 	max = type_to_mask(dev, type, &mask);
1627 
1628 	if (code > max || (int)max == -1)
1629 		return -1;
1630 
1631 	clear_bit(mask, code);
1632 
1633 	if (type == EV_ABS) {
1634 		if (code == ABS_MT_SLOT) {
1635 			if (init_slots(dev) != 0)
1636 				return -1;
1637 		} else if (code == ABS_MT_TRACKING_ID) {
1638 			reset_tracking_ids(dev);
1639 		}
1640 	}
1641 
1642 	return 0;
1643 }
1644 
1645 LIBEVDEV_EXPORT int
libevdev_kernel_set_abs_info(struct libevdev * dev,unsigned int code,const struct input_absinfo * abs)1646 libevdev_kernel_set_abs_info(struct libevdev *dev, unsigned int code, const struct input_absinfo *abs)
1647 {
1648 	int rc;
1649 
1650 	if (!dev->initialized) {
1651 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
1652 		return -EBADF;
1653 	}
1654 
1655 	if (dev->fd < 0)
1656 		return -EBADF;
1657 
1658 	if (code > ABS_MAX)
1659 		return -EINVAL;
1660 
1661 	rc = ioctl(dev->fd, EVIOCSABS(code), abs);
1662 	if (rc < 0)
1663 		rc = -errno;
1664 	else
1665 		rc = libevdev_enable_event_code(dev, EV_ABS, code, abs);
1666 
1667 	return rc;
1668 }
1669 
1670 LIBEVDEV_EXPORT int
libevdev_grab(struct libevdev * dev,enum libevdev_grab_mode grab)1671 libevdev_grab(struct libevdev *dev, enum libevdev_grab_mode grab)
1672 {
1673 	int rc = 0;
1674 
1675 	if (!dev->initialized) {
1676 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
1677 		return -EBADF;
1678 	}
1679 
1680 	if (dev->fd < 0)
1681 		return -EBADF;
1682 
1683 	if (grab != LIBEVDEV_GRAB && grab != LIBEVDEV_UNGRAB) {
1684 		log_bug(dev, "invalid grab parameter %#x\n", grab);
1685 		return -EINVAL;
1686 	}
1687 
1688 	if (grab == dev->grabbed)
1689 		return 0;
1690 
1691 	if (grab == LIBEVDEV_GRAB)
1692 		rc = ioctl(dev->fd, EVIOCGRAB, (void *)1);
1693 	else if (grab == LIBEVDEV_UNGRAB)
1694 		rc = ioctl(dev->fd, EVIOCGRAB, (void *)0);
1695 
1696 	if (rc == 0)
1697 		dev->grabbed = grab;
1698 
1699 	return rc < 0 ? -errno : 0;
1700 }
1701 
1702 LIBEVDEV_EXPORT int
libevdev_event_is_type(const struct input_event * ev,unsigned int type)1703 libevdev_event_is_type(const struct input_event *ev, unsigned int type)
1704 {
1705 	return type < EV_CNT && ev->type == type;
1706 }
1707 
1708 LIBEVDEV_EXPORT int
libevdev_event_is_code(const struct input_event * ev,unsigned int type,unsigned int code)1709 libevdev_event_is_code(const struct input_event *ev, unsigned int type, unsigned int code)
1710 {
1711 	int max;
1712 
1713 	if (!libevdev_event_is_type(ev, type))
1714 		return 0;
1715 
1716 	max = libevdev_event_type_get_max(type);
1717 	return (max > -1 && code <= (unsigned int)max && ev->code == code);
1718 }
1719 
1720 LIBEVDEV_EXPORT const char*
libevdev_event_type_get_name(unsigned int type)1721 libevdev_event_type_get_name(unsigned int type)
1722 {
1723 	if (type > EV_MAX)
1724 		return NULL;
1725 
1726 	return ev_map[type];
1727 }
1728 
1729 LIBEVDEV_EXPORT const char*
libevdev_event_code_get_name(unsigned int type,unsigned int code)1730 libevdev_event_code_get_name(unsigned int type, unsigned int code)
1731 {
1732 	int max = libevdev_event_type_get_max(type);
1733 
1734 	if (max == -1 || code > (unsigned int)max)
1735 		return NULL;
1736 
1737 	return event_type_map[type][code];
1738 }
1739 
1740 LIBEVDEV_EXPORT const char *
libevdev_event_value_get_name(unsigned int type,unsigned int code,int value)1741 libevdev_event_value_get_name(unsigned int type,
1742 			      unsigned int code,
1743 			      int value)
1744 {
1745 	/* This is a simplified version because nothing else
1746 	   is an enum like ABS_MT_TOOL_TYPE so we don't need
1747 	   a generic lookup */
1748 	if (type != EV_ABS || code != ABS_MT_TOOL_TYPE)
1749 		return NULL;
1750 
1751 	if (value < 0 || value > MT_TOOL_MAX)
1752 		return NULL;
1753 
1754 	return mt_tool_map[value];
1755 }
1756 
1757 LIBEVDEV_EXPORT const char*
libevdev_property_get_name(unsigned int prop)1758 libevdev_property_get_name(unsigned int prop)
1759 {
1760 	if (prop > INPUT_PROP_MAX)
1761 		return NULL;
1762 
1763 	return input_prop_map[prop];
1764 }
1765 
1766 LIBEVDEV_EXPORT int
libevdev_event_type_get_max(unsigned int type)1767 libevdev_event_type_get_max(unsigned int type)
1768 {
1769 	if (type > EV_MAX)
1770 		return -1;
1771 
1772 	return ev_max[type];
1773 }
1774 
1775 LIBEVDEV_EXPORT int
libevdev_get_repeat(const struct libevdev * dev,int * delay,int * period)1776 libevdev_get_repeat(const struct libevdev *dev, int *delay, int *period)
1777 {
1778 	if (!libevdev_has_event_type(dev, EV_REP))
1779 		return -1;
1780 
1781 	if (delay != NULL)
1782 		*delay = dev->rep_values[REP_DELAY];
1783 	if (period != NULL)
1784 		*period = dev->rep_values[REP_PERIOD];
1785 
1786 	return 0;
1787 }
1788 
1789 LIBEVDEV_EXPORT int
libevdev_kernel_set_led_value(struct libevdev * dev,unsigned int code,enum libevdev_led_value value)1790 libevdev_kernel_set_led_value(struct libevdev *dev, unsigned int code, enum libevdev_led_value value)
1791 {
1792 	return libevdev_kernel_set_led_values(dev, code, value, -1);
1793 }
1794 
1795 LIBEVDEV_EXPORT int
libevdev_kernel_set_led_values(struct libevdev * dev,...)1796 libevdev_kernel_set_led_values(struct libevdev *dev, ...)
1797 {
1798 	struct input_event ev[LED_MAX + 1];
1799 	enum libevdev_led_value val;
1800 	va_list args;
1801 	int code;
1802 	int rc = 0;
1803 	size_t nleds = 0;
1804 
1805 	if (!dev->initialized) {
1806 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
1807 		return -EBADF;
1808 	}
1809 
1810 	if (dev->fd < 0)
1811 		return -EBADF;
1812 
1813 	memset(ev, 0, sizeof(ev));
1814 
1815 	va_start(args, dev);
1816 	code = va_arg(args, unsigned int);
1817 	while (code != -1) {
1818 		if (code > LED_MAX) {
1819 			rc = -EINVAL;
1820 			break;
1821 		}
1822 		val = va_arg(args, enum libevdev_led_value);
1823 		if (val != LIBEVDEV_LED_ON && val != LIBEVDEV_LED_OFF) {
1824 			rc = -EINVAL;
1825 			break;
1826 		}
1827 
1828 		if (libevdev_has_event_code(dev, EV_LED, code)) {
1829 			struct input_event *e = ev;
1830 
1831 			while (e->type > 0 && e->code != code)
1832 				e++;
1833 
1834 			if (e->type == 0)
1835 				nleds++;
1836 			e->type = EV_LED;
1837 			e->code = code;
1838 			e->value = (val == LIBEVDEV_LED_ON);
1839 		}
1840 		code = va_arg(args, unsigned int);
1841 	}
1842 	va_end(args);
1843 
1844 	if (rc == 0 && nleds > 0) {
1845 		ev[nleds].type = EV_SYN;
1846 		ev[nleds++].code = SYN_REPORT;
1847 
1848 		rc = write(libevdev_get_fd(dev), ev, nleds * sizeof(ev[0]));
1849 		if (rc > 0) {
1850 			nleds--; /* last is EV_SYN */
1851 			while (nleds--)
1852 				update_led_state(dev, &ev[nleds]);
1853 		}
1854 		rc = (rc != -1) ? 0 : -errno;
1855 	}
1856 
1857 	return rc;
1858 }
1859 
1860 LIBEVDEV_EXPORT int
libevdev_set_clock_id(struct libevdev * dev,int clockid)1861 libevdev_set_clock_id(struct libevdev *dev, int clockid)
1862 {
1863 	if (!dev->initialized) {
1864 		log_bug(dev, "device not initialized. call libevdev_set_fd() first\n");
1865 		return -EBADF;
1866 	}
1867 
1868 	if (dev->fd < 0)
1869 		return -EBADF;
1870 
1871 	return ioctl(dev->fd, EVIOCSCLOCKID, &clockid) ? -errno : 0;
1872 }
1873