VirtualBox

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

Last change on this file since 34461 was 34456, checked in by vboxsync, 14 years ago

Main/linux/USB and Installer/linux: switch to using our own device tree under /dev

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