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", "ACPI", 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 return (invalid_event);
144 } else if (ctx->usb_event_mode == usb_event_devd) {
145 char buf[DEVCTL_MAXBUF];
146 ssize_t len;
147
148 len = read(ctx->devd_pipe, buf, sizeof(buf));
149 if (len == 0 || (len < 0 && errno != EWOULDBLOCK))
150 return (broken_event);
151 if (len > 0 && strstr(buf, "system=USB") != NULL &&
152 strstr(buf, "subsystem=DEVICE") != NULL)
153 return (valid_event);
154 return (invalid_event);
155 }
156 return (broken_event);
157 }
158
159 static int
libusb_hotplug_equal(libusb_device * _adev,libusb_device * _bdev)160 libusb_hotplug_equal(libusb_device *_adev, libusb_device *_bdev)
161 {
162 struct libusb20_device *adev = _adev->os_priv;
163 struct libusb20_device *bdev = _bdev->os_priv;
164
165 if (adev->bus_number != bdev->bus_number)
166 return (0);
167 if (adev->device_address != bdev->device_address)
168 return (0);
169 if (memcmp(&adev->ddesc, &bdev->ddesc, sizeof(adev->ddesc)))
170 return (0);
171 if (memcmp(&adev->session_data, &bdev->session_data, sizeof(adev->session_data)))
172 return (0);
173 return (1);
174 }
175
176 static int
libusb_hotplug_filter(libusb_context * ctx,libusb_hotplug_callback_handle pcbh,libusb_device * dev,libusb_hotplug_event event)177 libusb_hotplug_filter(libusb_context *ctx, libusb_hotplug_callback_handle pcbh,
178 libusb_device *dev, libusb_hotplug_event event)
179 {
180 if (!(pcbh->events & event))
181 return (0);
182 if (pcbh->vendor != LIBUSB_HOTPLUG_MATCH_ANY &&
183 pcbh->vendor != libusb20_dev_get_device_desc(dev->os_priv)->idVendor)
184 return (0);
185 if (pcbh->product != LIBUSB_HOTPLUG_MATCH_ANY &&
186 pcbh->product != libusb20_dev_get_device_desc(dev->os_priv)->idProduct)
187 return (0);
188 if (pcbh->devclass != LIBUSB_HOTPLUG_MATCH_ANY &&
189 pcbh->devclass != libusb20_dev_get_device_desc(dev->os_priv)->bDeviceClass)
190 return (0);
191 return (pcbh->fn(ctx, dev, event, pcbh->user_data));
192 }
193
194 static int
libusb_hotplug_enumerate(libusb_context * ctx,struct libusb_device_head * phead)195 libusb_hotplug_enumerate(libusb_context *ctx, struct libusb_device_head *phead)
196 {
197 libusb_device **ppdev;
198 ssize_t count;
199 ssize_t x;
200
201 count = libusb_get_device_list(ctx, &ppdev);
202 if (count < 0)
203 return (-1);
204
205 for (x = 0; x != count; x++)
206 TAILQ_INSERT_TAIL(phead, ppdev[x], hotplug_entry);
207
208 libusb_free_device_list(ppdev, 0);
209 return (0);
210 }
211
212 static void *
libusb_hotplug_scan(void * arg)213 libusb_hotplug_scan(void *arg)
214 {
215 struct pollfd pfd;
216 struct libusb_device_head hotplug_devs;
217 libusb_hotplug_callback_handle acbh;
218 libusb_hotplug_callback_handle bcbh;
219 libusb_context *ctx = arg;
220 libusb_device *temp;
221 libusb_device *adev;
222 libusb_device *bdev;
223 int timeout = INFTIM;
224 int nfds;
225
226 memset(&pfd, 0, sizeof(pfd));
227 if (ctx->usb_event_mode == usb_event_devd) {
228 pfd.fd = ctx->devd_pipe;
229 pfd.events = POLLIN | POLLERR;
230 nfds = 1;
231 } else if (ctx->usb_event_mode == usb_event_netlink) {
232 pfd.fd = ctx->ss.fd;
233 pfd.events = POLLIN | POLLERR;
234 nfds = 1;
235 } else {
236 nfds = 0;
237 timeout = 4000;
238 }
239 for (;;) {
240 pfd.revents = 0;
241 if (poll(&pfd, nfds, timeout) > 0) {
242 switch (verify_event_validity(ctx)) {
243 case invalid_event:
244 continue;
245 case valid_event:
246 break;
247 case broken_event:
248 /* There are 2 cases for broken events:
249 * - devd and netlink sockets are not available
250 * anymore (devd restarted, nlsysevent unloaded)
251 * - libusb_exit has been called as it sets NO_THREAD
252 * this will result in exiting this loop and this thread
253 * immediately
254 */
255 nfds = 0;
256 if (ctx->usb_event_mode == usb_event_devd) {
257 if (ctx->devd_pipe != -1)
258 close(ctx->devd_pipe);
259 } else if (ctx->usb_event_mode == usb_event_netlink) {
260 if (ctx->ss.fd != -1)
261 close(ctx->ss.fd);
262 }
263 ctx->usb_event_mode = usb_event_scan;
264 timeout = 4000;
265 break;
266 }
267 }
268
269 HOTPLUG_LOCK(ctx);
270 if (ctx->hotplug_handler == NO_THREAD) {
271 while ((adev = TAILQ_FIRST(&ctx->hotplug_devs)) != NULL) {
272 TAILQ_REMOVE(&ctx->hotplug_devs, adev, hotplug_entry);
273 libusb_unref_device(adev);
274 }
275 if (ctx->usb_event_mode == usb_event_devd)
276 close(ctx->devd_pipe);
277 else if (ctx->usb_event_mode == usb_event_netlink)
278 close(ctx->ss.fd);
279 HOTPLUG_UNLOCK(ctx);
280 break;
281 }
282
283 TAILQ_INIT(&hotplug_devs);
284
285 if (libusb_hotplug_enumerate(ctx, &hotplug_devs) < 0) {
286 HOTPLUG_UNLOCK(ctx);
287 continue;
288 }
289
290 /* figure out which devices are gone */
291 TAILQ_FOREACH_SAFE(adev, &ctx->hotplug_devs, hotplug_entry, temp) {
292 TAILQ_FOREACH(bdev, &hotplug_devs, hotplug_entry) {
293 if (libusb_hotplug_equal(adev, bdev))
294 break;
295 }
296 if (bdev == NULL) {
297 TAILQ_REMOVE(&ctx->hotplug_devs, adev, hotplug_entry);
298 TAILQ_FOREACH_SAFE(acbh, &ctx->hotplug_cbh, entry, bcbh) {
299 if (libusb_hotplug_filter(ctx, acbh, adev,
300 LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT) == 0)
301 continue;
302 TAILQ_REMOVE(&ctx->hotplug_cbh, acbh, entry);
303 free(acbh);
304 }
305 libusb_unref_device(adev);
306 }
307 }
308
309 /* figure out which devices are new */
310 TAILQ_FOREACH_SAFE(adev, &hotplug_devs, hotplug_entry, temp) {
311 TAILQ_FOREACH(bdev, &ctx->hotplug_devs, hotplug_entry) {
312 if (libusb_hotplug_equal(adev, bdev))
313 break;
314 }
315 if (bdev == NULL) {
316 TAILQ_REMOVE(&hotplug_devs, adev, hotplug_entry);
317 TAILQ_INSERT_TAIL(&ctx->hotplug_devs, adev, hotplug_entry);
318 TAILQ_FOREACH_SAFE(acbh, &ctx->hotplug_cbh, entry, bcbh) {
319 if (libusb_hotplug_filter(ctx, acbh, adev,
320 LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) == 0)
321 continue;
322 TAILQ_REMOVE(&ctx->hotplug_cbh, acbh, entry);
323 free(acbh);
324 }
325 }
326 }
327 HOTPLUG_UNLOCK(ctx);
328
329 /* unref remaining devices */
330 while ((adev = TAILQ_FIRST(&hotplug_devs)) != NULL) {
331 TAILQ_REMOVE(&hotplug_devs, adev, hotplug_entry);
332 libusb_unref_device(adev);
333 }
334 }
335 return (NULL);
336 }
337
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)338 int libusb_hotplug_register_callback(libusb_context *ctx,
339 libusb_hotplug_event events, libusb_hotplug_flag flags,
340 int vendor_id, int product_id, int dev_class,
341 libusb_hotplug_callback_fn cb_fn, void *user_data,
342 libusb_hotplug_callback_handle *phandle)
343 {
344 libusb_hotplug_callback_handle handle;
345 struct libusb_device *adev;
346
347 ctx = GET_CONTEXT(ctx);
348
349 if (ctx->usb_event_mode == usb_event_none) {
350 HOTPLUG_LOCK(ctx);
351 if (!netlink_init(ctx) && !devd_init(ctx))
352 ctx->usb_event_mode = usb_event_scan;
353 HOTPLUG_UNLOCK(ctx);
354 }
355
356 if (ctx == NULL || cb_fn == NULL || events == 0 ||
357 vendor_id < -1 || vendor_id > 0xffff ||
358 product_id < -1 || product_id > 0xffff ||
359 dev_class < -1 || dev_class > 0xff)
360 return (LIBUSB_ERROR_INVALID_PARAM);
361
362 handle = malloc(sizeof(*handle));
363 if (handle == NULL)
364 return (LIBUSB_ERROR_NO_MEM);
365
366 HOTPLUG_LOCK(ctx);
367 if (ctx->hotplug_handler == NO_THREAD) {
368 libusb_hotplug_enumerate(ctx, &ctx->hotplug_devs);
369
370 if (pthread_create(&ctx->hotplug_handler, NULL,
371 &libusb_hotplug_scan, ctx) != 0)
372 ctx->hotplug_handler = NO_THREAD;
373 }
374 handle->events = events;
375 handle->vendor = vendor_id;
376 handle->product = product_id;
377 handle->devclass = dev_class;
378 handle->fn = cb_fn;
379 handle->user_data = user_data;
380
381 if (flags & LIBUSB_HOTPLUG_ENUMERATE) {
382 TAILQ_FOREACH(adev, &ctx->hotplug_devs, hotplug_entry) {
383 if (libusb_hotplug_filter(ctx, handle, adev,
384 LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED) == 0)
385 continue;
386 free(handle);
387 handle = NULL;
388 break;
389 }
390 }
391 if (handle != NULL)
392 TAILQ_INSERT_TAIL(&ctx->hotplug_cbh, handle, entry);
393 HOTPLUG_UNLOCK(ctx);
394
395 if (phandle != NULL)
396 *phandle = handle;
397 return (LIBUSB_SUCCESS);
398 }
399
libusb_hotplug_deregister_callback(libusb_context * ctx,libusb_hotplug_callback_handle handle)400 void libusb_hotplug_deregister_callback(libusb_context *ctx,
401 libusb_hotplug_callback_handle handle)
402 {
403 ctx = GET_CONTEXT(ctx);
404
405 if (ctx == NULL || handle == NULL)
406 return;
407
408 HOTPLUG_LOCK(ctx);
409 TAILQ_REMOVE(&ctx->hotplug_cbh, handle, entry);
410 HOTPLUG_UNLOCK(ctx);
411
412 free(handle);
413 }
414