VirtualBox

source: vbox/trunk/src/VBox/Main/linux/USBGetDevices.cpp@ 32880

最後變更 在這個檔案從32880是 32469,由 vboxsync 提交於 15 年 前

Main/USB/linux: minor fixes to USBGetDevides

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 47.3 KB
 
1/* $Id: USBGetDevices.cpp 32469 2010-09-14 10:01:17Z 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.alldomusa.eu.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/string.h>
37#include "vector.h"
38
39#include <linux/usbdevice_fs.h>
40
41#include <sys/types.h>
42#include <sys/stat.h>
43#include <sys/vfs.h>
44
45#include <dirent.h>
46#include <errno.h>
47#include <fcntl.h>
48#include <stdio.h>
49#include <string.h>
50#include <unistd.h>
51
52/*******************************************************************************
53* Structures and Typedefs *
54*******************************************************************************/
55/** Suffix translation. */
56typedef struct USBSUFF
57{
58 char szSuff[4];
59 unsigned cchSuff;
60 unsigned uMul;
61 unsigned uDiv;
62} USBSUFF, *PUSBSUFF;
63typedef const USBSUFF *PCUSBSUFF;
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* Global Variables *
79*******************************************************************************/
80/**
81 * Suffixes for the endpoint polling interval.
82 */
83static const USBSUFF s_aIntervalSuff[] =
84{
85 { "ms", 2, 1, 0 },
86 { "us", 2, 1, 1000 },
87 { "ns", 2, 1, 1000000 },
88 { "s", 1, 1000, 0 },
89 { "", 0, 0, 0 } /* term */
90};
91
92
93int USBProxyLinuxCheckForUsbfs(const char *pcszDevices)
94{
95 int fd;
96
97 fd = open(pcszDevices, O_RDONLY, 00600);
98 if (fd)
99 {
100 /*
101 * Check that we're actually on the usbfs.
102 */
103 struct statfs StFS;
104 if (!fstatfs(fd, &StFS))
105 {
106 if (StFS.f_type == USBDEVICE_SUPER_MAGIC)
107 return VINF_SUCCESS;
108 else
109 return VERR_NOT_FOUND;
110 }
111 else
112 return RTErrConvertFromErrno(errno);
113 }
114 else
115 return RTErrConvertFromErrno(errno);
116 return 0;
117}
118
119
120/**
121 * "reads" the number suffix. It's more like validating it and
122 * skipping the necessary number of chars.
123 */
124static int usbReadSkipSuffix(char **ppszNext)
125{
126 char *pszNext = *ppszNext;
127 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
128 {
129 /* skip unit */
130 if (pszNext[0] == 'm' && pszNext[1] == 's')
131 pszNext += 2;
132 else if (pszNext[0] == 'm' && pszNext[1] == 'A')
133 pszNext += 2;
134
135 /* skip parenthesis */
136 if (*pszNext == '(')
137 {
138 pszNext = strchr(pszNext, ')');
139 if (!pszNext++)
140 {
141 AssertMsgFailed(("*ppszNext=%s\n", *ppszNext));
142 return VERR_PARSE_ERROR;
143 }
144 }
145
146 /* blank or end of the line. */
147 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
148 {
149 AssertMsgFailed(("pszNext=%s\n", pszNext));
150 return VERR_PARSE_ERROR;
151 }
152
153 /* it's ok. */
154 *ppszNext = pszNext;
155 }
156
157 return VINF_SUCCESS;
158}
159
160
161/**
162 * Reads a USB number returning the number and the position of the next character to parse.
163 */
164static int usbReadNum(const char *pszValue, unsigned uBase, uint32_t u32Mask, PCUSBSUFF paSuffs, void *pvNum, char **ppszNext)
165{
166 /*
167 * Initialize return value to zero and strip leading spaces.
168 */
169 switch (u32Mask)
170 {
171 case 0xff: *(uint8_t *)pvNum = 0; break;
172 case 0xffff: *(uint16_t *)pvNum = 0; break;
173 case 0xffffffff: *(uint32_t *)pvNum = 0; break;
174 }
175 pszValue = RTStrStripL(pszValue);
176 if (*pszValue)
177 {
178 /*
179 * Try convert the number.
180 */
181 char *pszNext;
182 uint32_t u32 = 0;
183 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32);
184 if (pszNext == pszValue)
185 {
186 AssertMsgFailed(("pszValue=%d\n", pszValue));
187 return VERR_NO_DATA;
188 }
189
190 /*
191 * Check the range.
192 */
193 if (u32 & ~u32Mask)
194 {
195 AssertMsgFailed(("pszValue=%d u32=%#x lMask=%#x\n", pszValue, u32, u32Mask));
196 return VERR_OUT_OF_RANGE;
197 }
198
199 /*
200 * Validate and skip stuff following the number.
201 */
202 if (paSuffs)
203 {
204 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
205 {
206 for (PCUSBSUFF pSuff = paSuffs; pSuff->szSuff[0]; pSuff++)
207 {
208 if ( !strncmp(pSuff->szSuff, pszNext, pSuff->cchSuff)
209 && (!pszNext[pSuff->cchSuff] || RT_C_IS_SPACE(pszNext[pSuff->cchSuff])))
210 {
211 if (pSuff->uDiv)
212 u32 /= pSuff->uDiv;
213 else
214 u32 *= pSuff->uMul;
215 break;
216 }
217 }
218 }
219 }
220 else
221 {
222 int rc = usbReadSkipSuffix(&pszNext);
223 if (RT_FAILURE(rc))
224 return rc;
225 }
226
227 *ppszNext = pszNext;
228
229 /*
230 * Set the value.
231 */
232 switch (u32Mask)
233 {
234 case 0xff: *(uint8_t *)pvNum = (uint8_t)u32; break;
235 case 0xffff: *(uint16_t *)pvNum = (uint16_t)u32; break;
236 case 0xffffffff: *(uint32_t *)pvNum = (uint32_t)u32; break;
237 }
238 }
239 return VINF_SUCCESS;
240}
241
242
243static int usbRead8(const char *pszValue, unsigned uBase, uint8_t *pu8, char **ppszNext)
244{
245 return usbReadNum(pszValue, uBase, 0xff, NULL, pu8, ppszNext);
246}
247
248
249static int usbRead16(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
250{
251 return usbReadNum(pszValue, uBase, 0xffff, NULL, pu16, ppszNext);
252}
253
254
255#if 0
256static int usbRead16Suff(const char *pszValue, unsigned uBase, PCUSBSUFF paSuffs, uint16_t *pu16, char **ppszNext)
257{
258 return usbReadNum(pszValue, uBase, 0xffff, paSuffs, pu16, ppszNext);
259}
260#endif
261
262
263/**
264 * Reads a USB BCD number returning the number and the position of the next character to parse.
265 * The returned number contains the integer part in the high byte and the decimal part in the low byte.
266 */
267static int usbReadBCD(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
268{
269 /*
270 * Initialize return value to zero and strip leading spaces.
271 */
272 *pu16 = 0;
273 pszValue = RTStrStripL(pszValue);
274 if (*pszValue)
275 {
276 /*
277 * Try convert the number.
278 */
279 /* integer part */
280 char *pszNext;
281 uint32_t u32Int = 0;
282 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32Int);
283 if (pszNext == pszValue)
284 {
285 AssertMsgFailed(("pszValue=%s\n", pszValue));
286 return VERR_NO_DATA;
287 }
288 if (u32Int & ~0xff)
289 {
290 AssertMsgFailed(("pszValue=%s u32Int=%#x (int)\n", pszValue, u32Int));
291 return VERR_OUT_OF_RANGE;
292 }
293
294 /* skip dot and read decimal part */
295 if (*pszNext != '.')
296 {
297 AssertMsgFailed(("pszValue=%s pszNext=%s (int)\n", pszValue, pszNext));
298 return VERR_PARSE_ERROR;
299 }
300 char *pszValue2 = RTStrStripL(pszNext + 1);
301 uint32_t u32Dec = 0;
302 RTStrToUInt32Ex(pszValue2, &pszNext, uBase, &u32Dec);
303 if (pszNext == pszValue)
304 {
305 AssertMsgFailed(("pszValue=%s\n", pszValue));
306 return VERR_NO_DATA;
307 }
308 if (u32Dec & ~0xff)
309 {
310 AssertMsgFailed(("pszValue=%s u32Dec=%#x\n", pszValue, u32Dec));
311 return VERR_OUT_OF_RANGE;
312 }
313
314 /*
315 * Validate and skip stuff following the number.
316 */
317 int rc = usbReadSkipSuffix(&pszNext);
318 if (RT_FAILURE(rc))
319 return rc;
320 *ppszNext = pszNext;
321
322 /*
323 * Set the value.
324 */
325 *pu16 = (uint16_t)u32Int << 8 | (uint16_t)u32Dec;
326 }
327 return VINF_SUCCESS;
328}
329
330
331/**
332 * Reads a string, i.e. allocates memory and copies it.
333 *
334 * We assume that a string is pure ASCII, if that's not the case
335 * tell me how to figure out the codeset please.
336 */
337static int usbReadStr(const char *pszValue, const char **ppsz)
338{
339 if (*ppsz)
340 RTStrFree((char *)*ppsz);
341 *ppsz = RTStrDup(pszValue);
342 if (*ppsz)
343 return VINF_SUCCESS;
344 return VERR_NO_MEMORY;
345}
346
347
348/**
349 * Skips the current property.
350 */
351static char *usbReadSkip(char *pszValue)
352{
353 char *psz = strchr(pszValue, '=');
354 if (psz)
355 psz = strchr(psz + 1, '=');
356 if (!psz)
357 return strchr(pszValue, '\0');
358 while (psz > pszValue && !RT_C_IS_SPACE(psz[-1]))
359 psz--;
360 Assert(psz > pszValue);
361 return psz;
362}
363
364
365/**
366 * Determine the USB speed.
367 */
368static int usbReadSpeed(const char *pszValue, USBDEVICESPEED *pSpd, char **ppszNext)
369{
370 pszValue = RTStrStripL(pszValue);
371 /* verified with Linux 2.4.0 ... Linux 2.6.25 */
372 if (!strncmp(pszValue, "1.5", 3))
373 *pSpd = USBDEVICESPEED_LOW;
374 else if (!strncmp(pszValue, "12 ", 3))
375 *pSpd = USBDEVICESPEED_FULL;
376 else if (!strncmp(pszValue, "480", 3))
377 *pSpd = USBDEVICESPEED_HIGH;
378 else
379 *pSpd = USBDEVICESPEED_UNKNOWN;
380 while (pszValue[0] != '\0' && !RT_C_IS_SPACE(pszValue[0]))
381 pszValue++;
382 *ppszNext = (char *)pszValue;
383 return VINF_SUCCESS;
384}
385
386
387/**
388 * Compare a prefix and returns pointer to the char following it if it matches.
389 */
390static char *usbPrefix(char *psz, const char *pszPref, size_t cchPref)
391{
392 if (strncmp(psz, pszPref, cchPref))
393 return NULL;
394 return psz + cchPref;
395}
396
397
398/**
399 * Does some extra checks to improve the detected device state.
400 *
401 * We cannot distinguish between USED_BY_HOST_CAPTURABLE and
402 * USED_BY_GUEST, HELD_BY_PROXY all that well and it shouldn't be
403 * necessary either.
404 *
405 * We will however, distinguish between the device we have permissions
406 * to open and those we don't. This is necessary for two reasons.
407 *
408 * Firstly, because it's futile to even attempt opening a device which we
409 * don't have access to, it only serves to confuse the user. (That said,
410 * it might also be a bit confusing for the user to see that a USB device
411 * is grayed out with no further explanation, and no way of generating an
412 * error hinting at why this is the case.)
413 *
414 * Secondly and more importantly, we're racing against udevd with respect
415 * to permissions and group settings on newly plugged devices. When we
416 * detect a new device that we cannot access we will poll on it for a few
417 * seconds to give udevd time to fix it. The polling is actually triggered
418 * in the 'new device' case in the compare loop.
419 *
420 * The USBDEVICESTATE_USED_BY_HOST state is only used for this no-access
421 * case, while USBDEVICESTATE_UNSUPPORTED is only used in the 'hub' case.
422 * When it's neither of these, we set USBDEVICESTATE_UNUSED or
423 * USBDEVICESTATE_USED_BY_HOST_CAPTURABLE depending on whether there is
424 * a driver associated with any of the interfaces.
425 *
426 * All except the access check and a special idVendor == 0 precaution
427 * is handled at parse time.
428 *
429 * @returns The adjusted state.
430 * @param pDevice The device.
431 */
432static USBDEVICESTATE usbDeterminState(PCUSBDEVICE pDevice)
433{
434 /*
435 * If it's already flagged as unsupported, there is nothing to do.
436 */
437 USBDEVICESTATE enmState = pDevice->enmState;
438 if (enmState == USBDEVICESTATE_UNSUPPORTED)
439 return USBDEVICESTATE_UNSUPPORTED;
440
441 /*
442 * Root hubs and similar doesn't have any vendor id, just
443 * refuse these device.
444 */
445 if (!pDevice->idVendor)
446 return USBDEVICESTATE_UNSUPPORTED;
447
448 /*
449 * Check if we've got access to the device, if we haven't flag
450 * it as used-by-host.
451 */
452#ifndef VBOX_USB_WITH_SYSFS
453 const char *pszAddress = pDevice->pszAddress;
454#else
455 if (pDevice->pszAddress == NULL)
456 /* We can't do much with the device without an address. */
457 return USBDEVICESTATE_UNSUPPORTED;
458 const char *pszAddress = strstr(pDevice->pszAddress, "//device:");
459 pszAddress = pszAddress != NULL
460 ? pszAddress + sizeof("//device:") - 1
461 : pDevice->pszAddress;
462#endif
463 if ( access(pszAddress, R_OK | W_OK) != 0
464 && errno == EACCES)
465 return USBDEVICESTATE_USED_BY_HOST;
466
467#ifdef VBOX_USB_WITH_SYSFS
468 /**
469 * @todo Check that any other essential fields are present and mark as
470 * invalid if not. Particularly to catch the case where the device was
471 * unplugged while we were reading in its properties.
472 */
473#endif
474
475 return enmState;
476}
477
478
479/** Just a worker for USBProxyServiceLinux::getDevices that avoids some code duplication. */
480static int addDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, const char *pcszUsbfsRoot, int rc)
481{
482 /* usbDeterminState requires the address. */
483 PUSBDEVICE pDevNew = (PUSBDEVICE)RTMemDup(pDev, sizeof(*pDev));
484 if (pDevNew)
485 {
486 RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", pcszUsbfsRoot, pDevNew->bBus, pDevNew->bDevNum);
487 if (pDevNew->pszAddress)
488 {
489 pDevNew->enmState = usbDeterminState(pDevNew);
490 if (pDevNew->enmState != USBDEVICESTATE_UNSUPPORTED)
491 {
492 if (*pppNext)
493 **pppNext = pDevNew;
494 else
495 *ppFirst = pDevNew;
496 *pppNext = &pDevNew->pNext;
497 }
498 else
499 deviceFree(pDevNew);
500 }
501 else
502 {
503 deviceFree(pDevNew);
504 rc = VERR_NO_MEMORY;
505 }
506 }
507 else
508 {
509 rc = VERR_NO_MEMORY;
510 deviceFreeMembers(pDev);
511 }
512
513 return rc;
514}
515
516
517static int openDevicesFile(const char *pcszUsbfsRoot, FILE **ppFile)
518{
519 char *pszPath;
520 FILE *pFile;
521 RTStrAPrintf(&pszPath, "%s/devices", pcszUsbfsRoot);
522 if (!pszPath)
523 return VERR_NO_MEMORY;
524 pFile = fopen(pszPath, "r");
525 RTStrFree(pszPath);
526 if (!pFile)
527 return RTErrConvertFromErrno(errno);
528 *ppFile = pFile;
529 return VINF_SUCCESS;
530}
531
532/**
533 * USBProxyService::getDevices() implementation for usbfs.
534 */
535static PUSBDEVICE getDevicesFromUsbfs(const char *pcszUsbfsRoot)
536{
537 PUSBDEVICE pFirst = NULL;
538 FILE *pFile = NULL;
539 int rc;
540 rc = openDevicesFile(pcszUsbfsRoot, &pFile);
541 if (RT_SUCCESS(rc))
542 {
543 PUSBDEVICE *ppNext = NULL;
544 int cHits = 0;
545 char szLine[1024];
546 USBDEVICE Dev;
547 RT_ZERO(Dev);
548 Dev.enmState = USBDEVICESTATE_UNUSED;
549
550 rc = VINF_SUCCESS;
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 occurence.)
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, 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
784 /*
785 * Add the current entry.
786 */
787 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
788 if (cHits >= 3)
789 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, pcszUsbfsRoot, rc);
790
791 /*
792 * Success?
793 */
794 if (RT_FAILURE(rc))
795 {
796 while (pFirst)
797 {
798 PUSBDEVICE pFree = pFirst;
799 pFirst = pFirst->pNext;
800 deviceFree(pFree);
801 }
802 }
803 }
804 if (RT_FAILURE(rc))
805 LogFlow(("USBProxyServiceLinux::getDevices: rc=%Rrc\n", rc));
806 return pFirst;
807}
808
809#ifdef VBOX_USB_WITH_SYSFS
810
811static void USBDevInfoCleanup(USBDeviceInfo *pSelf)
812{
813 RTStrFree(pSelf->mDevice);
814 RTStrFree(pSelf->mSysfsPath);
815 pSelf->mDevice = pSelf->mSysfsPath = NULL;
816 VEC_CLEANUP_PTR(&pSelf->mvecpszInterfaces);
817}
818
819static int USBDevInfoInit(USBDeviceInfo *pSelf, const char *aDevice,
820 const char *aSystemID)
821{
822 pSelf->mDevice = aDevice ? RTStrDup(aDevice) : NULL;
823 pSelf->mSysfsPath = aSystemID ? RTStrDup(aSystemID) : NULL;
824 VEC_INIT_PTR(&pSelf->mvecpszInterfaces, char *, RTStrFree);
825 if ((aDevice && !pSelf->mDevice) || (aSystemID && ! pSelf->mSysfsPath))
826 {
827 USBDevInfoCleanup(pSelf);
828 return 0;
829 }
830 return 1;
831}
832
833#define USBDEVICE_MAJOR 189
834
835/** Deduce the bus that a USB device is plugged into from the device node
836 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
837static unsigned usbBusFromDevNum(dev_t devNum)
838{
839 AssertReturn(devNum, 0);
840 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
841 return (minor(devNum) >> 7) + 1;
842}
843
844
845/** Deduce the device number of a USB device on the bus from the device node
846 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
847static unsigned usbDeviceFromDevNum(dev_t devNum)
848{
849 AssertReturn(devNum, 0);
850 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
851 return (minor(devNum) & 127) + 1;
852}
853
854
855/**
856 * If a file @a pcszNode from /sys/bus/usb/devices is a device rather than an
857 * interface add an element for the device to @a pvecDevInfo.
858 */
859static int addIfDevice(const char *pcszNode,
860 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
861{
862 const char *pcszFile = strrchr(pcszNode, '/');
863 if (strchr(pcszFile, ':'))
864 return VINF_SUCCESS;
865 dev_t devnum = RTLinuxSysFsReadDevNumFile("%s/dev", pcszNode);
866 /* Sanity test of our static helpers */
867 Assert(usbBusFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 5);
868 Assert(usbDeviceFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 6);
869 if (!devnum)
870 return VINF_SUCCESS;
871 char szDevPath[RTPATH_MAX];
872 ssize_t cchDevPath;
873 cchDevPath = RTLinuxFindDevicePath(devnum, RTFS_TYPE_DEV_CHAR,
874 szDevPath, sizeof(szDevPath),
875 "/dev/bus/usb/%.3d/%.3d",
876 usbBusFromDevNum(devnum),
877 usbDeviceFromDevNum(devnum));
878 if (cchDevPath < 0)
879 return VINF_SUCCESS;
880
881 USBDeviceInfo info;
882 if (USBDevInfoInit(&info, szDevPath, pcszNode))
883 if (RT_SUCCESS(VEC_PUSH_BACK_OBJ(pvecDevInfo, USBDeviceInfo,
884 &info)))
885 return VINF_SUCCESS;
886 USBDevInfoCleanup(&info);
887 return VERR_NO_MEMORY;
888}
889
890/** The logic for testing whether a sysfs address corresponds to an
891 * interface of a device. Both must be referenced by their canonical
892 * sysfs paths. This is not tested, as the test requires file-system
893 * interaction. */
894static bool muiIsAnInterfaceOf(const char *pcszIface, const char *pcszDev)
895{
896 size_t cchDev = strlen(pcszDev);
897
898 AssertPtr(pcszIface);
899 AssertPtr(pcszDev);
900 Assert(pcszIface[0] == '/');
901 Assert(pcszDev[0] == '/');
902 Assert(pcszDev[cchDev - 1] != '/');
903 /* If this passes, pcszIface is at least cchDev long */
904 if (strncmp(pcszIface, pcszDev, cchDev))
905 return false;
906 /* If this passes, pcszIface is longer than cchDev */
907 if (pcszIface[cchDev] != '/')
908 return false;
909 /* In sysfs an interface is an immediate subdirectory of the device */
910 if (strchr(pcszIface + cchDev + 1, '/'))
911 return false;
912 /* And it always has a colon in its name */
913 if (!strchr(pcszIface + cchDev + 1, ':'))
914 return false;
915 /* And hopefully we have now elimitated everything else */
916 return true;
917}
918
919#ifdef DEBUG
920# ifdef __cplusplus
921/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
922class testIsAnInterfaceOf
923{
924public:
925 testIsAnInterfaceOf()
926 {
927 Assert(muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0",
928 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
929 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-1",
930 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
931 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0/driver",
932 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
933 }
934};
935static testIsAnInterfaceOf testIsAnInterfaceOfInst;
936# endif /* __cplusplus */
937#endif /* DEBUG */
938
939/**
940 * Tell whether a file in /sys/bus/usb/devices is an interface rather than a
941 * device. To be used with getDeviceInfoFromSysfs().
942 */
943static int addIfInterfaceOf(const char *pcszNode, USBDeviceInfo *pInfo)
944{
945 if (!muiIsAnInterfaceOf(pcszNode, pInfo->mSysfsPath))
946 return VINF_SUCCESS;
947 char *pszDup = (char *)RTStrDup(pcszNode);
948 if (pszDup)
949 if (RT_SUCCESS(VEC_PUSH_BACK_PTR(&pInfo->mvecpszInterfaces,
950 char *, pszDup)))
951 return VINF_SUCCESS;
952 RTStrFree(pszDup);
953 return VERR_NO_MEMORY;
954}
955
956/** Helper for readFilePaths(). Adds the entries from the open directory
957 * @a pDir to the vector @a pvecpchDevs using either the full path or the
958 * realpath() and skipping hidden files and files on which realpath() fails. */
959static int readFilePathsFromDir(const char *pcszPath, DIR *pDir,
960 VECTOR_PTR(char *) *pvecpchDevs)
961{
962 struct dirent entry, *pResult;
963 int err, rc;
964
965 for (err = readdir_r(pDir, &entry, &pResult); pResult;
966 err = readdir_r(pDir, &entry, &pResult))
967 {
968 char szPath[RTPATH_MAX + 1], szRealPath[RTPATH_MAX + 1], *pszPath;
969 if (entry.d_name[0] == '.')
970 continue;
971 if (snprintf(szPath, sizeof(szPath), "%s/%s", pcszPath,
972 entry.d_name) < 0)
973 return RTErrConvertFromErrno(errno);
974 pszPath = RTStrDup(realpath(szPath, szRealPath));
975 if (!pszPath)
976 return VERR_NO_MEMORY;
977 if (RT_FAILURE(rc = VEC_PUSH_BACK_PTR(pvecpchDevs, char *, pszPath)))
978 return rc;
979 }
980 return RTErrConvertFromErrno(err);
981}
982
983/**
984 * Dump the names of a directory's entries into a vector of char pointers.
985 *
986 * @returns zero on success or (positive) posix error value.
987 * @param pcszPath the path to dump.
988 * @param pvecpchDevs an empty vector of char pointers - must be cleaned up
989 * by the caller even on failure.
990 * @param withRealPath whether to canonicalise the filename with realpath
991 */
992static int readFilePaths(const char *pcszPath, VECTOR_PTR(char *) *pvecpchDevs)
993{
994 DIR *pDir;
995 int rc;
996
997 AssertPtrReturn(pvecpchDevs, EINVAL);
998 AssertReturn(VEC_SIZE_PTR(pvecpchDevs) == 0, EINVAL);
999 AssertPtrReturn(pcszPath, EINVAL);
1000
1001 pDir = opendir(pcszPath);
1002 if (!pDir)
1003 return RTErrConvertFromErrno(errno);
1004 rc = readFilePathsFromDir(pcszPath, pDir, pvecpchDevs);
1005 if (closedir(pDir) < 0 && RT_SUCCESS(rc))
1006 rc = RTErrConvertFromErrno(errno);
1007 return rc;
1008}
1009
1010/**
1011 * Logic for USBSysfsEnumerateHostDevices.
1012 * @param pvecDevInfo vector of device information structures to add device
1013 * information to
1014 * @param pvecpchDevs empty scratch vector which will be freed by the caller
1015 */
1016static int doSysfsEnumerateHostDevices(VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo,
1017 VECTOR_PTR(char *) *pvecpchDevs)
1018{
1019 char **ppszEntry;
1020 USBDeviceInfo *pInfo;
1021 int rc;
1022
1023 AssertPtrReturn(pvecDevInfo, VERR_INVALID_POINTER);
1024 LogFlowFunc (("pvecDevInfo=%p\n", pvecDevInfo));
1025
1026 rc = readFilePaths("/sys/bus/usb/devices", pvecpchDevs);
1027 if (RT_FAILURE(rc))
1028 return rc;
1029 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1030 if (RT_FAILURE(rc = addIfDevice(*ppszEntry, pvecDevInfo)))
1031 return rc;
1032 VEC_FOR_EACH(pvecDevInfo, USBDeviceInfo, pInfo)
1033 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1034 if (RT_FAILURE(rc = addIfInterfaceOf(*ppszEntry, pInfo)))
1035 return rc;
1036 return VINF_SUCCESS;
1037}
1038
1039static int USBSysfsEnumerateHostDevices(VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
1040{
1041 VECTOR_PTR(char *) vecpchDevs;
1042 int rc = VERR_NOT_IMPLEMENTED;
1043
1044 AssertReturn(VEC_SIZE_OBJ(pvecDevInfo) == 0, VERR_INVALID_PARAMETER);
1045 LogFlowFunc(("entered\n"));
1046 VEC_INIT_PTR(&vecpchDevs, char *, RTStrFree);
1047 rc = doSysfsEnumerateHostDevices(pvecDevInfo, &vecpchDevs);
1048 VEC_CLEANUP_PTR(&vecpchDevs);
1049 LogFlowFunc(("rc=%Rrc\n", rc));
1050 return rc;
1051}
1052
1053/**
1054 * Helper function for extracting the port number on the parent device from
1055 * the sysfs path value.
1056 *
1057 * The sysfs path is a chain of elements separated by forward slashes, and for
1058 * USB devices, the last element in the chain takes the form
1059 * <port>-<port>.[...].<port>[:<config>.<interface>]
1060 * where the first <port> is the port number on the root hub, and the following
1061 * (optional) ones are the port numbers on any other hubs between the device
1062 * and the root hub. The last part (:<config.interface>) is only present for
1063 * interfaces, not for devices. This API should only be called for devices.
1064 * For compatibility with usbfs, which enumerates from zero up, we subtract one
1065 * from the port number.
1066 *
1067 * For root hubs, the last element in the chain takes the form
1068 * usb<hub number>
1069 * and usbfs always returns port number zero.
1070 *
1071 * @returns VBox status. pu8Port is set on success.
1072 * @param pszPath The sysfs path to parse.
1073 * @param pu8Port Where to store the port number.
1074 */
1075static int usbGetPortFromSysfsPath(const char *pszPath, uint8_t *pu8Port)
1076{
1077 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1078 AssertPtrReturn(pu8Port, VERR_INVALID_POINTER);
1079
1080 /*
1081 * This should not be possible until we get PCs with USB as their primary bus.
1082 * Note: We don't assert this, as we don't expect the caller to validate the
1083 * sysfs path.
1084 */
1085 const char *pszLastComp = strrchr(pszPath, '/');
1086 if (!pszLastComp)
1087 {
1088 Log(("usbGetPortFromSysfsPath(%s): failed [1]\n", pszPath));
1089 return VERR_INVALID_PARAMETER;
1090 }
1091 pszLastComp++; /* skip the slash */
1092
1093 /*
1094 * This API should not be called for interfaces, so the last component
1095 * of the path should not contain a colon. We *do* assert this, as it
1096 * might indicate a caller bug.
1097 */
1098 AssertMsgReturn(strchr(pszLastComp, ':') == NULL, ("%s\n", pszPath), VERR_INVALID_PARAMETER);
1099
1100 /*
1101 * Look for the start of the last number.
1102 */
1103 const char *pchDash = strrchr(pszLastComp, '-');
1104 const char *pchDot = strrchr(pszLastComp, '.');
1105 if (!pchDash && !pchDot)
1106 {
1107 /* No -/. so it must be a root hub. Check that it's usb<something>. */
1108 if (strncmp(pszLastComp, "usb", sizeof("usb") - 1) != 0)
1109 {
1110 Log(("usbGetPortFromSysfsPath(%s): failed [2]\n", pszPath));
1111 return VERR_INVALID_PARAMETER;
1112 }
1113 return VERR_NOT_SUPPORTED;
1114 }
1115 else
1116 {
1117 const char *pszLastPort = pchDot != NULL
1118 ? pchDot + 1
1119 : pchDash + 1;
1120 int rc = RTStrToUInt8Full(pszLastPort, 10, pu8Port);
1121 if (rc != VINF_SUCCESS)
1122 {
1123 Log(("usbGetPortFromSysfsPath(%s): failed [3], rc=%Rrc\n", pszPath, rc));
1124 return VERR_INVALID_PARAMETER;
1125 }
1126 if (*pu8Port == 0)
1127 {
1128 Log(("usbGetPortFromSysfsPath(%s): failed [4]\n", pszPath));
1129 return VERR_INVALID_PARAMETER;
1130 }
1131
1132 /* usbfs compatibility, 0-based port number. */
1133 *pu8Port -= 1;
1134 }
1135 return VINF_SUCCESS;
1136}
1137
1138
1139/**
1140 * Dumps a USBDEVICE structure to the log using LogLevel 3.
1141 * @param pDev The structure to log.
1142 * @todo This is really common code.
1143 */
1144DECLINLINE(void) usbLogDevice(PUSBDEVICE pDev)
1145{
1146 NOREF(pDev);
1147
1148 Log3(("USB device:\n"));
1149 Log3(("Product: %s (%x)\n", pDev->pszProduct, pDev->idProduct));
1150 Log3(("Manufacturer: %s (Vendor ID %x)\n", pDev->pszManufacturer, pDev->idVendor));
1151 Log3(("Serial number: %s (%llx)\n", pDev->pszSerialNumber, pDev->u64SerialHash));
1152 Log3(("Device revision: %d\n", pDev->bcdDevice));
1153 Log3(("Device class: %x\n", pDev->bDeviceClass));
1154 Log3(("Device subclass: %x\n", pDev->bDeviceSubClass));
1155 Log3(("Device protocol: %x\n", pDev->bDeviceProtocol));
1156 Log3(("USB version number: %d\n", pDev->bcdUSB));
1157 Log3(("Device speed: %s\n",
1158 pDev->enmSpeed == USBDEVICESPEED_UNKNOWN ? "unknown"
1159 : pDev->enmSpeed == USBDEVICESPEED_LOW ? "1.5 MBit/s"
1160 : pDev->enmSpeed == USBDEVICESPEED_FULL ? "12 MBit/s"
1161 : pDev->enmSpeed == USBDEVICESPEED_HIGH ? "480 MBit/s"
1162 : pDev->enmSpeed == USBDEVICESPEED_VARIABLE ? "variable"
1163 : "invalid"));
1164 Log3(("Number of configurations: %d\n", pDev->bNumConfigurations));
1165 Log3(("Bus number: %d\n", pDev->bBus));
1166 Log3(("Port number: %d\n", pDev->bPort));
1167 Log3(("Device number: %d\n", pDev->bDevNum));
1168 Log3(("Device state: %s\n",
1169 pDev->enmState == USBDEVICESTATE_UNSUPPORTED ? "unsupported"
1170 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST ? "in use by host"
1171 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE ? "in use by host, possibly capturable"
1172 : pDev->enmState == USBDEVICESTATE_UNUSED ? "not in use"
1173 : pDev->enmState == USBDEVICESTATE_HELD_BY_PROXY ? "held by proxy"
1174 : pDev->enmState == USBDEVICESTATE_USED_BY_GUEST ? "used by guest"
1175 : "invalid"));
1176 Log3(("OS device address: %s\n", pDev->pszAddress));
1177}
1178
1179/**
1180 * In contrast to usbReadBCD() this function can handle BCD values without
1181 * a decimal separator. This is necessary for parsing bcdDevice.
1182 * @param pszBuf Pointer to the string buffer.
1183 * @param pu15 Pointer to the return value.
1184 * @returns IPRT status code.
1185 */
1186static int convertSysfsStrToBCD(const char *pszBuf, uint16_t *pu16)
1187{
1188 char *pszNext;
1189 int32_t i32;
1190
1191 pszBuf = RTStrStripL(pszBuf);
1192 int rc = RTStrToInt32Ex(pszBuf, &pszNext, 16, &i32);
1193 if ( RT_FAILURE(rc)
1194 || rc == VWRN_NUMBER_TOO_BIG
1195 || i32 < 0)
1196 return VERR_NUMBER_TOO_BIG;
1197 if (*pszNext == '.')
1198 {
1199 if (i32 > 255)
1200 return VERR_NUMBER_TOO_BIG;
1201 int32_t i32Lo;
1202 rc = RTStrToInt32Ex(pszNext+1, &pszNext, 16, &i32Lo);
1203 if ( RT_FAILURE(rc)
1204 || rc == VWRN_NUMBER_TOO_BIG
1205 || i32Lo > 255
1206 || i32Lo < 0)
1207 return VERR_NUMBER_TOO_BIG;
1208 i32 = (i32 << 8) | i32Lo;
1209 }
1210 if ( i32 > 65535
1211 || (*pszNext != '\0' && *pszNext != ' '))
1212 return VERR_NUMBER_TOO_BIG;
1213
1214 *pu16 = (uint16_t)i32;
1215 return VINF_SUCCESS;
1216}
1217
1218#endif /* VBOX_USB_WITH_SYSFS */
1219
1220static void fillInDeviceFromSysfs(USBDEVICE *Dev, USBDeviceInfo *pInfo)
1221{
1222 int rc;
1223 const char *pszSysfsPath = pInfo->mSysfsPath;
1224
1225 /* Fill in the simple fields */
1226 Dev->enmState = USBDEVICESTATE_UNUSED;
1227 Dev->bBus = RTLinuxSysFsReadIntFile(10, "%s/busnum", pszSysfsPath);
1228 Dev->bDeviceClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceClass", pszSysfsPath);
1229 Dev->bDeviceSubClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceSubClass", pszSysfsPath);
1230 Dev->bDeviceProtocol = RTLinuxSysFsReadIntFile(16, "%s/bDeviceProtocol", pszSysfsPath);
1231 Dev->bNumConfigurations = RTLinuxSysFsReadIntFile(10, "%s/bNumConfigurations", pszSysfsPath);
1232 Dev->idVendor = RTLinuxSysFsReadIntFile(16, "%s/idVendor", pszSysfsPath);
1233 Dev->idProduct = RTLinuxSysFsReadIntFile(16, "%s/idProduct", pszSysfsPath);
1234 Dev->bDevNum = RTLinuxSysFsReadIntFile(10, "%s/devnum", pszSysfsPath);
1235
1236 /* Now deal with the non-numeric bits. */
1237 char szBuf[1024]; /* Should be larger than anything a sane device
1238 * will need, and insane devices can be unsupported
1239 * until further notice. */
1240 ssize_t cchRead;
1241
1242 /* For simplicity, we just do strcmps on the next one. */
1243 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/speed",
1244 pszSysfsPath);
1245 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1246 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1247 else
1248 Dev->enmSpeed = !strcmp(szBuf, "1.5") ? USBDEVICESPEED_LOW
1249 : !strcmp(szBuf, "12") ? USBDEVICESPEED_FULL
1250 : !strcmp(szBuf, "480") ? USBDEVICESPEED_HIGH
1251 : USBDEVICESPEED_UNKNOWN;
1252
1253 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/version",
1254 pszSysfsPath);
1255 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1256 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1257 else
1258 {
1259 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdUSB);
1260 if (RT_FAILURE(rc))
1261 {
1262 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1263 Dev->bcdUSB = (uint16_t)-1;
1264 }
1265 }
1266
1267 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/bcdDevice",
1268 pszSysfsPath);
1269 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1270 Dev->bcdDevice = (uint16_t)-1;
1271 else
1272 {
1273 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdDevice);
1274 if (RT_FAILURE(rc))
1275 Dev->bcdDevice = (uint16_t)-1;
1276 }
1277
1278 /* Now do things that need string duplication */
1279 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/product",
1280 pszSysfsPath);
1281 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1282 {
1283 RTStrPurgeEncoding(szBuf);
1284 Dev->pszProduct = RTStrDup(szBuf);
1285 }
1286
1287 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/serial",
1288 pszSysfsPath);
1289 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1290 {
1291 RTStrPurgeEncoding(szBuf);
1292 Dev->pszSerialNumber = RTStrDup(szBuf);
1293 Dev->u64SerialHash = USBLibHashSerial(szBuf);
1294 }
1295
1296 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/manufacturer",
1297 pszSysfsPath);
1298 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1299 {
1300 RTStrPurgeEncoding(szBuf);
1301 Dev->pszManufacturer = RTStrDup(szBuf);
1302 }
1303
1304 /* Work out the port number */
1305 if (RT_FAILURE(usbGetPortFromSysfsPath(pszSysfsPath, &Dev->bPort)))
1306 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1307
1308 /* Check the interfaces to see if we can support the device. */
1309 char **ppszIf;
1310 VEC_FOR_EACH(&pInfo->mvecpszInterfaces, char *, ppszIf)
1311 {
1312 ssize_t cb = RTLinuxSysFsGetLinkDest(szBuf, sizeof(szBuf), "%s/driver",
1313 *ppszIf);
1314 if (cb > 0 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED)
1315 Dev->enmState = (strcmp(szBuf, "hub") == 0)
1316 ? USBDEVICESTATE_UNSUPPORTED
1317 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1318 if (RTLinuxSysFsReadIntFile(16, "%s/bInterfaceClass",
1319 *ppszIf) == 9 /* hub */)
1320 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1321 }
1322
1323 /* We use a double slash as a separator in the pszAddress field. This is
1324 * alright as the two paths can't contain a slash due to the way we build
1325 * them. */
1326 char *pszAddress = NULL;
1327 RTStrAPrintf(&pszAddress, "sysfs:%s//device:%s", pszSysfsPath,
1328 pInfo->mDevice);
1329 Dev->pszAddress = pszAddress;
1330
1331 /* Work out from the data collected whether we can support this device. */
1332 Dev->enmState = usbDeterminState(Dev);
1333 usbLogDevice(Dev);
1334}
1335
1336/**
1337 * USBProxyService::getDevices() implementation for sysfs.
1338 */
1339static PUSBDEVICE getDevicesFromSysfs(void)
1340{
1341#ifdef VBOX_USB_WITH_SYSFS
1342 /* Add each of the devices found to the chain. */
1343 PUSBDEVICE pFirst = NULL;
1344 PUSBDEVICE pLast = NULL;
1345 VECTOR_OBJ(USBDeviceInfo) vecDevInfo;
1346 USBDeviceInfo *pInfo;
1347 int rc;
1348
1349 VEC_INIT_OBJ(&vecDevInfo, USBDeviceInfo, USBDevInfoCleanup);
1350 rc = USBSysfsEnumerateHostDevices(&vecDevInfo);
1351 if (RT_FAILURE(rc))
1352 return NULL;
1353 VEC_FOR_EACH(&vecDevInfo, USBDeviceInfo, pInfo)
1354 {
1355 USBDEVICE *Dev = (USBDEVICE *)RTMemAllocZ(sizeof(USBDEVICE));
1356 if (!Dev)
1357 rc = VERR_NO_MEMORY;
1358 if (RT_SUCCESS(rc))
1359 {
1360 fillInDeviceFromSysfs(Dev, pInfo);
1361 }
1362 if ( RT_SUCCESS(rc)
1363 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED
1364 && Dev->pszAddress != NULL
1365 )
1366 {
1367 if (pLast != NULL)
1368 {
1369 pLast->pNext = Dev;
1370 pLast = pLast->pNext;
1371 }
1372 else
1373 pFirst = pLast = Dev;
1374 }
1375 else
1376 deviceFree(Dev);
1377 if (RT_FAILURE(rc))
1378 break;
1379 }
1380 if (RT_FAILURE(rc))
1381 deviceListFree(&pFirst);
1382
1383 VEC_CLEANUP_OBJ(&vecDevInfo);
1384 return pFirst;
1385#else /* !VBOX_USB_WITH_SYSFS */
1386 return NULL;
1387#endif /* !VBOX_USB_WITH_SYSFS */
1388}
1389
1390PUSBDEVICE USBProxyLinuxGetDevices(const char *pcszUsbfsRoot)
1391{
1392 if (pcszUsbfsRoot)
1393 return getDevicesFromUsbfs(pcszUsbfsRoot);
1394 else
1395 return getDevicesFromSysfs();
1396}
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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