VirtualBox

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

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

USBGetDevices.cpp: Remove control chars from strings, replace tab with space. bugref:8284

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