VirtualBox

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

Last change on this file since 33868 was 33540, checked in by vboxsync, 14 years ago

*: spelling fixes, thanks Timeless!

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 47.5 KB
Line 
1/* $Id: USBGetDevices.cpp 33540 2010-10-28 09:27:05Z 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 pure ASCII, if that's not the case
337 * tell me how to figure out the codeset please.
338 */
339static int usbReadStr(const char *pszValue, const char **ppsz)
340{
341 if (*ppsz)
342 RTStrFree((char *)*ppsz);
343 *ppsz = RTStrDup(pszValue);
344 if (*ppsz)
345 return VINF_SUCCESS;
346 return VERR_NO_MEMORY;
347}
348
349
350/**
351 * Skips the current property.
352 */
353static char *usbReadSkip(char *pszValue)
354{
355 char *psz = strchr(pszValue, '=');
356 if (psz)
357 psz = strchr(psz + 1, '=');
358 if (!psz)
359 return strchr(pszValue, '\0');
360 while (psz > pszValue && !RT_C_IS_SPACE(psz[-1]))
361 psz--;
362 Assert(psz > pszValue);
363 return psz;
364}
365
366
367/**
368 * Determine the USB speed.
369 */
370static int usbReadSpeed(const char *pszValue, USBDEVICESPEED *pSpd, char **ppszNext)
371{
372 pszValue = RTStrStripL(pszValue);
373 /* verified with Linux 2.4.0 ... Linux 2.6.25 */
374 if (!strncmp(pszValue, "1.5", 3))
375 *pSpd = USBDEVICESPEED_LOW;
376 else if (!strncmp(pszValue, "12 ", 3))
377 *pSpd = USBDEVICESPEED_FULL;
378 else if (!strncmp(pszValue, "480", 3))
379 *pSpd = USBDEVICESPEED_HIGH;
380 else
381 *pSpd = USBDEVICESPEED_UNKNOWN;
382 while (pszValue[0] != '\0' && !RT_C_IS_SPACE(pszValue[0]))
383 pszValue++;
384 *ppszNext = (char *)pszValue;
385 return VINF_SUCCESS;
386}
387
388
389/**
390 * Compare a prefix and returns pointer to the char following it if it matches.
391 */
392static char *usbPrefix(char *psz, const char *pszPref, size_t cchPref)
393{
394 if (strncmp(psz, pszPref, cchPref))
395 return NULL;
396 return psz + cchPref;
397}
398
399
400/**
401 * Does some extra checks to improve the detected device state.
402 *
403 * We cannot distinguish between USED_BY_HOST_CAPTURABLE and
404 * USED_BY_GUEST, HELD_BY_PROXY all that well and it shouldn't be
405 * necessary either.
406 *
407 * We will however, distinguish between the device we have permissions
408 * to open and those we don't. This is necessary for two reasons.
409 *
410 * Firstly, because it's futile to even attempt opening a device which we
411 * don't have access to, it only serves to confuse the user. (That said,
412 * it might also be a bit confusing for the user to see that a USB device
413 * is grayed out with no further explanation, and no way of generating an
414 * error hinting at why this is the case.)
415 *
416 * Secondly and more importantly, we're racing against udevd with respect
417 * to permissions and group settings on newly plugged devices. When we
418 * detect a new device that we cannot access we will poll on it for a few
419 * seconds to give udevd time to fix it. The polling is actually triggered
420 * in the 'new device' case in the compare loop.
421 *
422 * The USBDEVICESTATE_USED_BY_HOST state is only used for this no-access
423 * case, while USBDEVICESTATE_UNSUPPORTED is only used in the 'hub' case.
424 * When it's neither of these, we set USBDEVICESTATE_UNUSED or
425 * USBDEVICESTATE_USED_BY_HOST_CAPTURABLE depending on whether there is
426 * a driver associated with any of the interfaces.
427 *
428 * All except the access check and a special idVendor == 0 precaution
429 * is handled at parse time.
430 *
431 * @returns The adjusted state.
432 * @param pDevice The device.
433 */
434static USBDEVICESTATE usbDeterminState(PCUSBDEVICE pDevice)
435{
436 /*
437 * If it's already flagged as unsupported, there is nothing to do.
438 */
439 USBDEVICESTATE enmState = pDevice->enmState;
440 if (enmState == USBDEVICESTATE_UNSUPPORTED)
441 return USBDEVICESTATE_UNSUPPORTED;
442
443 /*
444 * Root hubs and similar doesn't have any vendor id, just
445 * refuse these device.
446 */
447 if (!pDevice->idVendor)
448 return USBDEVICESTATE_UNSUPPORTED;
449
450 /*
451 * Check if we've got access to the device, if we haven't flag
452 * it as used-by-host.
453 */
454#ifndef VBOX_USB_WITH_SYSFS
455 const char *pszAddress = pDevice->pszAddress;
456#else
457 if (pDevice->pszAddress == NULL)
458 /* We can't do much with the device without an address. */
459 return USBDEVICESTATE_UNSUPPORTED;
460 const char *pszAddress = strstr(pDevice->pszAddress, "//device:");
461 pszAddress = pszAddress != NULL
462 ? pszAddress + sizeof("//device:") - 1
463 : pDevice->pszAddress;
464#endif
465 if ( access(pszAddress, R_OK | W_OK) != 0
466 && errno == EACCES)
467 return USBDEVICESTATE_USED_BY_HOST;
468
469#ifdef VBOX_USB_WITH_SYSFS
470 /**
471 * @todo Check that any other essential fields are present and mark as
472 * invalid if not. Particularly to catch the case where the device was
473 * unplugged while we were reading in its properties.
474 */
475#endif
476
477 return enmState;
478}
479
480
481/** Just a worker for USBProxyServiceLinux::getDevices that avoids some code duplication. */
482static int addDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, const char *pcszUsbfsRoot, int rc)
483{
484 /* usbDeterminState requires the address. */
485 PUSBDEVICE pDevNew = (PUSBDEVICE)RTMemDup(pDev, sizeof(*pDev));
486 if (pDevNew)
487 {
488 RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", pcszUsbfsRoot, pDevNew->bBus, pDevNew->bDevNum);
489 if (pDevNew->pszAddress)
490 {
491 pDevNew->enmState = usbDeterminState(pDevNew);
492 if (pDevNew->enmState != USBDEVICESTATE_UNSUPPORTED)
493 {
494 if (*pppNext)
495 **pppNext = pDevNew;
496 else
497 *ppFirst = pDevNew;
498 *pppNext = &pDevNew->pNext;
499 }
500 else
501 deviceFree(pDevNew);
502 }
503 else
504 {
505 deviceFree(pDevNew);
506 rc = VERR_NO_MEMORY;
507 }
508 }
509 else
510 {
511 rc = VERR_NO_MEMORY;
512 deviceFreeMembers(pDev);
513 }
514
515 return rc;
516}
517
518
519static int openDevicesFile(const char *pcszUsbfsRoot, FILE **ppFile)
520{
521 char *pszPath;
522 FILE *pFile;
523 RTStrAPrintf(&pszPath, "%s/devices", pcszUsbfsRoot);
524 if (!pszPath)
525 return VERR_NO_MEMORY;
526 pFile = fopen(pszPath, "r");
527 RTStrFree(pszPath);
528 if (!pFile)
529 return RTErrConvertFromErrno(errno);
530 *ppFile = pFile;
531 return VINF_SUCCESS;
532}
533
534/**
535 * USBProxyService::getDevices() implementation for usbfs.
536 */
537static PUSBDEVICE getDevicesFromUsbfs(const char *pcszUsbfsRoot)
538{
539 PUSBDEVICE pFirst = NULL;
540 FILE *pFile = NULL;
541 int rc;
542 rc = openDevicesFile(pcszUsbfsRoot, &pFile);
543 if (RT_SUCCESS(rc))
544 {
545 PUSBDEVICE *ppNext = NULL;
546 int cHits = 0;
547 char szLine[1024];
548 USBDEVICE Dev;
549 RT_ZERO(Dev);
550 Dev.enmState = USBDEVICESTATE_UNUSED;
551
552 /* Set close on exit and hope no one is racing us. */
553 rc = fcntl(fileno(pFile), F_SETFD, FD_CLOEXEC) >= 0
554 ? VINF_SUCCESS
555 : RTErrConvertFromErrno(errno);
556 while ( RT_SUCCESS(rc)
557 && fgets(szLine, sizeof(szLine), pFile))
558 {
559 char *psz;
560 char *pszValue;
561
562 /* validate and remove the trailing newline. */
563 psz = strchr(szLine, '\0');
564 if (psz[-1] != '\n' && !feof(pFile))
565 {
566 AssertMsgFailed(("Line too long. (cch=%d)\n", strlen(szLine)));
567 continue;
568 }
569
570 /* strip */
571 psz = RTStrStrip(szLine);
572 if (!*psz)
573 continue;
574
575 /*
576 * Interpret the line.
577 * (Ordered by normal occurrence.)
578 */
579 char ch = psz[0];
580 if (psz[1] != ':')
581 continue;
582 psz = RTStrStripL(psz + 3);
583#define PREFIX(str) ( (pszValue = usbPrefix(psz, str, sizeof(str) - 1)) != NULL )
584 switch (ch)
585 {
586 /*
587 * T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd
588 * | | | | | | | | |__MaxChildren
589 * | | | | | | | |__Device Speed in Mbps
590 * | | | | | | |__DeviceNumber
591 * | | | | | |__Count of devices at this level
592 * | | | | |__Connector/Port on Parent for this device
593 * | | | |__Parent DeviceNumber
594 * | | |__Level in topology for this bus
595 * | |__Bus number
596 * |__Topology info tag
597 */
598 case 'T':
599 /* add */
600 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
601 if (cHits >= 3)
602 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, pcszUsbfsRoot, rc);
603 else
604 deviceFreeMembers(&Dev);
605
606 /* Reset device state */
607 memset(&Dev, 0, sizeof (Dev));
608 Dev.enmState = USBDEVICESTATE_UNUSED;
609 cHits = 1;
610
611 /* parse the line. */
612 while (*psz && RT_SUCCESS(rc))
613 {
614 if (PREFIX("Bus="))
615 rc = usbRead8(pszValue, 10, &Dev.bBus, &psz);
616 else if (PREFIX("Port="))
617 rc = usbRead8(pszValue, 10, &Dev.bPort, &psz);
618 else if (PREFIX("Spd="))
619 rc = usbReadSpeed(pszValue, &Dev.enmSpeed, &psz);
620 else if (PREFIX("Dev#="))
621 rc = usbRead8(pszValue, 10, &Dev.bDevNum, &psz);
622 else
623 psz = usbReadSkip(psz);
624 psz = RTStrStripL(psz);
625 }
626 break;
627
628 /*
629 * Bandwidth info:
630 * B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
631 * | | | |__Number of isochronous requests
632 * | | |__Number of interrupt requests
633 * | |__Total Bandwidth allocated to this bus
634 * |__Bandwidth info tag
635 */
636 case 'B':
637 break;
638
639 /*
640 * D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
641 * | | | | | | |__NumberConfigurations
642 * | | | | | |__MaxPacketSize of Default Endpoint
643 * | | | | |__DeviceProtocol
644 * | | | |__DeviceSubClass
645 * | | |__DeviceClass
646 * | |__Device USB version
647 * |__Device info tag #1
648 */
649 case 'D':
650 while (*psz && RT_SUCCESS(rc))
651 {
652 if (PREFIX("Ver="))
653 rc = usbReadBCD(pszValue, 16, &Dev.bcdUSB, &psz);
654 else if (PREFIX("Cls="))
655 {
656 rc = usbRead8(pszValue, 16, &Dev.bDeviceClass, &psz);
657 if (RT_SUCCESS(rc) && Dev.bDeviceClass == 9 /* HUB */)
658 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
659 }
660 else if (PREFIX("Sub="))
661 rc = usbRead8(pszValue, 16, &Dev.bDeviceSubClass, &psz);
662 else if (PREFIX("Prot="))
663 rc = usbRead8(pszValue, 16, &Dev.bDeviceProtocol, &psz);
664 //else if (PREFIX("MxPS="))
665 // rc = usbRead16(pszValue, 10, &Dev.wMaxPacketSize, &psz);
666 else if (PREFIX("#Cfgs="))
667 rc = usbRead8(pszValue, 10, &Dev.bNumConfigurations, &psz);
668 else
669 psz = usbReadSkip(psz);
670 psz = RTStrStripL(psz);
671 }
672 cHits++;
673 break;
674
675 /*
676 * P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
677 * | | | |__Product revision number
678 * | | |__Product ID code
679 * | |__Vendor ID code
680 * |__Device info tag #2
681 */
682 case 'P':
683 while (*psz && RT_SUCCESS(rc))
684 {
685 if (PREFIX("Vendor="))
686 rc = usbRead16(pszValue, 16, &Dev.idVendor, &psz);
687 else if (PREFIX("ProdID="))
688 rc = usbRead16(pszValue, 16, &Dev.idProduct, &psz);
689 else if (PREFIX("Rev="))
690 rc = usbReadBCD(pszValue, 16, &Dev.bcdDevice, &psz);
691 else
692 psz = usbReadSkip(psz);
693 psz = RTStrStripL(psz);
694 }
695 cHits++;
696 break;
697
698 /*
699 * String.
700 */
701 case 'S':
702 if (PREFIX("Manufacturer="))
703 rc = usbReadStr(pszValue, &Dev.pszManufacturer);
704 else if (PREFIX("Product="))
705 rc = usbReadStr(pszValue, &Dev.pszProduct);
706 else if (PREFIX("SerialNumber="))
707 {
708 rc = usbReadStr(pszValue, &Dev.pszSerialNumber);
709 if (RT_SUCCESS(rc))
710 Dev.u64SerialHash = USBLibHashSerial(pszValue);
711 }
712 break;
713
714 /*
715 * C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
716 * | | | | | |__MaxPower in mA
717 * | | | | |__Attributes
718 * | | | |__ConfiguratioNumber
719 * | | |__NumberOfInterfaces
720 * | |__ "*" indicates the active configuration (others are " ")
721 * |__Config info tag
722 */
723 case 'C':
724 break;
725
726 /*
727 * I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
728 * | | | | | | | |__Driver name
729 * | | | | | | | or "(none)"
730 * | | | | | | |__InterfaceProtocol
731 * | | | | | |__InterfaceSubClass
732 * | | | | |__InterfaceClass
733 * | | | |__NumberOfEndpoints
734 * | | |__AlternateSettingNumber
735 * | |__InterfaceNumber
736 * |__Interface info tag
737 */
738 case 'I':
739 {
740 /* Check for thing we don't support. */
741 while (*psz && RT_SUCCESS(rc))
742 {
743 if (PREFIX("Driver="))
744 {
745 const char *pszDriver = NULL;
746 rc = usbReadStr(pszValue, &pszDriver);
747 if ( !pszDriver
748 || !*pszDriver
749 || !strcmp(pszDriver, "(none)")
750 || !strcmp(pszDriver, "(no driver)"))
751 /* no driver */;
752 else if (!strcmp(pszDriver, "hub"))
753 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
754 else if (Dev.enmState == USBDEVICESTATE_UNUSED)
755 Dev.enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
756 RTStrFree((char *)pszDriver);
757 break; /* last attrib */
758 }
759 else if (PREFIX("Cls="))
760 {
761 uint8_t bInterfaceClass;
762 rc = usbRead8(pszValue, 16, &bInterfaceClass, &psz);
763 if (RT_SUCCESS(rc) && bInterfaceClass == 9 /* HUB */)
764 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
765 }
766 else
767 psz = usbReadSkip(psz);
768 psz = RTStrStripL(psz);
769 }
770 break;
771 }
772
773
774 /*
775 * E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddms
776 * | | | | |__Interval (max) between transfers
777 * | | | |__EndpointMaxPacketSize
778 * | | |__Attributes(EndpointType)
779 * | |__EndpointAddress(I=In,O=Out)
780 * |__Endpoint info tag
781 */
782 case 'E':
783 break;
784
785 }
786#undef PREFIX
787 } /* parse loop */
788 fclose(pFile);
789
790 /*
791 * Add the current entry.
792 */
793 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
794 if (cHits >= 3)
795 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, pcszUsbfsRoot, rc);
796
797 /*
798 * Success?
799 */
800 if (RT_FAILURE(rc))
801 {
802 while (pFirst)
803 {
804 PUSBDEVICE pFree = pFirst;
805 pFirst = pFirst->pNext;
806 deviceFree(pFree);
807 }
808 }
809 }
810 if (RT_FAILURE(rc))
811 LogFlow(("USBProxyServiceLinux::getDevices: rc=%Rrc\n", rc));
812 return pFirst;
813}
814
815#ifdef VBOX_USB_WITH_SYSFS
816
817static void USBDevInfoCleanup(USBDeviceInfo *pSelf)
818{
819 RTStrFree(pSelf->mDevice);
820 RTStrFree(pSelf->mSysfsPath);
821 pSelf->mDevice = pSelf->mSysfsPath = NULL;
822 VEC_CLEANUP_PTR(&pSelf->mvecpszInterfaces);
823}
824
825static int USBDevInfoInit(USBDeviceInfo *pSelf, const char *aDevice,
826 const char *aSystemID)
827{
828 pSelf->mDevice = aDevice ? RTStrDup(aDevice) : NULL;
829 pSelf->mSysfsPath = aSystemID ? RTStrDup(aSystemID) : NULL;
830 VEC_INIT_PTR(&pSelf->mvecpszInterfaces, char *, RTStrFree);
831 if ((aDevice && !pSelf->mDevice) || (aSystemID && ! pSelf->mSysfsPath))
832 {
833 USBDevInfoCleanup(pSelf);
834 return 0;
835 }
836 return 1;
837}
838
839#define USBDEVICE_MAJOR 189
840
841/** Deduce the bus that a USB device is plugged into from the device node
842 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
843static unsigned usbBusFromDevNum(dev_t devNum)
844{
845 AssertReturn(devNum, 0);
846 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
847 return (minor(devNum) >> 7) + 1;
848}
849
850
851/** Deduce the device number of a USB device on the bus from the device node
852 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
853static unsigned usbDeviceFromDevNum(dev_t devNum)
854{
855 AssertReturn(devNum, 0);
856 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
857 return (minor(devNum) & 127) + 1;
858}
859
860
861/**
862 * If a file @a pcszNode from /sys/bus/usb/devices is a device rather than an
863 * interface add an element for the device to @a pvecDevInfo.
864 */
865static int addIfDevice(const char *pcszNode,
866 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
867{
868 const char *pcszFile = strrchr(pcszNode, '/');
869 if (strchr(pcszFile, ':'))
870 return VINF_SUCCESS;
871 dev_t devnum = RTLinuxSysFsReadDevNumFile("%s/dev", pcszNode);
872 /* Sanity test of our static helpers */
873 Assert(usbBusFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 5);
874 Assert(usbDeviceFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 6);
875 if (!devnum)
876 return VINF_SUCCESS;
877 char szDevPath[RTPATH_MAX];
878 ssize_t cchDevPath;
879 cchDevPath = RTLinuxFindDevicePath(devnum, RTFS_TYPE_DEV_CHAR,
880 szDevPath, sizeof(szDevPath),
881 "/dev/bus/usb/%.3d/%.3d",
882 usbBusFromDevNum(devnum),
883 usbDeviceFromDevNum(devnum));
884 if (cchDevPath < 0)
885 return VINF_SUCCESS;
886
887 USBDeviceInfo info;
888 if (USBDevInfoInit(&info, szDevPath, pcszNode))
889 if (RT_SUCCESS(VEC_PUSH_BACK_OBJ(pvecDevInfo, USBDeviceInfo,
890 &info)))
891 return VINF_SUCCESS;
892 USBDevInfoCleanup(&info);
893 return VERR_NO_MEMORY;
894}
895
896/** The logic for testing whether a sysfs address corresponds to an
897 * interface of a device. Both must be referenced by their canonical
898 * sysfs paths. This is not tested, as the test requires file-system
899 * interaction. */
900static bool muiIsAnInterfaceOf(const char *pcszIface, const char *pcszDev)
901{
902 size_t cchDev = strlen(pcszDev);
903
904 AssertPtr(pcszIface);
905 AssertPtr(pcszDev);
906 Assert(pcszIface[0] == '/');
907 Assert(pcszDev[0] == '/');
908 Assert(pcszDev[cchDev - 1] != '/');
909 /* If this passes, pcszIface is at least cchDev long */
910 if (strncmp(pcszIface, pcszDev, cchDev))
911 return false;
912 /* If this passes, pcszIface is longer than cchDev */
913 if (pcszIface[cchDev] != '/')
914 return false;
915 /* In sysfs an interface is an immediate subdirectory of the device */
916 if (strchr(pcszIface + cchDev + 1, '/'))
917 return false;
918 /* And it always has a colon in its name */
919 if (!strchr(pcszIface + cchDev + 1, ':'))
920 return false;
921 /* And hopefully we have now elimitated everything else */
922 return true;
923}
924
925#ifdef DEBUG
926# ifdef __cplusplus
927/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
928class testIsAnInterfaceOf
929{
930public:
931 testIsAnInterfaceOf()
932 {
933 Assert(muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0",
934 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
935 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-1",
936 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
937 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0/driver",
938 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
939 }
940};
941static testIsAnInterfaceOf testIsAnInterfaceOfInst;
942# endif /* __cplusplus */
943#endif /* DEBUG */
944
945/**
946 * Tell whether a file in /sys/bus/usb/devices is an interface rather than a
947 * device. To be used with getDeviceInfoFromSysfs().
948 */
949static int addIfInterfaceOf(const char *pcszNode, USBDeviceInfo *pInfo)
950{
951 if (!muiIsAnInterfaceOf(pcszNode, pInfo->mSysfsPath))
952 return VINF_SUCCESS;
953 char *pszDup = (char *)RTStrDup(pcszNode);
954 if (pszDup)
955 if (RT_SUCCESS(VEC_PUSH_BACK_PTR(&pInfo->mvecpszInterfaces,
956 char *, pszDup)))
957 return VINF_SUCCESS;
958 RTStrFree(pszDup);
959 return VERR_NO_MEMORY;
960}
961
962/** Helper for readFilePaths(). Adds the entries from the open directory
963 * @a pDir to the vector @a pvecpchDevs using either the full path or the
964 * realpath() and skipping hidden files and files on which realpath() fails. */
965static int readFilePathsFromDir(const char *pcszPath, DIR *pDir,
966 VECTOR_PTR(char *) *pvecpchDevs)
967{
968 struct dirent entry, *pResult;
969 int err, rc;
970
971 for (err = readdir_r(pDir, &entry, &pResult); pResult;
972 err = readdir_r(pDir, &entry, &pResult))
973 {
974 char szPath[RTPATH_MAX + 1], szRealPath[RTPATH_MAX + 1], *pszPath;
975 if (entry.d_name[0] == '.')
976 continue;
977 if (snprintf(szPath, sizeof(szPath), "%s/%s", pcszPath,
978 entry.d_name) < 0)
979 return RTErrConvertFromErrno(errno);
980 pszPath = RTStrDup(realpath(szPath, szRealPath));
981 if (!pszPath)
982 return VERR_NO_MEMORY;
983 if (RT_FAILURE(rc = VEC_PUSH_BACK_PTR(pvecpchDevs, char *, pszPath)))
984 return rc;
985 }
986 return RTErrConvertFromErrno(err);
987}
988
989/**
990 * Dump the names of a directory's entries into a vector of char pointers.
991 *
992 * @returns zero on success or (positive) posix error value.
993 * @param pcszPath the path to dump.
994 * @param pvecpchDevs an empty vector of char pointers - must be cleaned up
995 * by the caller even on failure.
996 * @param withRealPath whether to canonicalise the filename with realpath
997 */
998static int readFilePaths(const char *pcszPath, VECTOR_PTR(char *) *pvecpchDevs)
999{
1000 DIR *pDir;
1001 int rc;
1002
1003 AssertPtrReturn(pvecpchDevs, EINVAL);
1004 AssertReturn(VEC_SIZE_PTR(pvecpchDevs) == 0, EINVAL);
1005 AssertPtrReturn(pcszPath, EINVAL);
1006
1007 pDir = opendir(pcszPath);
1008 if (!pDir)
1009 return RTErrConvertFromErrno(errno);
1010 rc = readFilePathsFromDir(pcszPath, pDir, pvecpchDevs);
1011 if (closedir(pDir) < 0 && RT_SUCCESS(rc))
1012 rc = RTErrConvertFromErrno(errno);
1013 return rc;
1014}
1015
1016/**
1017 * Logic for USBSysfsEnumerateHostDevices.
1018 * @param pvecDevInfo vector of device information structures to add device
1019 * information to
1020 * @param pvecpchDevs empty scratch vector which will be freed by the caller
1021 */
1022static int doSysfsEnumerateHostDevices(VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo,
1023 VECTOR_PTR(char *) *pvecpchDevs)
1024{
1025 char **ppszEntry;
1026 USBDeviceInfo *pInfo;
1027 int rc;
1028
1029 AssertPtrReturn(pvecDevInfo, VERR_INVALID_POINTER);
1030 LogFlowFunc (("pvecDevInfo=%p\n", pvecDevInfo));
1031
1032 rc = readFilePaths("/sys/bus/usb/devices", pvecpchDevs);
1033 if (RT_FAILURE(rc))
1034 return rc;
1035 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1036 if (RT_FAILURE(rc = addIfDevice(*ppszEntry, pvecDevInfo)))
1037 return rc;
1038 VEC_FOR_EACH(pvecDevInfo, USBDeviceInfo, pInfo)
1039 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1040 if (RT_FAILURE(rc = addIfInterfaceOf(*ppszEntry, pInfo)))
1041 return rc;
1042 return VINF_SUCCESS;
1043}
1044
1045static int USBSysfsEnumerateHostDevices(VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
1046{
1047 VECTOR_PTR(char *) vecpchDevs;
1048 int rc = VERR_NOT_IMPLEMENTED;
1049
1050 AssertReturn(VEC_SIZE_OBJ(pvecDevInfo) == 0, VERR_INVALID_PARAMETER);
1051 LogFlowFunc(("entered\n"));
1052 VEC_INIT_PTR(&vecpchDevs, char *, RTStrFree);
1053 rc = doSysfsEnumerateHostDevices(pvecDevInfo, &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(void)
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(&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
1396PUSBDEVICE USBProxyLinuxGetDevices(const char *pcszUsbfsRoot)
1397{
1398 if (pcszUsbfsRoot)
1399 return getDevicesFromUsbfs(pcszUsbfsRoot);
1400 else
1401 return getDevicesFromSysfs();
1402}
Note: See TracBrowser for help on using the repository browser.

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