VirtualBox

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

最後變更 在這個檔案從33100是 33100,由 vboxsync 提交於 14 年 前

Main/linux/USB enumeration: set close-on-exec and close files

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

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