VirtualBox

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

Last change on this file since 48366 was 47117, checked in by vboxsync, 11 years ago

Main: RT_ZERO() / RTStrCopy()

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

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette