VirtualBox

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

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

Main/linux/USB: better permissions checking and code cleanup

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.1 KB
Line 
1/* $Id: USBGetDevices.cpp 36958 2011-05-04 14:50:32Z vboxsync $ */
2/** @file
3 * VirtualBox Linux host USB device enumeration.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22
23#include "USBGetDevices.h"
24
25#include <VBox/usb.h>
26#include <VBox/usblib.h>
27
28#include <iprt/linux/sysfs.h>
29#include <iprt/cdefs.h>
30#include <iprt/ctype.h>
31#include <iprt/err.h>
32#include <iprt/fs.h>
33#include <iprt/log.h>
34#include <iprt/mem.h>
35#include <iprt/param.h>
36#include <iprt/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/** Deduce the bus that a USB device is plugged into from the device node
828 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
829static unsigned usbBusFromDevNum(dev_t devNum)
830{
831 AssertReturn(devNum, 0);
832 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
833 return (minor(devNum) >> 7) + 1;
834}
835
836
837/** Deduce the device number of a USB device on the bus from the device node
838 * number. See drivers/usb/core/hub.c:usb_new_device as of Linux 2.6.20. */
839static unsigned usbDeviceFromDevNum(dev_t devNum)
840{
841 AssertReturn(devNum, 0);
842 AssertReturn(major(devNum) == USBDEVICE_MAJOR, 0);
843 return (minor(devNum) & 127) + 1;
844}
845
846
847/**
848 * If a file @a pcszNode from /sys/bus/usb/devices is a device rather than an
849 * interface add an element for the device to @a pvecDevInfo.
850 */
851static int addIfDevice(const char *pcszDevicesRoot,
852 const char *pcszNode,
853 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
854{
855 const char *pcszFile = strrchr(pcszNode, '/');
856 if (strchr(pcszFile, ':'))
857 return VINF_SUCCESS;
858 dev_t devnum = RTLinuxSysFsReadDevNumFile("%s/dev", pcszNode);
859 /* Sanity test of our static helpers */
860 Assert(usbBusFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 5);
861 Assert(usbDeviceFromDevNum(makedev(USBDEVICE_MAJOR, 517)) == 6);
862 if (!devnum)
863 return VINF_SUCCESS;
864 char szDevPath[RTPATH_MAX];
865 ssize_t cchDevPath;
866 cchDevPath = RTLinuxFindDevicePath(devnum, RTFS_TYPE_DEV_CHAR,
867 szDevPath, sizeof(szDevPath),
868 "%s/%.3d/%.3d",
869 pcszDevicesRoot,
870 usbBusFromDevNum(devnum),
871 usbDeviceFromDevNum(devnum));
872 if (cchDevPath < 0)
873 return VINF_SUCCESS;
874
875 USBDeviceInfo info;
876 if (USBDevInfoInit(&info, szDevPath, pcszNode))
877 if (RT_SUCCESS(VEC_PUSH_BACK_OBJ(pvecDevInfo, USBDeviceInfo,
878 &info)))
879 return VINF_SUCCESS;
880 USBDevInfoCleanup(&info);
881 return VERR_NO_MEMORY;
882}
883
884/** The logic for testing whether a sysfs address corresponds to an
885 * interface of a device. Both must be referenced by their canonical
886 * sysfs paths. This is not tested, as the test requires file-system
887 * interaction. */
888static bool muiIsAnInterfaceOf(const char *pcszIface, const char *pcszDev)
889{
890 size_t cchDev = strlen(pcszDev);
891
892 AssertPtr(pcszIface);
893 AssertPtr(pcszDev);
894 Assert(pcszIface[0] == '/');
895 Assert(pcszDev[0] == '/');
896 Assert(pcszDev[cchDev - 1] != '/');
897 /* If this passes, pcszIface is at least cchDev long */
898 if (strncmp(pcszIface, pcszDev, cchDev))
899 return false;
900 /* If this passes, pcszIface is longer than cchDev */
901 if (pcszIface[cchDev] != '/')
902 return false;
903 /* In sysfs an interface is an immediate subdirectory of the device */
904 if (strchr(pcszIface + cchDev + 1, '/'))
905 return false;
906 /* And it always has a colon in its name */
907 if (!strchr(pcszIface + cchDev + 1, ':'))
908 return false;
909 /* And hopefully we have now elimitated everything else */
910 return true;
911}
912
913#ifdef DEBUG
914# ifdef __cplusplus
915/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
916class testIsAnInterfaceOf
917{
918public:
919 testIsAnInterfaceOf()
920 {
921 Assert(muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0",
922 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
923 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-1",
924 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
925 Assert(!muiIsAnInterfaceOf("/sys/devices/pci0000:00/0000:00:1a.0/usb3/3-0:1.0/driver",
926 "/sys/devices/pci0000:00/0000:00:1a.0/usb3"));
927 }
928};
929static testIsAnInterfaceOf testIsAnInterfaceOfInst;
930# endif /* __cplusplus */
931#endif /* DEBUG */
932
933/**
934 * Tell whether a file in /sys/bus/usb/devices is an interface rather than a
935 * device. To be used with getDeviceInfoFromSysfs().
936 */
937static int addIfInterfaceOf(const char *pcszNode, USBDeviceInfo *pInfo)
938{
939 if (!muiIsAnInterfaceOf(pcszNode, pInfo->mSysfsPath))
940 return VINF_SUCCESS;
941 char *pszDup = (char *)RTStrDup(pcszNode);
942 if (pszDup)
943 if (RT_SUCCESS(VEC_PUSH_BACK_PTR(&pInfo->mvecpszInterfaces,
944 char *, pszDup)))
945 return VINF_SUCCESS;
946 RTStrFree(pszDup);
947 return VERR_NO_MEMORY;
948}
949
950/** Helper for readFilePaths(). Adds the entries from the open directory
951 * @a pDir to the vector @a pvecpchDevs using either the full path or the
952 * realpath() and skipping hidden files and files on which realpath() fails. */
953static int readFilePathsFromDir(const char *pcszPath, DIR *pDir,
954 VECTOR_PTR(char *) *pvecpchDevs)
955{
956 struct dirent entry, *pResult;
957 int err, rc;
958
959 for (err = readdir_r(pDir, &entry, &pResult); pResult;
960 err = readdir_r(pDir, &entry, &pResult))
961 {
962 char szPath[RTPATH_MAX + 1], szRealPath[RTPATH_MAX + 1], *pszPath;
963 if (entry.d_name[0] == '.')
964 continue;
965 if (snprintf(szPath, sizeof(szPath), "%s/%s", pcszPath,
966 entry.d_name) < 0)
967 return RTErrConvertFromErrno(errno);
968 if (!realpath(szPath, szRealPath))
969 return RTErrConvertFromErrno(errno);
970 pszPath = RTStrDup(szRealPath);
971 if (!pszPath)
972 return VERR_NO_MEMORY;
973 if (RT_FAILURE(rc = VEC_PUSH_BACK_PTR(pvecpchDevs, char *, pszPath)))
974 return rc;
975 }
976 return RTErrConvertFromErrno(err);
977}
978
979/**
980 * Dump the names of a directory's entries into a vector of char pointers.
981 *
982 * @returns zero on success or (positive) posix error value.
983 * @param pcszPath the path to dump.
984 * @param pvecpchDevs an empty vector of char pointers - must be cleaned up
985 * by the caller even on failure.
986 * @param withRealPath whether to canonicalise the filename with realpath
987 */
988static int readFilePaths(const char *pcszPath, VECTOR_PTR(char *) *pvecpchDevs)
989{
990 DIR *pDir;
991 int rc;
992
993 AssertPtrReturn(pvecpchDevs, EINVAL);
994 AssertReturn(VEC_SIZE_PTR(pvecpchDevs) == 0, EINVAL);
995 AssertPtrReturn(pcszPath, EINVAL);
996
997 pDir = opendir(pcszPath);
998 if (!pDir)
999 return RTErrConvertFromErrno(errno);
1000 rc = readFilePathsFromDir(pcszPath, pDir, pvecpchDevs);
1001 if (closedir(pDir) < 0 && RT_SUCCESS(rc))
1002 rc = RTErrConvertFromErrno(errno);
1003 return rc;
1004}
1005
1006/**
1007 * Logic for USBSysfsEnumerateHostDevices.
1008 * @param pvecDevInfo vector of device information structures to add device
1009 * information to
1010 * @param pvecpchDevs empty scratch vector which will be freed by the caller,
1011 * to simplify exit logic
1012 */
1013static int doSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
1014 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo,
1015 VECTOR_PTR(char *) *pvecpchDevs)
1016{
1017 char **ppszEntry;
1018 USBDeviceInfo *pInfo;
1019 int rc;
1020
1021 AssertPtrReturn(pvecDevInfo, VERR_INVALID_POINTER);
1022 LogFlowFunc (("pvecDevInfo=%p\n", pvecDevInfo));
1023
1024 rc = readFilePaths("/sys/bus/usb/devices", pvecpchDevs);
1025 if (RT_FAILURE(rc))
1026 return rc;
1027 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1028 if (RT_FAILURE(rc = addIfDevice(pcszDevicesRoot, *ppszEntry,
1029 pvecDevInfo)))
1030 return rc;
1031 VEC_FOR_EACH(pvecDevInfo, USBDeviceInfo, pInfo)
1032 VEC_FOR_EACH(pvecpchDevs, char *, ppszEntry)
1033 if (RT_FAILURE(rc = addIfInterfaceOf(*ppszEntry, pInfo)))
1034 return rc;
1035 return VINF_SUCCESS;
1036}
1037
1038static int USBSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
1039 VECTOR_OBJ(USBDeviceInfo) *pvecDevInfo)
1040{
1041 VECTOR_PTR(char *) vecpchDevs;
1042 int rc = VERR_NOT_IMPLEMENTED;
1043
1044 AssertReturn(VEC_SIZE_OBJ(pvecDevInfo) == 0, VERR_INVALID_PARAMETER);
1045 LogFlowFunc(("entered\n"));
1046 VEC_INIT_PTR(&vecpchDevs, char *, RTStrFree);
1047 rc = doSysfsEnumerateHostDevices(pcszDevicesRoot, pvecDevInfo,
1048 &vecpchDevs);
1049 VEC_CLEANUP_PTR(&vecpchDevs);
1050 LogFlowFunc(("rc=%Rrc\n", rc));
1051 return rc;
1052}
1053
1054/**
1055 * Helper function for extracting the port number on the parent device from
1056 * the sysfs path value.
1057 *
1058 * The sysfs path is a chain of elements separated by forward slashes, and for
1059 * USB devices, the last element in the chain takes the form
1060 * <port>-<port>.[...].<port>[:<config>.<interface>]
1061 * where the first <port> is the port number on the root hub, and the following
1062 * (optional) ones are the port numbers on any other hubs between the device
1063 * and the root hub. The last part (:<config.interface>) is only present for
1064 * interfaces, not for devices. This API should only be called for devices.
1065 * For compatibility with usbfs, which enumerates from zero up, we subtract one
1066 * from the port number.
1067 *
1068 * For root hubs, the last element in the chain takes the form
1069 * usb<hub number>
1070 * and usbfs always returns port number zero.
1071 *
1072 * @returns VBox status. pu8Port is set on success.
1073 * @param pszPath The sysfs path to parse.
1074 * @param pu8Port Where to store the port number.
1075 */
1076static int usbGetPortFromSysfsPath(const char *pszPath, uint8_t *pu8Port)
1077{
1078 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1079 AssertPtrReturn(pu8Port, VERR_INVALID_POINTER);
1080
1081 /*
1082 * This should not be possible until we get PCs with USB as their primary bus.
1083 * Note: We don't assert this, as we don't expect the caller to validate the
1084 * sysfs path.
1085 */
1086 const char *pszLastComp = strrchr(pszPath, '/');
1087 if (!pszLastComp)
1088 {
1089 Log(("usbGetPortFromSysfsPath(%s): failed [1]\n", pszPath));
1090 return VERR_INVALID_PARAMETER;
1091 }
1092 pszLastComp++; /* skip the slash */
1093
1094 /*
1095 * This API should not be called for interfaces, so the last component
1096 * of the path should not contain a colon. We *do* assert this, as it
1097 * might indicate a caller bug.
1098 */
1099 AssertMsgReturn(strchr(pszLastComp, ':') == NULL, ("%s\n", pszPath), VERR_INVALID_PARAMETER);
1100
1101 /*
1102 * Look for the start of the last number.
1103 */
1104 const char *pchDash = strrchr(pszLastComp, '-');
1105 const char *pchDot = strrchr(pszLastComp, '.');
1106 if (!pchDash && !pchDot)
1107 {
1108 /* No -/. so it must be a root hub. Check that it's usb<something>. */
1109 if (strncmp(pszLastComp, "usb", sizeof("usb") - 1) != 0)
1110 {
1111 Log(("usbGetPortFromSysfsPath(%s): failed [2]\n", pszPath));
1112 return VERR_INVALID_PARAMETER;
1113 }
1114 return VERR_NOT_SUPPORTED;
1115 }
1116 else
1117 {
1118 const char *pszLastPort = pchDot != NULL
1119 ? pchDot + 1
1120 : pchDash + 1;
1121 int rc = RTStrToUInt8Full(pszLastPort, 10, pu8Port);
1122 if (rc != VINF_SUCCESS)
1123 {
1124 Log(("usbGetPortFromSysfsPath(%s): failed [3], rc=%Rrc\n", pszPath, rc));
1125 return VERR_INVALID_PARAMETER;
1126 }
1127 if (*pu8Port == 0)
1128 {
1129 Log(("usbGetPortFromSysfsPath(%s): failed [4]\n", pszPath));
1130 return VERR_INVALID_PARAMETER;
1131 }
1132
1133 /* usbfs compatibility, 0-based port number. */
1134 *pu8Port -= 1;
1135 }
1136 return VINF_SUCCESS;
1137}
1138
1139
1140/**
1141 * Dumps a USBDEVICE structure to the log using LogLevel 3.
1142 * @param pDev The structure to log.
1143 * @todo This is really common code.
1144 */
1145DECLINLINE(void) usbLogDevice(PUSBDEVICE pDev)
1146{
1147 NOREF(pDev);
1148
1149 Log3(("USB device:\n"));
1150 Log3(("Product: %s (%x)\n", pDev->pszProduct, pDev->idProduct));
1151 Log3(("Manufacturer: %s (Vendor ID %x)\n", pDev->pszManufacturer, pDev->idVendor));
1152 Log3(("Serial number: %s (%llx)\n", pDev->pszSerialNumber, pDev->u64SerialHash));
1153 Log3(("Device revision: %d\n", pDev->bcdDevice));
1154 Log3(("Device class: %x\n", pDev->bDeviceClass));
1155 Log3(("Device subclass: %x\n", pDev->bDeviceSubClass));
1156 Log3(("Device protocol: %x\n", pDev->bDeviceProtocol));
1157 Log3(("USB version number: %d\n", pDev->bcdUSB));
1158 Log3(("Device speed: %s\n",
1159 pDev->enmSpeed == USBDEVICESPEED_UNKNOWN ? "unknown"
1160 : pDev->enmSpeed == USBDEVICESPEED_LOW ? "1.5 MBit/s"
1161 : pDev->enmSpeed == USBDEVICESPEED_FULL ? "12 MBit/s"
1162 : pDev->enmSpeed == USBDEVICESPEED_HIGH ? "480 MBit/s"
1163 : pDev->enmSpeed == USBDEVICESPEED_VARIABLE ? "variable"
1164 : "invalid"));
1165 Log3(("Number of configurations: %d\n", pDev->bNumConfigurations));
1166 Log3(("Bus number: %d\n", pDev->bBus));
1167 Log3(("Port number: %d\n", pDev->bPort));
1168 Log3(("Device number: %d\n", pDev->bDevNum));
1169 Log3(("Device state: %s\n",
1170 pDev->enmState == USBDEVICESTATE_UNSUPPORTED ? "unsupported"
1171 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST ? "in use by host"
1172 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE ? "in use by host, possibly capturable"
1173 : pDev->enmState == USBDEVICESTATE_UNUSED ? "not in use"
1174 : pDev->enmState == USBDEVICESTATE_HELD_BY_PROXY ? "held by proxy"
1175 : pDev->enmState == USBDEVICESTATE_USED_BY_GUEST ? "used by guest"
1176 : "invalid"));
1177 Log3(("OS device address: %s\n", pDev->pszAddress));
1178}
1179
1180/**
1181 * In contrast to usbReadBCD() this function can handle BCD values without
1182 * a decimal separator. This is necessary for parsing bcdDevice.
1183 * @param pszBuf Pointer to the string buffer.
1184 * @param pu15 Pointer to the return value.
1185 * @returns IPRT status code.
1186 */
1187static int convertSysfsStrToBCD(const char *pszBuf, uint16_t *pu16)
1188{
1189 char *pszNext;
1190 int32_t i32;
1191
1192 pszBuf = RTStrStripL(pszBuf);
1193 int rc = RTStrToInt32Ex(pszBuf, &pszNext, 16, &i32);
1194 if ( RT_FAILURE(rc)
1195 || rc == VWRN_NUMBER_TOO_BIG
1196 || i32 < 0)
1197 return VERR_NUMBER_TOO_BIG;
1198 if (*pszNext == '.')
1199 {
1200 if (i32 > 255)
1201 return VERR_NUMBER_TOO_BIG;
1202 int32_t i32Lo;
1203 rc = RTStrToInt32Ex(pszNext+1, &pszNext, 16, &i32Lo);
1204 if ( RT_FAILURE(rc)
1205 || rc == VWRN_NUMBER_TOO_BIG
1206 || i32Lo > 255
1207 || i32Lo < 0)
1208 return VERR_NUMBER_TOO_BIG;
1209 i32 = (i32 << 8) | i32Lo;
1210 }
1211 if ( i32 > 65535
1212 || (*pszNext != '\0' && *pszNext != ' '))
1213 return VERR_NUMBER_TOO_BIG;
1214
1215 *pu16 = (uint16_t)i32;
1216 return VINF_SUCCESS;
1217}
1218
1219#endif /* VBOX_USB_WITH_SYSFS */
1220
1221static void fillInDeviceFromSysfs(USBDEVICE *Dev, USBDeviceInfo *pInfo)
1222{
1223 int rc;
1224 const char *pszSysfsPath = pInfo->mSysfsPath;
1225
1226 /* Fill in the simple fields */
1227 Dev->enmState = USBDEVICESTATE_UNUSED;
1228 Dev->bBus = RTLinuxSysFsReadIntFile(10, "%s/busnum", pszSysfsPath);
1229 Dev->bDeviceClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceClass", pszSysfsPath);
1230 Dev->bDeviceSubClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceSubClass", pszSysfsPath);
1231 Dev->bDeviceProtocol = RTLinuxSysFsReadIntFile(16, "%s/bDeviceProtocol", pszSysfsPath);
1232 Dev->bNumConfigurations = RTLinuxSysFsReadIntFile(10, "%s/bNumConfigurations", pszSysfsPath);
1233 Dev->idVendor = RTLinuxSysFsReadIntFile(16, "%s/idVendor", pszSysfsPath);
1234 Dev->idProduct = RTLinuxSysFsReadIntFile(16, "%s/idProduct", pszSysfsPath);
1235 Dev->bDevNum = RTLinuxSysFsReadIntFile(10, "%s/devnum", pszSysfsPath);
1236
1237 /* Now deal with the non-numeric bits. */
1238 char szBuf[1024]; /* Should be larger than anything a sane device
1239 * will need, and insane devices can be unsupported
1240 * until further notice. */
1241 ssize_t cchRead;
1242
1243 /* For simplicity, we just do strcmps on the next one. */
1244 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/speed",
1245 pszSysfsPath);
1246 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1247 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1248 else
1249 Dev->enmSpeed = !strcmp(szBuf, "1.5") ? USBDEVICESPEED_LOW
1250 : !strcmp(szBuf, "12") ? USBDEVICESPEED_FULL
1251 : !strcmp(szBuf, "480") ? USBDEVICESPEED_HIGH
1252 : USBDEVICESPEED_UNKNOWN;
1253
1254 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/version",
1255 pszSysfsPath);
1256 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1257 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1258 else
1259 {
1260 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdUSB);
1261 if (RT_FAILURE(rc))
1262 {
1263 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1264 Dev->bcdUSB = (uint16_t)-1;
1265 }
1266 }
1267
1268 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/bcdDevice",
1269 pszSysfsPath);
1270 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1271 Dev->bcdDevice = (uint16_t)-1;
1272 else
1273 {
1274 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdDevice);
1275 if (RT_FAILURE(rc))
1276 Dev->bcdDevice = (uint16_t)-1;
1277 }
1278
1279 /* Now do things that need string duplication */
1280 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/product",
1281 pszSysfsPath);
1282 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1283 {
1284 RTStrPurgeEncoding(szBuf);
1285 Dev->pszProduct = RTStrDup(szBuf);
1286 }
1287
1288 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/serial",
1289 pszSysfsPath);
1290 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1291 {
1292 RTStrPurgeEncoding(szBuf);
1293 Dev->pszSerialNumber = RTStrDup(szBuf);
1294 Dev->u64SerialHash = USBLibHashSerial(szBuf);
1295 }
1296
1297 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/manufacturer",
1298 pszSysfsPath);
1299 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1300 {
1301 RTStrPurgeEncoding(szBuf);
1302 Dev->pszManufacturer = RTStrDup(szBuf);
1303 }
1304
1305 /* Work out the port number */
1306 if (RT_FAILURE(usbGetPortFromSysfsPath(pszSysfsPath, &Dev->bPort)))
1307 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1308
1309 /* Check the interfaces to see if we can support the device. */
1310 char **ppszIf;
1311 VEC_FOR_EACH(&pInfo->mvecpszInterfaces, char *, ppszIf)
1312 {
1313 ssize_t cb = RTLinuxSysFsGetLinkDest(szBuf, sizeof(szBuf), "%s/driver",
1314 *ppszIf);
1315 if (cb > 0 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED)
1316 Dev->enmState = (strcmp(szBuf, "hub") == 0)
1317 ? USBDEVICESTATE_UNSUPPORTED
1318 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1319 if (RTLinuxSysFsReadIntFile(16, "%s/bInterfaceClass",
1320 *ppszIf) == 9 /* hub */)
1321 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1322 }
1323
1324 /* We use a double slash as a separator in the pszAddress field. This is
1325 * alright as the two paths can't contain a slash due to the way we build
1326 * them. */
1327 char *pszAddress = NULL;
1328 RTStrAPrintf(&pszAddress, "sysfs:%s//device:%s", pszSysfsPath,
1329 pInfo->mDevice);
1330 Dev->pszAddress = pszAddress;
1331
1332 /* Work out from the data collected whether we can support this device. */
1333 Dev->enmState = usbDeterminState(Dev);
1334 usbLogDevice(Dev);
1335}
1336
1337/**
1338 * USBProxyService::getDevices() implementation for sysfs.
1339 */
1340static PUSBDEVICE getDevicesFromSysfs(const char *pcszDevicesRoot, bool testfs)
1341{
1342#ifdef VBOX_USB_WITH_SYSFS
1343 /* Add each of the devices found to the chain. */
1344 PUSBDEVICE pFirst = NULL;
1345 PUSBDEVICE pLast = NULL;
1346 VECTOR_OBJ(USBDeviceInfo) vecDevInfo;
1347 USBDeviceInfo *pInfo;
1348 int rc;
1349
1350 VEC_INIT_OBJ(&vecDevInfo, USBDeviceInfo, USBDevInfoCleanup);
1351 rc = USBSysfsEnumerateHostDevices(pcszDevicesRoot, &vecDevInfo);
1352 if (RT_FAILURE(rc))
1353 return NULL;
1354 VEC_FOR_EACH(&vecDevInfo, USBDeviceInfo, pInfo)
1355 {
1356 USBDEVICE *Dev = (USBDEVICE *)RTMemAllocZ(sizeof(USBDEVICE));
1357 if (!Dev)
1358 rc = VERR_NO_MEMORY;
1359 if (RT_SUCCESS(rc))
1360 {
1361 fillInDeviceFromSysfs(Dev, pInfo);
1362 }
1363 if ( RT_SUCCESS(rc)
1364 && ( Dev->enmState != USBDEVICESTATE_UNSUPPORTED
1365 || testfs)
1366 && Dev->pszAddress != NULL
1367 )
1368 {
1369 if (pLast != NULL)
1370 {
1371 pLast->pNext = Dev;
1372 pLast = pLast->pNext;
1373 }
1374 else
1375 pFirst = pLast = Dev;
1376 }
1377 else
1378 deviceFree(Dev);
1379 if (RT_FAILURE(rc))
1380 break;
1381 }
1382 if (RT_FAILURE(rc))
1383 deviceListFree(&pFirst);
1384
1385 VEC_CLEANUP_OBJ(&vecDevInfo);
1386 return pFirst;
1387#else /* !VBOX_USB_WITH_SYSFS */
1388 return NULL;
1389#endif /* !VBOX_USB_WITH_SYSFS */
1390}
1391
1392/** Is inotify available and working on this system? This is a requirement
1393 * for using USB with sysfs */
1394static bool inotifyAvailable(void)
1395{
1396 int (*inotify_init)(void);
1397
1398 *(void **)(&inotify_init) = dlsym(RTLD_DEFAULT, "inotify_init");
1399 if (!inotify_init)
1400 return false;
1401 int fd = inotify_init();
1402 if (fd == -1)
1403 return false;
1404 close(fd);
1405 return true;
1406}
1407
1408bool USBProxyLinuxCheckDeviceRoot(const char *pcszRoot, bool fIsDeviceNodes)
1409{
1410 bool fOK = false;
1411 if (!fIsDeviceNodes) /* usbfs */
1412 {
1413 PUSBDEVICE pDevices;
1414
1415 pDevices = getDevicesFromUsbfs(pcszRoot, true);
1416 if (pDevices)
1417 {
1418 PUSBDEVICE pDevice;
1419
1420 fOK = true;
1421 for (pDevice = pDevices; pDevice && fOK; pDevice = pDevice->pNext)
1422 if (access(pDevice->pszAddress, R_OK | W_OK))
1423 fOK = false;
1424 deviceListFree(&pDevices);
1425 }
1426 }
1427 else /* device nodes */
1428 if (inotifyAvailable() && !access(pcszRoot, R_OK | X_OK))
1429 fOK = true;
1430 return fOK;
1431}
1432
1433
1434PUSBDEVICE USBProxyLinuxGetDevices(const char *pcszDevicesRoot,
1435 bool fUseSysfs)
1436{
1437 if (!fUseSysfs)
1438 return getDevicesFromUsbfs(pcszDevicesRoot, false);
1439 else
1440 return getDevicesFromSysfs(pcszDevicesRoot, false);
1441}
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