xref: /linux/tools/testing/selftests/hid/hid_common.h (revision b6f69097c8271cca30314fd6e4c802f90737bfcc)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 /* Copyright (c) 2022-2024 Red Hat */
3 
4 #include "kselftest_harness.h"
5 
6 #include <fcntl.h>
7 #include <fnmatch.h>
8 #include <dirent.h>
9 #include <poll.h>
10 #include <pthread.h>
11 #include <stdbool.h>
12 #include <linux/hidraw.h>
13 #include <linux/uhid.h>
14 
15 #define SHOW_UHID_DEBUG 0
16 #define MAX_BUF_SIZE 128
17 
18 #define min(a, b) \
19 	({ __typeof__(a) _a = (a); \
20 	__typeof__(b) _b = (b); \
21 	_a < _b ? _a : _b; })
22 
23 struct uhid_device {
24 	int dev_id;		/* uniq (random) number to identify the device */
25 	int uhid_fd;
26 	int hid_id;		/* HID device id in the system */
27 	__u16 bus;
28 	__u32 vid;
29 	__u32 pid;
30 	pthread_t tid;		/* thread for reading uhid events */
31 };
32 
33 static unsigned char rdesc[] = {
34 	0x06, 0x00, 0xff,	/* Usage Page (Vendor Defined Page 1) */
35 	0x09, 0x21,		/* Usage (Vendor Usage 0x21) */
36 	0xa1, 0x01,		/* COLLECTION (Application) */
37 	0x09, 0x01,			/* Usage (Vendor Usage 0x01) */
38 	0xa1, 0x00,			/* COLLECTION (Physical) */
39 	0x85, 0x02,				/* REPORT_ID (2) */
40 	0x19, 0x01,				/* USAGE_MINIMUM (1) */
41 	0x29, 0x08,				/* USAGE_MAXIMUM (3) */
42 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
43 	0x25, 0xff,				/* LOGICAL_MAXIMUM (255) */
44 	0x95, 0x08,				/* REPORT_COUNT (8) */
45 	0x75, 0x08,				/* REPORT_SIZE (8) */
46 	0x81, 0x02,				/* INPUT (Data,Var,Abs) */
47 	0xc0,				/* END_COLLECTION */
48 	0x09, 0x01,			/* Usage (Vendor Usage 0x01) */
49 	0xa1, 0x00,			/* COLLECTION (Physical) */
50 	0x85, 0x01,				/* REPORT_ID (1) */
51 	0x06, 0x00, 0xff,			/* Usage Page (Vendor Defined Page 1) */
52 	0x19, 0x01,				/* USAGE_MINIMUM (1) */
53 	0x29, 0x03,				/* USAGE_MAXIMUM (3) */
54 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
55 	0x25, 0x01,				/* LOGICAL_MAXIMUM (1) */
56 	0x95, 0x03,				/* REPORT_COUNT (3) */
57 	0x75, 0x01,				/* REPORT_SIZE (1) */
58 	0x81, 0x02,				/* INPUT (Data,Var,Abs) */
59 	0x95, 0x01,				/* REPORT_COUNT (1) */
60 	0x75, 0x05,				/* REPORT_SIZE (5) */
61 	0x81, 0x01,				/* INPUT (Cnst,Var,Abs) */
62 	0x05, 0x01,				/* USAGE_PAGE (Generic Desktop) */
63 	0x09, 0x30,				/* USAGE (X) */
64 	0x09, 0x31,				/* USAGE (Y) */
65 	0x15, 0x81,				/* LOGICAL_MINIMUM (-127) */
66 	0x25, 0x7f,				/* LOGICAL_MAXIMUM (127) */
67 	0x75, 0x10,				/* REPORT_SIZE (16) */
68 	0x95, 0x02,				/* REPORT_COUNT (2) */
69 	0x81, 0x06,				/* INPUT (Data,Var,Rel) */
70 
71 	0x06, 0x00, 0xff,			/* Usage Page (Vendor Defined Page 1) */
72 	0x19, 0x01,				/* USAGE_MINIMUM (1) */
73 	0x29, 0x03,				/* USAGE_MAXIMUM (3) */
74 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
75 	0x25, 0x01,				/* LOGICAL_MAXIMUM (1) */
76 	0x95, 0x03,				/* REPORT_COUNT (3) */
77 	0x75, 0x01,				/* REPORT_SIZE (1) */
78 	0x91, 0x02,				/* Output (Data,Var,Abs) */
79 	0x95, 0x01,				/* REPORT_COUNT (1) */
80 	0x75, 0x05,				/* REPORT_SIZE (5) */
81 	0x91, 0x01,				/* Output (Cnst,Var,Abs) */
82 
83 	0x06, 0x00, 0xff,			/* Usage Page (Vendor Defined Page 1) */
84 	0x19, 0x06,				/* USAGE_MINIMUM (6) */
85 	0x29, 0x08,				/* USAGE_MAXIMUM (8) */
86 	0x15, 0x00,				/* LOGICAL_MINIMUM (0) */
87 	0x25, 0x01,				/* LOGICAL_MAXIMUM (1) */
88 	0x95, 0x03,				/* REPORT_COUNT (3) */
89 	0x75, 0x01,				/* REPORT_SIZE (1) */
90 	0xb1, 0x02,				/* Feature (Data,Var,Abs) */
91 	0x95, 0x01,				/* REPORT_COUNT (1) */
92 	0x75, 0x05,				/* REPORT_SIZE (5) */
93 	0x91, 0x01,				/* Output (Cnst,Var,Abs) */
94 
95 	0xc0,				/* END_COLLECTION */
96 	0xc0,			/* END_COLLECTION */
97 };
98 
99 static __u8 feature_data[] = { 1, 2 };
100 
101 static __maybe_unused unsigned char fido2_rdesc[] = {
102 	0x06, 0xd0, 0xf1,	/* Usage Page (FIDO Alliance) */
103 	0x09, 0x01,		/* Usage (U2F Authenticator Device) */
104 	0xa1, 0x01,		/* Collection (Application) */
105 	0x09, 0x20,		/*  Usage (Input Report Data) */
106 	0x15, 0x00,		/*  Logical Minimum (0) */
107 	0x26, 0xff, 0x00,	/*  Logical Maximum (255) */
108 	0x75, 0x08,		/*  Report Size (8) */
109 	0x95, 0x40,		/*  Report Count (64) */
110 	0x81, 0x02,		/*  Input (Data,Var,Abs) */
111 	0x09, 0x21,		/*  Usage (Output Report Data) */
112 	0x15, 0x00,		/*  Logical Minimum (0) */
113 	0x26, 0xff, 0x00,	/*  Logical Maximum (255) */
114 	0x75, 0x08,		/*  Report Size (8) */
115 	0x95, 0x40,		/*  Report Count (64) */
116 	0x91, 0x02,		/*  Output (Data,Var,Abs) */
117 	0x06, 0x00, 0xff,	/*  Usage Page (Vendor Defined Page 1) */
118 	0x09, 0x22,		/*  Usage (Vendor Usage 0x22) */
119 	0xb1, 0x02,		/*  Feature (Data,Var,Abs) */
120 	0xc0,			/* End Collection */
121 };
122 
123 #define ASSERT_OK(data) ASSERT_FALSE(data)
124 #define ASSERT_OK_PTR(ptr) ASSERT_NE(NULL, ptr)
125 
126 #define UHID_LOG(fmt, ...) do { \
127 	if (SHOW_UHID_DEBUG) \
128 		TH_LOG(fmt, ##__VA_ARGS__); \
129 } while (0)
130 
131 static pthread_mutex_t uhid_started_mtx = PTHREAD_MUTEX_INITIALIZER;
132 static pthread_cond_t uhid_started = PTHREAD_COND_INITIALIZER;
133 
134 static pthread_mutex_t uhid_output_mtx = PTHREAD_MUTEX_INITIALIZER;
135 static pthread_cond_t uhid_output_cond = PTHREAD_COND_INITIALIZER;
136 static unsigned char output_report[MAX_BUF_SIZE];
137 
138 /* no need to protect uhid_stopped, only one thread accesses it */
139 static bool uhid_stopped;
140 
141 static int uhid_write(struct __test_metadata *_metadata, int fd, const struct uhid_event *ev)
142 {
143 	ssize_t ret;
144 
145 	ret = write(fd, ev, sizeof(*ev));
146 	if (ret < 0) {
147 		TH_LOG("Cannot write to uhid: %m");
148 		return -errno;
149 	} else if (ret != sizeof(*ev)) {
150 		TH_LOG("Wrong size written to uhid: %zd != %zu",
151 			ret, sizeof(ev));
152 		return -EFAULT;
153 	} else {
154 		return 0;
155 	}
156 }
157 
158 static int uhid_create(struct __test_metadata *_metadata, int fd, int rand_nb,
159 		       __u16 bus, __u32 vid, __u32 pid, __u8 *rdesc,
160 		       size_t rdesc_size)
161 {
162 	struct uhid_event ev;
163 	char buf[25];
164 
165 	sprintf(buf, "test-uhid-device-%d", rand_nb);
166 
167 	memset(&ev, 0, sizeof(ev));
168 	ev.type = UHID_CREATE;
169 	strcpy((char *)ev.u.create.name, buf);
170 	ev.u.create.rd_data = rdesc;
171 	ev.u.create.rd_size = rdesc_size;
172 	ev.u.create.bus = bus;
173 	ev.u.create.vendor = vid;
174 	ev.u.create.product = pid;
175 	ev.u.create.version = 0;
176 	ev.u.create.country = 0;
177 
178 	sprintf(buf, "%d", rand_nb);
179 	strcpy((char *)ev.u.create.phys, buf);
180 
181 	return uhid_write(_metadata, fd, &ev);
182 }
183 
184 static void uhid_destroy(struct __test_metadata *_metadata, struct uhid_device *hid)
185 {
186 	struct uhid_event ev;
187 
188 	memset(&ev, 0, sizeof(ev));
189 	ev.type = UHID_DESTROY;
190 
191 	uhid_write(_metadata, hid->uhid_fd, &ev);
192 }
193 
194 static int uhid_event(struct __test_metadata *_metadata, int fd)
195 {
196 	struct uhid_event ev, answer;
197 	ssize_t ret;
198 
199 	memset(&ev, 0, sizeof(ev));
200 	ret = read(fd, &ev, sizeof(ev));
201 	if (ret == 0) {
202 		UHID_LOG("Read HUP on uhid-cdev");
203 		return -EFAULT;
204 	} else if (ret < 0) {
205 		UHID_LOG("Cannot read uhid-cdev: %m");
206 		return -errno;
207 	} else if (ret != sizeof(ev)) {
208 		UHID_LOG("Invalid size read from uhid-dev: %zd != %zu",
209 			ret, sizeof(ev));
210 		return -EFAULT;
211 	}
212 
213 	switch (ev.type) {
214 	case UHID_START:
215 		pthread_mutex_lock(&uhid_started_mtx);
216 		pthread_cond_signal(&uhid_started);
217 		pthread_mutex_unlock(&uhid_started_mtx);
218 
219 		UHID_LOG("UHID_START from uhid-dev");
220 		break;
221 	case UHID_STOP:
222 		uhid_stopped = true;
223 
224 		UHID_LOG("UHID_STOP from uhid-dev");
225 		break;
226 	case UHID_OPEN:
227 		UHID_LOG("UHID_OPEN from uhid-dev");
228 		break;
229 	case UHID_CLOSE:
230 		UHID_LOG("UHID_CLOSE from uhid-dev");
231 		break;
232 	case UHID_OUTPUT:
233 		UHID_LOG("UHID_OUTPUT from uhid-dev");
234 
235 		pthread_mutex_lock(&uhid_output_mtx);
236 		memcpy(output_report,
237 		       ev.u.output.data,
238 		       min(ev.u.output.size, sizeof(output_report)));
239 		pthread_cond_signal(&uhid_output_cond);
240 		pthread_mutex_unlock(&uhid_output_mtx);
241 		break;
242 	case UHID_GET_REPORT:
243 		UHID_LOG("UHID_GET_REPORT from uhid-dev");
244 
245 		answer.type = UHID_GET_REPORT_REPLY;
246 		answer.u.get_report_reply.id = ev.u.get_report.id;
247 		answer.u.get_report_reply.err = ev.u.get_report.rnum == 1 ? 0 : -EIO;
248 		answer.u.get_report_reply.size = sizeof(feature_data);
249 		memcpy(answer.u.get_report_reply.data, feature_data, sizeof(feature_data));
250 
251 		uhid_write(_metadata, fd, &answer);
252 
253 		break;
254 	case UHID_SET_REPORT:
255 		UHID_LOG("UHID_SET_REPORT from uhid-dev");
256 
257 		answer.type = UHID_SET_REPORT_REPLY;
258 		answer.u.set_report_reply.id = ev.u.set_report.id;
259 		answer.u.set_report_reply.err = 0; /* success */
260 
261 		uhid_write(_metadata, fd, &answer);
262 		break;
263 	default:
264 		TH_LOG("Invalid event from uhid-dev: %u", ev.type);
265 	}
266 
267 	return 0;
268 }
269 
270 struct uhid_thread_args {
271 	int fd;
272 	struct __test_metadata *_metadata;
273 };
274 static void *uhid_read_events_thread(void *arg)
275 {
276 	struct uhid_thread_args *args = (struct uhid_thread_args *)arg;
277 	struct __test_metadata *_metadata = args->_metadata;
278 	struct pollfd pfds[1];
279 	int fd = args->fd;
280 	int ret = 0;
281 
282 	pfds[0].fd = fd;
283 	pfds[0].events = POLLIN;
284 
285 	uhid_stopped = false;
286 
287 	while (!uhid_stopped) {
288 		ret = poll(pfds, 1, 100);
289 		if (ret < 0) {
290 			TH_LOG("Cannot poll for fds: %m");
291 			break;
292 		}
293 		if (pfds[0].revents & POLLIN) {
294 			ret = uhid_event(_metadata, fd);
295 			if (ret)
296 				break;
297 		}
298 	}
299 
300 	return (void *)(long)ret;
301 }
302 
303 static int uhid_start_listener(struct __test_metadata *_metadata, pthread_t *tid, int uhid_fd)
304 {
305 	struct uhid_thread_args args = {
306 		.fd = uhid_fd,
307 		._metadata = _metadata,
308 	};
309 	int err;
310 
311 	pthread_mutex_lock(&uhid_started_mtx);
312 	err = pthread_create(tid, NULL, uhid_read_events_thread, (void *)&args);
313 	ASSERT_EQ(0, err) {
314 		TH_LOG("Could not start the uhid thread: %d", err);
315 		pthread_mutex_unlock(&uhid_started_mtx);
316 		close(uhid_fd);
317 		return -EIO;
318 	}
319 	pthread_cond_wait(&uhid_started, &uhid_started_mtx);
320 	pthread_mutex_unlock(&uhid_started_mtx);
321 
322 	return 0;
323 }
324 
325 static int uhid_send_event(struct __test_metadata *_metadata, struct uhid_device *hid,
326 			   __u8 *buf, size_t size)
327 {
328 	struct uhid_event ev;
329 
330 	if (size > sizeof(ev.u.input.data))
331 		return -E2BIG;
332 
333 	memset(&ev, 0, sizeof(ev));
334 	ev.type = UHID_INPUT2;
335 	ev.u.input2.size = size;
336 
337 	memcpy(ev.u.input2.data, buf, size);
338 
339 	return uhid_write(_metadata, hid->uhid_fd, &ev);
340 }
341 
342 static bool match_sysfs_device(struct uhid_device *hid, const char *workdir, struct dirent *dir)
343 {
344 	char target[20] = "";
345 	char phys[512];
346 	char uevent[1024];
347 	char temp[512];
348 	int fd, nread;
349 	bool found = false;
350 
351 	snprintf(target, sizeof(target), "%04X:%04X:%04X.*", hid->bus, hid->vid, hid->pid);
352 
353 	if (fnmatch(target, dir->d_name, 0))
354 		return false;
355 
356 	/* we found the correct VID/PID, now check for phys */
357 	sprintf(uevent, "%s/%s/uevent", workdir, dir->d_name);
358 
359 	fd = open(uevent, O_RDONLY | O_NONBLOCK);
360 	if (fd < 0)
361 		return false;
362 
363 	sprintf(phys, "PHYS=%d", hid->dev_id);
364 
365 	nread = read(fd, temp, ARRAY_SIZE(temp));
366 	if (nread > 0 && (strstr(temp, phys)) != NULL)
367 		found = true;
368 
369 	close(fd);
370 
371 	return found;
372 }
373 
374 static int get_hid_id(struct uhid_device *hid)
375 {
376 	const char *workdir = "/sys/devices/virtual/misc/uhid";
377 	const char *str_id;
378 	DIR *d;
379 	struct dirent *dir;
380 	int found = -1, attempts = 3;
381 
382 	/* it would be nice to be able to use nftw, but the no_alu32 target doesn't support it */
383 
384 	while (found < 0 && attempts > 0) {
385 		attempts--;
386 		d = opendir(workdir);
387 		if (d) {
388 			while ((dir = readdir(d)) != NULL) {
389 				if (!match_sysfs_device(hid, workdir, dir))
390 					continue;
391 
392 				str_id = dir->d_name + sizeof("0000:0000:0000.");
393 				found = (int)strtol(str_id, NULL, 16);
394 
395 				break;
396 			}
397 			closedir(d);
398 		}
399 		if (found < 0)
400 			usleep(100000);
401 	}
402 
403 	return found;
404 }
405 
406 static int get_hidraw(struct uhid_device *hid)
407 {
408 	const char *workdir = "/sys/devices/virtual/misc/uhid";
409 	char sysfs[1024];
410 	DIR *d, *subd;
411 	struct dirent *dir, *subdir;
412 	int i, found = -1;
413 
414 	/* retry 5 times in case the system is loaded */
415 	for (i = 5; i > 0; i--) {
416 		usleep(10);
417 		d = opendir(workdir);
418 
419 		if (!d)
420 			continue;
421 
422 		while ((dir = readdir(d)) != NULL) {
423 			if (!match_sysfs_device(hid, workdir, dir))
424 				continue;
425 
426 			sprintf(sysfs, "%s/%s/hidraw", workdir, dir->d_name);
427 
428 			subd = opendir(sysfs);
429 			if (!subd)
430 				continue;
431 
432 			while ((subdir = readdir(subd)) != NULL) {
433 				if (fnmatch("hidraw*", subdir->d_name, 0))
434 					continue;
435 
436 				found = atoi(subdir->d_name + strlen("hidraw"));
437 			}
438 
439 			closedir(subd);
440 
441 			if (found > 0)
442 				break;
443 		}
444 		closedir(d);
445 	}
446 
447 	return found;
448 }
449 
450 static int open_hidraw(struct uhid_device *hid)
451 {
452 	int hidraw_number;
453 	char hidraw_path[64] = { 0 };
454 
455 	hidraw_number = get_hidraw(hid);
456 	if (hidraw_number < 0)
457 		return hidraw_number;
458 
459 	/* open hidraw node to check the other side of the pipe */
460 	sprintf(hidraw_path, "/dev/hidraw%d", hidraw_number);
461 	return open(hidraw_path, O_RDWR | O_NONBLOCK);
462 }
463 
464 static int setup_uhid(struct __test_metadata *_metadata, struct uhid_device *hid,
465 		      __u16 bus, __u32 vid, __u32 pid, const __u8 *rdesc, size_t rdesc_size)
466 {
467 	const char *path = "/dev/uhid";
468 	time_t t;
469 	int ret;
470 
471 	/* initialize random number generator */
472 	srand((unsigned int)time(&t));
473 
474 	hid->dev_id = rand() % 1024;
475 	hid->bus = bus;
476 	hid->vid = vid;
477 	hid->pid = pid;
478 
479 	hid->uhid_fd = open(path, O_RDWR | O_CLOEXEC);
480 	ASSERT_GE(hid->uhid_fd, 0) TH_LOG("open uhid-cdev failed; %d", hid->uhid_fd);
481 
482 	ret = uhid_create(_metadata, hid->uhid_fd, hid->dev_id, bus, vid, pid,
483 			  (__u8 *)rdesc, rdesc_size);
484 	ASSERT_EQ(0, ret) {
485 		TH_LOG("create uhid device failed: %d", ret);
486 		close(hid->uhid_fd);
487 		return ret;
488 	}
489 
490 	/* locate the uevent file of the created device */
491 	hid->hid_id = get_hid_id(hid);
492 	ASSERT_GT(hid->hid_id, 0)
493 		TH_LOG("Could not locate uhid device id: %d", hid->hid_id);
494 
495 	ret = uhid_start_listener(_metadata, &hid->tid, hid->uhid_fd);
496 	ASSERT_EQ(0, ret) {
497 		TH_LOG("could not start udev listener: %d", ret);
498 		close(hid->uhid_fd);
499 		return ret;
500 	}
501 
502 	return 0;
503 }
504