1 /*
2  * Copyright © 2008 Kristian Høgsberg
3  * Copyright © 2013-2015 Red Hat, Inc.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
9  * and/or sell copies of the Software, and to permit persons to whom the
10  * Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  */
24 
25 #ifndef LIBINPUT_UTIL_H
26 #define LIBINPUT_UTIL_H
27 
28 #include "config.h"
29 
30 #include <assert.h>
31 #include <ctype.h>
32 #include <errno.h>
33 #include <limits.h>
34 #include <locale.h>
35 #ifdef HAVE_XLOCALE_H
36 #include <xlocale.h>
37 #endif
38 #include <math.h>
39 #include <stdarg.h>
40 #include <stdbool.h>
41 #include <stddef.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
45 #include <time.h>
46 #include <unistd.h>
47 #include <linux/input.h>
48 
49 #include "libinput.h"
50 
51 #define VENDOR_ID_APPLE 0x5ac
52 #define VENDOR_ID_CHICONY 0x4f2
53 #define VENDOR_ID_LOGITECH 0x46d
54 #define VENDOR_ID_WACOM 0x56a
55 #define VENDOR_ID_SYNAPTICS_SERIAL 0x002
56 #define PRODUCT_ID_APPLE_KBD_TOUCHPAD 0x273
57 #define PRODUCT_ID_APPLE_APPLETOUCH 0x21a
58 #define PRODUCT_ID_SYNAPTICS_SERIAL 0x007
59 #define PRODUCT_ID_WACOM_EKR 0x0331
60 
61 /* The HW DPI rate we normalize to before calculating pointer acceleration */
62 #define DEFAULT_MOUSE_DPI 1000
63 #define DEFAULT_TRACKPOINT_SENSITIVITY 128
64 
65 #define ANSI_HIGHLIGHT		"\x1B[0;1;39m"
66 #define ANSI_RED		"\x1B[0;31m"
67 #define ANSI_GREEN		"\x1B[0;32m"
68 #define ANSI_YELLOW		"\x1B[0;33m"
69 #define ANSI_BLUE		"\x1B[0;34m"
70 #define ANSI_MAGENTA		"\x1B[0;35m"
71 #define ANSI_CYAN		"\x1B[0;36m"
72 #define ANSI_BRIGHT_RED		"\x1B[0;31;1m"
73 #define ANSI_BRIGHT_GREEN	"\x1B[0;32;1m"
74 #define ANSI_BRIGHT_YELLOW	"\x1B[0;33;1m"
75 #define ANSI_BRIGHT_BLUE	"\x1B[0;34;1m"
76 #define ANSI_BRIGHT_MAGENTA	"\x1B[0;35;1m"
77 #define ANSI_BRIGHT_CYAN	"\x1B[0;36;1m"
78 #define ANSI_NORMAL		"\x1B[0m"
79 
80 #define CASE_RETURN_STRING(a) case a: return #a
81 
82 /*
83  * This list data structure is a verbatim copy from wayland-util.h from the
84  * Wayland project; except that wl_ prefix has been removed.
85  */
86 
87 struct list {
88 	struct list *prev;
89 	struct list *next;
90 };
91 
92 void list_init(struct list *list);
93 void list_insert(struct list *list, struct list *elm);
94 void list_append(struct list *list, struct list *elm);
95 void list_remove(struct list *elm);
96 bool list_empty(const struct list *list);
97 
98 #define container_of(ptr, type, member)					\
99 	(__typeof__(type) *)((char *)(ptr) -				\
100 		 offsetof(__typeof__(type), member))
101 
102 #define list_first_entry(head, pos, member)				\
103 	container_of((head)->next, __typeof__(*pos), member)
104 
105 #define list_for_each(pos, head, member)				\
106 	for (pos = 0, pos = list_first_entry(head, pos, member);	\
107 	     &pos->member != (head);					\
108 	     pos = list_first_entry(&pos->member, pos, member))
109 
110 #define list_for_each_safe(pos, tmp, head, member)			\
111 	for (pos = 0, tmp = 0,						\
112 	     pos = list_first_entry(head, pos, member),			\
113 	     tmp = list_first_entry(&pos->member, tmp, member);		\
114 	     &pos->member != (head);					\
115 	     pos = tmp,							\
116 	     tmp = list_first_entry(&pos->member, tmp, member))
117 
118 #define NBITS(b) (b * 8)
119 #define LONG_BITS (sizeof(long) * 8)
120 #define NLONGS(x) (((x) + LONG_BITS - 1) / LONG_BITS)
121 #define ARRAY_LENGTH(a) (sizeof (a) / sizeof (a)[0])
122 #define ARRAY_FOR_EACH(_arr, _elem) \
123 	for (size_t _i = 0; _i < ARRAY_LENGTH(_arr) && (_elem = &_arr[_i]); _i++)
124 #define AS_MASK(v) (1 << (v))
125 
126 #define min(a, b) (((a) < (b)) ? (a) : (b))
127 #define max(a, b) (((a) > (b)) ? (a) : (b))
128 #define streq(s1, s2) (strcmp((s1), (s2)) == 0)
129 #define strneq(s1, s2, n) (strncmp((s1), (s2), (n)) == 0)
130 
131 #define NCHARS(x) ((size_t)(((x) + 7) / 8))
132 
133 #ifdef DEBUG_TRACE
134 #define debug_trace(...) \
135 	do { \
136 	printf("%s:%d %s() - ", __FILE__, __LINE__, __func__); \
137 	printf(__VA_ARGS__); \
138 	} while (0)
139 #else
140 #define debug_trace(...) { }
141 #endif
142 
143 #define LIBINPUT_EXPORT __attribute__ ((visibility("default")))
144 
145 static inline void *
zalloc(size_t size)146 zalloc(size_t size)
147 {
148 	void *p;
149 
150 	/* We never need to alloc anything more than 1,5 MB so we can assume
151 	 * if we ever get above that something's going wrong */
152 	if (size > 1536 * 1024)
153 		assert(!"bug: internal malloc size limit exceeded");
154 
155 	p = calloc(1, size);
156 	if (!p)
157 		abort();
158 
159 	return p;
160 }
161 
162 /**
163  * strdup guaranteed to succeed. If the input string is NULL, the output
164  * string is NULL. If the input string is a string pointer, we strdup or
165  * abort on failure.
166  */
167 static inline char*
safe_strdup(const char * str)168 safe_strdup(const char *str)
169 {
170 	char *s;
171 
172 	if (!str)
173 		return NULL;
174 
175 	s = strdup(str);
176 	if (!s)
177 		abort();
178 	return s;
179 }
180 
181 /* This bitfield helper implementation is taken from from libevdev-util.h,
182  * except that it has been modified to work with arrays of unsigned chars
183  */
184 
185 static inline bool
bit_is_set(const unsigned char * array,int bit)186 bit_is_set(const unsigned char *array, int bit)
187 {
188 	return !!(array[bit / 8] & (1 << (bit % 8)));
189 }
190 
191 	static inline void
set_bit(unsigned char * array,int bit)192 set_bit(unsigned char *array, int bit)
193 {
194 	array[bit / 8] |= (1 << (bit % 8));
195 }
196 
197 	static inline void
clear_bit(unsigned char * array,int bit)198 clear_bit(unsigned char *array, int bit)
199 {
200 	array[bit / 8] &= ~(1 << (bit % 8));
201 }
202 
203 static inline void
msleep(unsigned int ms)204 msleep(unsigned int ms)
205 {
206 	usleep(ms * 1000);
207 }
208 
209 static inline bool
long_bit_is_set(const unsigned long * array,int bit)210 long_bit_is_set(const unsigned long *array, int bit)
211 {
212 	return !!(array[bit / LONG_BITS] & (1ULL << (bit % LONG_BITS)));
213 }
214 
215 static inline void
long_set_bit(unsigned long * array,int bit)216 long_set_bit(unsigned long *array, int bit)
217 {
218 	array[bit / LONG_BITS] |= (1ULL << (bit % LONG_BITS));
219 }
220 
221 static inline void
long_clear_bit(unsigned long * array,int bit)222 long_clear_bit(unsigned long *array, int bit)
223 {
224 	array[bit / LONG_BITS] &= ~(1ULL << (bit % LONG_BITS));
225 }
226 
227 static inline void
long_set_bit_state(unsigned long * array,int bit,int state)228 long_set_bit_state(unsigned long *array, int bit, int state)
229 {
230 	if (state)
231 		long_set_bit(array, bit);
232 	else
233 		long_clear_bit(array, bit);
234 }
235 
236 static inline bool
long_any_bit_set(unsigned long * array,size_t size)237 long_any_bit_set(unsigned long *array, size_t size)
238 {
239 	unsigned long i;
240 
241 	assert(size > 0);
242 
243 	for (i = 0; i < size; i++)
244 		if (array[i] != 0)
245 			return true;
246 	return false;
247 }
248 
249 static inline double
deg2rad(int degree)250 deg2rad(int degree)
251 {
252 	return M_PI * degree / 180.0;
253 }
254 
255 struct matrix {
256 	float val[3][3]; /* [row][col] */
257 };
258 
259 static inline void
matrix_init_identity(struct matrix * m)260 matrix_init_identity(struct matrix *m)
261 {
262 	memset(m, 0, sizeof(*m));
263 	m->val[0][0] = 1;
264 	m->val[1][1] = 1;
265 	m->val[2][2] = 1;
266 }
267 
268 static inline void
matrix_from_farray6(struct matrix * m,const float values[6])269 matrix_from_farray6(struct matrix *m, const float values[6])
270 {
271 	matrix_init_identity(m);
272 	m->val[0][0] = values[0];
273 	m->val[0][1] = values[1];
274 	m->val[0][2] = values[2];
275 	m->val[1][0] = values[3];
276 	m->val[1][1] = values[4];
277 	m->val[1][2] = values[5];
278 }
279 
280 static inline void
matrix_init_scale(struct matrix * m,float sx,float sy)281 matrix_init_scale(struct matrix *m, float sx, float sy)
282 {
283 	matrix_init_identity(m);
284 	m->val[0][0] = sx;
285 	m->val[1][1] = sy;
286 }
287 
288 static inline void
matrix_init_translate(struct matrix * m,float x,float y)289 matrix_init_translate(struct matrix *m, float x, float y)
290 {
291 	matrix_init_identity(m);
292 	m->val[0][2] = x;
293 	m->val[1][2] = y;
294 }
295 
296 static inline void
matrix_init_rotate(struct matrix * m,int degrees)297 matrix_init_rotate(struct matrix *m, int degrees)
298 {
299 	double s, c;
300 
301 	s = sin(deg2rad(degrees));
302 	c = cos(deg2rad(degrees));
303 
304 	matrix_init_identity(m);
305 	m->val[0][0] = c;
306 	m->val[0][1] = -s;
307 	m->val[1][0] = s;
308 	m->val[1][1] = c;
309 }
310 
311 static inline bool
matrix_is_identity(const struct matrix * m)312 matrix_is_identity(const struct matrix *m)
313 {
314 	return (m->val[0][0] == 1 &&
315 		m->val[0][1] == 0 &&
316 		m->val[0][2] == 0 &&
317 		m->val[1][0] == 0 &&
318 		m->val[1][1] == 1 &&
319 		m->val[1][2] == 0 &&
320 		m->val[2][0] == 0 &&
321 		m->val[2][1] == 0 &&
322 		m->val[2][2] == 1);
323 }
324 
325 static inline void
matrix_mult(struct matrix * dest,const struct matrix * m1,const struct matrix * m2)326 matrix_mult(struct matrix *dest,
327 	    const struct matrix *m1,
328 	    const struct matrix *m2)
329 {
330 	struct matrix m; /* allow for dest == m1 or dest == m2 */
331 	int row, col, i;
332 
333 	for (row = 0; row < 3; row++) {
334 		for (col = 0; col < 3; col++) {
335 			double v = 0;
336 			for (i = 0; i < 3; i++) {
337 				v += m1->val[row][i] * m2->val[i][col];
338 			}
339 			m.val[row][col] = v;
340 		}
341 	}
342 
343 	memcpy(dest, &m, sizeof(m));
344 }
345 
346 static inline void
matrix_mult_vec(const struct matrix * m,int * x,int * y)347 matrix_mult_vec(const struct matrix *m, int *x, int *y)
348 {
349 	int tx, ty;
350 
351 	tx = *x * m->val[0][0] + *y * m->val[0][1] + m->val[0][2];
352 	ty = *x * m->val[1][0] + *y * m->val[1][1] + m->val[1][2];
353 
354 	*x = tx;
355 	*y = ty;
356 }
357 
358 static inline void
matrix_to_farray6(const struct matrix * m,float out[6])359 matrix_to_farray6(const struct matrix *m, float out[6])
360 {
361 	out[0] = m->val[0][0];
362 	out[1] = m->val[0][1];
363 	out[2] = m->val[0][2];
364 	out[3] = m->val[1][0];
365 	out[4] = m->val[1][1];
366 	out[5] = m->val[1][2];
367 }
368 
369 static inline void
matrix_to_relative(struct matrix * dest,const struct matrix * src)370 matrix_to_relative(struct matrix *dest, const struct matrix *src)
371 {
372 	matrix_init_identity(dest);
373 	dest->val[0][0] = src->val[0][0];
374 	dest->val[0][1] = src->val[0][1];
375 	dest->val[1][0] = src->val[1][0];
376 	dest->val[1][1] = src->val[1][1];
377 }
378 
379 /**
380  * Simple wrapper for asprintf that ensures the passed in-pointer is set
381  * to NULL upon error.
382  * The standard asprintf() call does not guarantee the passed in pointer
383  * will be NULL'ed upon failure, whereas this wrapper does.
384  *
385  * @param strp pointer to set to newly allocated string.
386  * This pointer should be passed to free() to release when done.
387  * @param fmt the format string to use for printing.
388  * @return The number of bytes printed (excluding the null byte terminator)
389  * upon success or -1 upon failure. In the case of failure the pointer is set
390  * to NULL.
391  */
392 LIBINPUT_ATTRIBUTE_PRINTF(2, 3)
393 static inline int
xasprintf(char ** strp,const char * fmt,...)394 xasprintf(char **strp, const char *fmt, ...)
395 {
396 	int rc = 0;
397 	va_list args;
398 
399 	va_start(args, fmt);
400 	rc = vasprintf(strp, fmt, args);
401 	va_end(args);
402 	if ((rc == -1) && strp)
403 		*strp = NULL;
404 
405 	return rc;
406 }
407 
408 enum ratelimit_state {
409 	RATELIMIT_EXCEEDED,
410 	RATELIMIT_THRESHOLD,
411 	RATELIMIT_PASS,
412 };
413 
414 struct ratelimit {
415 	uint64_t interval;
416 	uint64_t begin;
417 	unsigned int burst;
418 	unsigned int num;
419 };
420 
421 void ratelimit_init(struct ratelimit *r, uint64_t ival_ms, unsigned int burst);
422 enum ratelimit_state ratelimit_test(struct ratelimit *r);
423 
424 int parse_mouse_dpi_property(const char *prop);
425 int parse_mouse_wheel_click_angle_property(const char *prop);
426 int parse_mouse_wheel_click_count_property(const char *prop);
427 bool parse_dimension_property(const char *prop, size_t *width, size_t *height);
428 bool parse_calibration_property(const char *prop, float calibration[6]);
429 bool parse_range_property(const char *prop, int *hi, int *lo);
430 #define EVENT_CODE_UNDEFINED 0xffff
431 bool parse_evcode_property(const char *prop, struct input_event *events, size_t *nevents);
432 
433 enum tpkbcombo_layout {
434 	TPKBCOMBO_LAYOUT_UNKNOWN,
435 	TPKBCOMBO_LAYOUT_BELOW,
436 };
437 bool parse_tpkbcombo_layout_poperty(const char *prop,
438 				    enum tpkbcombo_layout *layout);
439 
440 enum switch_reliability {
441 	RELIABILITY_UNKNOWN,
442 	RELIABILITY_RELIABLE,
443 	RELIABILITY_WRITE_OPEN,
444 };
445 
446 bool
447 parse_switch_reliability_property(const char *prop,
448 				  enum switch_reliability *reliability);
449 
450 static inline uint64_t
us(uint64_t us)451 us(uint64_t us)
452 {
453 	return us;
454 }
455 
456 static inline uint64_t
ns2us(uint64_t ns)457 ns2us(uint64_t ns)
458 {
459 	return us(ns / 1000);
460 }
461 
462 static inline uint64_t
ms2us(uint64_t ms)463 ms2us(uint64_t ms)
464 {
465 	return us(ms * 1000);
466 }
467 
468 static inline uint64_t
s2us(uint64_t s)469 s2us(uint64_t s)
470 {
471 	return ms2us(s * 1000);
472 }
473 
474 static inline uint32_t
us2ms(uint64_t us)475 us2ms(uint64_t us)
476 {
477 	return (uint32_t)(us / 1000);
478 }
479 
480 static inline uint64_t
tv2us(const struct timeval * tv)481 tv2us(const struct timeval *tv)
482 {
483 	return s2us(tv->tv_sec) + tv->tv_usec;
484 }
485 
486 static inline struct timeval
us2tv(uint64_t time)487 us2tv(uint64_t time)
488 {
489 	struct timeval tv;
490 
491 	tv.tv_sec = time / ms2us(1000);
492 	tv.tv_usec = time % ms2us(1000);
493 
494 	return tv;
495 }
496 
497 static inline bool
safe_atoi_base(const char * str,int * val,int base)498 safe_atoi_base(const char *str, int *val, int base)
499 {
500 	char *endptr;
501 	long v;
502 
503 	assert(base == 10 || base == 16 || base == 8);
504 
505 	errno = 0;
506 	v = strtol(str, &endptr, base);
507 	if (errno > 0)
508 		return false;
509 	if (str == endptr)
510 		return false;
511 	if (*str != '\0' && *endptr != '\0')
512 		return false;
513 
514 	if (v > INT_MAX || v < INT_MIN)
515 		return false;
516 
517 	*val = v;
518 	return true;
519 }
520 
521 static inline bool
safe_atoi(const char * str,int * val)522 safe_atoi(const char *str, int *val)
523 {
524 	return safe_atoi_base(str, val, 10);
525 }
526 
527 static inline bool
safe_atou_base(const char * str,unsigned int * val,int base)528 safe_atou_base(const char *str, unsigned int *val, int base)
529 {
530 	char *endptr;
531 	unsigned long v;
532 
533 	assert(base == 10 || base == 16 || base == 8);
534 
535 	errno = 0;
536 	v = strtoul(str, &endptr, base);
537 	if (errno > 0)
538 		return false;
539 	if (str == endptr)
540 		return false;
541 	if (*str != '\0' && *endptr != '\0')
542 		return false;
543 
544 	if ((long)v < 0)
545 		return false;
546 
547 	*val = v;
548 	return true;
549 }
550 
551 static inline bool
safe_atou(const char * str,unsigned int * val)552 safe_atou(const char *str, unsigned int *val)
553 {
554 	return safe_atou_base(str, val, 10);
555 }
556 
557 static inline bool
safe_atod(const char * str,double * val)558 safe_atod(const char *str, double *val)
559 {
560 	char *endptr;
561 	double v;
562 	locale_t c_locale;
563 	size_t slen = strlen(str);
564 
565 	/* We don't have a use-case where we want to accept hex for a double
566 	 * or any of the other values strtod can parse */
567 	for (size_t i = 0; i < slen; i++) {
568 		char c = str[i];
569 
570 		if (isdigit(c))
571 		       continue;
572 		switch(c) {
573 		case '+':
574 		case '-':
575 		case '.':
576 			break;
577 		default:
578 			return false;
579 		}
580 	}
581 
582 	/* Create a "C" locale to force strtod to use '.' as separator */
583 	c_locale = newlocale(LC_NUMERIC_MASK, "C", (locale_t)0);
584 	if (c_locale == (locale_t)0)
585 		return false;
586 
587 	errno = 0;
588 	v = strtod_l(str, &endptr, c_locale);
589 	freelocale(c_locale);
590 	if (errno > 0)
591 		return false;
592 	if (str == endptr)
593 		return false;
594 	if (*str != '\0' && *endptr != '\0')
595 		return false;
596 	if (v != 0.0 && !isnormal(v))
597 		return false;
598 
599 	*val = v;
600 	return true;
601 }
602 
603 char **strv_from_string(const char *string, const char *separator);
604 char *strv_join(char **strv, const char *separator);
605 
606 static inline void
strv_free(char ** strv)607 strv_free(char **strv) {
608 	char **s = strv;
609 
610 	if (!strv)
611 		return;
612 
613 	while (*s != NULL) {
614 		free(*s);
615 		*s = (char*)0x1; /* detect use-after-free */
616 		s++;
617 	}
618 
619 	free (strv);
620 }
621 
622 struct key_value_double {
623 	double key;
624 	double value;
625 };
626 
627 static inline ssize_t
kv_double_from_string(const char * string,const char * pair_separator,const char * kv_separator,struct key_value_double ** result_out)628 kv_double_from_string(const char *string,
629 		      const char *pair_separator,
630 		      const char *kv_separator,
631 		      struct key_value_double **result_out)
632 
633 {
634 	char **pairs;
635 	char **pair;
636 	struct key_value_double *result = NULL;
637 	ssize_t npairs = 0;
638 	unsigned int idx = 0;
639 
640 	if (!pair_separator || pair_separator[0] == '\0' ||
641 	    !kv_separator || kv_separator[0] == '\0')
642 		return -1;
643 
644 	pairs = strv_from_string(string, pair_separator);
645 	if (!pairs)
646 		return -1;
647 
648 	for (pair = pairs; *pair; pair++)
649 		npairs++;
650 
651 	if (npairs == 0)
652 		goto error;
653 
654 	result = zalloc(npairs * sizeof *result);
655 
656 	for (pair = pairs; *pair; pair++) {
657 		char **kv = strv_from_string(*pair, kv_separator);
658 		double k, v;
659 
660 		if (!kv || !kv[0] || !kv[1] || kv[2] ||
661 		    !safe_atod(kv[0], &k) ||
662 		    !safe_atod(kv[1], &v)) {
663 			strv_free(kv);
664 			goto error;
665 		}
666 
667 		result[idx].key = k;
668 		result[idx].value = v;
669 		idx++;
670 
671 		strv_free(kv);
672 	}
673 
674 	strv_free(pairs);
675 
676 	*result_out = result;
677 
678 	return npairs;
679 
680 error:
681 	strv_free(pairs);
682 	free(result);
683 	return -1;
684 }
685 #endif /* LIBINPUT_UTIL_H */
686