VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/linux/USBGetDevices.cpp@ 97698

Last change on this file since 97698 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 60.0 KB
Line 
1/* $Id: USBGetDevices.cpp 96407 2022-08-22 17:43:14Z vboxsync $ */
2/** @file
3 * VirtualBox Linux host USB device enumeration.
4 */
5
6/*
7 * Copyright (C) 2006-2022 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#define VBOX_USB_WITH_USBFS
33#include "USBGetDevices.h"
34
35#include <VBox/err.h>
36#include <VBox/usb.h>
37#include <VBox/usblib.h>
38
39#include <iprt/linux/sysfs.h>
40#include <iprt/cdefs.h>
41#include <iprt/ctype.h>
42#include <iprt/dir.h>
43#include <iprt/env.h>
44#include <iprt/file.h>
45#include <iprt/fs.h>
46#include <iprt/log.h>
47#include <iprt/mem.h>
48#include <iprt/param.h>
49#include <iprt/path.h>
50#include <iprt/string.h>
51#include "vector.h"
52
53#ifdef VBOX_WITH_LINUX_COMPILER_H
54# include <linux/compiler.h>
55#endif
56#include <linux/usbdevice_fs.h>
57
58#include <sys/sysmacros.h>
59#include <sys/types.h>
60#include <sys/stat.h>
61#include <sys/vfs.h>
62
63#include <dirent.h>
64#include <dlfcn.h>
65#include <errno.h>
66#include <fcntl.h>
67#include <stdio.h>
68#include <string.h>
69#include <unistd.h>
70
71
72/*********************************************************************************************************************************
73* Structures and Typedefs *
74*********************************************************************************************************************************/
75/** Structure describing a host USB device */
76typedef struct USBDeviceInfo
77{
78 /** The device node of the device. */
79 char *mDevice;
80 /** The system identifier of the device. Specific to the probing
81 * method. */
82 char *mSysfsPath;
83 /** List of interfaces as sysfs paths */
84 VECTOR_PTR(char *) mvecpszInterfaces;
85} USBDeviceInfo;
86
87
88/**
89 * Does some extra checks to improve the detected device state.
90 *
91 * We cannot distinguish between USED_BY_HOST_CAPTURABLE and
92 * USED_BY_GUEST, HELD_BY_PROXY all that well and it shouldn't be
93 * necessary either.
94 *
95 * We will however, distinguish between the device we have permissions
96 * to open and those we don't. This is necessary for two reasons.
97 *
98 * Firstly, because it's futile to even attempt opening a device which we
99 * don't have access to, it only serves to confuse the user. (That said,
100 * it might also be a bit confusing for the user to see that a USB device
101 * is grayed out with no further explanation, and no way of generating an
102 * error hinting at why this is the case.)
103 *
104 * Secondly and more importantly, we're racing against udevd with respect
105 * to permissions and group settings on newly plugged devices. When we
106 * detect a new device that we cannot access we will poll on it for a few
107 * seconds to give udevd time to fix it. The polling is actually triggered
108 * in the 'new device' case in the compare loop.
109 *
110 * The USBDEVICESTATE_USED_BY_HOST state is only used for this no-access
111 * case, while USBDEVICESTATE_UNSUPPORTED is only used in the 'hub' case.
112 * When it's neither of these, we set USBDEVICESTATE_UNUSED or
113 * USBDEVICESTATE_USED_BY_HOST_CAPTURABLE depending on whether there is
114 * a driver associated with any of the interfaces.
115 *
116 * All except the access check and a special idVendor == 0 precaution
117 * is handled at parse time.
118 *
119 * @returns The adjusted state.
120 * @param pDevice The device.
121 */
122static USBDEVICESTATE usbDeterminState(PCUSBDEVICE pDevice)
123{
124 /*
125 * If it's already flagged as unsupported, there is nothing to do.
126 */
127 USBDEVICESTATE enmState = pDevice->enmState;
128 if (enmState == USBDEVICESTATE_UNSUPPORTED)
129 return USBDEVICESTATE_UNSUPPORTED;
130
131 /*
132 * Root hubs and similar doesn't have any vendor id, just
133 * refuse these device.
134 */
135 if (!pDevice->idVendor)
136 return USBDEVICESTATE_UNSUPPORTED;
137
138 /*
139 * Check if we've got access to the device, if we haven't flag
140 * it as used-by-host.
141 */
142#ifndef VBOX_USB_WITH_SYSFS
143 const char *pszAddress = pDevice->pszAddress;
144#else
145 if (pDevice->pszAddress == NULL)
146 /* We can't do much with the device without an address. */
147 return USBDEVICESTATE_UNSUPPORTED;
148 const char *pszAddress = strstr(pDevice->pszAddress, "//device:");
149 pszAddress = pszAddress != NULL
150 ? pszAddress + sizeof("//device:") - 1
151 : pDevice->pszAddress;
152#endif
153 if ( access(pszAddress, R_OK | W_OK) != 0
154 && errno == EACCES)
155 return USBDEVICESTATE_USED_BY_HOST;
156
157#ifdef VBOX_USB_WITH_SYSFS
158 /**
159 * @todo Check that any other essential fields are present and mark as
160 * invalid if not. Particularly to catch the case where the device was
161 * unplugged while we were reading in its properties.
162 */
163#endif
164
165 return enmState;
166}
167
168
169/**
170 * Dumps a USBDEVICE structure to the log using LogLevel 3.
171 * @param pDev The structure to log.
172 * @todo This is really common code.
173 */
174static void usbLogDevice(PUSBDEVICE pDev)
175{
176 NOREF(pDev);
177 if (LogIs3Enabled())
178 {
179 Log3(("USB device:\n"));
180 Log3(("Product: %s (%x)\n", pDev->pszProduct, pDev->idProduct));
181 Log3(("Manufacturer: %s (Vendor ID %x)\n", pDev->pszManufacturer, pDev->idVendor));
182 Log3(("Serial number: %s (%llx)\n", pDev->pszSerialNumber, pDev->u64SerialHash));
183 Log3(("Device revision: %d\n", pDev->bcdDevice));
184 Log3(("Device class: %x\n", pDev->bDeviceClass));
185 Log3(("Device subclass: %x\n", pDev->bDeviceSubClass));
186 Log3(("Device protocol: %x\n", pDev->bDeviceProtocol));
187 Log3(("USB version number: %d\n", pDev->bcdUSB));
188 Log3(("Device speed: %s\n",
189 pDev->enmSpeed == USBDEVICESPEED_UNKNOWN ? "unknown"
190 : pDev->enmSpeed == USBDEVICESPEED_LOW ? "1.5 MBit/s"
191 : pDev->enmSpeed == USBDEVICESPEED_FULL ? "12 MBit/s"
192 : pDev->enmSpeed == USBDEVICESPEED_HIGH ? "480 MBit/s"
193 : pDev->enmSpeed == USBDEVICESPEED_SUPER ? "5.0 GBit/s"
194 : pDev->enmSpeed == USBDEVICESPEED_VARIABLE ? "variable"
195 : "invalid"));
196 Log3(("Number of configurations: %d\n", pDev->bNumConfigurations));
197 Log3(("Bus number: %d\n", pDev->bBus));
198 Log3(("Port number: %d\n", pDev->bPort));
199 Log3(("Device number: %d\n", pDev->bDevNum));
200 Log3(("Device state: %s\n",
201 pDev->enmState == USBDEVICESTATE_UNSUPPORTED ? "unsupported"
202 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST ? "in use by host"
203 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE ? "in use by host, possibly capturable"
204 : pDev->enmState == USBDEVICESTATE_UNUSED ? "not in use"
205 : pDev->enmState == USBDEVICESTATE_HELD_BY_PROXY ? "held by proxy"
206 : pDev->enmState == USBDEVICESTATE_USED_BY_GUEST ? "used by guest"
207 : "invalid"));
208 Log3(("OS device address: %s\n", pDev->pszAddress));
209 }
210}
211
212
213#ifdef VBOX_USB_WITH_USBFS
214
215/**
216 * "reads" the number suffix.
217 *
218 * It's more like validating it and skipping the necessary number of chars.
219 */
220static int usbfsReadSkipSuffix(char **ppszNext)
221{
222 char *pszNext = *ppszNext;
223 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
224 {
225 /* skip unit */
226 if (pszNext[0] == 'm' && pszNext[1] == 's')
227 pszNext += 2;
228 else if (pszNext[0] == 'm' && pszNext[1] == 'A')
229 pszNext += 2;
230
231 /* skip parenthesis */
232 if (*pszNext == '(')
233 {
234 pszNext = strchr(pszNext, ')');
235 if (!pszNext++)
236 {
237 AssertMsgFailed(("*ppszNext=%s\n", *ppszNext));
238 return VERR_PARSE_ERROR;
239 }
240 }
241
242 /* blank or end of the line. */
243 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
244 {
245 AssertMsgFailed(("pszNext=%s\n", pszNext));
246 return VERR_PARSE_ERROR;
247 }
248
249 /* it's ok. */
250 *ppszNext = pszNext;
251 }
252
253 return VINF_SUCCESS;
254}
255
256
257/**
258 * Reads a USB number returning the number and the position of the next character to parse.
259 */
260static int usbfsReadNum(const char *pszValue, unsigned uBase, uint32_t u32Mask, void *pvNum, char **ppszNext)
261{
262 /*
263 * Initialize return value to zero and strip leading spaces.
264 */
265 switch (u32Mask)
266 {
267 case 0xff: *(uint8_t *)pvNum = 0; break;
268 case 0xffff: *(uint16_t *)pvNum = 0; break;
269 case 0xffffffff: *(uint32_t *)pvNum = 0; break;
270 }
271 pszValue = RTStrStripL(pszValue);
272 if (*pszValue)
273 {
274 /*
275 * Try convert the number.
276 */
277 char *pszNext;
278 uint32_t u32 = 0;
279 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32);
280 if (pszNext == pszValue)
281 {
282 AssertMsgFailed(("pszValue=%d\n", pszValue));
283 return VERR_NO_DATA;
284 }
285
286 /*
287 * Check the range.
288 */
289 if (u32 & ~u32Mask)
290 {
291 AssertMsgFailed(("pszValue=%d u32=%#x lMask=%#x\n", pszValue, u32, u32Mask));
292 return VERR_OUT_OF_RANGE;
293 }
294
295 int rc = usbfsReadSkipSuffix(&pszNext);
296 if (RT_FAILURE(rc))
297 return rc;
298
299 *ppszNext = pszNext;
300
301 /*
302 * Set the value.
303 */
304 switch (u32Mask)
305 {
306 case 0xff: *(uint8_t *)pvNum = (uint8_t)u32; break;
307 case 0xffff: *(uint16_t *)pvNum = (uint16_t)u32; break;
308 case 0xffffffff: *(uint32_t *)pvNum = (uint32_t)u32; break;
309 }
310 }
311 return VINF_SUCCESS;
312}
313
314
315static int usbfsRead8(const char *pszValue, unsigned uBase, uint8_t *pu8, char **ppszNext)
316{
317 return usbfsReadNum(pszValue, uBase, 0xff, pu8, ppszNext);
318}
319
320
321static int usbfsRead16(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
322{
323 return usbfsReadNum(pszValue, uBase, 0xffff, pu16, ppszNext);
324}
325
326
327/**
328 * Reads a USB BCD number returning the number and the position of the next character to parse.
329 * The returned number contains the integer part in the high byte and the decimal part in the low byte.
330 */
331static int usbfsReadBCD(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
332{
333 /*
334 * Initialize return value to zero and strip leading spaces.
335 */
336 *pu16 = 0;
337 pszValue = RTStrStripL(pszValue);
338 if (*pszValue)
339 {
340 /*
341 * Try convert the number.
342 */
343 /* integer part */
344 char *pszNext;
345 uint32_t u32Int = 0;
346 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32Int);
347 if (pszNext == pszValue)
348 {
349 AssertMsgFailed(("pszValue=%s\n", pszValue));
350 return VERR_NO_DATA;
351 }
352 if (u32Int & ~0xff)
353 {
354 AssertMsgFailed(("pszValue=%s u32Int=%#x (int)\n", pszValue, u32Int));
355 return VERR_OUT_OF_RANGE;
356 }
357
358 /* skip dot and read decimal part */
359 if (*pszNext != '.')
360 {
361 AssertMsgFailed(("pszValue=%s pszNext=%s (int)\n", pszValue, pszNext));
362 return VERR_PARSE_ERROR;
363 }
364 char *pszValue2 = RTStrStripL(pszNext + 1);
365 uint32_t u32Dec = 0;
366 RTStrToUInt32Ex(pszValue2, &pszNext, uBase, &u32Dec);
367 if (pszNext == pszValue)
368 {
369 AssertMsgFailed(("pszValue=%s\n", pszValue));
370 return VERR_NO_DATA;
371 }
372 if (u32Dec & ~0xff)
373 {
374 AssertMsgFailed(("pszValue=%s u32Dec=%#x\n", pszValue, u32Dec));
375 return VERR_OUT_OF_RANGE;
376 }
377
378 /*
379 * Validate and skip stuff following the number.
380 */
381 int rc = usbfsReadSkipSuffix(&pszNext);
382 if (RT_FAILURE(rc))
383 return rc;
384 *ppszNext = pszNext;
385
386 /*
387 * Set the value.
388 */
389 *pu16 = (uint16_t)((u32Int << 8) | (uint16_t)u32Dec);
390 }
391 return VINF_SUCCESS;
392}
393
394
395/**
396 * Reads a string, i.e. allocates memory and copies it.
397 *
398 * We assume that a string is Utf8 and if that's not the case
399 * (pre-2.6.32-kernels used Latin-1, but so few devices return non-ASCII that
400 * this usually goes unnoticed) then we mercilessly force it to be so.
401 */
402static int usbfsReadStr(const char *pszValue, const char **ppsz)
403{
404 char *psz;
405
406 if (*ppsz)
407 RTStrFree((char *)*ppsz);
408 psz = RTStrDup(pszValue);
409 if (psz)
410 {
411 USBLibPurgeEncoding(psz);
412 *ppsz = psz;
413 return VINF_SUCCESS;
414 }
415 return VERR_NO_MEMORY;
416}
417
418
419/**
420 * Skips the current property.
421 */
422static char *usbfsReadSkip(char *pszValue)
423{
424 char *psz = strchr(pszValue, '=');
425 if (psz)
426 psz = strchr(psz + 1, '=');
427 if (!psz)
428 return strchr(pszValue, '\0');
429 while (psz > pszValue && !RT_C_IS_SPACE(psz[-1]))
430 psz--;
431 Assert(psz > pszValue);
432 return psz;
433}
434
435
436/**
437 * Determine the USB speed.
438 */
439static int usbfsReadSpeed(const char *pszValue, USBDEVICESPEED *pSpd, char **ppszNext)
440{
441 pszValue = RTStrStripL(pszValue);
442 /* verified with Linux 2.4.0 ... Linux 2.6.25 */
443 if (!strncmp(pszValue, RT_STR_TUPLE("1.5")))
444 *pSpd = USBDEVICESPEED_LOW;
445 else if (!strncmp(pszValue, RT_STR_TUPLE("12 ")))
446 *pSpd = USBDEVICESPEED_FULL;
447 else if (!strncmp(pszValue, RT_STR_TUPLE("480")))
448 *pSpd = USBDEVICESPEED_HIGH;
449 else if (!strncmp(pszValue, RT_STR_TUPLE("5000")))
450 *pSpd = USBDEVICESPEED_SUPER;
451 else
452 *pSpd = USBDEVICESPEED_UNKNOWN;
453 while (pszValue[0] != '\0' && !RT_C_IS_SPACE(pszValue[0]))
454 pszValue++;
455 *ppszNext = (char *)pszValue;
456 return VINF_SUCCESS;
457}
458
459
460/**
461 * Compare a prefix and returns pointer to the char following it if it matches.
462 */
463static char *usbfsPrefix(char *psz, const char *pszPref, size_t cchPref)
464{
465 if (strncmp(psz, pszPref, cchPref))
466 return NULL;
467 return psz + cchPref;
468}
469
470
471/** Just a worker for USBProxyServiceLinux::getDevices that avoids some code duplication. */
472static int usbfsAddDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, const char *pszUsbfsRoot,
473 bool fUnsupportedDevicesToo, int rc)
474{
475 /* usbDeterminState requires the address. */
476 PUSBDEVICE pDevNew = (PUSBDEVICE)RTMemDup(pDev, sizeof(*pDev));
477 if (pDevNew)
478 {
479 RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", pszUsbfsRoot, pDevNew->bBus, pDevNew->bDevNum);
480 if (pDevNew->pszAddress)
481 {
482 pDevNew->enmState = usbDeterminState(pDevNew);
483 if (pDevNew->enmState != USBDEVICESTATE_UNSUPPORTED || fUnsupportedDevicesToo)
484 {
485 if (*pppNext)
486 **pppNext = pDevNew;
487 else
488 *ppFirst = pDevNew;
489 *pppNext = &pDevNew->pNext;
490 }
491 else
492 deviceFree(pDevNew);
493 }
494 else
495 {
496 deviceFree(pDevNew);
497 rc = VERR_NO_MEMORY;
498 }
499 }
500 else
501 {
502 rc = VERR_NO_MEMORY;
503 deviceFreeMembers(pDev);
504 }
505
506 return rc;
507}
508
509
510static int usbfsOpenDevicesFile(const char *pszUsbfsRoot, FILE **ppFile)
511{
512 char *pszPath;
513 FILE *pFile;
514 RTStrAPrintf(&pszPath, "%s/devices", pszUsbfsRoot);
515 if (!pszPath)
516 return VERR_NO_MEMORY;
517 pFile = fopen(pszPath, "r");
518 RTStrFree(pszPath);
519 if (!pFile)
520 return RTErrConvertFromErrno(errno);
521 *ppFile = pFile;
522 return VINF_SUCCESS;
523}
524
525
526/**
527 * USBProxyService::getDevices() implementation for usbfs.
528 *
529 * The @a fUnsupportedDevicesToo flag tells the function to return information
530 * about unsupported devices as well. This is used as a sanity test to check
531 * that a devices file is really what we expect.
532 */
533static PUSBDEVICE usbfsGetDevices(const char *pszUsbfsRoot, bool fUnsupportedDevicesToo)
534{
535 PUSBDEVICE pFirst = NULL;
536 FILE *pFile = NULL;
537 int rc;
538 rc = usbfsOpenDevicesFile(pszUsbfsRoot, &pFile);
539 if (RT_SUCCESS(rc))
540 {
541 PUSBDEVICE *ppNext = NULL;
542 int cHits = 0;
543 char szLine[1024];
544 USBDEVICE Dev;
545 RT_ZERO(Dev);
546 Dev.enmState = USBDEVICESTATE_UNUSED;
547
548 /* Set close on exit and hope no one is racing us. */
549 rc = fcntl(fileno(pFile), F_SETFD, FD_CLOEXEC) >= 0
550 ? VINF_SUCCESS
551 : RTErrConvertFromErrno(errno);
552 while ( RT_SUCCESS(rc)
553 && fgets(szLine, sizeof(szLine), pFile))
554 {
555 char *psz;
556 char *pszValue;
557
558 /* validate and remove the trailing newline. */
559 psz = strchr(szLine, '\0');
560 if (psz[-1] != '\n' && !feof(pFile))
561 {
562 AssertMsgFailed(("Line too long. (cch=%d)\n", strlen(szLine)));
563 continue;
564 }
565
566 /* strip */
567 psz = RTStrStrip(szLine);
568 if (!*psz)
569 continue;
570
571 /*
572 * Interpret the line.
573 * (Ordered by normal occurrence.)
574 */
575 char ch = psz[0];
576 if (psz[1] != ':')
577 continue;
578 psz = RTStrStripL(psz + 3);
579#define PREFIX(str) ( (pszValue = usbfsPrefix(psz, str, sizeof(str) - 1)) != NULL )
580 switch (ch)
581 {
582 /*
583 * T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd
584 * | | | | | | | | |__MaxChildren
585 * | | | | | | | |__Device Speed in Mbps
586 * | | | | | | |__DeviceNumber
587 * | | | | | |__Count of devices at this level
588 * | | | | |__Connector/Port on Parent for this device
589 * | | | |__Parent DeviceNumber
590 * | | |__Level in topology for this bus
591 * | |__Bus number
592 * |__Topology info tag
593 */
594 case 'T':
595 /* add */
596 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
597 if (cHits >= 3)
598 rc = usbfsAddDeviceToChain(&Dev, &pFirst, &ppNext, pszUsbfsRoot, fUnsupportedDevicesToo, rc);
599 else
600 deviceFreeMembers(&Dev);
601
602 /* Reset device state */
603 RT_ZERO(Dev);
604 Dev.enmState = USBDEVICESTATE_UNUSED;
605 cHits = 1;
606
607 /* parse the line. */
608 while (*psz && RT_SUCCESS(rc))
609 {
610 if (PREFIX("Bus="))
611 rc = usbfsRead8(pszValue, 10, &Dev.bBus, &psz);
612 else if (PREFIX("Port="))
613 rc = usbfsRead8(pszValue, 10, &Dev.bPort, &psz);
614 else if (PREFIX("Spd="))
615 rc = usbfsReadSpeed(pszValue, &Dev.enmSpeed, &psz);
616 else if (PREFIX("Dev#="))
617 rc = usbfsRead8(pszValue, 10, &Dev.bDevNum, &psz);
618 else
619 psz = usbfsReadSkip(psz);
620 psz = RTStrStripL(psz);
621 }
622 break;
623
624 /*
625 * Bandwidth info:
626 * B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
627 * | | | |__Number of isochronous requests
628 * | | |__Number of interrupt requests
629 * | |__Total Bandwidth allocated to this bus
630 * |__Bandwidth info tag
631 */
632 case 'B':
633 break;
634
635 /*
636 * D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
637 * | | | | | | |__NumberConfigurations
638 * | | | | | |__MaxPacketSize of Default Endpoint
639 * | | | | |__DeviceProtocol
640 * | | | |__DeviceSubClass
641 * | | |__DeviceClass
642 * | |__Device USB version
643 * |__Device info tag #1
644 */
645 case 'D':
646 while (*psz && RT_SUCCESS(rc))
647 {
648 if (PREFIX("Ver="))
649 rc = usbfsReadBCD(pszValue, 16, &Dev.bcdUSB, &psz);
650 else if (PREFIX("Cls="))
651 {
652 rc = usbfsRead8(pszValue, 16, &Dev.bDeviceClass, &psz);
653 if (RT_SUCCESS(rc) && Dev.bDeviceClass == 9 /* HUB */)
654 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
655 }
656 else if (PREFIX("Sub="))
657 rc = usbfsRead8(pszValue, 16, &Dev.bDeviceSubClass, &psz);
658 else if (PREFIX("Prot="))
659 rc = usbfsRead8(pszValue, 16, &Dev.bDeviceProtocol, &psz);
660 //else if (PREFIX("MxPS="))
661 // rc = usbRead16(pszValue, 10, &Dev.wMaxPacketSize, &psz);
662 else if (PREFIX("#Cfgs="))
663 rc = usbfsRead8(pszValue, 10, &Dev.bNumConfigurations, &psz);
664 else
665 psz = usbfsReadSkip(psz);
666 psz = RTStrStripL(psz);
667 }
668 cHits++;
669 break;
670
671 /*
672 * P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
673 * | | | |__Product revision number
674 * | | |__Product ID code
675 * | |__Vendor ID code
676 * |__Device info tag #2
677 */
678 case 'P':
679 while (*psz && RT_SUCCESS(rc))
680 {
681 if (PREFIX("Vendor="))
682 rc = usbfsRead16(pszValue, 16, &Dev.idVendor, &psz);
683 else if (PREFIX("ProdID="))
684 rc = usbfsRead16(pszValue, 16, &Dev.idProduct, &psz);
685 else if (PREFIX("Rev="))
686 rc = usbfsReadBCD(pszValue, 16, &Dev.bcdDevice, &psz);
687 else
688 psz = usbfsReadSkip(psz);
689 psz = RTStrStripL(psz);
690 }
691 cHits++;
692 break;
693
694 /*
695 * String.
696 */
697 case 'S':
698 if (PREFIX("Manufacturer="))
699 rc = usbfsReadStr(pszValue, &Dev.pszManufacturer);
700 else if (PREFIX("Product="))
701 rc = usbfsReadStr(pszValue, &Dev.pszProduct);
702 else if (PREFIX("SerialNumber="))
703 {
704 rc = usbfsReadStr(pszValue, &Dev.pszSerialNumber);
705 if (RT_SUCCESS(rc))
706 Dev.u64SerialHash = USBLibHashSerial(pszValue);
707 }
708 break;
709
710 /*
711 * C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
712 * | | | | | |__MaxPower in mA
713 * | | | | |__Attributes
714 * | | | |__ConfiguratioNumber
715 * | | |__NumberOfInterfaces
716 * | |__ "*" indicates the active configuration (others are " ")
717 * |__Config info tag
718 */
719 case 'C':
720 break;
721
722 /*
723 * I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
724 * | | | | | | | |__Driver name
725 * | | | | | | | or "(none)"
726 * | | | | | | |__InterfaceProtocol
727 * | | | | | |__InterfaceSubClass
728 * | | | | |__InterfaceClass
729 * | | | |__NumberOfEndpoints
730 * | | |__AlternateSettingNumber
731 * | |__InterfaceNumber
732 * |__Interface info tag
733 */
734 case 'I':
735 {
736 /* Check for thing we don't support. */
737 while (*psz && RT_SUCCESS(rc))
738 {
739 if (PREFIX("Driver="))
740 {
741 const char *pszDriver = NULL;
742 rc = usbfsReadStr(pszValue, &pszDriver);
743 if ( !pszDriver
744 || !*pszDriver
745 || !strcmp(pszDriver, "(none)")
746 || !strcmp(pszDriver, "(no driver)"))
747 /* no driver */;
748 else if (!strcmp(pszDriver, "hub"))
749 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
750 else if (Dev.enmState == USBDEVICESTATE_UNUSED)
751 Dev.enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
752 RTStrFree((char *)pszDriver);
753 break; /* last attrib */
754 }
755 else if (PREFIX("Cls="))
756 {
757 uint8_t bInterfaceClass;
758 rc = usbfsRead8(pszValue, 16, &bInterfaceClass, &psz);
759 if (RT_SUCCESS(rc) && bInterfaceClass == 9 /* HUB */)
760 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
761 }
762 else
763 psz = usbfsReadSkip(psz);
764 psz = RTStrStripL(psz);
765 }
766 break;
767 }
768
769
770 /*
771 * E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddms
772 * | | | | |__Interval (max) between transfers
773 * | | | |__EndpointMaxPacketSize
774 * | | |__Attributes(EndpointType)
775 * | |__EndpointAddress(I=In,O=Out)
776 * |__Endpoint info tag
777 */
778 case 'E':
779 break;
780
781 }
782#undef PREFIX
783 } /* parse loop */
784 fclose(pFile);
785
786 /*
787 * Add the current entry.
788 */
789 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
790 if (cHits >= 3)
791 rc = usbfsAddDeviceToChain(&Dev, &pFirst, &ppNext, pszUsbfsRoot, fUnsupportedDevicesToo, rc);
792
793 /*
794 * Success?
795 */
796 if (RT_FAILURE(rc))
797 {
798 while (pFirst)
799 {
800 PUSBDEVICE pFree = pFirst;
801 pFirst = pFirst->pNext;
802 deviceFree(pFree);
803 }
804 }
805 }
806 if (RT_FAILURE(rc))
807 LogFlow(("USBProxyServiceLinux::getDevices: rc=%Rrc\n", rc));
808 return pFirst;
809}
810
811#endif /* VBOX_USB_WITH_USBFS */
812#ifdef VBOX_USB_WITH_SYSFS
813
814static void usbsysfsCleanupDevInfo(USBDeviceInfo *pSelf)
815{
816 RTStrFree(pSelf->mDevice);
817 RTStrFree(pSelf->mSysfsPath);
818 pSelf->mDevice = pSelf->mSysfsPath = NULL;
819 VEC_CLEANUP_PTR(&pSelf->mvecpszInterfaces);
820}
821
822
823static int usbsysfsInitDevInfo(USBDeviceInfo *pSelf, const char *aDevice, const char *aSystemID)
824{
825 pSelf->mDevice = aDevice ? RTStrDup(aDevice) : NULL;
826 pSelf->mSysfsPath = aSystemID ? RTStrDup(aSystemID) : NULL;
827 VEC_INIT_PTR(&pSelf->mvecpszInterfaces, char *, RTStrFree);
828 if ((aDevice && !pSelf->mDevice) || (aSystemID && ! pSelf->mSysfsPath))
829 {
830 usbsysfsCleanupDevInfo(pSelf);
831 return 0;
832 }
833 return 1;
834}
835
836# define USBDEVICE_MAJOR 189
837
838/**
839 * Calculate the bus (a.k.a root hub) number of a USB device from it's sysfs
840 * path.
841 *
842 * sysfs nodes representing root hubs have file names of the form
843 * usb<n>, where n is the bus number; other devices start with that number.
844 * See [http://www.linux-usb.org/FAQ.html#i6] and
845 * [http://www.kernel.org/doc/Documentation/usb/proc_usb_info.txt] for
846 * equivalent information about usbfs.
847 *
848 * @returns a bus number greater than 0 on success or 0 on failure.
849 */
850static unsigned usbsysfsGetBusFromPath(const char *pszPath)
851{
852 const char *pszFile = strrchr(pszPath, '/');
853 if (!pszFile)
854 return 0;
855 unsigned bus = RTStrToUInt32(pszFile + 1);
856 if ( !bus
857 && pszFile[1] == 'u' && pszFile[2] == 's' && pszFile[3] == 'b')
858 bus = RTStrToUInt32(pszFile + 4);
859 return bus;
860}
861
862
863/**
864 * Calculate the device number of a USB device.
865 *
866 * See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20.
867 */
868static dev_t usbsysfsMakeDevNum(unsigned bus, unsigned device)
869{
870 AssertReturn(bus > 0, 0);
871 AssertReturn(((device - 1) & ~127) == 0, 0);
872 AssertReturn(device > 0, 0);
873 return makedev(USBDEVICE_MAJOR, ((bus - 1) << 7) + device - 1);
874}
875
876
877/**
878 * If a file @a pszNode from /sys/bus/usb/devices is a device rather than an
879 * interface add an element for the device to @a pvecDevInfo.
880 */
881static int usbsysfsAddIfDevice(const char *pszDevicesRoot, const char *pszNode, VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
882{
883 const char *pszFile = strrchr(pszNode, '/');
884 if (!pszFile)
885 return VERR_INVALID_PARAMETER;
886 if (strchr(pszFile, ':'))
887 return VINF_SUCCESS;
888
889 unsigned bus = usbsysfsGetBusFromPath(pszNode);
890 if (!bus)
891 return VINF_SUCCESS;
892
893 int64_t device;
894 int rc = RTLinuxSysFsReadIntFile(10, &device, "%s/devnum", pszNode);
895 if (RT_FAILURE(rc))
896 return VINF_SUCCESS;
897
898 dev_t devnum = usbsysfsMakeDevNum(bus, (int)device);
899 if (!devnum)
900 return VINF_SUCCESS;
901
902 char szDevPath[RTPATH_MAX];
903 rc = RTLinuxCheckDevicePath(devnum, RTFS_TYPE_DEV_CHAR,
904 szDevPath, sizeof(szDevPath),
905 "%s/%.3d/%.3d",
906 pszDevicesRoot, bus, device);
907 if (RT_FAILURE(rc))
908 return VINF_SUCCESS;
909
910 USBDeviceInfo info;
911 if (usbsysfsInitDevInfo(&info, szDevPath, pszNode))
912 {
913 rc = VEC_PUSH_BACK_OBJ(pvecDevInfo, USBDeviceInfo, &info);
914 if (RT_SUCCESS(rc))
915 return VINF_SUCCESS;
916 }
917 usbsysfsCleanupDevInfo(&info);
918 return VERR_NO_MEMORY;
919}
920
921
922/**
923 * The logic for testing whether a sysfs address corresponds to an interface of
924 * a device.
925 *
926 * Both must be referenced by their canonical sysfs paths. This is not tested,
927 * as the test requires file-system interaction.
928 */
929static bool usbsysfsMuiIsAnInterfaceOf(const char *pszIface, const char *pszDev)
930{
931 size_t cchDev = strlen(pszDev);
932
933 AssertPtr(pszIface);
934 AssertPtr(pszDev);
935 Assert(pszIface[0] == '/');
936 Assert(pszDev[0] == '/');
937 Assert(pszDev[cchDev - 1] != '/');
938
939 /* If this passes, pszIface is at least cchDev long */
940 if (strncmp(pszIface, pszDev, cchDev))
941 return false;
942
943 /* If this passes, pszIface is longer than cchDev */
944 if (pszIface[cchDev] != '/')
945 return false;
946
947 /* In sysfs an interface is an immediate subdirectory of the device */
948 if (strchr(pszIface + cchDev + 1, '/'))
949 return false;
950
951 /* And it always has a colon in its name */
952 if (!strchr(pszIface + cchDev + 1, ':'))
953 return false;
954
955 /* And hopefully we have now elimitated everything else */
956 return true;
957}
958
959
960# ifdef DEBUG
961# ifdef __cplusplus
962/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
963class testIsAnInterfaceOf
964{
965public:
966 testIsAnInterfaceOf()
967 {
968 Assert(usbsysfsMuiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0",
969 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
970 Assert(!usbsysfsMuiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-1",
971 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
972 Assert(!usbsysfsMuiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0/driver",
973 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
974 }
975};
976static testIsAnInterfaceOf testIsAnInterfaceOfInst;
977# endif /* __cplusplus */
978# endif /* DEBUG */
979
980
981/**
982 * Tell whether a file in /sys/bus/usb/devices is an interface rather than a
983 * device.
984 */
985static int usbsysfsAddIfInterfaceOf(const char *pszNode, USBDeviceInfo *pInfo)
986{
987 if (!usbsysfsMuiIsAnInterfaceOf(pszNode, pInfo->mSysfsPath))
988 return VINF_SUCCESS;
989
990 char *pszDup = (char *)RTStrDup(pszNode);
991 if (pszDup)
992 {
993 int rc = VEC_PUSH_BACK_PTR(&pInfo->mvecpszInterfaces, char *, pszDup);
994 if (RT_SUCCESS(rc))
995 return VINF_SUCCESS;
996 RTStrFree(pszDup);
997 }
998 return VERR_NO_MEMORY;
999}
1000
1001
1002/**
1003 * Helper for usbsysfsReadFilePaths().
1004 *
1005 * Adds the entries from the open directory @a pDir to the vector @a pvecpchDevs
1006 * using either the full path or the realpath() and skipping hidden files and
1007 * files on which realpath() fails.
1008 */
1009static int usbsysfsReadFilePathsFromDir(const char *pszPath, DIR *pDir, VECTOR_PTR(char *) *pvecpchDevs)
1010{
1011 struct dirent entry, *pResult;
1012 int err, rc;
1013
1014#if RT_GNUC_PREREQ(4, 6)
1015# pragma GCC diagnostic push
1016# pragma GCC diagnostic ignored "-Wdeprecated-declarations"
1017#endif
1018 for (err = readdir_r(pDir, &entry, &pResult); pResult;
1019 err = readdir_r(pDir, &entry, &pResult))
1020#if RT_GNUC_PREREQ(4, 6)
1021# pragma GCC diagnostic pop
1022#endif
1023 {
1024 char szPath[RTPATH_MAX + 1];
1025 char szRealPath[RTPATH_MAX + 1];
1026 if (entry.d_name[0] == '.')
1027 continue;
1028 if (snprintf(szPath, sizeof(szPath), "%s/%s", pszPath, entry.d_name) < 0)
1029 return RTErrConvertFromErrno(errno); /** @todo r=bird: snprintf isn't document to set errno. Also, wouldn't it be better to continue on errors? Finally, you don't need to copy pszPath each time... */
1030 if (!realpath(szPath, szRealPath))
1031 return RTErrConvertFromErrno(errno);
1032 char *pszPathCopy = RTStrDup(szRealPath);
1033 if (!pszPathCopy)
1034 return VERR_NO_MEMORY;
1035 if (RT_FAILURE(rc = VEC_PUSH_BACK_PTR(pvecpchDevs, char *, pszPathCopy)))
1036 return rc;
1037 }
1038 return RTErrConvertFromErrno(err);
1039}
1040
1041
1042/**
1043 * Dump the names of a directory's entries into a vector of char pointers.
1044 *
1045 * @returns zero on success or (positive) posix error value.
1046 * @param pszPath the path to dump.
1047 * @param pvecpchDevs an empty vector of char pointers - must be cleaned up
1048 * by the caller even on failure.
1049 * @param withRealPath whether to canonicalise the filename with realpath
1050 */
1051static int usbsysfsReadFilePaths(const char *pszPath, VECTOR_PTR(char *) *pvecpchDevs)
1052{
1053 AssertPtrReturn(pvecpchDevs, EINVAL);
1054 AssertReturn(VEC_SIZE_PTR(pvecpchDevs) == 0, EINVAL);
1055 AssertPtrReturn(pszPath, EINVAL);
1056
1057 DIR *pDir = opendir(pszPath);
1058 if (!pDir)
1059 return RTErrConvertFromErrno(errno);
1060 int rc = usbsysfsReadFilePathsFromDir(pszPath, pDir, pvecpchDevs);
1061 if (closedir(pDir) < 0 && RT_SUCCESS(rc))
1062 rc = RTErrConvertFromErrno(errno);
1063 return rc;
1064}
1065
1066
1067/**
1068 * Logic for USBSysfsEnumerateHostDevices.
1069 *
1070 * @param pvecDevInfo vector of device information structures to add device
1071 * information to
1072 * @param pvecpchDevs empty scratch vector which will be freed by the caller,
1073 * to simplify exit logic
1074 */
1075static int usbsysfsEnumerateHostDevicesWorker(const char *pszDevicesRoot,
1076 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo,
1077 VECTOR_PTR(char *) *pvecpchDevs)
1078{
1079
1080 AssertPtrReturn(pvecDevInfo, VERR_INVALID_POINTER);
1081 LogFlowFunc (("pvecDevInfo=%p\n", pvecDevInfo));
1082
1083 int rc = usbsysfsReadFilePaths("/sys/bus/usb/devices", pvecpchDevs);
1084 if (RT_FAILURE(rc))
1085 return rc;
1086
1087 char **ppszEntry;
1088 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1089 {
1090 rc = usbsysfsAddIfDevice(pszDevicesRoot, *ppszEntry, pvecDevInfo);
1091 if (RT_FAILURE(rc))
1092 return rc;
1093 }
1094
1095 USBDeviceInfo *pInfo;
1096 VEC_FOR_EACH(pvecDevInfo, USBDeviceInfo, pInfo)
1097 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1098 {
1099 rc = usbsysfsAddIfInterfaceOf(*ppszEntry, pInfo);
1100 if (RT_FAILURE(rc))
1101 return rc;
1102 }
1103 return VINF_SUCCESS;
1104}
1105
1106
1107static int usbsysfsEnumerateHostDevices(const char *pszDevicesRoot, VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
1108{
1109 VECTOR_PTR(char *) vecpchDevs;
1110
1111 AssertReturn(VEC_SIZE_OBJ(pvecDevInfo) == 0, VERR_INVALID_PARAMETER);
1112 LogFlowFunc(("entered\n"));
1113 VEC_INIT_PTR(&vecpchDevs, char *, RTStrFree);
1114 int rc = usbsysfsEnumerateHostDevicesWorker(pszDevicesRoot, pvecDevInfo, &vecpchDevs);
1115 VEC_CLEANUP_PTR(&vecpchDevs);
1116 LogFlowFunc(("rc=%Rrc\n", rc));
1117 return rc;
1118}
1119
1120
1121/**
1122 * Helper function for extracting the port number on the parent device from
1123 * the sysfs path value.
1124 *
1125 * The sysfs path is a chain of elements separated by forward slashes, and for
1126 * USB devices, the last element in the chain takes the form
1127 * <port>-<port>.[...].<port>[:<config>.<interface>]
1128 * where the first <port> is the port number on the root hub, and the following
1129 * (optional) ones are the port numbers on any other hubs between the device
1130 * and the root hub. The last part (:<config.interface>) is only present for
1131 * interfaces, not for devices. This API should only be called for devices.
1132 * For compatibility with usbfs, which enumerates from zero up, we subtract one
1133 * from the port number.
1134 *
1135 * For root hubs, the last element in the chain takes the form
1136 * usb<hub number>
1137 * and usbfs always returns port number zero.
1138 *
1139 * @returns VBox status code. pu8Port is set on success.
1140 * @param pszPath The sysfs path to parse.
1141 * @param pu8Port Where to store the port number.
1142 */
1143static int usbsysfsGetPortFromStr(const char *pszPath, uint8_t *pu8Port)
1144{
1145 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1146 AssertPtrReturn(pu8Port, VERR_INVALID_POINTER);
1147
1148 /*
1149 * This should not be possible until we get PCs with USB as their primary bus.
1150 * Note: We don't assert this, as we don't expect the caller to validate the
1151 * sysfs path.
1152 */
1153 const char *pszLastComp = strrchr(pszPath, '/');
1154 if (!pszLastComp)
1155 {
1156 Log(("usbGetPortFromSysfsPath(%s): failed [1]\n", pszPath));
1157 return VERR_INVALID_PARAMETER;
1158 }
1159 pszLastComp++; /* skip the slash */
1160
1161 /*
1162 * This API should not be called for interfaces, so the last component
1163 * of the path should not contain a colon. We *do* assert this, as it
1164 * might indicate a caller bug.
1165 */
1166 AssertMsgReturn(strchr(pszLastComp, ':') == NULL, ("%s\n", pszPath), VERR_INVALID_PARAMETER);
1167
1168 /*
1169 * Look for the start of the last number.
1170 */
1171 const char *pchDash = strrchr(pszLastComp, '-');
1172 const char *pchDot = strrchr(pszLastComp, '.');
1173 if (!pchDash && !pchDot)
1174 {
1175 /* No -/. so it must be a root hub. Check that it's usb<something>. */
1176 if (strncmp(pszLastComp, RT_STR_TUPLE("usb")) != 0)
1177 {
1178 Log(("usbGetPortFromSysfsPath(%s): failed [2]\n", pszPath));
1179 return VERR_INVALID_PARAMETER;
1180 }
1181 return VERR_NOT_SUPPORTED;
1182 }
1183
1184 const char *pszLastPort = pchDot != NULL
1185 ? pchDot + 1
1186 : pchDash + 1;
1187 int rc = RTStrToUInt8Full(pszLastPort, 10, pu8Port);
1188 if (rc != VINF_SUCCESS)
1189 {
1190 Log(("usbGetPortFromSysfsPath(%s): failed [3], rc=%Rrc\n", pszPath, rc));
1191 return VERR_INVALID_PARAMETER;
1192 }
1193 if (*pu8Port == 0)
1194 {
1195 Log(("usbGetPortFromSysfsPath(%s): failed [4]\n", pszPath));
1196 return VERR_INVALID_PARAMETER;
1197 }
1198
1199 /* usbfs compatibility, 0-based port number. */
1200 *pu8Port = (uint8_t)(*pu8Port - 1);
1201 return VINF_SUCCESS;
1202}
1203
1204
1205/**
1206 * Converts a sysfs BCD value into a uint16_t.
1207 *
1208 * In contrast to usbReadBCD() this function can handle BCD values without
1209 * a decimal separator. This is necessary for parsing bcdDevice.
1210 *
1211 * @param pszBuf Pointer to the string buffer.
1212 * @param pu15 Pointer to the return value.
1213 * @returns IPRT status code.
1214 */
1215static int usbsysfsConvertStrToBCD(const char *pszBuf, uint16_t *pu16)
1216{
1217 char *pszNext;
1218 int32_t i32;
1219
1220 pszBuf = RTStrStripL(pszBuf);
1221 int rc = RTStrToInt32Ex(pszBuf, &pszNext, 16, &i32);
1222 if ( RT_FAILURE(rc)
1223 || rc == VWRN_NUMBER_TOO_BIG
1224 || i32 < 0)
1225 return VERR_NUMBER_TOO_BIG;
1226 if (*pszNext == '.')
1227 {
1228 if (i32 > 255)
1229 return VERR_NUMBER_TOO_BIG;
1230 int32_t i32Lo;
1231 rc = RTStrToInt32Ex(pszNext+1, &pszNext, 16, &i32Lo);
1232 if ( RT_FAILURE(rc)
1233 || rc == VWRN_NUMBER_TOO_BIG
1234 || i32Lo > 255
1235 || i32Lo < 0)
1236 return VERR_NUMBER_TOO_BIG;
1237 i32 = (i32 << 8) | i32Lo;
1238 }
1239 if ( i32 > 65535
1240 || (*pszNext != '\0' && *pszNext != ' '))
1241 return VERR_NUMBER_TOO_BIG;
1242
1243 *pu16 = (uint16_t)i32;
1244 return VINF_SUCCESS;
1245}
1246
1247
1248/**
1249 * Returns the byte value for the given device property or sets the given default if an
1250 * error occurs while obtaining it.
1251 *
1252 * @returns uint8_t value of the given property.
1253 * @param uBase The base of the number in the sysfs property.
1254 * @param bDef The default to set on error.
1255 * @param pszFormat The format string for the property.
1256 * @param ... Arguments for the format string.
1257 */
1258static uint8_t usbsysfsReadDevicePropertyU8Def(unsigned uBase, uint8_t bDef, const char *pszFormat, ...)
1259{
1260 int64_t i64Tmp = 0;
1261
1262 va_list va;
1263 va_start(va, pszFormat);
1264 int rc = RTLinuxSysFsReadIntFileV(uBase, &i64Tmp, pszFormat, va);
1265 va_end(va);
1266 if (RT_SUCCESS(rc))
1267 return (uint8_t)i64Tmp;
1268 else
1269 return bDef;
1270}
1271
1272
1273/**
1274 * Returns the uint16_t value for the given device property or sets the given default if an
1275 * error occurs while obtaining it.
1276 *
1277 * @returns uint16_t value of the given property.
1278 * @param uBase The base of the number in the sysfs property.
1279 * @param u16Def The default to set on error.
1280 * @param pszFormat The format string for the property.
1281 * @param ... Arguments for the format string.
1282 */
1283static uint16_t usbsysfsReadDevicePropertyU16Def(unsigned uBase, uint16_t u16Def, const char *pszFormat, ...)
1284{
1285 int64_t i64Tmp = 0;
1286
1287 va_list va;
1288 va_start(va, pszFormat);
1289 int rc = RTLinuxSysFsReadIntFileV(uBase, &i64Tmp, pszFormat, va);
1290 va_end(va);
1291 if (RT_SUCCESS(rc))
1292 return (uint16_t)i64Tmp;
1293 else
1294 return u16Def;
1295}
1296
1297
1298static void usbsysfsFillInDevice(USBDEVICE *pDev, USBDeviceInfo *pInfo)
1299{
1300 int rc;
1301 const char *pszSysfsPath = pInfo->mSysfsPath;
1302
1303 /* Fill in the simple fields */
1304 pDev->enmState = USBDEVICESTATE_UNUSED;
1305 pDev->bBus = (uint8_t)usbsysfsGetBusFromPath(pszSysfsPath);
1306 pDev->bDeviceClass = usbsysfsReadDevicePropertyU8Def(16, 0, "%s/bDeviceClass", pszSysfsPath);
1307 pDev->bDeviceSubClass = usbsysfsReadDevicePropertyU8Def(16, 0, "%s/bDeviceSubClass", pszSysfsPath);
1308 pDev->bDeviceProtocol = usbsysfsReadDevicePropertyU8Def(16, 0, "%s/bDeviceProtocol", pszSysfsPath);
1309 pDev->bNumConfigurations = usbsysfsReadDevicePropertyU8Def(10, 0, "%s/bNumConfigurations", pszSysfsPath);
1310 pDev->idVendor = usbsysfsReadDevicePropertyU16Def(16, 0, "%s/idVendor", pszSysfsPath);
1311 pDev->idProduct = usbsysfsReadDevicePropertyU16Def(16, 0, "%s/idProduct", pszSysfsPath);
1312 pDev->bDevNum = usbsysfsReadDevicePropertyU8Def(10, 0, "%s/devnum", pszSysfsPath);
1313
1314 /* Now deal with the non-numeric bits. */
1315 char szBuf[1024]; /* Should be larger than anything a sane device
1316 * will need, and insane devices can be unsupported
1317 * until further notice. */
1318 size_t cchRead;
1319
1320 /* For simplicity, we just do strcmps on the next one. */
1321 rc = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), &cchRead, "%s/speed", pszSysfsPath);
1322 if (RT_FAILURE(rc) || cchRead == sizeof(szBuf))
1323 pDev->enmState = USBDEVICESTATE_UNSUPPORTED;
1324 else
1325 pDev->enmSpeed = !strcmp(szBuf, "1.5") ? USBDEVICESPEED_LOW
1326 : !strcmp(szBuf, "12") ? USBDEVICESPEED_FULL
1327 : !strcmp(szBuf, "480") ? USBDEVICESPEED_HIGH
1328 : !strcmp(szBuf, "5000") ? USBDEVICESPEED_SUPER
1329 : USBDEVICESPEED_UNKNOWN;
1330
1331 rc = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), &cchRead, "%s/version", pszSysfsPath);
1332 if (RT_FAILURE(rc) || cchRead == sizeof(szBuf))
1333 pDev->enmState = USBDEVICESTATE_UNSUPPORTED;
1334 else
1335 {
1336 rc = usbsysfsConvertStrToBCD(szBuf, &pDev->bcdUSB);
1337 if (RT_FAILURE(rc))
1338 {
1339 pDev->enmState = USBDEVICESTATE_UNSUPPORTED;
1340 pDev->bcdUSB = UINT16_MAX;
1341 }
1342 }
1343
1344 rc = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), &cchRead, "%s/bcdDevice", pszSysfsPath);
1345 if (RT_FAILURE(rc) || cchRead == sizeof(szBuf))
1346 pDev->bcdDevice = UINT16_MAX;
1347 else
1348 {
1349 rc = usbsysfsConvertStrToBCD(szBuf, &pDev->bcdDevice);
1350 if (RT_FAILURE(rc))
1351 pDev->bcdDevice = UINT16_MAX;
1352 }
1353
1354 /* Now do things that need string duplication */
1355 rc = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), &cchRead, "%s/product", pszSysfsPath);
1356 if (RT_SUCCESS(rc) && cchRead < sizeof(szBuf))
1357 {
1358 USBLibPurgeEncoding(szBuf);
1359 pDev->pszProduct = RTStrDup(szBuf);
1360 }
1361
1362 rc = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), &cchRead, "%s/serial", pszSysfsPath);
1363 if (RT_SUCCESS(rc) && cchRead < sizeof(szBuf))
1364 {
1365 USBLibPurgeEncoding(szBuf);
1366 pDev->pszSerialNumber = RTStrDup(szBuf);
1367 pDev->u64SerialHash = USBLibHashSerial(szBuf);
1368 }
1369
1370 rc = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), &cchRead, "%s/manufacturer", pszSysfsPath);
1371 if (RT_SUCCESS(rc) && cchRead < sizeof(szBuf))
1372 {
1373 USBLibPurgeEncoding(szBuf);
1374 pDev->pszManufacturer = RTStrDup(szBuf);
1375 }
1376
1377 /* Work out the port number */
1378 if (RT_FAILURE(usbsysfsGetPortFromStr(pszSysfsPath, &pDev->bPort)))
1379 pDev->enmState = USBDEVICESTATE_UNSUPPORTED;
1380
1381 /* Check the interfaces to see if we can support the device. */
1382 char **ppszIf;
1383 VEC_FOR_EACH(&pInfo->mvecpszInterfaces, char *, ppszIf)
1384 {
1385 rc = RTLinuxSysFsGetLinkDest(szBuf, sizeof(szBuf), NULL, "%s/driver", *ppszIf);
1386 if (RT_SUCCESS(rc) && pDev->enmState != USBDEVICESTATE_UNSUPPORTED)
1387 pDev->enmState = (strcmp(szBuf, "hub") == 0)
1388 ? USBDEVICESTATE_UNSUPPORTED
1389 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1390 if (usbsysfsReadDevicePropertyU8Def(16, 9 /* bDev */, "%s/bInterfaceClass", *ppszIf) == 9 /* hub */)
1391 pDev->enmState = USBDEVICESTATE_UNSUPPORTED;
1392 }
1393
1394 /* We use a double slash as a separator in the pszAddress field. This is
1395 * alright as the two paths can't contain a slash due to the way we build
1396 * them. */
1397 char *pszAddress = NULL;
1398 RTStrAPrintf(&pszAddress, "sysfs:%s//device:%s", pszSysfsPath, pInfo->mDevice);
1399 pDev->pszAddress = pszAddress;
1400 pDev->pszBackend = RTStrDup("host");
1401
1402 /* Work out from the data collected whether we can support this device. */
1403 pDev->enmState = usbDeterminState(pDev);
1404 usbLogDevice(pDev);
1405}
1406
1407
1408/**
1409 * USBProxyService::getDevices() implementation for sysfs.
1410 */
1411static PUSBDEVICE usbsysfsGetDevices(const char *pszDevicesRoot, bool fUnsupportedDevicesToo)
1412{
1413 /* Add each of the devices found to the chain. */
1414 PUSBDEVICE pFirst = NULL;
1415 PUSBDEVICE pLast = NULL;
1416 VECTOR_OBJ(USBDeviceInfo) vecDevInfo;
1417 USBDeviceInfo *pInfo;
1418 int rc;
1419
1420 VEC_INIT_OBJ(&vecDevInfo, USBDeviceInfo, usbsysfsCleanupDevInfo);
1421 rc = usbsysfsEnumerateHostDevices(pszDevicesRoot, &vecDevInfo);
1422 if (RT_FAILURE(rc))
1423 return NULL;
1424 VEC_FOR_EACH(&vecDevInfo, USBDeviceInfo, pInfo)
1425 {
1426 USBDEVICE *pDev = (USBDEVICE *)RTMemAllocZ(sizeof(USBDEVICE));
1427 if (!pDev)
1428 rc = VERR_NO_MEMORY;
1429 if (RT_SUCCESS(rc))
1430 usbsysfsFillInDevice(pDev, pInfo);
1431 if ( RT_SUCCESS(rc)
1432 && ( pDev->enmState != USBDEVICESTATE_UNSUPPORTED
1433 || fUnsupportedDevicesToo)
1434 && pDev->pszAddress != NULL
1435 )
1436 {
1437 if (pLast != NULL)
1438 {
1439 pLast->pNext = pDev;
1440 pLast = pLast->pNext;
1441 }
1442 else
1443 pFirst = pLast = pDev;
1444 }
1445 else
1446 deviceFree(pDev);
1447 if (RT_FAILURE(rc))
1448 break;
1449 }
1450 if (RT_FAILURE(rc))
1451 deviceListFree(&pFirst);
1452
1453 VEC_CLEANUP_OBJ(&vecDevInfo);
1454 return pFirst;
1455}
1456
1457#endif /* VBOX_USB_WITH_SYSFS */
1458#ifdef UNIT_TEST
1459
1460/* Set up mock functions for USBProxyLinuxCheckDeviceRoot - here dlsym and close
1461 * for the inotify presence check. */
1462static int testInotifyInitGood(void) { return 0; }
1463static int testInotifyInitBad(void) { return -1; }
1464static bool s_fHaveInotifyLibC = true;
1465static bool s_fHaveInotifyKernel = true;
1466
1467static void *testDLSym(void *handle, const char *symbol)
1468{
1469 RT_NOREF(handle, symbol);
1470 Assert(handle == RTLD_DEFAULT);
1471 Assert(!RTStrCmp(symbol, "inotify_init"));
1472 if (!s_fHaveInotifyLibC)
1473 return NULL;
1474 if (s_fHaveInotifyKernel)
1475 return (void *)(uintptr_t)testInotifyInitGood;
1476 return (void *)(uintptr_t)testInotifyInitBad;
1477}
1478
1479void TestUSBSetInotifyAvailable(bool fHaveInotifyLibC, bool fHaveInotifyKernel)
1480{
1481 s_fHaveInotifyLibC = fHaveInotifyLibC;
1482 s_fHaveInotifyKernel = fHaveInotifyKernel;
1483}
1484# define dlsym testDLSym
1485# define close(a) do {} while (0)
1486
1487#endif /* UNIT_TEST */
1488
1489/**
1490 * Is inotify available and working on this system?
1491 *
1492 * This is a requirement for using USB with sysfs
1493 */
1494static bool usbsysfsInotifyAvailable(void)
1495{
1496 int (*inotify_init)(void);
1497
1498 *(void **)(&inotify_init) = dlsym(RTLD_DEFAULT, "inotify_init");
1499 if (!inotify_init)
1500 return false;
1501 int fd = inotify_init();
1502 if (fd == -1)
1503 return false;
1504 close(fd);
1505 return true;
1506}
1507
1508#ifdef UNIT_TEST
1509
1510# undef dlsym
1511# undef close
1512
1513/** Unit test list of usbfs addresses of connected devices. */
1514static const char **g_papszUsbfsDeviceAddresses = NULL;
1515
1516static PUSBDEVICE testGetUsbfsDevices(const char *pszUsbfsRoot, bool fUnsupportedDevicesToo)
1517{
1518 RT_NOREF(pszUsbfsRoot, fUnsupportedDevicesToo);
1519 const char **psz;
1520 PUSBDEVICE pList = NULL, pTail = NULL;
1521 for (psz = g_papszUsbfsDeviceAddresses; psz && *psz; ++psz)
1522 {
1523 PUSBDEVICE pNext = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
1524 if (pNext)
1525 pNext->pszAddress = RTStrDup(*psz);
1526 if (!pNext || !pNext->pszAddress)
1527 {
1528 if (pNext)
1529 RTMemFree(pNext);
1530 deviceListFree(&pList);
1531 return NULL;
1532 }
1533 if (pTail)
1534 pTail->pNext = pNext;
1535 else
1536 pList = pNext;
1537 pTail = pNext;
1538 }
1539 return pList;
1540}
1541# define usbfsGetDevices testGetUsbfsDevices
1542
1543/**
1544 * Specify the list of devices that will appear to be available through
1545 * usbfs during unit testing (of USBProxyLinuxGetDevices)
1546 * @param pacszDeviceAddresses NULL terminated array of usbfs device addresses
1547 */
1548void TestUSBSetAvailableUsbfsDevices(const char **papszDeviceAddresses)
1549{
1550 g_papszUsbfsDeviceAddresses = papszDeviceAddresses;
1551}
1552
1553/** Unit test list of files reported as accessible by access(3). We only do
1554 * accessible or not accessible. */
1555static const char **g_papszAccessibleFiles = NULL;
1556
1557static int testAccess(const char *pszPath, int mode)
1558{
1559 RT_NOREF(mode);
1560 const char **psz;
1561 for (psz = g_papszAccessibleFiles; psz && *psz; ++psz)
1562 if (!RTStrCmp(pszPath, *psz))
1563 return 0;
1564 return -1;
1565}
1566# define access testAccess
1567
1568
1569/**
1570 * Specify the list of files that access will report as accessible (at present
1571 * we only do accessible or not accessible) during unit testing (of
1572 * USBProxyLinuxGetDevices)
1573 * @param papszAccessibleFiles NULL terminated array of file paths to be
1574 * reported accessible
1575 */
1576void TestUSBSetAccessibleFiles(const char **papszAccessibleFiles)
1577{
1578 g_papszAccessibleFiles = papszAccessibleFiles;
1579}
1580
1581
1582/** The path we pretend the usbfs root is located at, or NULL. */
1583const char *s_pszTestUsbfsRoot;
1584/** Should usbfs be accessible to the current user? */
1585bool s_fTestUsbfsAccessible;
1586/** The path we pretend the device node tree root is located at, or NULL. */
1587const char *s_pszTestDevicesRoot;
1588/** Should the device node tree be accessible to the current user? */
1589bool s_fTestDevicesAccessible;
1590/** The result of the usbfs/inotify-specific init */
1591int s_rcTestMethodInitResult;
1592/** The value of the VBOX_USB environment variable. */
1593const char *s_pszTestEnvUsb;
1594/** The value of the VBOX_USB_ROOT environment variable. */
1595const char *s_pszTestEnvUsbRoot;
1596
1597
1598/** Select which access methods will be available to the @a init method
1599 * during unit testing, and (hack!) what return code it will see from
1600 * the access method-specific initialisation. */
1601void TestUSBSetupInit(const char *pszUsbfsRoot, bool fUsbfsAccessible,
1602 const char *pszDevicesRoot, bool fDevicesAccessible,
1603 int rcMethodInitResult)
1604{
1605 s_pszTestUsbfsRoot = pszUsbfsRoot;
1606 s_fTestUsbfsAccessible = fUsbfsAccessible;
1607 s_pszTestDevicesRoot = pszDevicesRoot;
1608 s_fTestDevicesAccessible = fDevicesAccessible;
1609 s_rcTestMethodInitResult = rcMethodInitResult;
1610}
1611
1612
1613/** Specify the environment that the @a init method will see during unit
1614 * testing. */
1615void TestUSBSetEnv(const char *pszEnvUsb, const char *pszEnvUsbRoot)
1616{
1617 s_pszTestEnvUsb = pszEnvUsb;
1618 s_pszTestEnvUsbRoot = pszEnvUsbRoot;
1619}
1620
1621/* For testing we redefine anything that accesses the outside world to
1622 * return test values. */
1623# define RTEnvGet(a) \
1624 ( !RTStrCmp(a, "VBOX_USB") ? s_pszTestEnvUsb \
1625 : !RTStrCmp(a, "VBOX_USB_ROOT") ? s_pszTestEnvUsbRoot \
1626 : NULL)
1627# define USBProxyLinuxCheckDeviceRoot(pszPath, fUseNodes) \
1628 ( ((fUseNodes) && s_fTestDevicesAccessible \
1629 && !RTStrCmp(pszPath, s_pszTestDevicesRoot)) \
1630 || (!(fUseNodes) && s_fTestUsbfsAccessible \
1631 && !RTStrCmp(pszPath, s_pszTestUsbfsRoot)))
1632# define RTDirExists(pszDir) \
1633 ( (pszDir) \
1634 && ( !RTStrCmp(pszDir, s_pszTestDevicesRoot) \
1635 || !RTStrCmp(pszDir, s_pszTestUsbfsRoot)))
1636# define RTFileExists(pszFile) \
1637 ( (pszFile) \
1638 && s_pszTestUsbfsRoot \
1639 && !RTStrNCmp(pszFile, s_pszTestUsbfsRoot, strlen(s_pszTestUsbfsRoot)) \
1640 && !RTStrCmp(pszFile + strlen(s_pszTestUsbfsRoot), "/devices"))
1641
1642#endif /* UNIT_TEST */
1643
1644/**
1645 * Use USBFS-like or sysfs/device node-like access method?
1646 *
1647 * Selects the access method that will be used to access USB devices based on
1648 * what is available on the host and what if anything the user has specified
1649 * in the environment.
1650 *
1651 * @returns iprt status value
1652 * @param pfUsingUsbfsDevices on success this will be set to true if
1653 * the prefered access method is USBFS-like and to
1654 * false if it is sysfs/device node-like
1655 * @param ppszDevicesRoot on success the root of the tree of USBFS-like
1656 * device nodes will be stored here
1657 */
1658int USBProxyLinuxChooseMethod(bool *pfUsingUsbfsDevices, const char **ppszDevicesRoot)
1659{
1660 /*
1661 * We have two methods available for getting host USB device data - using
1662 * USBFS and using sysfs. The default choice is sysfs; if that is not
1663 * available we fall back to USBFS.
1664 * In the event of both failing, an appropriate error will be returned.
1665 * The user may also specify a method and root using the VBOX_USB and
1666 * VBOX_USB_ROOT environment variables. In this case we don't check
1667 * the root they provide for validity.
1668 */
1669 bool fUsbfsChosen = false;
1670 bool fSysfsChosen = false;
1671 const char *pszUsbFromEnv = RTEnvGet("VBOX_USB");
1672 const char *pszUsbRoot = NULL;
1673 if (pszUsbFromEnv)
1674 {
1675 bool fValidVBoxUSB = true;
1676
1677 pszUsbRoot = RTEnvGet("VBOX_USB_ROOT");
1678 if (!RTStrICmp(pszUsbFromEnv, "USBFS"))
1679 {
1680 LogRel(("Default USB access method set to \"usbfs\" from environment\n"));
1681 fUsbfsChosen = true;
1682 }
1683 else if (!RTStrICmp(pszUsbFromEnv, "SYSFS"))
1684 {
1685 LogRel(("Default USB method set to \"sysfs\" from environment\n"));
1686 fSysfsChosen = true;
1687 }
1688 else
1689 {
1690 LogRel(("Invalid VBOX_USB environment variable setting \"%s\"\n", pszUsbFromEnv));
1691 fValidVBoxUSB = false;
1692 pszUsbFromEnv = NULL;
1693 }
1694 if (!fValidVBoxUSB && pszUsbRoot)
1695 pszUsbRoot = NULL;
1696 }
1697 if (!pszUsbRoot)
1698 {
1699 if ( !fUsbfsChosen
1700 && USBProxyLinuxCheckDeviceRoot("/dev/vboxusb", true))
1701 {
1702 fSysfsChosen = true;
1703 pszUsbRoot = "/dev/vboxusb";
1704 }
1705 else if ( !fSysfsChosen
1706 && USBProxyLinuxCheckDeviceRoot("/proc/bus/usb", false))
1707 {
1708 fUsbfsChosen = true;
1709 pszUsbRoot = "/proc/bus/usb";
1710 }
1711 }
1712 else if (!USBProxyLinuxCheckDeviceRoot(pszUsbRoot, fSysfsChosen))
1713 pszUsbRoot = NULL;
1714 if (pszUsbRoot)
1715 {
1716 *pfUsingUsbfsDevices = fUsbfsChosen;
1717 *ppszDevicesRoot = pszUsbRoot;
1718 return VINF_SUCCESS;
1719 }
1720 /* else */
1721 return pszUsbFromEnv ? VERR_NOT_FOUND
1722 : RTDirExists("/dev/vboxusb") ? VERR_VUSB_USB_DEVICE_PERMISSION
1723 : RTFileExists("/proc/bus/usb/devices") ? VERR_VUSB_USBFS_PERMISSION
1724 : VERR_NOT_FOUND;
1725}
1726
1727#ifdef UNIT_TEST
1728# undef RTEnvGet
1729# undef USBProxyLinuxCheckDeviceRoot
1730# undef RTDirExists
1731# undef RTFileExists
1732#endif
1733
1734/**
1735 * Check whether a USB device tree root is usable.
1736 *
1737 * @param pszRoot the path to the root of the device tree
1738 * @param fIsDeviceNodes whether this is a device node (or usbfs) tree
1739 * @note returns a pointer into a static array so it will stay valid
1740 */
1741bool USBProxyLinuxCheckDeviceRoot(const char *pszRoot, bool fIsDeviceNodes)
1742{
1743 bool fOK = false;
1744 if (!fIsDeviceNodes) /* usbfs */
1745 {
1746#ifdef VBOX_USB_WITH_USBFS
1747 if (!access(pszRoot, R_OK | X_OK))
1748 {
1749 fOK = true;
1750 PUSBDEVICE pDevices = usbfsGetDevices(pszRoot, true);
1751 if (pDevices)
1752 {
1753 PUSBDEVICE pDevice;
1754 for (pDevice = pDevices; pDevice && fOK; pDevice = pDevice->pNext)
1755 if (access(pDevice->pszAddress, R_OK | W_OK))
1756 fOK = false;
1757 deviceListFree(&pDevices);
1758 }
1759 }
1760#endif
1761 }
1762#ifdef VBOX_USB_WITH_SYSFS
1763 /* device nodes */
1764 else if (usbsysfsInotifyAvailable() && !access(pszRoot, R_OK | X_OK))
1765 fOK = true;
1766#endif
1767 return fOK;
1768}
1769
1770#ifdef UNIT_TEST
1771# undef usbfsGetDevices
1772# undef access
1773#endif
1774
1775/**
1776 * Get the list of USB devices supported by the system.
1777 *
1778 * Result should be freed using #deviceFree or something equivalent.
1779 *
1780 * @param pszDevicesRoot the path to the root of the device tree
1781 * @param fUseSysfs whether to use sysfs (or usbfs) for enumeration
1782 */
1783PUSBDEVICE USBProxyLinuxGetDevices(const char *pszDevicesRoot, bool fUseSysfs)
1784{
1785 if (!fUseSysfs)
1786 {
1787#ifdef VBOX_USB_WITH_USBFS
1788 return usbfsGetDevices(pszDevicesRoot, false);
1789#else
1790 return NULL;
1791#endif
1792 }
1793
1794#ifdef VBOX_USB_WITH_SYSFS
1795 return usbsysfsGetDevices(pszDevicesRoot, false);
1796#else
1797 return NULL;
1798#endif
1799}
1800
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette