VirtualBox

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

Last change on this file since 60147 was 60147, checked in by vboxsync, 9 years ago

USBGetDevices.cpp: prefix functions, doxygen brief style (short sentence describing function (single line), optionally followed by detailed description), space between logical blocks.

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