VirtualBox

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

Last change on this file since 36670 was 36417, checked in by vboxsync, 14 years ago

Installer/Linux and Main: USB enumeration: fix detection of USB via sysfs/usb_device

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.7 KB
Line 
1/* $Id: USBGetDevices.cpp 36417 2011-03-24 22:49:51Z vboxsync $ */
2/** @file
3 * VirtualBox Linux host USB device enumeration.
4 */
5
6/*
7 * Copyright (C) 2006-2010 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
23#include "USBGetDevices.h"
24
25#include <VBox/usb.h>
26#include <VBox/usblib.h>
27
28#include <iprt/linux/sysfs.h>
29#include <iprt/cdefs.h>
30#include <iprt/ctype.h>
31#include <iprt/err.h>
32#include <iprt/fs.h>
33#include <iprt/log.h>
34#include <iprt/mem.h>
35#include <iprt/param.h>
36#include <iprt/path.h>
37#include <iprt/string.h>
38#include "vector.h"
39
40#ifdef VBOX_WITH_LINUX_COMPILER_H
41# include <linux/compiler.h>
42#endif
43#include <linux/usbdevice_fs.h>
44
45#include <sys/types.h>
46#include <sys/stat.h>
47#include <sys/vfs.h>
48
49#include <dirent.h>
50#include <dlfcn.h>
51#include <errno.h>
52#include <fcntl.h>
53#include <stdio.h>
54#include <string.h>
55#include <unistd.h>
56
57/*******************************************************************************
58* Structures and Typedefs *
59*******************************************************************************/
60/** Suffix translation. */
61typedef struct USBSUFF
62{
63 char szSuff[4];
64 unsigned cchSuff;
65 unsigned uMul;
66 unsigned uDiv;
67} USBSUFF, *PUSBSUFF;
68typedef const USBSUFF *PCUSBSUFF;
69
70/** Structure describing a host USB device */
71typedef struct USBDeviceInfo
72{
73 /** The device node of the device. */
74 char *mDevice;
75 /** The system identifier of the device. Specific to the probing
76 * method. */
77 char *mSysfsPath;
78 /** List of interfaces as sysfs paths */
79 VECTOR_PTR(char *) mvecpszInterfaces;
80} USBDeviceInfo;
81
82/*******************************************************************************
83* Global Variables *
84*******************************************************************************/
85/**
86 * Suffixes for the endpoint polling interval.
87 */
88static const USBSUFF s_aIntervalSuff[] =
89{
90 { "ms", 2, 1, 0 },
91 { "us", 2, 1, 1000 },
92 { "ns", 2, 1, 1000000 },
93 { "s", 1, 1000, 0 },
94 { "", 0, 0, 0 } /* term */
95};
96
97/**
98 * List of well-known USB device tree locations.
99 */
100static const USBDEVTREELOCATION s_aTreeLocations[] =
101{
102 { "/dev/vboxusb", true },
103 { "/proc/bus/usb", false },
104};
105
106
107/**
108 * "reads" the number suffix. It's more like validating it and
109 * skipping the necessary number of chars.
110 */
111static int usbReadSkipSuffix(char **ppszNext)
112{
113 char *pszNext = *ppszNext;
114 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
115 {
116 /* skip unit */
117 if (pszNext[0] == 'm' && pszNext[1] == 's')
118 pszNext += 2;
119 else if (pszNext[0] == 'm' && pszNext[1] == 'A')
120 pszNext += 2;
121
122 /* skip parenthesis */
123 if (*pszNext == '(')
124 {
125 pszNext = strchr(pszNext, ')');
126 if (!pszNext++)
127 {
128 AssertMsgFailed(("*ppszNext=%s\n", *ppszNext));
129 return VERR_PARSE_ERROR;
130 }
131 }
132
133 /* blank or end of the line. */
134 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
135 {
136 AssertMsgFailed(("pszNext=%s\n", pszNext));
137 return VERR_PARSE_ERROR;
138 }
139
140 /* it's ok. */
141 *ppszNext = pszNext;
142 }
143
144 return VINF_SUCCESS;
145}
146
147
148/**
149 * Reads a USB number returning the number and the position of the next character to parse.
150 */
151static int usbReadNum(const char *pszValue, unsigned uBase, uint32_t u32Mask, PCUSBSUFF paSuffs, void *pvNum, char **ppszNext)
152{
153 /*
154 * Initialize return value to zero and strip leading spaces.
155 */
156 switch (u32Mask)
157 {
158 case 0xff: *(uint8_t *)pvNum = 0; break;
159 case 0xffff: *(uint16_t *)pvNum = 0; break;
160 case 0xffffffff: *(uint32_t *)pvNum = 0; break;
161 }
162 pszValue = RTStrStripL(pszValue);
163 if (*pszValue)
164 {
165 /*
166 * Try convert the number.
167 */
168 char *pszNext;
169 uint32_t u32 = 0;
170 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32);
171 if (pszNext == pszValue)
172 {
173 AssertMsgFailed(("pszValue=%d\n", pszValue));
174 return VERR_NO_DATA;
175 }
176
177 /*
178 * Check the range.
179 */
180 if (u32 & ~u32Mask)
181 {
182 AssertMsgFailed(("pszValue=%d u32=%#x lMask=%#x\n", pszValue, u32, u32Mask));
183 return VERR_OUT_OF_RANGE;
184 }
185
186 /*
187 * Validate and skip stuff following the number.
188 */
189 if (paSuffs)
190 {
191 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
192 {
193 for (PCUSBSUFF pSuff = paSuffs; pSuff->szSuff[0]; pSuff++)
194 {
195 if ( !strncmp(pSuff->szSuff, pszNext, pSuff->cchSuff)
196 && (!pszNext[pSuff->cchSuff] || RT_C_IS_SPACE(pszNext[pSuff->cchSuff])))
197 {
198 if (pSuff->uDiv)
199 u32 /= pSuff->uDiv;
200 else
201 u32 *= pSuff->uMul;
202 break;
203 }
204 }
205 }
206 }
207 else
208 {
209 int rc = usbReadSkipSuffix(&pszNext);
210 if (RT_FAILURE(rc))
211 return rc;
212 }
213
214 *ppszNext = pszNext;
215
216 /*
217 * Set the value.
218 */
219 switch (u32Mask)
220 {
221 case 0xff: *(uint8_t *)pvNum = (uint8_t)u32; break;
222 case 0xffff: *(uint16_t *)pvNum = (uint16_t)u32; break;
223 case 0xffffffff: *(uint32_t *)pvNum = (uint32_t)u32; break;
224 }
225 }
226 return VINF_SUCCESS;
227}
228
229
230static int usbRead8(const char *pszValue, unsigned uBase, uint8_t *pu8, char **ppszNext)
231{
232 return usbReadNum(pszValue, uBase, 0xff, NULL, pu8, ppszNext);
233}
234
235
236static int usbRead16(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
237{
238 return usbReadNum(pszValue, uBase, 0xffff, NULL, pu16, ppszNext);
239}
240
241
242#if 0
243static int usbRead16Suff(const char *pszValue, unsigned uBase, PCUSBSUFF paSuffs, uint16_t *pu16, char **ppszNext)
244{
245 return usbReadNum(pszValue, uBase, 0xffff, paSuffs, pu16, ppszNext);
246}
247#endif
248
249
250/**
251 * Reads a USB BCD number returning the number and the position of the next character to parse.
252 * The returned number contains the integer part in the high byte and the decimal part in the low byte.
253 */
254static int usbReadBCD(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
255{
256 /*
257 * Initialize return value to zero and strip leading spaces.
258 */
259 *pu16 = 0;
260 pszValue = RTStrStripL(pszValue);
261 if (*pszValue)
262 {
263 /*
264 * Try convert the number.
265 */
266 /* integer part */
267 char *pszNext;
268 uint32_t u32Int = 0;
269 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32Int);
270 if (pszNext == pszValue)
271 {
272 AssertMsgFailed(("pszValue=%s\n", pszValue));
273 return VERR_NO_DATA;
274 }
275 if (u32Int & ~0xff)
276 {
277 AssertMsgFailed(("pszValue=%s u32Int=%#x (int)\n", pszValue, u32Int));
278 return VERR_OUT_OF_RANGE;
279 }
280
281 /* skip dot and read decimal part */
282 if (*pszNext != '.')
283 {
284 AssertMsgFailed(("pszValue=%s pszNext=%s (int)\n", pszValue, pszNext));
285 return VERR_PARSE_ERROR;
286 }
287 char *pszValue2 = RTStrStripL(pszNext + 1);
288 uint32_t u32Dec = 0;
289 RTStrToUInt32Ex(pszValue2, &pszNext, uBase, &u32Dec);
290 if (pszNext == pszValue)
291 {
292 AssertMsgFailed(("pszValue=%s\n", pszValue));
293 return VERR_NO_DATA;
294 }
295 if (u32Dec & ~0xff)
296 {
297 AssertMsgFailed(("pszValue=%s u32Dec=%#x\n", pszValue, u32Dec));
298 return VERR_OUT_OF_RANGE;
299 }
300
301 /*
302 * Validate and skip stuff following the number.
303 */
304 int rc = usbReadSkipSuffix(&pszNext);
305 if (RT_FAILURE(rc))
306 return rc;
307 *ppszNext = pszNext;
308
309 /*
310 * Set the value.
311 */
312 *pu16 = (uint16_t)u32Int << 8 | (uint16_t)u32Dec;
313 }
314 return VINF_SUCCESS;
315}
316
317
318/**
319 * Reads a string, i.e. allocates memory and copies it.
320 *
321 * We assume that a string is Utf8 and if that's not the case
322 * (pre-2.6.32-kernels used Latin-1, but so few devices return non-ASCII that
323 * this usually goes unnoticed) then we mercilessly force it to be so.
324 */
325static int usbReadStr(const char *pszValue, const char **ppsz)
326{
327 char *psz;
328
329 if (*ppsz)
330 RTStrFree((char *)*ppsz);
331 psz = RTStrDup(pszValue);
332 if (psz)
333 {
334 RTStrPurgeEncoding(psz);
335 *ppsz = psz;
336 return VINF_SUCCESS;
337 }
338 return VERR_NO_MEMORY;
339}
340
341
342/**
343 * Skips the current property.
344 */
345static char *usbReadSkip(char *pszValue)
346{
347 char *psz = strchr(pszValue, '=');
348 if (psz)
349 psz = strchr(psz + 1, '=');
350 if (!psz)
351 return strchr(pszValue, '\0');
352 while (psz > pszValue && !RT_C_IS_SPACE(psz[-1]))
353 psz--;
354 Assert(psz > pszValue);
355 return psz;
356}
357
358
359/**
360 * Determine the USB speed.
361 */
362static int usbReadSpeed(const char *pszValue, USBDEVICESPEED *pSpd, char **ppszNext)
363{
364 pszValue = RTStrStripL(pszValue);
365 /* verified with Linux 2.4.0 ... Linux 2.6.25 */
366 if (!strncmp(pszValue, "1.5", 3))
367 *pSpd = USBDEVICESPEED_LOW;
368 else if (!strncmp(pszValue, "12 ", 3))
369 *pSpd = USBDEVICESPEED_FULL;
370 else if (!strncmp(pszValue, "480", 3))
371 *pSpd = USBDEVICESPEED_HIGH;
372 else
373 *pSpd = USBDEVICESPEED_UNKNOWN;
374 while (pszValue[0] != '\0' && !RT_C_IS_SPACE(pszValue[0]))
375 pszValue++;
376 *ppszNext = (char *)pszValue;
377 return VINF_SUCCESS;
378}
379
380
381/**
382 * Compare a prefix and returns pointer to the char following it if it matches.
383 */
384static char *usbPrefix(char *psz, const char *pszPref, size_t cchPref)
385{
386 if (strncmp(psz, pszPref, cchPref))
387 return NULL;
388 return psz + cchPref;
389}
390
391
392/**
393 * Does some extra checks to improve the detected device state.
394 *
395 * We cannot distinguish between USED_BY_HOST_CAPTURABLE and
396 * USED_BY_GUEST, HELD_BY_PROXY all that well and it shouldn't be
397 * necessary either.
398 *
399 * We will however, distinguish between the device we have permissions
400 * to open and those we don't. This is necessary for two reasons.
401 *
402 * Firstly, because it's futile to even attempt opening a device which we
403 * don't have access to, it only serves to confuse the user. (That said,
404 * it might also be a bit confusing for the user to see that a USB device
405 * is grayed out with no further explanation, and no way of generating an
406 * error hinting at why this is the case.)
407 *
408 * Secondly and more importantly, we're racing against udevd with respect
409 * to permissions and group settings on newly plugged devices. When we
410 * detect a new device that we cannot access we will poll on it for a few
411 * seconds to give udevd time to fix it. The polling is actually triggered
412 * in the 'new device' case in the compare loop.
413 *
414 * The USBDEVICESTATE_USED_BY_HOST state is only used for this no-access
415 * case, while USBDEVICESTATE_UNSUPPORTED is only used in the 'hub' case.
416 * When it's neither of these, we set USBDEVICESTATE_UNUSED or
417 * USBDEVICESTATE_USED_BY_HOST_CAPTURABLE depending on whether there is
418 * a driver associated with any of the interfaces.
419 *
420 * All except the access check and a special idVendor == 0 precaution
421 * is handled at parse time.
422 *
423 * @returns The adjusted state.
424 * @param pDevice The device.
425 */
426static USBDEVICESTATE usbDeterminState(PCUSBDEVICE pDevice)
427{
428 /*
429 * If it's already flagged as unsupported, there is nothing to do.
430 */
431 USBDEVICESTATE enmState = pDevice->enmState;
432 if (enmState == USBDEVICESTATE_UNSUPPORTED)
433 return USBDEVICESTATE_UNSUPPORTED;
434
435 /*
436 * Root hubs and similar doesn't have any vendor id, just
437 * refuse these device.
438 */
439 if (!pDevice->idVendor)
440 return USBDEVICESTATE_UNSUPPORTED;
441
442 /*
443 * Check if we've got access to the device, if we haven't flag
444 * it as used-by-host.
445 */
446#ifndef VBOX_USB_WITH_SYSFS
447 const char *pszAddress = pDevice->pszAddress;
448#else
449 if (pDevice->pszAddress == NULL)
450 /* We can't do much with the device without an address. */
451 return USBDEVICESTATE_UNSUPPORTED;
452 const char *pszAddress = strstr(pDevice->pszAddress, "//device:");
453 pszAddress = pszAddress != NULL
454 ? pszAddress + sizeof("//device:") - 1
455 : pDevice->pszAddress;
456#endif
457 if ( access(pszAddress, R_OK | W_OK) != 0
458 && errno == EACCES)
459 return USBDEVICESTATE_USED_BY_HOST;
460
461#ifdef VBOX_USB_WITH_SYSFS
462 /**
463 * @todo Check that any other essential fields are present and mark as
464 * invalid if not. Particularly to catch the case where the device was
465 * unplugged while we were reading in its properties.
466 */
467#endif
468
469 return enmState;
470}
471
472
473/** Just a worker for USBProxyServiceLinux::getDevices that avoids some code duplication. */
474static int addDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, const char *pcszUsbfsRoot, bool testfs, int rc)
475{
476 /* usbDeterminState requires the address. */
477 PUSBDEVICE pDevNew = (PUSBDEVICE)RTMemDup(pDev, sizeof(*pDev));
478 if (pDevNew)
479 {
480 RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", pcszUsbfsRoot, pDevNew->bBus, pDevNew->bDevNum);
481 if (pDevNew->pszAddress)
482 {
483 pDevNew->enmState = usbDeterminState(pDevNew);
484 if (pDevNew->enmState != USBDEVICESTATE_UNSUPPORTED || testfs)
485 {
486 if (*pppNext)
487 **pppNext = pDevNew;
488 else
489 *ppFirst = pDevNew;
490 *pppNext = &pDevNew->pNext;
491 }
492 else
493 deviceFree(pDevNew);
494 }
495 else
496 {
497 deviceFree(pDevNew);
498 rc = VERR_NO_MEMORY;
499 }
500 }
501 else
502 {
503 rc = VERR_NO_MEMORY;
504 deviceFreeMembers(pDev);
505 }
506
507 return rc;
508}
509
510
511static int openDevicesFile(const char *pcszUsbfsRoot, FILE **ppFile)
512{
513 char *pszPath;
514 FILE *pFile;
515 RTStrAPrintf(&pszPath, "%s/devices", pcszUsbfsRoot);
516 if (!pszPath)
517 return VERR_NO_MEMORY;
518 pFile = fopen(pszPath, "r");
519 RTStrFree(pszPath);
520 if (!pFile)
521 return RTErrConvertFromErrno(errno);
522 *ppFile = pFile;
523 return VINF_SUCCESS;
524}
525
526/**
527 * USBProxyService::getDevices() implementation for usbfs. The @a testfs flag
528 * tells the function to return information about unsupported devices as well.
529 * This is used as a sanity test to check that a devices file is really what
530 * we expect.
531 */
532static PUSBDEVICE getDevicesFromUsbfs(const char *pcszUsbfsRoot, bool testfs)
533{
534 PUSBDEVICE pFirst = NULL;
535 FILE *pFile = NULL;
536 int rc;
537 rc = openDevicesFile(pcszUsbfsRoot, &pFile);
538 if (RT_SUCCESS(rc))
539 {
540 PUSBDEVICE *ppNext = NULL;
541 int cHits = 0;
542 char szLine[1024];
543 USBDEVICE Dev;
544 RT_ZERO(Dev);
545 Dev.enmState = USBDEVICESTATE_UNUSED;
546
547 /* Set close on exit and hope no one is racing us. */
548 rc = fcntl(fileno(pFile), F_SETFD, FD_CLOEXEC) >= 0
549 ? VINF_SUCCESS
550 : RTErrConvertFromErrno(errno);
551 while ( RT_SUCCESS(rc)
552 && fgets(szLine, sizeof(szLine), pFile))
553 {
554 char *psz;
555 char *pszValue;
556
557 /* validate and remove the trailing newline. */
558 psz = strchr(szLine, '\0');
559 if (psz[-1] != '\n' && !feof(pFile))
560 {
561 AssertMsgFailed(("Line too long. (cch=%d)\n", strlen(szLine)));
562 continue;
563 }
564
565 /* strip */
566 psz = RTStrStrip(szLine);
567 if (!*psz)
568 continue;
569
570 /*
571 * Interpret the line.
572 * (Ordered by normal occurrence.)
573 */
574 char ch = psz[0];
575 if (psz[1] != ':')
576 continue;
577 psz = RTStrStripL(psz + 3);
578#define PREFIX(str) ( (pszValue = usbPrefix(psz, str, sizeof(str) - 1)) != NULL )
579 switch (ch)
580 {
581 /*
582 * T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd
583 * | | | | | | | | |__MaxChildren
584 * | | | | | | | |__Device Speed in Mbps
585 * | | | | | | |__DeviceNumber
586 * | | | | | |__Count of devices at this level
587 * | | | | |__Connector/Port on Parent for this device
588 * | | | |__Parent DeviceNumber
589 * | | |__Level in topology for this bus
590 * | |__Bus number
591 * |__Topology info tag
592 */
593 case 'T':
594 /* add */
595 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
596 if (cHits >= 3)
597 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, pcszUsbfsRoot, testfs, rc);
598 else
599 deviceFreeMembers(&Dev);
600
601 /* Reset device state */
602 memset(&Dev, 0, sizeof (Dev));
603 Dev.enmState = USBDEVICESTATE_UNUSED;
604 cHits = 1;
605
606 /* parse the line. */
607 while (*psz && RT_SUCCESS(rc))
608 {
609 if (PREFIX("Bus="))
610 rc = usbRead8(pszValue, 10, &Dev.bBus, &psz);
611 else if (PREFIX("Port="))
612 rc = usbRead8(pszValue, 10, &Dev.bPort, &psz);
613 else if (PREFIX("Spd="))
614 rc = usbReadSpeed(pszValue, &Dev.enmSpeed, &psz);
615 else if (PREFIX("Dev#="))
616 rc = usbRead8(pszValue, 10, &Dev.bDevNum, &psz);
617 else
618 psz = usbReadSkip(psz);
619 psz = RTStrStripL(psz);
620 }
621 break;
622
623 /*
624 * Bandwidth info:
625 * B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
626 * | | | |__Number of isochronous requests
627 * | | |__Number of interrupt requests
628 * | |__Total Bandwidth allocated to this bus
629 * |__Bandwidth info tag
630 */
631 case 'B':
632 break;
633
634 /*
635 * D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
636 * | | | | | | |__NumberConfigurations
637 * | | | | | |__MaxPacketSize of Default Endpoint
638 * | | | | |__DeviceProtocol
639 * | | | |__DeviceSubClass
640 * | | |__DeviceClass
641 * | |__Device USB version
642 * |__Device info tag #1
643 */
644 case 'D':
645 while (*psz && RT_SUCCESS(rc))
646 {
647 if (PREFIX("Ver="))
648 rc = usbReadBCD(pszValue, 16, &Dev.bcdUSB, &psz);
649 else if (PREFIX("Cls="))
650 {
651 rc = usbRead8(pszValue, 16, &Dev.bDeviceClass, &psz);
652 if (RT_SUCCESS(rc) && Dev.bDeviceClass == 9 /* HUB */)
653 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
654 }
655 else if (PREFIX("Sub="))
656 rc = usbRead8(pszValue, 16, &Dev.bDeviceSubClass, &psz);
657 else if (PREFIX("Prot="))
658 rc = usbRead8(pszValue, 16, &Dev.bDeviceProtocol, &psz);
659 //else if (PREFIX("MxPS="))
660 // rc = usbRead16(pszValue, 10, &Dev.wMaxPacketSize, &psz);
661 else if (PREFIX("#Cfgs="))
662 rc = usbRead8(pszValue, 10, &Dev.bNumConfigurations, &psz);
663 else
664 psz = usbReadSkip(psz);
665 psz = RTStrStripL(psz);
666 }
667 cHits++;
668 break;
669
670 /*
671 * P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
672 * | | | |__Product revision number
673 * | | |__Product ID code
674 * | |__Vendor ID code
675 * |__Device info tag #2
676 */
677 case 'P':
678 while (*psz && RT_SUCCESS(rc))
679 {
680 if (PREFIX("Vendor="))
681 rc = usbRead16(pszValue, 16, &Dev.idVendor, &psz);
682 else if (PREFIX("ProdID="))
683 rc = usbRead16(pszValue, 16, &Dev.idProduct, &psz);
684 else if (PREFIX("Rev="))
685 rc = usbReadBCD(pszValue, 16, &Dev.bcdDevice, &psz);
686 else
687 psz = usbReadSkip(psz);
688 psz = RTStrStripL(psz);
689 }
690 cHits++;
691 break;
692
693 /*
694 * String.
695 */
696 case 'S':
697 if (PREFIX("Manufacturer="))
698 rc = usbReadStr(pszValue, &Dev.pszManufacturer);
699 else if (PREFIX("Product="))
700 rc = usbReadStr(pszValue, &Dev.pszProduct);
701 else if (PREFIX("SerialNumber="))
702 {
703 rc = usbReadStr(pszValue, &Dev.pszSerialNumber);
704 if (RT_SUCCESS(rc))
705 Dev.u64SerialHash = USBLibHashSerial(pszValue);
706 }
707 break;
708
709 /*
710 * C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
711 * | | | | | |__MaxPower in mA
712 * | | | | |__Attributes
713 * | | | |__ConfiguratioNumber
714 * | | |__NumberOfInterfaces
715 * | |__ "*" indicates the active configuration (others are " ")
716 * |__Config info tag
717 */
718 case 'C':
719 break;
720
721 /*
722 * I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
723 * | | | | | | | |__Driver name
724 * | | | | | | | or "(none)"
725 * | | | | | | |__InterfaceProtocol
726 * | | | | | |__InterfaceSubClass
727 * | | | | |__InterfaceClass
728 * | | | |__NumberOfEndpoints
729 * | | |__AlternateSettingNumber
730 * | |__InterfaceNumber
731 * |__Interface info tag
732 */
733 case 'I':
734 {
735 /* Check for thing we don't support. */
736 while (*psz && RT_SUCCESS(rc))
737 {
738 if (PREFIX("Driver="))
739 {
740 const char *pszDriver = NULL;
741 rc = usbReadStr(pszValue, &pszDriver);
742 if ( !pszDriver
743 || !*pszDriver
744 || !strcmp(pszDriver, "(none)")
745 || !strcmp(pszDriver, "(no driver)"))
746 /* no driver */;
747 else if (!strcmp(pszDriver, "hub"))
748 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
749 else if (Dev.enmState == USBDEVICESTATE_UNUSED)
750 Dev.enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
751 RTStrFree((char *)pszDriver);
752 break; /* last attrib */
753 }
754 else if (PREFIX("Cls="))
755 {
756 uint8_t bInterfaceClass;
757 rc = usbRead8(pszValue, 16, &bInterfaceClass, &psz);
758 if (RT_SUCCESS(rc) && bInterfaceClass == 9 /* HUB */)
759 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
760 }
761 else
762 psz = usbReadSkip(psz);
763 psz = RTStrStripL(psz);
764 }
765 break;
766 }
767
768
769 /*
770 * E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddms
771 * | | | | |__Interval (max) between transfers
772 * | | | |__EndpointMaxPacketSize
773 * | | |__Attributes(EndpointType)
774 * | |__EndpointAddress(I=In,O=Out)
775 * |__Endpoint info tag
776 */
777 case 'E':
778 break;
779
780 }
781#undef PREFIX
782 } /* parse loop */
783 fclose(pFile);
784
785 /*
786 * Add the current entry.
787 */
788 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
789 if (cHits >= 3)
790 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, pcszUsbfsRoot, testfs, rc);
791
792 /*
793 * Success?
794 */
795 if (RT_FAILURE(rc))
796 {
797 while (pFirst)
798 {
799 PUSBDEVICE pFree = pFirst;
800 pFirst = pFirst->pNext;
801 deviceFree(pFree);
802 }
803 }
804 }
805 if (RT_FAILURE(rc))
806 LogFlow(("USBProxyServiceLinux::getDevices: rc=%Rrc\n", rc));
807 return pFirst;
808}
809
810#ifdef VBOX_USB_WITH_SYSFS
811
812static void USBDevInfoCleanup(USBDeviceInfo *pSelf)
813{
814 RTStrFree(pSelf->mDevice);
815 RTStrFree(pSelf->mSysfsPath);
816 pSelf->mDevice = pSelf->mSysfsPath = NULL;
817 VEC_CLEANUP_PTR(&pSelf->mvecpszInterfaces);
818}
819
820static int USBDevInfoInit(USBDeviceInfo *pSelf, const char *aDevice,
821 const char *aSystemID)
822{
823 pSelf->mDevice = aDevice ? RTStrDup(aDevice) : NULL;
824 pSelf->mSysfsPath = aSystemID ? RTStrDup(aSystemID) : NULL;
825 VEC_INIT_PTR(&pSelf->mvecpszInterfaces, char *, RTStrFree);
826 if ((aDevice && !pSelf->mDevice) || (aSystemID && ! pSelf->mSysfsPath))
827 {
828 USBDevInfoCleanup(pSelf);
829 return 0;
830 }
831 return 1;
832}
833
834#define USBDEVICE_MAJOR 189
835
836/** Deduce the bus that a USB device is plugged into from the device node
837 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
838static unsigned usbBusFromDevNum(dev_t devNum)
839{
840 AssertReturn(devNum, 0);
841 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
842 return (minor(devNum) >> 7) + 1;
843}
844
845
846/** Deduce the device number of a USB device on the bus from the device node
847 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
848static unsigned usbDeviceFromDevNum(dev_t devNum)
849{
850 AssertReturn(devNum, 0);
851 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
852 return (minor(devNum) & 127) + 1;
853}
854
855
856/**
857 * If a file @a pcszNode from /sys/bus/usb/devices is a device rather than an
858 * interface add an element for the device to @a pvecDevInfo.
859 */
860static int addIfDevice(const char *pcszDevicesRoot,
861 const char *pcszNode,
862 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
863{
864 const char *pcszFile = strrchr(pcszNode, '/');
865 if (strchr(pcszFile, ':'))
866 return VINF_SUCCESS;
867 dev_t devnum = RTLinuxSysFsReadDevNumFile("%s/dev", pcszNode);
868 /* Sanity test of our static helpers */
869 Assert(usbBusFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 5);
870 Assert(usbDeviceFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 6);
871 if (!devnum)
872 return VINF_SUCCESS;
873 char szDevPath[RTPATH_MAX];
874 ssize_t cchDevPath;
875 cchDevPath = RTLinuxFindDevicePath(devnum, RTFS_TYPE_DEV_CHAR,
876 szDevPath, sizeof(szDevPath),
877 "%s/%.3d/%.3d",
878 pcszDevicesRoot,
879 usbBusFromDevNum(devnum),
880 usbDeviceFromDevNum(devnum));
881 if (cchDevPath < 0)
882 return VINF_SUCCESS;
883
884 USBDeviceInfo info;
885 if (USBDevInfoInit(&info, szDevPath, pcszNode))
886 if (RT_SUCCESS(VEC_PUSH_BACK_OBJ(pvecDevInfo, USBDeviceInfo,
887 &info)))
888 return VINF_SUCCESS;
889 USBDevInfoCleanup(&info);
890 return VERR_NO_MEMORY;
891}
892
893/** The logic for testing whether a sysfs address corresponds to an
894 * interface of a device. Both must be referenced by their canonical
895 * sysfs paths. This is not tested, as the test requires file-system
896 * interaction. */
897static bool muiIsAnInterfaceOf(const char *pcszIface, const char *pcszDev)
898{
899 size_t cchDev = strlen(pcszDev);
900
901 AssertPtr(pcszIface);
902 AssertPtr(pcszDev);
903 Assert(pcszIface[0] == '/');
904 Assert(pcszDev[0] == '/');
905 Assert(pcszDev[cchDev - 1] != '/');
906 /* If this passes, pcszIface is at least cchDev long */
907 if (strncmp(pcszIface, pcszDev, cchDev))
908 return false;
909 /* If this passes, pcszIface is longer than cchDev */
910 if (pcszIface[cchDev] != '/')
911 return false;
912 /* In sysfs an interface is an immediate subdirectory of the device */
913 if (strchr(pcszIface + cchDev + 1, '/'))
914 return false;
915 /* And it always has a colon in its name */
916 if (!strchr(pcszIface + cchDev + 1, ':'))
917 return false;
918 /* And hopefully we have now elimitated everything else */
919 return true;
920}
921
922#ifdef DEBUG
923# ifdef __cplusplus
924/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
925class testIsAnInterfaceOf
926{
927public:
928 testIsAnInterfaceOf()
929 {
930 Assert(muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0",
931 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
932 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-1",
933 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
934 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0/driver",
935 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
936 }
937};
938static testIsAnInterfaceOf testIsAnInterfaceOfInst;
939# endif /* __cplusplus */
940#endif /* DEBUG */
941
942/**
943 * Tell whether a file in /sys/bus/usb/devices is an interface rather than a
944 * device. To be used with getDeviceInfoFromSysfs().
945 */
946static int addIfInterfaceOf(const char *pcszNode, USBDeviceInfo *pInfo)
947{
948 if (!muiIsAnInterfaceOf(pcszNode, pInfo->mSysfsPath))
949 return VINF_SUCCESS;
950 char *pszDup = (char *)RTStrDup(pcszNode);
951 if (pszDup)
952 if (RT_SUCCESS(VEC_PUSH_BACK_PTR(&pInfo->mvecpszInterfaces,
953 char *, pszDup)))
954 return VINF_SUCCESS;
955 RTStrFree(pszDup);
956 return VERR_NO_MEMORY;
957}
958
959/** Helper for readFilePaths(). Adds the entries from the open directory
960 * @a pDir to the vector @a pvecpchDevs using either the full path or the
961 * realpath() and skipping hidden files and files on which realpath() fails. */
962static int readFilePathsFromDir(const char *pcszPath, DIR *pDir,
963 VECTOR_PTR(char *) *pvecpchDevs)
964{
965 struct dirent entry, *pResult;
966 int err, rc;
967
968 for (err = readdir_r(pDir, &entry, &pResult); pResult;
969 err = readdir_r(pDir, &entry, &pResult))
970 {
971 char szPath[RTPATH_MAX + 1], szRealPath[RTPATH_MAX + 1], *pszPath;
972 if (entry.d_name[0] == '.')
973 continue;
974 if (snprintf(szPath, sizeof(szPath), "%s/%s", pcszPath,
975 entry.d_name) < 0)
976 return RTErrConvertFromErrno(errno);
977 if (!realpath(szPath, szRealPath))
978 return RTErrConvertFromErrno(errno);
979 pszPath = RTStrDup(szRealPath);
980 if (!pszPath)
981 return VERR_NO_MEMORY;
982 if (RT_FAILURE(rc = VEC_PUSH_BACK_PTR(pvecpchDevs, char *, pszPath)))
983 return rc;
984 }
985 return RTErrConvertFromErrno(err);
986}
987
988/**
989 * Dump the names of a directory's entries into a vector of char pointers.
990 *
991 * @returns zero on success or (positive) posix error value.
992 * @param pcszPath the path to dump.
993 * @param pvecpchDevs an empty vector of char pointers - must be cleaned up
994 * by the caller even on failure.
995 * @param withRealPath whether to canonicalise the filename with realpath
996 */
997static int readFilePaths(const char *pcszPath, VECTOR_PTR(char *) *pvecpchDevs)
998{
999 DIR *pDir;
1000 int rc;
1001
1002 AssertPtrReturn(pvecpchDevs, EINVAL);
1003 AssertReturn(VEC_SIZE_PTR(pvecpchDevs) == 0, EINVAL);
1004 AssertPtrReturn(pcszPath, EINVAL);
1005
1006 pDir = opendir(pcszPath);
1007 if (!pDir)
1008 return RTErrConvertFromErrno(errno);
1009 rc = readFilePathsFromDir(pcszPath, pDir, pvecpchDevs);
1010 if (closedir(pDir) < 0 && RT_SUCCESS(rc))
1011 rc = RTErrConvertFromErrno(errno);
1012 return rc;
1013}
1014
1015/**
1016 * Logic for USBSysfsEnumerateHostDevices.
1017 * @param pvecDevInfo vector of device information structures to add device
1018 * information to
1019 * @param pvecpchDevs empty scratch vector which will be freed by the caller,
1020 * to simplify exit logic
1021 */
1022static int doSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
1023 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo,
1024 VECTOR_PTR(char *) *pvecpchDevs)
1025{
1026 char **ppszEntry;
1027 USBDeviceInfo *pInfo;
1028 int rc;
1029
1030 AssertPtrReturn(pvecDevInfo, VERR_INVALID_POINTER);
1031 LogFlowFunc (("pvecDevInfo=%p\n", pvecDevInfo));
1032
1033 rc = readFilePaths("/sys/bus/usb/devices", pvecpchDevs);
1034 if (RT_FAILURE(rc))
1035 return rc;
1036 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1037 if (RT_FAILURE(rc = addIfDevice(pcszDevicesRoot, *ppszEntry,
1038 pvecDevInfo)))
1039 return rc;
1040 VEC_FOR_EACH(pvecDevInfo, USBDeviceInfo, pInfo)
1041 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1042 if (RT_FAILURE(rc = addIfInterfaceOf(*ppszEntry, pInfo)))
1043 return rc;
1044 return VINF_SUCCESS;
1045}
1046
1047static int USBSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
1048 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
1049{
1050 VECTOR_PTR(char *) vecpchDevs;
1051 int rc = VERR_NOT_IMPLEMENTED;
1052
1053 AssertReturn(VEC_SIZE_OBJ(pvecDevInfo) == 0, VERR_INVALID_PARAMETER);
1054 LogFlowFunc(("entered\n"));
1055 VEC_INIT_PTR(&vecpchDevs, char *, RTStrFree);
1056 rc = doSysfsEnumerateHostDevices(pcszDevicesRoot, pvecDevInfo,
1057 &vecpchDevs);
1058 VEC_CLEANUP_PTR(&vecpchDevs);
1059 LogFlowFunc(("rc=%Rrc\n", rc));
1060 return rc;
1061}
1062
1063/**
1064 * Helper function for extracting the port number on the parent device from
1065 * the sysfs path value.
1066 *
1067 * The sysfs path is a chain of elements separated by forward slashes, and for
1068 * USB devices, the last element in the chain takes the form
1069 * <port>-<port>.[...].<port>[:<config>.<interface>]
1070 * where the first <port> is the port number on the root hub, and the following
1071 * (optional) ones are the port numbers on any other hubs between the device
1072 * and the root hub. The last part (:<config.interface>) is only present for
1073 * interfaces, not for devices. This API should only be called for devices.
1074 * For compatibility with usbfs, which enumerates from zero up, we subtract one
1075 * from the port number.
1076 *
1077 * For root hubs, the last element in the chain takes the form
1078 * usb<hub number>
1079 * and usbfs always returns port number zero.
1080 *
1081 * @returns VBox status. pu8Port is set on success.
1082 * @param pszPath The sysfs path to parse.
1083 * @param pu8Port Where to store the port number.
1084 */
1085static int usbGetPortFromSysfsPath(const char *pszPath, uint8_t *pu8Port)
1086{
1087 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1088 AssertPtrReturn(pu8Port, VERR_INVALID_POINTER);
1089
1090 /*
1091 * This should not be possible until we get PCs with USB as their primary bus.
1092 * Note: We don't assert this, as we don't expect the caller to validate the
1093 * sysfs path.
1094 */
1095 const char *pszLastComp = strrchr(pszPath, '/');
1096 if (!pszLastComp)
1097 {
1098 Log(("usbGetPortFromSysfsPath(%s): failed [1]\n", pszPath));
1099 return VERR_INVALID_PARAMETER;
1100 }
1101 pszLastComp++; /* skip the slash */
1102
1103 /*
1104 * This API should not be called for interfaces, so the last component
1105 * of the path should not contain a colon. We *do* assert this, as it
1106 * might indicate a caller bug.
1107 */
1108 AssertMsgReturn(strchr(pszLastComp, ':') == NULL, ("%s\n", pszPath), VERR_INVALID_PARAMETER);
1109
1110 /*
1111 * Look for the start of the last number.
1112 */
1113 const char *pchDash = strrchr(pszLastComp, '-');
1114 const char *pchDot = strrchr(pszLastComp, '.');
1115 if (!pchDash && !pchDot)
1116 {
1117 /* No -/. so it must be a root hub. Check that it's usb<something>. */
1118 if (strncmp(pszLastComp, "usb", sizeof("usb") - 1) != 0)
1119 {
1120 Log(("usbGetPortFromSysfsPath(%s): failed [2]\n", pszPath));
1121 return VERR_INVALID_PARAMETER;
1122 }
1123 return VERR_NOT_SUPPORTED;
1124 }
1125 else
1126 {
1127 const char *pszLastPort = pchDot != NULL
1128 ? pchDot + 1
1129 : pchDash + 1;
1130 int rc = RTStrToUInt8Full(pszLastPort, 10, pu8Port);
1131 if (rc != VINF_SUCCESS)
1132 {
1133 Log(("usbGetPortFromSysfsPath(%s): failed [3], rc=%Rrc\n", pszPath, rc));
1134 return VERR_INVALID_PARAMETER;
1135 }
1136 if (*pu8Port == 0)
1137 {
1138 Log(("usbGetPortFromSysfsPath(%s): failed [4]\n", pszPath));
1139 return VERR_INVALID_PARAMETER;
1140 }
1141
1142 /* usbfs compatibility, 0-based port number. */
1143 *pu8Port -= 1;
1144 }
1145 return VINF_SUCCESS;
1146}
1147
1148
1149/**
1150 * Dumps a USBDEVICE structure to the log using LogLevel 3.
1151 * @param pDev The structure to log.
1152 * @todo This is really common code.
1153 */
1154DECLINLINE(void) usbLogDevice(PUSBDEVICE pDev)
1155{
1156 NOREF(pDev);
1157
1158 Log3(("USB device:\n"));
1159 Log3(("Product: %s (%x)\n", pDev->pszProduct, pDev->idProduct));
1160 Log3(("Manufacturer: %s (Vendor ID %x)\n", pDev->pszManufacturer, pDev->idVendor));
1161 Log3(("Serial number: %s (%llx)\n", pDev->pszSerialNumber, pDev->u64SerialHash));
1162 Log3(("Device revision: %d\n", pDev->bcdDevice));
1163 Log3(("Device class: %x\n", pDev->bDeviceClass));
1164 Log3(("Device subclass: %x\n", pDev->bDeviceSubClass));
1165 Log3(("Device protocol: %x\n", pDev->bDeviceProtocol));
1166 Log3(("USB version number: %d\n", pDev->bcdUSB));
1167 Log3(("Device speed: %s\n",
1168 pDev->enmSpeed == USBDEVICESPEED_UNKNOWN ? "unknown"
1169 : pDev->enmSpeed == USBDEVICESPEED_LOW ? "1.5 MBit/s"
1170 : pDev->enmSpeed == USBDEVICESPEED_FULL ? "12 MBit/s"
1171 : pDev->enmSpeed == USBDEVICESPEED_HIGH ? "480 MBit/s"
1172 : pDev->enmSpeed == USBDEVICESPEED_VARIABLE ? "variable"
1173 : "invalid"));
1174 Log3(("Number of configurations: %d\n", pDev->bNumConfigurations));
1175 Log3(("Bus number: %d\n", pDev->bBus));
1176 Log3(("Port number: %d\n", pDev->bPort));
1177 Log3(("Device number: %d\n", pDev->bDevNum));
1178 Log3(("Device state: %s\n",
1179 pDev->enmState == USBDEVICESTATE_UNSUPPORTED ? "unsupported"
1180 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST ? "in use by host"
1181 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE ? "in use by host, possibly capturable"
1182 : pDev->enmState == USBDEVICESTATE_UNUSED ? "not in use"
1183 : pDev->enmState == USBDEVICESTATE_HELD_BY_PROXY ? "held by proxy"
1184 : pDev->enmState == USBDEVICESTATE_USED_BY_GUEST ? "used by guest"
1185 : "invalid"));
1186 Log3(("OS device address: %s\n", pDev->pszAddress));
1187}
1188
1189/**
1190 * In contrast to usbReadBCD() this function can handle BCD values without
1191 * a decimal separator. This is necessary for parsing bcdDevice.
1192 * @param pszBuf Pointer to the string buffer.
1193 * @param pu15 Pointer to the return value.
1194 * @returns IPRT status code.
1195 */
1196static int convertSysfsStrToBCD(const char *pszBuf, uint16_t *pu16)
1197{
1198 char *pszNext;
1199 int32_t i32;
1200
1201 pszBuf = RTStrStripL(pszBuf);
1202 int rc = RTStrToInt32Ex(pszBuf, &pszNext, 16, &i32);
1203 if ( RT_FAILURE(rc)
1204 || rc == VWRN_NUMBER_TOO_BIG
1205 || i32 < 0)
1206 return VERR_NUMBER_TOO_BIG;
1207 if (*pszNext == '.')
1208 {
1209 if (i32 > 255)
1210 return VERR_NUMBER_TOO_BIG;
1211 int32_t i32Lo;
1212 rc = RTStrToInt32Ex(pszNext+1, &pszNext, 16, &i32Lo);
1213 if ( RT_FAILURE(rc)
1214 || rc == VWRN_NUMBER_TOO_BIG
1215 || i32Lo > 255
1216 || i32Lo < 0)
1217 return VERR_NUMBER_TOO_BIG;
1218 i32 = (i32 << 8) | i32Lo;
1219 }
1220 if ( i32 > 65535
1221 || (*pszNext != '\0' && *pszNext != ' '))
1222 return VERR_NUMBER_TOO_BIG;
1223
1224 *pu16 = (uint16_t)i32;
1225 return VINF_SUCCESS;
1226}
1227
1228#endif /* VBOX_USB_WITH_SYSFS */
1229
1230static void fillInDeviceFromSysfs(USBDEVICE *Dev, USBDeviceInfo *pInfo)
1231{
1232 int rc;
1233 const char *pszSysfsPath = pInfo->mSysfsPath;
1234
1235 /* Fill in the simple fields */
1236 Dev->enmState = USBDEVICESTATE_UNUSED;
1237 Dev->bBus = RTLinuxSysFsReadIntFile(10, "%s/busnum", pszSysfsPath);
1238 Dev->bDeviceClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceClass", pszSysfsPath);
1239 Dev->bDeviceSubClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceSubClass", pszSysfsPath);
1240 Dev->bDeviceProtocol = RTLinuxSysFsReadIntFile(16, "%s/bDeviceProtocol", pszSysfsPath);
1241 Dev->bNumConfigurations = RTLinuxSysFsReadIntFile(10, "%s/bNumConfigurations", pszSysfsPath);
1242 Dev->idVendor = RTLinuxSysFsReadIntFile(16, "%s/idVendor", pszSysfsPath);
1243 Dev->idProduct = RTLinuxSysFsReadIntFile(16, "%s/idProduct", pszSysfsPath);
1244 Dev->bDevNum = RTLinuxSysFsReadIntFile(10, "%s/devnum", pszSysfsPath);
1245
1246 /* Now deal with the non-numeric bits. */
1247 char szBuf[1024]; /* Should be larger than anything a sane device
1248 * will need, and insane devices can be unsupported
1249 * until further notice. */
1250 ssize_t cchRead;
1251
1252 /* For simplicity, we just do strcmps on the next one. */
1253 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/speed",
1254 pszSysfsPath);
1255 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1256 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1257 else
1258 Dev->enmSpeed = !strcmp(szBuf, "1.5") ? USBDEVICESPEED_LOW
1259 : !strcmp(szBuf, "12") ? USBDEVICESPEED_FULL
1260 : !strcmp(szBuf, "480") ? USBDEVICESPEED_HIGH
1261 : USBDEVICESPEED_UNKNOWN;
1262
1263 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/version",
1264 pszSysfsPath);
1265 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1266 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1267 else
1268 {
1269 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdUSB);
1270 if (RT_FAILURE(rc))
1271 {
1272 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1273 Dev->bcdUSB = (uint16_t)-1;
1274 }
1275 }
1276
1277 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/bcdDevice",
1278 pszSysfsPath);
1279 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1280 Dev->bcdDevice = (uint16_t)-1;
1281 else
1282 {
1283 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdDevice);
1284 if (RT_FAILURE(rc))
1285 Dev->bcdDevice = (uint16_t)-1;
1286 }
1287
1288 /* Now do things that need string duplication */
1289 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/product",
1290 pszSysfsPath);
1291 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1292 {
1293 RTStrPurgeEncoding(szBuf);
1294 Dev->pszProduct = RTStrDup(szBuf);
1295 }
1296
1297 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/serial",
1298 pszSysfsPath);
1299 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1300 {
1301 RTStrPurgeEncoding(szBuf);
1302 Dev->pszSerialNumber = RTStrDup(szBuf);
1303 Dev->u64SerialHash = USBLibHashSerial(szBuf);
1304 }
1305
1306 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/manufacturer",
1307 pszSysfsPath);
1308 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1309 {
1310 RTStrPurgeEncoding(szBuf);
1311 Dev->pszManufacturer = RTStrDup(szBuf);
1312 }
1313
1314 /* Work out the port number */
1315 if (RT_FAILURE(usbGetPortFromSysfsPath(pszSysfsPath, &Dev->bPort)))
1316 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1317
1318 /* Check the interfaces to see if we can support the device. */
1319 char **ppszIf;
1320 VEC_FOR_EACH(&pInfo->mvecpszInterfaces, char *, ppszIf)
1321 {
1322 ssize_t cb = RTLinuxSysFsGetLinkDest(szBuf, sizeof(szBuf), "%s/driver",
1323 *ppszIf);
1324 if (cb > 0 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED)
1325 Dev->enmState = (strcmp(szBuf, "hub") == 0)
1326 ? USBDEVICESTATE_UNSUPPORTED
1327 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1328 if (RTLinuxSysFsReadIntFile(16, "%s/bInterfaceClass",
1329 *ppszIf) == 9 /* hub */)
1330 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1331 }
1332
1333 /* We use a double slash as a separator in the pszAddress field. This is
1334 * alright as the two paths can't contain a slash due to the way we build
1335 * them. */
1336 char *pszAddress = NULL;
1337 RTStrAPrintf(&pszAddress, "sysfs:%s//device:%s", pszSysfsPath,
1338 pInfo->mDevice);
1339 Dev->pszAddress = pszAddress;
1340
1341 /* Work out from the data collected whether we can support this device. */
1342 Dev->enmState = usbDeterminState(Dev);
1343 usbLogDevice(Dev);
1344}
1345
1346/**
1347 * USBProxyService::getDevices() implementation for sysfs.
1348 */
1349static PUSBDEVICE getDevicesFromSysfs(const char *pcszDevicesRoot, bool testfs)
1350{
1351#ifdef VBOX_USB_WITH_SYSFS
1352 /* Add each of the devices found to the chain. */
1353 PUSBDEVICE pFirst = NULL;
1354 PUSBDEVICE pLast = NULL;
1355 VECTOR_OBJ(USBDeviceInfo) vecDevInfo;
1356 USBDeviceInfo *pInfo;
1357 int rc;
1358
1359 VEC_INIT_OBJ(&vecDevInfo, USBDeviceInfo, USBDevInfoCleanup);
1360 rc = USBSysfsEnumerateHostDevices(pcszDevicesRoot, &vecDevInfo);
1361 if (RT_FAILURE(rc))
1362 return NULL;
1363 VEC_FOR_EACH(&vecDevInfo, USBDeviceInfo, pInfo)
1364 {
1365 USBDEVICE *Dev = (USBDEVICE *)RTMemAllocZ(sizeof(USBDEVICE));
1366 if (!Dev)
1367 rc = VERR_NO_MEMORY;
1368 if (RT_SUCCESS(rc))
1369 {
1370 fillInDeviceFromSysfs(Dev, pInfo);
1371 }
1372 if ( RT_SUCCESS(rc)
1373 && ( Dev->enmState != USBDEVICESTATE_UNSUPPORTED
1374 || testfs)
1375 && Dev->pszAddress != NULL
1376 )
1377 {
1378 if (pLast != NULL)
1379 {
1380 pLast->pNext = Dev;
1381 pLast = pLast->pNext;
1382 }
1383 else
1384 pFirst = pLast = Dev;
1385 }
1386 else
1387 deviceFree(Dev);
1388 if (RT_FAILURE(rc))
1389 break;
1390 }
1391 if (RT_FAILURE(rc))
1392 deviceListFree(&pFirst);
1393
1394 VEC_CLEANUP_OBJ(&vecDevInfo);
1395 return pFirst;
1396#else /* !VBOX_USB_WITH_SYSFS */
1397 return NULL;
1398#endif /* !VBOX_USB_WITH_SYSFS */
1399}
1400
1401/** Is inotify available and working on this system? This is a requirement
1402 * for using USB with sysfs */
1403/** @todo test the "inotify in glibc but not in the kernel" case. */
1404static bool inotifyAvailable(void)
1405{
1406 int (*inotify_init)(void);
1407
1408 *(void **)(&inotify_init) = dlsym(RTLD_DEFAULT, "inotify_init");
1409 if (!inotify_init)
1410 return false;
1411 int fd = inotify_init();
1412 if (fd == -1)
1413 return false;
1414 close(fd);
1415 return true;
1416}
1417
1418PCUSBDEVTREELOCATION USBProxyLinuxGetDeviceRoot(bool fPreferSysfs)
1419{
1420 PCUSBDEVTREELOCATION pcBestUsbfs = NULL;
1421 PCUSBDEVTREELOCATION pcBestSysfs = NULL;
1422
1423 bool fHaveInotify = inotifyAvailable();
1424 for (unsigned i = 0; i < RT_ELEMENTS(s_aTreeLocations); ++i)
1425 if (!s_aTreeLocations[i].fUseSysfs)
1426 {
1427 if (!pcBestUsbfs)
1428 {
1429 PUSBDEVICE pDevices;
1430
1431 pDevices = getDevicesFromUsbfs(s_aTreeLocations[i].szDevicesRoot,
1432 true);
1433 if (pDevices)
1434 {
1435 pcBestUsbfs = &s_aTreeLocations[i];
1436 deviceListFree(&pDevices);
1437 }
1438 }
1439 }
1440 else
1441 {
1442 if ( fHaveInotify
1443 && !pcBestSysfs
1444 && RTPathExists(s_aTreeLocations[i].szDevicesRoot))
1445 pcBestSysfs = &s_aTreeLocations[i];
1446 }
1447 if (pcBestUsbfs && !fPreferSysfs)
1448 return pcBestUsbfs;
1449 return pcBestSysfs;
1450}
1451
1452
1453PUSBDEVICE USBProxyLinuxGetDevices(const char *pcszDevicesRoot,
1454 bool fUseSysfs)
1455{
1456 if (!fUseSysfs)
1457 return getDevicesFromUsbfs(pcszDevicesRoot, false);
1458 else
1459 return getDevicesFromSysfs(pcszDevicesRoot, false);
1460}
Note: See TracBrowser for help on using the repository browser.

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