VirtualBox

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

Last change on this file since 34216 was 34165, checked in by vboxsync, 15 years ago

Main/linux/USBGetDevices: force Utf8 for the usbfs too

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