xref: /freebsd/lib/libusb/libusb10_hotplug.c (revision 4981b8968d19f009347ee8844770e84f9b83311e)
1 /*-
2  * Copyright (c) 2016-2019 Hans Petter Selasky. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25 
26 #include <netlink/netlink_snl_generic.h>
27 #ifdef LIBUSB_GLOBAL_INCLUDE_FILE
28 #include LIBUSB_GLOBAL_INCLUDE_FILE
29 #else
30 #include <assert.h>
31 #include <errno.h>
32 #include <poll.h>
33 #include <pthread.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <time.h>
39 #include <sys/fcntl.h>
40 #include <sys/ioctl.h>
41 #include <sys/queue.h>
42 #include <sys/endian.h>
43 #include <sys/socket.h>
44 #include <sys/un.h>
45 #include <sys/module.h>
46 #include <sys/linker.h>
47 #endif
48 
49 #define	libusb_device_handle libusb20_device
50 
51 #include "libusb20.h"
52 #include "libusb20_desc.h"
53 #include "libusb20_int.h"
54 #include "libusb.h"
55 #include "libusb10.h"
56 
57 #define DEVDPIPE	"/var/run/devd.seqpacket.pipe"
58 #define DEVCTL_MAXBUF	1024
59 
60 typedef enum {
61 	broken_event,
62 	invalid_event,
63 	valid_event,
64 } event_t;
65 
66 static bool
netlink_init(libusb_context * ctx)67 netlink_init(libusb_context *ctx)
68 {
69 	uint32_t group;
70 
71 	if (modfind("nlsysevent") < 0)
72 		kldload("nlsysevent");
73 	if (modfind("nlsysevent") < 0)
74 		return (false);
75 	if (!snl_init(&ctx->ss, NETLINK_GENERIC) || (group =
76 	    snl_get_genl_mcast_group(&ctx->ss, "nlsysevent", "USB", NULL)) == 0)
77 		return (false);
78 
79 	if (setsockopt(ctx->ss.fd, SOL_NETLINK, NETLINK_ADD_MEMBERSHIP, &group,
80 	    sizeof(group)) == -1)
81 		return (false);
82 
83 	ctx->usb_event_mode = usb_event_netlink;
84 	return (true);
85 }
86 
87 static bool
devd_init(libusb_context * ctx)88 devd_init(libusb_context *ctx)
89 {
90 	struct sockaddr_un devd_addr;
91 
92 	bzero(&devd_addr, sizeof(devd_addr));
93 	if ((ctx->devd_pipe = socket(PF_LOCAL, SOCK_SEQPACKET|SOCK_NONBLOCK, 0)) < 0)
94 		return (false);
95 
96 	devd_addr.sun_family = PF_LOCAL;
97 	strlcpy(devd_addr.sun_path, DEVDPIPE, sizeof(devd_addr.sun_path));
98 	if (connect(ctx->devd_pipe, (struct sockaddr *)&devd_addr,
99 	    sizeof(devd_addr)) == -1) {
100 		close(ctx->devd_pipe);
101 		ctx->devd_pipe = -1;
102 		return (false);
103 	}
104 
105 	ctx->usb_event_mode = usb_event_devd;
106 	return (true);
107 }
108 
109 struct nlevent {
110 	const char *name;
111 	const char *subsystem;
112 	const char *type;
113 	const char *data;
114 };
115 
116 #define	_OUT(_field)	offsetof(struct nlevent, _field)
117 static struct snl_attr_parser ap_nlevent_get[] = {
118 	{ .type = NLSE_ATTR_SYSTEM, .off = _OUT(name), .cb = snl_attr_get_string },
119 	{ .type = NLSE_ATTR_SUBSYSTEM, .off = _OUT(subsystem), .cb = snl_attr_get_string },
120 	{ .type = NLSE_ATTR_TYPE, .off = _OUT(type), .cb = snl_attr_get_string },
121 	{ .type = NLSE_ATTR_DATA, .off = _OUT(data), .cb = snl_attr_get_string },
122 };
123 #undef _OUT
124 
125 SNL_DECLARE_GENL_PARSER(nlevent_get_parser, ap_nlevent_get);
126 
127 static event_t
verify_event_validity(libusb_context * ctx)128 verify_event_validity(libusb_context *ctx)
129 {
130 	if (ctx->usb_event_mode == usb_event_netlink) {
131 		struct nlmsghdr *hdr;
132 		struct nlevent ne;
133 
134 		hdr = snl_read_message(&ctx->ss);
135 		if (hdr != NULL && hdr->nlmsg_type != NLMSG_ERROR) {
136 			memset(&ne, 0, sizeof(ne));
137 			if (!snl_parse_nlmsg(&ctx->ss, hdr, &nlevent_get_parser, &ne))
138 				return (broken_event);
139 			if (strcmp(ne.subsystem, "DEVICE") == 0)
140 				return (valid_event);
141 			return (invalid_event);
142 		}
143 		if (errno == EBADF)
144 			return (broken_event);
145 		return (invalid_event);
146 	} else if (ctx->usb_event_mode == usb_event_devd) {
147 		char buf[DEVCTL_MAXBUF];
148 		ssize_t len;
149 
150 		len = read(ctx->devd_pipe, buf, sizeof(buf));
151 		if (len == 0 || (len < 0 && errno != EWOULDBLOCK))
152 			return (broken_event);
153 		if (len > 0 && strstr(buf, "system=USB") != NULL &&
154 		    strstr(buf, "subsystem=DEVICE") != NULL)
155 			return (valid_event);
156 		return (invalid_event);
157 	}
158 	return (broken_event);
159 }
160 
161 static int
libusb_hotplug_equal(libusb_device * _adev,libusb_device * _bdev)162 libusb_hotplug_equal(libusb_device *_adev, libusb_device *_bdev)
163 {
164 	struct libusb20_device *adev = _adev->os_priv;
165 	struct libusb20_device *bdev = _bdev->os_priv;
166 
167 	if (adev->bus_number != bdev->bus_number)
168 		return (0);
169 	if (adev->device_address != bdev->device_address)
170 		return (0);
171 	if (memcmp(&adev->ddesc, &bdev->ddesc, sizeof(adev->ddesc)))
172 		return (0);
173 	if (memcmp(&adev->session_data, &bdev->session_data, sizeof(adev->session_data)))
174 		return (0);
175 	return (1);
176 }
177 
178 static int
libusb_hotplug_filter(libusb_context * ctx,libusb_hotplug_callback_handle pcbh,libusb_device * dev,libusb_hotplug_event event)179 libusb_hotplug_filter(libusb_context *ctx, libusb_hotplug_callback_handle pcbh,
180     libusb_device *dev, libusb_hotplug_event event)
181 {
182 	if (!(pcbh->events & event))
183 		return (0);
184 	if (pcbh->vendor != LIBUSB_HOTPLUG_MATCH_ANY &&
185 	    pcbh->vendor != libusb20_dev_get_device_desc(dev->os_priv)->idVendor)
186 		return (0);
187 	if (pcbh->product != LIBUSB_HOTPLUG_MATCH_ANY &&
188 	    pcbh->product != libusb20_dev_get_device_desc(dev->os_priv)->idProduct)
189 		return (0);
190 	if (pcbh->devclass != LIBUSB_HOTPLUG_MATCH_ANY &&
191 	    pcbh->devclass != libusb20_dev_get_device_desc(dev->os_priv)->bDeviceClass)
192 		return (0);
193 	return (pcbh->fn(ctx, dev, event, pcbh->user_data));
194 }
195 
196 static int
libusb_hotplug_enumerate(libusb_context * ctx,struct libusb_device_head * phead)197 libusb_hotplug_enumerate(libusb_context *ctx, struct libusb_device_head *phead)
198 {
199 	libusb_device **ppdev;
200 	ssize_t count;
201 	ssize_t x;
202 
203 	count = libusb_get_device_list(ctx, &ppdev);
204 	if (count < 0)
205 		return (-1);
206 
207 	for (x = 0; x != count; x++)
208 		TAILQ_INSERT_TAIL(phead, ppdev[x], hotplug_entry);
209 
210 	libusb_free_device_list(ppdev, 0);
211 	return (0);
212 }
213 
214 static void *
libusb_hotplug_scan(void * arg)215 libusb_hotplug_scan(void *arg)
216 {
217 	struct pollfd pfd;
218 	struct libusb_device_head hotplug_devs;
219 	libusb_hotplug_callback_handle acbh;
220 	libusb_hotplug_callback_handle bcbh;
221 	libusb_context *ctx = arg;
222 	libusb_device *temp;
223 	libusb_device *adev;
224 	libusb_device *bdev;
225 	int timeout = INFTIM;
226 	int nfds;
227 
228 	memset(&pfd, 0, sizeof(pfd));
229 	if (ctx->usb_event_mode == usb_event_devd) {
230 		pfd.fd = ctx->devd_pipe;
231 		pfd.events = POLLIN | POLLERR;
232 		nfds = 1;
233 	} else if (ctx->usb_event_mode == usb_event_netlink) {
234 		pfd.fd = ctx->ss.fd;
235 		pfd.events = POLLIN | POLLERR;
236 		nfds = 1;
237 	} else {
238 		nfds = 0;
239 		timeout = 4000;
240 	}
241 	for (;;) {
242 		pfd.revents = 0;
243 		if (poll(&pfd, nfds, timeout) > 0)  {
244 			switch (verify_event_validity(ctx)) {
245 			case invalid_event:
246 				continue;
247 			case valid_event:
248 				break;
249 			case broken_event:
250 				/* There are 2 cases for broken events:
251 				 * - devd and netlink sockets are not available
252 				 *   anymore (devd restarted, nlsysevent unloaded)
253 				 * - libusb_exit has been called as it sets NO_THREAD
254 				 *   this will result in exiting this loop and this thread
255 				 *   immediately
256 				 */
257 				nfds = 0;
258 				if (ctx->usb_event_mode == usb_event_devd) {
259 					if (ctx->devd_pipe != -1)
260 						close(ctx->devd_pipe);
261 				} else if (ctx->usb_event_mode == usb_event_netlink) {
262 					if (ctx->ss.fd != -1)
263 						close(ctx->ss.fd);
264 				}
265 				ctx->usb_event_mode = usb_event_scan;
266 				timeout = 4000;
267 				break;
268 			}
269 		}
270 
271 		HOTPLUG_LOCK(ctx);
272 		if (ctx->hotplug_handler == NO_THREAD) {
273 			while ((adev = TAILQ_FIRST(&ctx->hotplug_devs)) != NULL) {
274 				TAILQ_REMOVE(&ctx->hotplug_devs, adev, hotplug_entry);
275 				libusb_unref_device(adev);
276 			}
277 			if (ctx->usb_event_mode == usb_event_devd)
278 				close(ctx->devd_pipe);
279 			else if (ctx->usb_event_mode == usb_event_netlink)
280 				close(ctx->ss.fd);
281 			HOTPLUG_UNLOCK(ctx);
282 			break;
283 		}
284 
285 		TAILQ_INIT(&hotplug_devs);
286 
287 		if (libusb_hotplug_enumerate(ctx, &hotplug_devs) < 0) {
288 			HOTPLUG_UNLOCK(ctx);
289 			continue;
290 		}
291 
292 		/* figure out which devices are gone */
293 		TAILQ_FOREACH_SAFE(adev, &ctx->hotplug_devs, hotplug_entry, temp) {
294 			TAILQ_FOREACH(bdev, &hotplug_devs, hotplug_entry) {
295 				if (libusb_hotplug_equal(adev, bdev))
296 					break;
297 			}
298 			if (bdev == NULL) {
299 				TAILQ_REMOVE(&ctx->hotplug_devs, adev, hotplug_entry);
300 				TAILQ_FOREACH_SAFE(acbh, &ctx->hotplug_cbh, entry, bcbh) {
301 					if (libusb_hotplug_filter(ctx, acbh, adev,
302 					    LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) == 0)
303 						continue;
304 					TAILQ_REMOVE(&ctx->hotplug_cbh, acbh, entry);
305 					free(acbh);
306 				}
307 				libusb_unref_device(adev);
308 			}
309 		}
310 
311 		/* figure out which devices are new */
312 		TAILQ_FOREACH_SAFE(adev, &hotplug_devs, hotplug_entry, temp) {
313 			TAILQ_FOREACH(bdev, &ctx->hotplug_devs, hotplug_entry) {
314 				if (libusb_hotplug_equal(adev, bdev))
315 					break;
316 			}
317 			if (bdev == NULL) {
318 				TAILQ_REMOVE(&hotplug_devs, adev, hotplug_entry);
319 				TAILQ_INSERT_TAIL(&ctx->hotplug_devs, adev, hotplug_entry);
320 				TAILQ_FOREACH_SAFE(acbh, &ctx->hotplug_cbh, entry, bcbh) {
321 					if (libusb_hotplug_filter(ctx, acbh, adev,
322 					    LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) == 0)
323 						continue;
324 					TAILQ_REMOVE(&ctx->hotplug_cbh, acbh, entry);
325 					free(acbh);
326 				}
327 			}
328 		}
329 		HOTPLUG_UNLOCK(ctx);
330 
331 		/* unref remaining devices */
332 		while ((adev = TAILQ_FIRST(&hotplug_devs)) != NULL) {
333 			TAILQ_REMOVE(&hotplug_devs, adev, hotplug_entry);
334 			libusb_unref_device(adev);
335 		}
336 	}
337 	return (NULL);
338 }
339 
libusb_hotplug_register_callback(libusb_context * ctx,libusb_hotplug_event events,libusb_hotplug_flag flags,int vendor_id,int product_id,int dev_class,libusb_hotplug_callback_fn cb_fn,void * user_data,libusb_hotplug_callback_handle * phandle)340 int libusb_hotplug_register_callback(libusb_context *ctx,
341     libusb_hotplug_event events, libusb_hotplug_flag flags,
342     int vendor_id, int product_id, int dev_class,
343     libusb_hotplug_callback_fn cb_fn, void *user_data,
344     libusb_hotplug_callback_handle *phandle)
345 {
346 	libusb_hotplug_callback_handle handle;
347 	struct libusb_device *adev;
348 
349 	ctx = GET_CONTEXT(ctx);
350 
351 	if (ctx->usb_event_mode == usb_event_none) {
352 		HOTPLUG_LOCK(ctx);
353 		if (!netlink_init(ctx) && !devd_init(ctx))
354 			ctx->usb_event_mode = usb_event_scan;
355 		HOTPLUG_UNLOCK(ctx);
356 	}
357 
358 	if (ctx == NULL || cb_fn == NULL || events == 0 ||
359 	    vendor_id < -1 || vendor_id > 0xffff ||
360 	    product_id < -1 || product_id > 0xffff ||
361 	    dev_class < -1 || dev_class > 0xff)
362 		return (LIBUSB_ERROR_INVALID_PARAM);
363 
364 	handle = malloc(sizeof(*handle));
365 	if (handle == NULL)
366 		return (LIBUSB_ERROR_NO_MEM);
367 
368 	HOTPLUG_LOCK(ctx);
369 	if (ctx->hotplug_handler == NO_THREAD) {
370 	  	libusb_hotplug_enumerate(ctx, &ctx->hotplug_devs);
371 
372 		if (pthread_create(&ctx->hotplug_handler, NULL,
373 		    &libusb_hotplug_scan, ctx) != 0)
374 			ctx->hotplug_handler = NO_THREAD;
375 	}
376 	handle->events = events;
377 	handle->vendor = vendor_id;
378 	handle->product = product_id;
379 	handle->devclass = dev_class;
380 	handle->fn = cb_fn;
381 	handle->user_data = user_data;
382 
383 	if (flags & LIBUSB_HOTPLUG_ENUMERATE) {
384 		TAILQ_FOREACH(adev, &ctx->hotplug_devs, hotplug_entry) {
385 			if (libusb_hotplug_filter(ctx, handle, adev,
386 			    LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) == 0)
387 				continue;
388 			free(handle);
389 			handle = NULL;
390 			break;
391 		}
392 	}
393 	if (handle != NULL)
394 		TAILQ_INSERT_TAIL(&ctx->hotplug_cbh, handle, entry);
395 	HOTPLUG_UNLOCK(ctx);
396 
397 	if (phandle != NULL)
398 		*phandle = handle;
399 	return (LIBUSB_SUCCESS);
400 }
401 
libusb_hotplug_deregister_callback(libusb_context * ctx,libusb_hotplug_callback_handle handle)402 void libusb_hotplug_deregister_callback(libusb_context *ctx,
403     libusb_hotplug_callback_handle handle)
404 {
405   	ctx = GET_CONTEXT(ctx);
406 
407 	if (ctx == NULL || handle == NULL)
408 		return;
409 
410 	HOTPLUG_LOCK(ctx);
411 	TAILQ_REMOVE(&ctx->hotplug_cbh, handle, entry);
412 	libusb_interrupt_event_handler(ctx);
413 	HOTPLUG_UNLOCK(ctx);
414 
415 	free(handle);
416 }
417