VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/linux/USBGetDevices.cpp@ 37377

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

Main/USB/linux: attempt to fix USB detection on CentOS/RHEL 5, fix

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