VirtualBox

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

Last change on this file since 69731 was 69500, checked in by vboxsync, 7 years ago

*: scm --update-copyright-year

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