VirtualBox

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

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

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

  • 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 37390 2011-06-08 16:22:59Z 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(bus > 0, 0);
852 AssertReturn(((device - 1) & ~127) == 0, 0);
853 AssertReturn(device > 0, 0);
854 return makedev(USBDEVICE_MAJOR, ((bus - 1) << 7) + device - 1);
855}
856
857/**
858 * If a file @a pcszNode from /sys/bus/usb/devices is a device rather than an
859 * interface add an element for the device to @a pvecDevInfo.
860 */
861static int addIfDevice(const char *pcszDevicesRoot,
862 const char *pcszNode,
863 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
864{
865 const char *pcszFile = strrchr(pcszNode, '/');
866 if (!pcszFile)
867 return VERR_INVALID_PARAMETER;
868 if (strchr(pcszFile, ':'))
869 return VINF_SUCCESS;
870 unsigned bus = usbGetBusFromSysfsPath(pcszNode);
871 if (!bus)
872 return VINF_SUCCESS;
873 unsigned device = RTLinuxSysFsReadIntFile(10, "%s/devnum", pcszNode);
874 dev_t devnum = usbMakeDevNum(bus, device);
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 "%s/%.3d/%.3d",
882 pcszDevicesRoot, bus, device);
883 if (cchDevPath < 0)
884 return VINF_SUCCESS;
885
886 USBDeviceInfo info;
887 if (USBDevInfoInit(&info, szDevPath, pcszNode))
888 if (RT_SUCCESS(VEC_PUSH_BACK_OBJ(pvecDevInfo, USBDeviceInfo,
889 &info)))
890 return VINF_SUCCESS;
891 USBDevInfoCleanup(&info);
892 return VERR_NO_MEMORY;
893}
894
895/** The logic for testing whether a sysfs address corresponds to an
896 * interface of a device. Both must be referenced by their canonical
897 * sysfs paths. This is not tested, as the test requires file-system
898 * interaction. */
899static bool muiIsAnInterfaceOf(const char *pcszIface, const char *pcszDev)
900{
901 size_t cchDev = strlen(pcszDev);
902
903 AssertPtr(pcszIface);
904 AssertPtr(pcszDev);
905 Assert(pcszIface[0] == '/');
906 Assert(pcszDev[0] == '/');
907 Assert(pcszDev[cchDev - 1] != '/');
908 /* If this passes, pcszIface is at least cchDev long */
909 if (strncmp(pcszIface, pcszDev, cchDev))
910 return false;
911 /* If this passes, pcszIface is longer than cchDev */
912 if (pcszIface[cchDev] != '/')
913 return false;
914 /* In sysfs an interface is an immediate subdirectory of the device */
915 if (strchr(pcszIface + cchDev + 1, '/'))
916 return false;
917 /* And it always has a colon in its name */
918 if (!strchr(pcszIface + cchDev + 1, ':'))
919 return false;
920 /* And hopefully we have now elimitated everything else */
921 return true;
922}
923
924#ifdef DEBUG
925# ifdef __cplusplus
926/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
927class testIsAnInterfaceOf
928{
929public:
930 testIsAnInterfaceOf()
931 {
932 Assert(muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0",
933 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
934 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-1",
935 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
936 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0/driver",
937 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
938 }
939};
940static testIsAnInterfaceOf testIsAnInterfaceOfInst;
941# endif /* __cplusplus */
942#endif /* DEBUG */
943
944/**
945 * Tell whether a file in /sys/bus/usb/devices is an interface rather than a
946 * device. To be used with getDeviceInfoFromSysfs().
947 */
948static int addIfInterfaceOf(const char *pcszNode, USBDeviceInfo *pInfo)
949{
950 if (!muiIsAnInterfaceOf(pcszNode, pInfo->mSysfsPath))
951 return VINF_SUCCESS;
952 char *pszDup = (char *)RTStrDup(pcszNode);
953 if (pszDup)
954 if (RT_SUCCESS(VEC_PUSH_BACK_PTR(&pInfo->mvecpszInterfaces,
955 char *, pszDup)))
956 return VINF_SUCCESS;
957 RTStrFree(pszDup);
958 return VERR_NO_MEMORY;
959}
960
961/** Helper for readFilePaths(). Adds the entries from the open directory
962 * @a pDir to the vector @a pvecpchDevs using either the full path or the
963 * realpath() and skipping hidden files and files on which realpath() fails. */
964static int readFilePathsFromDir(const char *pcszPath, DIR *pDir,
965 VECTOR_PTR(char *) *pvecpchDevs)
966{
967 struct dirent entry, *pResult;
968 int err, rc;
969
970 for (err = readdir_r(pDir, &entry, &pResult); pResult;
971 err = readdir_r(pDir, &entry, &pResult))
972 {
973 char szPath[RTPATH_MAX + 1], szRealPath[RTPATH_MAX + 1], *pszPath;
974 if (entry.d_name[0] == '.')
975 continue;
976 if (snprintf(szPath, sizeof(szPath), "%s/%s", pcszPath,
977 entry.d_name) < 0)
978 return RTErrConvertFromErrno(errno);
979 if (!realpath(szPath, szRealPath))
980 return RTErrConvertFromErrno(errno);
981 pszPath = RTStrDup(szRealPath);
982 if (!pszPath)
983 return VERR_NO_MEMORY;
984 if (RT_FAILURE(rc = VEC_PUSH_BACK_PTR(pvecpchDevs, char *, pszPath)))
985 return rc;
986 }
987 return RTErrConvertFromErrno(err);
988}
989
990/**
991 * Dump the names of a directory's entries into a vector of char pointers.
992 *
993 * @returns zero on success or (positive) posix error value.
994 * @param pcszPath the path to dump.
995 * @param pvecpchDevs an empty vector of char pointers - must be cleaned up
996 * by the caller even on failure.
997 * @param withRealPath whether to canonicalise the filename with realpath
998 */
999static int readFilePaths(const char *pcszPath, VECTOR_PTR(char *) *pvecpchDevs)
1000{
1001 DIR *pDir;
1002 int rc;
1003
1004 AssertPtrReturn(pvecpchDevs, EINVAL);
1005 AssertReturn(VEC_SIZE_PTR(pvecpchDevs) == 0, EINVAL);
1006 AssertPtrReturn(pcszPath, EINVAL);
1007
1008 pDir = opendir(pcszPath);
1009 if (!pDir)
1010 return RTErrConvertFromErrno(errno);
1011 rc = readFilePathsFromDir(pcszPath, pDir, pvecpchDevs);
1012 if (closedir(pDir) < 0 && RT_SUCCESS(rc))
1013 rc = RTErrConvertFromErrno(errno);
1014 return rc;
1015}
1016
1017/**
1018 * Logic for USBSysfsEnumerateHostDevices.
1019 * @param pvecDevInfo vector of device information structures to add device
1020 * information to
1021 * @param pvecpchDevs empty scratch vector which will be freed by the caller,
1022 * to simplify exit logic
1023 */
1024static int doSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
1025 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo,
1026 VECTOR_PTR(char *) *pvecpchDevs)
1027{
1028 char **ppszEntry;
1029 USBDeviceInfo *pInfo;
1030 int rc;
1031
1032 AssertPtrReturn(pvecDevInfo, VERR_INVALID_POINTER);
1033 LogFlowFunc (("pvecDevInfo=%p\n", pvecDevInfo));
1034
1035 rc = readFilePaths("/sys/bus/usb/devices", pvecpchDevs);
1036 if (RT_FAILURE(rc))
1037 return rc;
1038 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1039 if (RT_FAILURE(rc = addIfDevice(pcszDevicesRoot, *ppszEntry,
1040 pvecDevInfo)))
1041 return rc;
1042 VEC_FOR_EACH(pvecDevInfo, USBDeviceInfo, pInfo)
1043 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1044 if (RT_FAILURE(rc = addIfInterfaceOf(*ppszEntry, pInfo)))
1045 return rc;
1046 return VINF_SUCCESS;
1047}
1048
1049static int USBSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
1050 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
1051{
1052 VECTOR_PTR(char *) vecpchDevs;
1053 int rc = VERR_NOT_IMPLEMENTED;
1054
1055 AssertReturn(VEC_SIZE_OBJ(pvecDevInfo) == 0, VERR_INVALID_PARAMETER);
1056 LogFlowFunc(("entered\n"));
1057 VEC_INIT_PTR(&vecpchDevs, char *, RTStrFree);
1058 rc = doSysfsEnumerateHostDevices(pcszDevicesRoot, pvecDevInfo,
1059 &vecpchDevs);
1060 VEC_CLEANUP_PTR(&vecpchDevs);
1061 LogFlowFunc(("rc=%Rrc\n", rc));
1062 return rc;
1063}
1064
1065/**
1066 * Helper function for extracting the port number on the parent device from
1067 * the sysfs path value.
1068 *
1069 * The sysfs path is a chain of elements separated by forward slashes, and for
1070 * USB devices, the last element in the chain takes the form
1071 * <port>-<port>.[...].<port>[:<config>.<interface>]
1072 * where the first <port> is the port number on the root hub, and the following
1073 * (optional) ones are the port numbers on any other hubs between the device
1074 * and the root hub. The last part (:<config.interface>) is only present for
1075 * interfaces, not for devices. This API should only be called for devices.
1076 * For compatibility with usbfs, which enumerates from zero up, we subtract one
1077 * from the port number.
1078 *
1079 * For root hubs, the last element in the chain takes the form
1080 * usb<hub number>
1081 * and usbfs always returns port number zero.
1082 *
1083 * @returns VBox status. pu8Port is set on success.
1084 * @param pszPath The sysfs path to parse.
1085 * @param pu8Port Where to store the port number.
1086 */
1087static int usbGetPortFromSysfsPath(const char *pszPath, uint8_t *pu8Port)
1088{
1089 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1090 AssertPtrReturn(pu8Port, VERR_INVALID_POINTER);
1091
1092 /*
1093 * This should not be possible until we get PCs with USB as their primary bus.
1094 * Note: We don't assert this, as we don't expect the caller to validate the
1095 * sysfs path.
1096 */
1097 const char *pszLastComp = strrchr(pszPath, '/');
1098 if (!pszLastComp)
1099 {
1100 Log(("usbGetPortFromSysfsPath(%s): failed [1]\n", pszPath));
1101 return VERR_INVALID_PARAMETER;
1102 }
1103 pszLastComp++; /* skip the slash */
1104
1105 /*
1106 * This API should not be called for interfaces, so the last component
1107 * of the path should not contain a colon. We *do* assert this, as it
1108 * might indicate a caller bug.
1109 */
1110 AssertMsgReturn(strchr(pszLastComp, ':') == NULL, ("%s\n", pszPath), VERR_INVALID_PARAMETER);
1111
1112 /*
1113 * Look for the start of the last number.
1114 */
1115 const char *pchDash = strrchr(pszLastComp, '-');
1116 const char *pchDot = strrchr(pszLastComp, '.');
1117 if (!pchDash && !pchDot)
1118 {
1119 /* No -/. so it must be a root hub. Check that it's usb<something>. */
1120 if (strncmp(pszLastComp, "usb", sizeof("usb") - 1) != 0)
1121 {
1122 Log(("usbGetPortFromSysfsPath(%s): failed [2]\n", pszPath));
1123 return VERR_INVALID_PARAMETER;
1124 }
1125 return VERR_NOT_SUPPORTED;
1126 }
1127 else
1128 {
1129 const char *pszLastPort = pchDot != NULL
1130 ? pchDot + 1
1131 : pchDash + 1;
1132 int rc = RTStrToUInt8Full(pszLastPort, 10, pu8Port);
1133 if (rc != VINF_SUCCESS)
1134 {
1135 Log(("usbGetPortFromSysfsPath(%s): failed [3], rc=%Rrc\n", pszPath, rc));
1136 return VERR_INVALID_PARAMETER;
1137 }
1138 if (*pu8Port == 0)
1139 {
1140 Log(("usbGetPortFromSysfsPath(%s): failed [4]\n", pszPath));
1141 return VERR_INVALID_PARAMETER;
1142 }
1143
1144 /* usbfs compatibility, 0-based port number. */
1145 *pu8Port -= 1;
1146 }
1147 return VINF_SUCCESS;
1148}
1149
1150
1151/**
1152 * Dumps a USBDEVICE structure to the log using LogLevel 3.
1153 * @param pDev The structure to log.
1154 * @todo This is really common code.
1155 */
1156DECLINLINE(void) usbLogDevice(PUSBDEVICE pDev)
1157{
1158 NOREF(pDev);
1159
1160 Log3(("USB device:\n"));
1161 Log3(("Product: %s (%x)\n", pDev->pszProduct, pDev->idProduct));
1162 Log3(("Manufacturer: %s (Vendor ID %x)\n", pDev->pszManufacturer, pDev->idVendor));
1163 Log3(("Serial number: %s (%llx)\n", pDev->pszSerialNumber, pDev->u64SerialHash));
1164 Log3(("Device revision: %d\n", pDev->bcdDevice));
1165 Log3(("Device class: %x\n", pDev->bDeviceClass));
1166 Log3(("Device subclass: %x\n", pDev->bDeviceSubClass));
1167 Log3(("Device protocol: %x\n", pDev->bDeviceProtocol));
1168 Log3(("USB version number: %d\n", pDev->bcdUSB));
1169 Log3(("Device speed: %s\n",
1170 pDev->enmSpeed == USBDEVICESPEED_UNKNOWN ? "unknown"
1171 : pDev->enmSpeed == USBDEVICESPEED_LOW ? "1.5 MBit/s"
1172 : pDev->enmSpeed == USBDEVICESPEED_FULL ? "12 MBit/s"
1173 : pDev->enmSpeed == USBDEVICESPEED_HIGH ? "480 MBit/s"
1174 : pDev->enmSpeed == USBDEVICESPEED_VARIABLE ? "variable"
1175 : "invalid"));
1176 Log3(("Number of configurations: %d\n", pDev->bNumConfigurations));
1177 Log3(("Bus number: %d\n", pDev->bBus));
1178 Log3(("Port number: %d\n", pDev->bPort));
1179 Log3(("Device number: %d\n", pDev->bDevNum));
1180 Log3(("Device state: %s\n",
1181 pDev->enmState == USBDEVICESTATE_UNSUPPORTED ? "unsupported"
1182 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST ? "in use by host"
1183 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE ? "in use by host, possibly capturable"
1184 : pDev->enmState == USBDEVICESTATE_UNUSED ? "not in use"
1185 : pDev->enmState == USBDEVICESTATE_HELD_BY_PROXY ? "held by proxy"
1186 : pDev->enmState == USBDEVICESTATE_USED_BY_GUEST ? "used by guest"
1187 : "invalid"));
1188 Log3(("OS device address: %s\n", pDev->pszAddress));
1189}
1190
1191/**
1192 * In contrast to usbReadBCD() this function can handle BCD values without
1193 * a decimal separator. This is necessary for parsing bcdDevice.
1194 * @param pszBuf Pointer to the string buffer.
1195 * @param pu15 Pointer to the return value.
1196 * @returns IPRT status code.
1197 */
1198static int convertSysfsStrToBCD(const char *pszBuf, uint16_t *pu16)
1199{
1200 char *pszNext;
1201 int32_t i32;
1202
1203 pszBuf = RTStrStripL(pszBuf);
1204 int rc = RTStrToInt32Ex(pszBuf, &pszNext, 16, &i32);
1205 if ( RT_FAILURE(rc)
1206 || rc == VWRN_NUMBER_TOO_BIG
1207 || i32 < 0)
1208 return VERR_NUMBER_TOO_BIG;
1209 if (*pszNext == '.')
1210 {
1211 if (i32 > 255)
1212 return VERR_NUMBER_TOO_BIG;
1213 int32_t i32Lo;
1214 rc = RTStrToInt32Ex(pszNext+1, &pszNext, 16, &i32Lo);
1215 if ( RT_FAILURE(rc)
1216 || rc == VWRN_NUMBER_TOO_BIG
1217 || i32Lo > 255
1218 || i32Lo < 0)
1219 return VERR_NUMBER_TOO_BIG;
1220 i32 = (i32 << 8) | i32Lo;
1221 }
1222 if ( i32 > 65535
1223 || (*pszNext != '\0' && *pszNext != ' '))
1224 return VERR_NUMBER_TOO_BIG;
1225
1226 *pu16 = (uint16_t)i32;
1227 return VINF_SUCCESS;
1228}
1229
1230#endif /* VBOX_USB_WITH_SYSFS */
1231
1232static void fillInDeviceFromSysfs(USBDEVICE *Dev, USBDeviceInfo *pInfo)
1233{
1234 int rc;
1235 const char *pszSysfsPath = pInfo->mSysfsPath;
1236
1237 /* Fill in the simple fields */
1238 Dev->enmState = USBDEVICESTATE_UNUSED;
1239 Dev->bBus = usbGetBusFromSysfsPath(pszSysfsPath);
1240 Dev->bDeviceClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceClass", pszSysfsPath);
1241 Dev->bDeviceSubClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceSubClass", pszSysfsPath);
1242 Dev->bDeviceProtocol = RTLinuxSysFsReadIntFile(16, "%s/bDeviceProtocol", pszSysfsPath);
1243 Dev->bNumConfigurations = RTLinuxSysFsReadIntFile(10, "%s/bNumConfigurations", pszSysfsPath);
1244 Dev->idVendor = RTLinuxSysFsReadIntFile(16, "%s/idVendor", pszSysfsPath);
1245 Dev->idProduct = RTLinuxSysFsReadIntFile(16, "%s/idProduct", pszSysfsPath);
1246 Dev->bDevNum = RTLinuxSysFsReadIntFile(10, "%s/devnum", pszSysfsPath);
1247
1248 /* Now deal with the non-numeric bits. */
1249 char szBuf[1024]; /* Should be larger than anything a sane device
1250 * will need, and insane devices can be unsupported
1251 * until further notice. */
1252 ssize_t cchRead;
1253
1254 /* For simplicity, we just do strcmps on the next one. */
1255 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/speed",
1256 pszSysfsPath);
1257 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1258 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1259 else
1260 Dev->enmSpeed = !strcmp(szBuf, "1.5") ? USBDEVICESPEED_LOW
1261 : !strcmp(szBuf, "12") ? USBDEVICESPEED_FULL
1262 : !strcmp(szBuf, "480") ? USBDEVICESPEED_HIGH
1263 : USBDEVICESPEED_UNKNOWN;
1264
1265 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/version",
1266 pszSysfsPath);
1267 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1268 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1269 else
1270 {
1271 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdUSB);
1272 if (RT_FAILURE(rc))
1273 {
1274 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1275 Dev->bcdUSB = (uint16_t)-1;
1276 }
1277 }
1278
1279 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/bcdDevice",
1280 pszSysfsPath);
1281 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1282 Dev->bcdDevice = (uint16_t)-1;
1283 else
1284 {
1285 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdDevice);
1286 if (RT_FAILURE(rc))
1287 Dev->bcdDevice = (uint16_t)-1;
1288 }
1289
1290 /* Now do things that need string duplication */
1291 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/product",
1292 pszSysfsPath);
1293 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1294 {
1295 RTStrPurgeEncoding(szBuf);
1296 Dev->pszProduct = RTStrDup(szBuf);
1297 }
1298
1299 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/serial",
1300 pszSysfsPath);
1301 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1302 {
1303 RTStrPurgeEncoding(szBuf);
1304 Dev->pszSerialNumber = RTStrDup(szBuf);
1305 Dev->u64SerialHash = USBLibHashSerial(szBuf);
1306 }
1307
1308 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/manufacturer",
1309 pszSysfsPath);
1310 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1311 {
1312 RTStrPurgeEncoding(szBuf);
1313 Dev->pszManufacturer = RTStrDup(szBuf);
1314 }
1315
1316 /* Work out the port number */
1317 if (RT_FAILURE(usbGetPortFromSysfsPath(pszSysfsPath, &Dev->bPort)))
1318 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1319
1320 /* Check the interfaces to see if we can support the device. */
1321 char **ppszIf;
1322 VEC_FOR_EACH(&pInfo->mvecpszInterfaces, char *, ppszIf)
1323 {
1324 ssize_t cb = RTLinuxSysFsGetLinkDest(szBuf, sizeof(szBuf), "%s/driver",
1325 *ppszIf);
1326 if (cb > 0 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED)
1327 Dev->enmState = (strcmp(szBuf, "hub") == 0)
1328 ? USBDEVICESTATE_UNSUPPORTED
1329 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1330 if (RTLinuxSysFsReadIntFile(16, "%s/bInterfaceClass",
1331 *ppszIf) == 9 /* hub */)
1332 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1333 }
1334
1335 /* We use a double slash as a separator in the pszAddress field. This is
1336 * alright as the two paths can't contain a slash due to the way we build
1337 * them. */
1338 char *pszAddress = NULL;
1339 RTStrAPrintf(&pszAddress, "sysfs:%s//device:%s", pszSysfsPath,
1340 pInfo->mDevice);
1341 Dev->pszAddress = pszAddress;
1342
1343 /* Work out from the data collected whether we can support this device. */
1344 Dev->enmState = usbDeterminState(Dev);
1345 usbLogDevice(Dev);
1346}
1347
1348/**
1349 * USBProxyService::getDevices() implementation for sysfs.
1350 */
1351static PUSBDEVICE getDevicesFromSysfs(const char *pcszDevicesRoot, bool testfs)
1352{
1353#ifdef VBOX_USB_WITH_SYSFS
1354 /* Add each of the devices found to the chain. */
1355 PUSBDEVICE pFirst = NULL;
1356 PUSBDEVICE pLast = NULL;
1357 VECTOR_OBJ(USBDeviceInfo) vecDevInfo;
1358 USBDeviceInfo *pInfo;
1359 int rc;
1360
1361 VEC_INIT_OBJ(&vecDevInfo, USBDeviceInfo, USBDevInfoCleanup);
1362 rc = USBSysfsEnumerateHostDevices(pcszDevicesRoot, &vecDevInfo);
1363 if (RT_FAILURE(rc))
1364 return NULL;
1365 VEC_FOR_EACH(&vecDevInfo, USBDeviceInfo, pInfo)
1366 {
1367 USBDEVICE *Dev = (USBDEVICE *)RTMemAllocZ(sizeof(USBDEVICE));
1368 if (!Dev)
1369 rc = VERR_NO_MEMORY;
1370 if (RT_SUCCESS(rc))
1371 {
1372 fillInDeviceFromSysfs(Dev, pInfo);
1373 }
1374 if ( RT_SUCCESS(rc)
1375 && ( Dev->enmState != USBDEVICESTATE_UNSUPPORTED
1376 || testfs)
1377 && Dev->pszAddress != NULL
1378 )
1379 {
1380 if (pLast != NULL)
1381 {
1382 pLast->pNext = Dev;
1383 pLast = pLast->pNext;
1384 }
1385 else
1386 pFirst = pLast = Dev;
1387 }
1388 else
1389 deviceFree(Dev);
1390 if (RT_FAILURE(rc))
1391 break;
1392 }
1393 if (RT_FAILURE(rc))
1394 deviceListFree(&pFirst);
1395
1396 VEC_CLEANUP_OBJ(&vecDevInfo);
1397 return pFirst;
1398#else /* !VBOX_USB_WITH_SYSFS */
1399 return NULL;
1400#endif /* !VBOX_USB_WITH_SYSFS */
1401}
1402
1403#ifdef UNIT_TEST
1404/* Set up mock functions for USBProxyLinuxCheckDeviceRoot - here dlsym and close
1405 * for the inotify presence check. */
1406static int testInotifyInitGood(void) { return 0; }
1407static int testInotifyInitBad(void) { return -1; }
1408static bool s_fHaveInotifyLibC = true;
1409static bool s_fHaveInotifyKernel = true;
1410
1411static void *testDLSym(void *handle, const char *symbol)
1412{
1413 Assert(handle == RTLD_DEFAULT);
1414 Assert(!RTStrCmp(symbol, "inotify_init"));
1415 if (!s_fHaveInotifyLibC)
1416 return NULL;
1417 if (s_fHaveInotifyKernel)
1418 return (void *)testInotifyInitGood;
1419 return (void *)testInotifyInitBad;
1420}
1421
1422void TestUSBSetInotifyAvailable(bool fHaveInotifyLibC, bool fHaveInotifyKernel)
1423{
1424 s_fHaveInotifyLibC = fHaveInotifyLibC;
1425 s_fHaveInotifyKernel = fHaveInotifyKernel;
1426}
1427# define dlsym testDLSym
1428# define close(a) do {} while(0)
1429#endif
1430
1431/** Is inotify available and working on this system? This is a requirement
1432 * for using USB with sysfs */
1433static bool inotifyAvailable(void)
1434{
1435 int (*inotify_init)(void);
1436
1437 *(void **)(&inotify_init) = dlsym(RTLD_DEFAULT, "inotify_init");
1438 if (!inotify_init)
1439 return false;
1440 int fd = inotify_init();
1441 if (fd == -1)
1442 return false;
1443 close(fd);
1444 return true;
1445}
1446
1447#ifdef UNIT_TEST
1448# undef dlsym
1449# undef close
1450#endif
1451
1452#ifdef UNIT_TEST
1453/** Unit test list of usbfs addresses of connected devices. */
1454static const char **s_pacszUsbfsDeviceAddresses = NULL;
1455
1456static PUSBDEVICE testGetUsbfsDevices(const char *pcszUsbfsRoot, bool testfs)
1457{
1458 const char **pcsz;
1459 PUSBDEVICE pList = NULL, pTail = NULL;
1460 for (pcsz = s_pacszUsbfsDeviceAddresses; pcsz && *pcsz; ++pcsz)
1461 {
1462 PUSBDEVICE pNext = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
1463 if (pNext)
1464 pNext->pszAddress = RTStrDup(*pcsz);
1465 if (!pNext || !pNext->pszAddress)
1466 {
1467 deviceListFree(&pList);
1468 return NULL;
1469 }
1470 if (pTail)
1471 pTail->pNext = pNext;
1472 else
1473 pList = pNext;
1474 pTail = pNext;
1475 }
1476 return pList;
1477}
1478# define getDevicesFromUsbfs testGetUsbfsDevices
1479
1480void TestUSBSetAvailableUsbfsDevices(const char **pacszDeviceAddresses)
1481{
1482 s_pacszUsbfsDeviceAddresses = pacszDeviceAddresses;
1483}
1484
1485/** Unit test list of files reported as accessible by access(3). We only do
1486 * accessible or not accessible. */
1487static const char **s_pacszAccessibleFiles = NULL;
1488
1489static int testAccess(const char *pcszPath, int mode)
1490{
1491 const char **pcsz;
1492 for (pcsz = s_pacszAccessibleFiles; pcsz && *pcsz; ++pcsz)
1493 if (!RTStrCmp(pcszPath, *pcsz))
1494 return 0;
1495 return -1;
1496}
1497# define access testAccess
1498
1499void TestUSBSetAccessibleFiles(const char **pacszAccessibleFiles)
1500{
1501 s_pacszAccessibleFiles = pacszAccessibleFiles;
1502}
1503#endif
1504
1505bool USBProxyLinuxCheckDeviceRoot(const char *pcszRoot, bool fIsDeviceNodes)
1506{
1507 bool fOK = false;
1508 if (!fIsDeviceNodes) /* usbfs */
1509 {
1510 PUSBDEVICE pDevices;
1511
1512 if (!access(pcszRoot, R_OK | X_OK))
1513 {
1514 fOK = true;
1515 pDevices = getDevicesFromUsbfs(pcszRoot, true);
1516 if (pDevices)
1517 {
1518 PUSBDEVICE pDevice;
1519
1520 for (pDevice = pDevices; pDevice && fOK; pDevice = pDevice->pNext)
1521 if (access(pDevice->pszAddress, R_OK | W_OK))
1522 fOK = false;
1523 deviceListFree(&pDevices);
1524 }
1525 }
1526 }
1527 else /* device nodes */
1528 if (inotifyAvailable() && !access(pcszRoot, R_OK | X_OK))
1529 fOK = true;
1530 return fOK;
1531}
1532
1533#ifdef UNIT_TEST
1534# undef getDevicesFromUsbfs
1535# undef access
1536#endif
1537
1538PUSBDEVICE USBProxyLinuxGetDevices(const char *pcszDevicesRoot,
1539 bool fUseSysfs)
1540{
1541 if (!fUseSysfs)
1542 return getDevicesFromUsbfs(pcszDevicesRoot, false);
1543 else
1544 return getDevicesFromSysfs(pcszDevicesRoot, false);
1545}
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