VirtualBox

source: vbox/trunk/src/VBox/Main/linux/USBProxyServiceLinux.cpp@ 31891

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

Main: export USBProxyService and USBFilter to OSE

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.7 KB
Line 
1/* $Id: USBProxyServiceLinux.cpp 31891 2010-08-24 07:58:48Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Service, Linux Specialization.
4 */
5
6/*
7 * Copyright (C) 2006-2010 Oracle Corporation
8 *
9 * Oracle Corporation confidential
10 * All rights reserved
11 */
12
13
14/*******************************************************************************
15* Header Files *
16*******************************************************************************/
17#include "USBProxyService.h"
18#include "Logging.h"
19
20#include <VBox/usb.h>
21#include <VBox/usblib.h>
22#include <VBox/err.h>
23
24#include <iprt/string.h>
25#include <iprt/alloc.h>
26#include <iprt/assert.h>
27#include <iprt/ctype.h>
28#include <iprt/env.h>
29#include <iprt/file.h>
30#include <iprt/err.h>
31#include <iprt/mem.h>
32#include <iprt/param.h>
33#include <iprt/path.h>
34#include <iprt/stream.h>
35#include <iprt/linux/sysfs.h>
36
37#include <stdlib.h>
38#include <string.h>
39#include <stdio.h>
40#include <errno.h>
41#include <unistd.h>
42#include <sys/statfs.h>
43#include <sys/poll.h>
44#ifdef VBOX_WITH_LINUX_COMPILER_H
45# include <linux/compiler.h>
46#endif
47#include <linux/usbdevice_fs.h>
48
49
50/*******************************************************************************
51* Structures and Typedefs *
52*******************************************************************************/
53/** Suffix translation. */
54typedef struct USBSUFF
55{
56 char szSuff[4];
57 unsigned cchSuff;
58 unsigned uMul;
59 unsigned uDiv;
60} USBSUFF, *PUSBSUFF;
61typedef const USBSUFF *PCUSBSUFF;
62
63
64/*******************************************************************************
65* Global Variables *
66*******************************************************************************/
67/**
68 * Suffixes for the endpoint polling interval.
69 */
70static const USBSUFF s_aIntervalSuff[] =
71{
72 { "ms", 2, 1, 0 },
73 { "us", 2, 1, 1000 },
74 { "ns", 2, 1, 1000000 },
75 { "s", 1, 1000, 0 },
76 { "", 0, 0, 0 } /* term */
77};
78
79
80/**
81 * Initialize data members.
82 */
83USBProxyServiceLinux::USBProxyServiceLinux(Host *aHost, const char *aUsbfsRoot /* = "/proc/bus/usb" */)
84 : USBProxyService(aHost), mFile(NIL_RTFILE), mStream(NULL), mWakeupPipeR(NIL_RTFILE),
85 mWakeupPipeW(NIL_RTFILE), mUsbfsRoot(aUsbfsRoot), mUsingUsbfsDevices(true /* see init */), mUdevPolls(0)
86{
87 LogFlowThisFunc(("aHost=%p aUsbfsRoot=%p:{%s}\n", aHost, aUsbfsRoot, aUsbfsRoot));
88}
89
90
91/**
92 * Initializes the object (called right after construction).
93 *
94 * @returns S_OK on success and non-fatal failures, some COM error otherwise.
95 */
96HRESULT USBProxyServiceLinux::init(void)
97{
98 /*
99 * Call the superclass method first.
100 */
101 HRESULT hrc = USBProxyService::init();
102 AssertComRCReturn(hrc, hrc);
103
104 /*
105 * We have two methods available for getting host USB device data - using
106 * USBFS and using sysfs/hal. The default choice depends on build-time
107 * settings and an environment variable; if the default is not available
108 * we fall back to the second.
109 * In the event of both failing, the error from the second method tried
110 * will be presented to the user.
111 */
112#ifdef VBOX_WITH_SYSFS_BY_DEFAULT
113 mUsingUsbfsDevices = false;
114#else
115 mUsingUsbfsDevices = true;
116#endif
117 const char *pszUsbFromEnv = RTEnvGet("VBOX_USB");
118 if (pszUsbFromEnv)
119 {
120 if (!RTStrICmp(pszUsbFromEnv, "USBFS"))
121 {
122 LogRel(("Default USB access method set to \"usbfs\" from environment\n"));
123 mUsingUsbfsDevices = true;
124 }
125 else if (!RTStrICmp(pszUsbFromEnv, "SYSFS"))
126 {
127 LogRel(("Default USB method set to \"sysfs\" from environment\n"));
128 mUsingUsbfsDevices = false;
129 }
130 else
131 LogRel(("Invalid VBOX_USB environment variable setting \"%s\"\n",
132 pszUsbFromEnv));
133 }
134 int rc = mUsingUsbfsDevices ? initUsbfs() : initSysfs();
135 if (RT_FAILURE(rc))
136 {
137 /* For the day when we have VBoxSVC release logging... */
138 LogRel(("Failed to initialise host USB using %s\n",
139 mUsingUsbfsDevices ? "USBFS" : "sysfs/hal"));
140 mUsingUsbfsDevices = !mUsingUsbfsDevices;
141 rc = mUsingUsbfsDevices ? initUsbfs() : initSysfs();
142 }
143 LogRel((RT_SUCCESS(rc) ? "Successfully initialised host USB using %s\n"
144 : "Failed to initialise host USB using %s\n",
145 mUsingUsbfsDevices ? "USBFS" : "sysfs/hal"));
146 mLastError = rc;
147 return S_OK;
148}
149
150
151/**
152 * Initializiation routine for the usbfs based operation.
153 *
154 * @returns iprt status code.
155 */
156int USBProxyServiceLinux::initUsbfs(void)
157{
158 Assert(mUsingUsbfsDevices);
159
160 /*
161 * Open the devices file.
162 */
163 int rc;
164 char *pszDevices;
165 RTStrAPrintf(&pszDevices, "%s/devices", mUsbfsRoot.c_str());
166 if (pszDevices)
167 {
168 rc = RTFileOpen(&mFile, pszDevices, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
169 if (RT_SUCCESS(rc))
170 {
171 /*
172 * Check that we're actually on the usbfs.
173 */
174 struct statfs StFS;
175 if (!fstatfs(mFile, &StFS))
176 {
177 if (StFS.f_type == USBDEVICE_SUPER_MAGIC)
178 {
179 int pipes[2];
180 if (!pipe(pipes))
181 {
182 mWakeupPipeR = pipes[0];
183 mWakeupPipeW = pipes[1];
184 mStream = fdopen(mFile, "r");
185 if (mStream)
186 {
187 /*
188 * Start the poller thread.
189 */
190 rc = start();
191 if (RT_SUCCESS(rc))
192 {
193 RTStrFree(pszDevices);
194 LogFlowThisFunc(("returns successfully - mFile=%d mStream=%p mWakeupPipeR/W=%d/%d\n",
195 mFile, mStream, mWakeupPipeR, mWakeupPipeW));
196 /*
197 * Turn buffering off to work around rewind() problems, see getDevices().
198 */
199 setvbuf(mStream, NULL, _IONBF, 0);
200 return VINF_SUCCESS;
201 }
202
203 fclose(mStream);
204 mStream = NULL;
205 mFile = NIL_RTFILE;
206 }
207 else
208 {
209 rc = RTErrConvertFromErrno(errno);
210 Log(("USBProxyServiceLinux::USBProxyServiceLinux: fdopen failed, errno=%d\n", errno));
211 }
212
213 RTFileClose(mWakeupPipeR);
214 RTFileClose(mWakeupPipeW);
215 mWakeupPipeW = mWakeupPipeR = NIL_RTFILE;
216 }
217 else
218 {
219 rc = RTErrConvertFromErrno(errno);
220 Log(("USBProxyServiceLinux::USBProxyServiceLinux: pipe failed, errno=%d\n", errno));
221 }
222 }
223 else
224 {
225 Log(("USBProxyServiceLinux::USBProxyServiceLinux: StFS.f_type=%d expected=%d\n", StFS.f_type, USBDEVICE_SUPER_MAGIC));
226 rc = VERR_INVALID_PARAMETER;
227 }
228 }
229 else
230 {
231 rc = RTErrConvertFromErrno(errno);
232 Log(("USBProxyServiceLinux::USBProxyServiceLinux: fstatfs failed, errno=%d\n", errno));
233 }
234 RTFileClose(mFile);
235 mFile = NIL_RTFILE;
236 }
237 RTStrFree(pszDevices);
238 }
239 else
240 {
241 rc = VERR_NO_MEMORY;
242 Log(("USBProxyServiceLinux::USBProxyServiceLinux: out of memory!\n"));
243 }
244
245 LogFlowThisFunc(("returns failure!!! (rc=%Rrc)\n", rc));
246 return rc;
247}
248
249
250/**
251 * Initializiation routine for the sysfs based operation.
252 *
253 * @returns iprt status code
254 */
255int USBProxyServiceLinux::initSysfs(void)
256{
257 Assert(!mUsingUsbfsDevices);
258
259#ifdef VBOX_USB_WITH_SYSFS
260 if (!VBoxMainUSBDevInfoInit(&mDeviceList))
261 return VERR_NO_MEMORY;
262 int rc = mWaiter.getStatus();
263 if (RT_SUCCESS(rc) || rc == VERR_TIMEOUT || rc == VERR_TRY_AGAIN)
264 rc = start();
265 else if (rc == VERR_NOT_SUPPORTED)
266 /* This can legitimately happen if hal or DBus are not running, but of
267 * course we can't start in this case. */
268 rc = VINF_SUCCESS;
269 return rc;
270
271#else /* !VBOX_USB_WITH_SYSFS */
272 return VERR_NOT_IMPLEMENTED;
273#endif /* !VBOX_USB_WITH_SYSFS */
274}
275
276
277/**
278 * Stop all service threads and free the device chain.
279 */
280USBProxyServiceLinux::~USBProxyServiceLinux()
281{
282 LogFlowThisFunc(("\n"));
283
284 /*
285 * Stop the service.
286 */
287 if (isActive())
288 stop();
289
290 /*
291 * Free resources.
292 */
293 doUsbfsCleanupAsNeeded();
294
295 /* (No extra work for !mUsingUsbfsDevices.) */
296}
297
298
299/**
300 * If any Usbfs-releated resources are currently allocated, then free them
301 * and mark them as freed.
302 */
303void USBProxyServiceLinux::doUsbfsCleanupAsNeeded()
304{
305 /*
306 * Free resources.
307 */
308 if (mStream)
309 {
310 fclose(mStream);
311 mStream = NULL;
312 mFile = NIL_RTFILE;
313 }
314 else if (mFile != NIL_RTFILE)
315 {
316 RTFileClose(mFile);
317 mFile = NIL_RTFILE;
318 }
319
320 if (mWakeupPipeR != NIL_RTFILE)
321 RTFileClose(mWakeupPipeR);
322 if (mWakeupPipeW != NIL_RTFILE)
323 RTFileClose(mWakeupPipeW);
324 mWakeupPipeW = mWakeupPipeR = NIL_RTFILE;
325}
326
327
328int USBProxyServiceLinux::captureDevice(HostUSBDevice *aDevice)
329{
330 Log(("USBProxyServiceLinux::captureDevice: %p {%s}\n", aDevice, aDevice->getName().c_str()));
331 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
332 AssertReturn(aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
333
334 /*
335 * Don't think we need to do anything when the device is held... fake it.
336 */
337 Assert(aDevice->getUnistate() == kHostUSBDeviceState_Capturing);
338 interruptWait();
339
340 return VINF_SUCCESS;
341}
342
343
344int USBProxyServiceLinux::releaseDevice(HostUSBDevice *aDevice)
345{
346 Log(("USBProxyServiceLinux::releaseDevice: %p\n", aDevice));
347 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
348 AssertReturn(aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
349
350 /*
351 * We're not really holding it atm., just fake it.
352 */
353 Assert(aDevice->getUnistate() == kHostUSBDeviceState_ReleasingToHost);
354 interruptWait();
355
356 return VINF_SUCCESS;
357}
358
359
360bool USBProxyServiceLinux::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
361{
362 if ( aUSBDevice->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
363 && aDevice->mUsb->enmState == USBDEVICESTATE_USED_BY_HOST)
364 LogRel(("USBProxy: Device %04x:%04x (%s) has become accessible.\n",
365 aUSBDevice->idVendor, aUSBDevice->idProduct, aUSBDevice->pszAddress));
366 return updateDeviceStateFake(aDevice, aUSBDevice, aRunFilters, aIgnoreMachine);
367}
368
369
370/**
371 * A device was added, we need to adjust mUdevPolls.
372 *
373 * See USBProxyService::deviceAdded for details.
374 */
375void USBProxyServiceLinux::deviceAdded(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList &llOpenedMachines, PUSBDEVICE aUSBDevice)
376{
377 if (aUSBDevice->enmState == USBDEVICESTATE_USED_BY_HOST)
378 {
379 LogRel(("USBProxy: Device %04x:%04x (%s) isn't accessible. giving udev a few seconds to fix this...\n",
380 aUSBDevice->idVendor, aUSBDevice->idProduct, aUSBDevice->pszAddress));
381 mUdevPolls = 10; /* (10 * 500ms = 5s) */
382 }
383
384 USBProxyService::deviceAdded(aDevice, llOpenedMachines, aUSBDevice);
385}
386
387
388int USBProxyServiceLinux::wait(RTMSINTERVAL aMillies)
389{
390 int rc;
391 if (mUsingUsbfsDevices)
392 rc = waitUsbfs(aMillies);
393 else
394 rc = waitSysfs(aMillies);
395 return rc;
396}
397
398
399/** String written to the wakeup pipe. */
400#define WAKE_UP_STRING "WakeUp!"
401/** Length of the string written. */
402#define WAKE_UP_STRING_LEN ( sizeof(WAKE_UP_STRING) - 1 )
403
404int USBProxyServiceLinux::waitUsbfs(RTMSINTERVAL aMillies)
405{
406 struct pollfd PollFds[2];
407
408 /* Cap the wait interval if we're polling for udevd changing device permissions. */
409 if (aMillies > 500 && mUdevPolls > 0)
410 {
411 mUdevPolls--;
412 aMillies = 500;
413 }
414
415 memset(&PollFds, 0, sizeof(PollFds));
416 PollFds[0].fd = mFile;
417 PollFds[0].events = POLLIN;
418 PollFds[1].fd = mWakeupPipeR;
419 PollFds[1].events = POLLIN | POLLERR | POLLHUP;
420
421 int rc = poll(&PollFds[0], 2, aMillies);
422 if (rc == 0)
423 return VERR_TIMEOUT;
424 if (rc > 0)
425 {
426 /* drain the pipe */
427 if (PollFds[1].revents & POLLIN)
428 {
429 char szBuf[WAKE_UP_STRING_LEN];
430 rc = RTFileRead(mWakeupPipeR, szBuf, sizeof(szBuf), NULL);
431 AssertRC(rc);
432 }
433 return VINF_SUCCESS;
434 }
435 return RTErrConvertFromErrno(errno);
436}
437
438
439int USBProxyServiceLinux::waitSysfs(RTMSINTERVAL aMillies)
440{
441#ifdef VBOX_USB_WITH_SYSFS
442 int rc = mWaiter.Wait(aMillies);
443 if (rc == VERR_TRY_AGAIN)
444 {
445 RTThreadYield();
446 rc = VINF_SUCCESS;
447 }
448 return rc;
449#else /* !VBOX_USB_WITH_SYSFS */
450 return USBProxyService::wait(aMillies);
451#endif /* !VBOX_USB_WITH_SYSFS */
452}
453
454
455int USBProxyServiceLinux::interruptWait(void)
456{
457#ifdef VBOX_USB_WITH_SYSFS
458 LogFlowFunc(("mUsingUsbfsDevices=%d\n", mUsingUsbfsDevices));
459 if (!mUsingUsbfsDevices)
460 {
461 mWaiter.Interrupt();
462 LogFlowFunc(("Returning VINF_SUCCESS\n"));
463 return VINF_SUCCESS;
464 }
465#endif /* VBOX_USB_WITH_SYSFS */
466 int rc = RTFileWrite(mWakeupPipeW, WAKE_UP_STRING, WAKE_UP_STRING_LEN, NULL);
467 if (RT_SUCCESS(rc))
468 RTFileFlush(mWakeupPipeW);
469 LogFlowFunc(("returning %Rrc\n", rc));
470 return rc;
471}
472
473
474/**
475 * "reads" the number suffix. It's more like validating it and
476 * skipping the necessary number of chars.
477 */
478static int usbReadSkipSuffix(char **ppszNext)
479{
480 char *pszNext = *ppszNext;
481 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
482 {
483 /* skip unit */
484 if (pszNext[0] == 'm' && pszNext[1] == 's')
485 pszNext += 2;
486 else if (pszNext[0] == 'm' && pszNext[1] == 'A')
487 pszNext += 2;
488
489 /* skip parenthesis */
490 if (*pszNext == '(')
491 {
492 pszNext = strchr(pszNext, ')');
493 if (!pszNext++)
494 {
495 AssertMsgFailed(("*ppszNext=%s\n", *ppszNext));
496 return VERR_PARSE_ERROR;
497 }
498 }
499
500 /* blank or end of the line. */
501 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
502 {
503 AssertMsgFailed(("pszNext=%s\n", pszNext));
504 return VERR_PARSE_ERROR;
505 }
506
507 /* it's ok. */
508 *ppszNext = pszNext;
509 }
510
511 return VINF_SUCCESS;
512}
513
514
515/**
516 * Reads a USB number returning the number and the position of the next character to parse.
517 */
518static int usbReadNum(const char *pszValue, unsigned uBase, uint32_t u32Mask, PCUSBSUFF paSuffs, void *pvNum, char **ppszNext)
519{
520 /*
521 * Initialize return value to zero and strip leading spaces.
522 */
523 switch (u32Mask)
524 {
525 case 0xff: *(uint8_t *)pvNum = 0; break;
526 case 0xffff: *(uint16_t *)pvNum = 0; break;
527 case 0xffffffff: *(uint32_t *)pvNum = 0; break;
528 }
529 pszValue = RTStrStripL(pszValue);
530 if (*pszValue)
531 {
532 /*
533 * Try convert the number.
534 */
535 char *pszNext;
536 uint32_t u32 = 0;
537 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32);
538 if (pszNext == pszValue)
539 {
540 AssertMsgFailed(("pszValue=%d\n", pszValue));
541 return VERR_NO_DATA;
542 }
543
544 /*
545 * Check the range.
546 */
547 if (u32 & ~u32Mask)
548 {
549 AssertMsgFailed(("pszValue=%d u32=%#x lMask=%#x\n", pszValue, u32, u32Mask));
550 return VERR_OUT_OF_RANGE;
551 }
552
553 /*
554 * Validate and skip stuff following the number.
555 */
556 if (paSuffs)
557 {
558 if (!RT_C_IS_SPACE(*pszNext) && *pszNext)
559 {
560 for (PCUSBSUFF pSuff = paSuffs; pSuff->szSuff[0]; pSuff++)
561 {
562 if ( !strncmp(pSuff->szSuff, pszNext, pSuff->cchSuff)
563 && (!pszNext[pSuff->cchSuff] || RT_C_IS_SPACE(pszNext[pSuff->cchSuff])))
564 {
565 if (pSuff->uDiv)
566 u32 /= pSuff->uDiv;
567 else
568 u32 *= pSuff->uMul;
569 break;
570 }
571 }
572 }
573 }
574 else
575 {
576 int rc = usbReadSkipSuffix(&pszNext);
577 if (RT_FAILURE(rc))
578 return rc;
579 }
580
581 *ppszNext = pszNext;
582
583 /*
584 * Set the value.
585 */
586 switch (u32Mask)
587 {
588 case 0xff: *(uint8_t *)pvNum = (uint8_t)u32; break;
589 case 0xffff: *(uint16_t *)pvNum = (uint16_t)u32; break;
590 case 0xffffffff: *(uint32_t *)pvNum = (uint32_t)u32; break;
591 }
592 }
593 return VINF_SUCCESS;
594}
595
596
597static int usbRead8(const char *pszValue, unsigned uBase, uint8_t *pu8, char **ppszNext)
598{
599 return usbReadNum(pszValue, uBase, 0xff, NULL, pu8, ppszNext);
600}
601
602
603static int usbRead16(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
604{
605 return usbReadNum(pszValue, uBase, 0xffff, NULL, pu16, ppszNext);
606}
607
608
609#if 0
610static int usbRead16Suff(const char *pszValue, unsigned uBase, PCUSBSUFF paSuffs, uint16_t *pu16, char **ppszNext)
611{
612 return usbReadNum(pszValue, uBase, 0xffff, paSuffs, pu16, ppszNext);
613}
614#endif
615
616
617/**
618 * Reads a USB BCD number returning the number and the position of the next character to parse.
619 * The returned number contains the integer part in the high byte and the decimal part in the low byte.
620 */
621static int usbReadBCD(const char *pszValue, unsigned uBase, uint16_t *pu16, char **ppszNext)
622{
623 /*
624 * Initialize return value to zero and strip leading spaces.
625 */
626 *pu16 = 0;
627 pszValue = RTStrStripL(pszValue);
628 if (*pszValue)
629 {
630 /*
631 * Try convert the number.
632 */
633 /* integer part */
634 char *pszNext;
635 uint32_t u32Int = 0;
636 RTStrToUInt32Ex(pszValue, &pszNext, uBase, &u32Int);
637 if (pszNext == pszValue)
638 {
639 AssertMsgFailed(("pszValue=%s\n", pszValue));
640 return VERR_NO_DATA;
641 }
642 if (u32Int & ~0xff)
643 {
644 AssertMsgFailed(("pszValue=%s u32Int=%#x (int)\n", pszValue, u32Int));
645 return VERR_OUT_OF_RANGE;
646 }
647
648 /* skip dot and read decimal part */
649 if (*pszNext != '.')
650 {
651 AssertMsgFailed(("pszValue=%s pszNext=%s (int)\n", pszValue, pszNext));
652 return VERR_PARSE_ERROR;
653 }
654 char *pszValue2 = RTStrStripL(pszNext + 1);
655 uint32_t u32Dec = 0;
656 RTStrToUInt32Ex(pszValue2, &pszNext, uBase, &u32Dec);
657 if (pszNext == pszValue)
658 {
659 AssertMsgFailed(("pszValue=%s\n", pszValue));
660 return VERR_NO_DATA;
661 }
662 if (u32Dec & ~0xff)
663 {
664 AssertMsgFailed(("pszValue=%s u32Dec=%#x\n", pszValue, u32Dec));
665 return VERR_OUT_OF_RANGE;
666 }
667
668 /*
669 * Validate and skip stuff following the number.
670 */
671 int rc = usbReadSkipSuffix(&pszNext);
672 if (RT_FAILURE(rc))
673 return rc;
674 *ppszNext = pszNext;
675
676 /*
677 * Set the value.
678 */
679 *pu16 = (uint16_t)u32Int << 8 | (uint16_t)u32Dec;
680 }
681 return VINF_SUCCESS;
682}
683
684
685/**
686 * Reads a string, i.e. allocates memory and copies it.
687 *
688 * We assume that a string is pure ASCII, if that's not the case
689 * tell me how to figure out the codeset please.
690 */
691static int usbReadStr(const char *pszValue, const char **ppsz)
692{
693 if (*ppsz)
694 RTStrFree((char *)*ppsz);
695 *ppsz = RTStrDup(pszValue);
696 if (*ppsz)
697 return VINF_SUCCESS;
698 return VERR_NO_MEMORY;
699}
700
701
702/**
703 * Skips the current property.
704 */
705static char *usbReadSkip(char *pszValue)
706{
707 char *psz = strchr(pszValue, '=');
708 if (psz)
709 psz = strchr(psz + 1, '=');
710 if (!psz)
711 return strchr(pszValue, '\0');
712 while (psz > pszValue && !RT_C_IS_SPACE(psz[-1]))
713 psz--;
714 Assert(psz > pszValue);
715 return psz;
716}
717
718
719/**
720 * Determine the USB speed.
721 */
722static int usbReadSpeed(const char *pszValue, USBDEVICESPEED *pSpd, char **ppszNext)
723{
724 pszValue = RTStrStripL(pszValue);
725 /* verified with Linux 2.4.0 ... Linux 2.6.25 */
726 if (!strncmp(pszValue, "1.5", 3))
727 *pSpd = USBDEVICESPEED_LOW;
728 else if (!strncmp(pszValue, "12 ", 3))
729 *pSpd = USBDEVICESPEED_FULL;
730 else if (!strncmp(pszValue, "480", 3))
731 *pSpd = USBDEVICESPEED_HIGH;
732 else
733 *pSpd = USBDEVICESPEED_UNKNOWN;
734 while (pszValue[0] != '\0' && !RT_C_IS_SPACE(pszValue[0]))
735 pszValue++;
736 *ppszNext = (char *)pszValue;
737 return VINF_SUCCESS;
738}
739
740
741/**
742 * Compare a prefix and returns pointer to the char following it if it matches.
743 */
744static char *usbPrefix(char *psz, const char *pszPref, size_t cchPref)
745{
746 if (strncmp(psz, pszPref, cchPref))
747 return NULL;
748 return psz + cchPref;
749}
750
751
752/**
753 * Does some extra checks to improve the detected device state.
754 *
755 * We cannot distinguish between USED_BY_HOST_CAPTURABLE and
756 * USED_BY_GUEST, HELD_BY_PROXY all that well and it shouldn't be
757 * necessary either.
758 *
759 * We will however, distinguish between the device we have permissions
760 * to open and those we don't. This is necessary for two reasons.
761 *
762 * Firstly, because it's futile to even attempt opening a device which we
763 * don't have access to, it only serves to confuse the user. (That said,
764 * it might also be a bit confusing for the user to see that a USB device
765 * is grayed out with no further explanation, and no way of generating an
766 * error hinting at why this is the case.)
767 *
768 * Secondly and more importantly, we're racing against udevd with respect
769 * to permissions and group settings on newly plugged devices. When we
770 * detect a new device that we cannot access we will poll on it for a few
771 * seconds to give udevd time to fix it. The polling is actually triggered
772 * in the 'new device' case in the compare loop.
773 *
774 * The USBDEVICESTATE_USED_BY_HOST state is only used for this no-access
775 * case, while USBDEVICESTATE_UNSUPPORTED is only used in the 'hub' case.
776 * When it's neither of these, we set USBDEVICESTATE_UNUSED or
777 * USBDEVICESTATE_USED_BY_HOST_CAPTURABLE depending on whether there is
778 * a driver associated with any of the interfaces.
779 *
780 * All except the access check and a special idVendor == 0 precaution
781 * is handled at parse time.
782 *
783 * @returns The adjusted state.
784 * @param pDevice The device.
785 */
786static USBDEVICESTATE usbDeterminState(PCUSBDEVICE pDevice)
787{
788 /*
789 * If it's already flagged as unsupported, there is nothing to do.
790 */
791 USBDEVICESTATE enmState = pDevice->enmState;
792 if (enmState == USBDEVICESTATE_UNSUPPORTED)
793 return USBDEVICESTATE_UNSUPPORTED;
794
795 /*
796 * Root hubs and similar doesn't have any vendor id, just
797 * refuse these device.
798 */
799 if (!pDevice->idVendor)
800 return USBDEVICESTATE_UNSUPPORTED;
801
802 /*
803 * Check if we've got access to the device, if we haven't flag
804 * it as used-by-host.
805 */
806#ifndef VBOX_USB_WITH_SYSFS
807 const char *pszAddress = pDevice->pszAddress;
808#else
809 if (pDevice->pszAddress == NULL)
810 /* We can't do much with the device without an address. */
811 return USBDEVICESTATE_UNSUPPORTED;
812 const char *pszAddress = strstr(pDevice->pszAddress, "//device:");
813 pszAddress = pszAddress != NULL
814 ? pszAddress + sizeof("//device:") - 1
815 : pDevice->pszAddress;
816#endif
817 if ( access(pszAddress, R_OK | W_OK) != 0
818 && errno == EACCES)
819 return USBDEVICESTATE_USED_BY_HOST;
820
821#ifdef VBOX_USB_WITH_SYSFS
822 /**
823 * @todo Check that any other essential fields are present and mark as
824 * invalid if not. Particularly to catch the case where the device was
825 * unplugged while we were reading in its properties.
826 */
827#endif
828
829 return enmState;
830}
831
832
833/** Just a worker for USBProxyServiceLinux::getDevices that avoids some code duplication. */
834int USBProxyServiceLinux::addDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, int rc)
835{
836 /* usbDeterminState requires the address. */
837 PUSBDEVICE pDevNew = (PUSBDEVICE)RTMemDup(pDev, sizeof(*pDev));
838 if (pDevNew)
839 {
840 RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", mUsbfsRoot.c_str(), pDevNew->bBus, pDevNew->bDevNum);
841 if (pDevNew->pszAddress)
842 {
843 pDevNew->enmState = usbDeterminState(pDevNew);
844 if (pDevNew->enmState != USBDEVICESTATE_UNSUPPORTED)
845 {
846 if (*pppNext)
847 **pppNext = pDevNew;
848 else
849 *ppFirst = pDevNew;
850 *pppNext = &pDevNew->pNext;
851 }
852 else
853 freeDevice(pDevNew);
854 }
855 else
856 {
857 freeDevice(pDevNew);
858 rc = VERR_NO_MEMORY;
859 }
860 }
861 else
862 {
863 rc = VERR_NO_MEMORY;
864 freeDeviceMembers(pDev);
865 }
866
867 return rc;
868}
869
870
871/**
872 * USBProxyService::getDevices() implementation for usbfs.
873 */
874PUSBDEVICE USBProxyServiceLinux::getDevicesFromUsbfs(void)
875{
876 PUSBDEVICE pFirst = NULL;
877 if (mStream)
878 {
879 PUSBDEVICE *ppNext = NULL;
880 int cHits = 0;
881 char szLine[1024];
882 USBDEVICE Dev;
883 RT_ZERO(Dev);
884 Dev.enmState = USBDEVICESTATE_UNUSED;
885
886 /*
887 * Rewind the stream and make 100% sure we flush the buffer.
888 *
889 * We've had trouble with rewind() messing up on buffered streams when attaching
890 * device clusters such as the Bloomberg keyboard. Therefor the stream is now
891 * without a permanent buffer (see the constructor) and we'll employ a temporary
892 * stack buffer while parsing the file (speed).
893 */
894 rewind(mStream);
895 char szBuf[1024];
896 setvbuf(mStream, szBuf, _IOFBF, sizeof(szBuf));
897
898 int rc = VINF_SUCCESS;
899 while ( RT_SUCCESS(rc)
900 && fgets(szLine, sizeof(szLine), mStream))
901 {
902 char *psz;
903 char *pszValue;
904
905 /* validate and remove the trailing newline. */
906 psz = strchr(szLine, '\0');
907 if (psz[-1] != '\n' && !feof(mStream))
908 {
909 AssertMsgFailed(("Line too long. (cch=%d)\n", strlen(szLine)));
910 continue;
911 }
912
913 /* strip */
914 psz = RTStrStrip(szLine);
915 if (!*psz)
916 continue;
917
918 /*
919 * Interpret the line.
920 * (Ordered by normal occurence.)
921 */
922 char ch = psz[0];
923 if (psz[1] != ':')
924 continue;
925 psz = RTStrStripL(psz + 3);
926#define PREFIX(str) ( (pszValue = usbPrefix(psz, str, sizeof(str) - 1)) != NULL )
927 switch (ch)
928 {
929 /*
930 * T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd
931 * | | | | | | | | |__MaxChildren
932 * | | | | | | | |__Device Speed in Mbps
933 * | | | | | | |__DeviceNumber
934 * | | | | | |__Count of devices at this level
935 * | | | | |__Connector/Port on Parent for this device
936 * | | | |__Parent DeviceNumber
937 * | | |__Level in topology for this bus
938 * | |__Bus number
939 * |__Topology info tag
940 */
941 case 'T':
942 /* add */
943 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
944 if (cHits >= 3)
945 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, rc);
946 else
947 freeDeviceMembers(&Dev);
948
949 /* Reset device state */
950 memset(&Dev, 0, sizeof (Dev));
951 Dev.enmState = USBDEVICESTATE_UNUSED;
952 cHits = 1;
953
954 /* parse the line. */
955 while (*psz && RT_SUCCESS(rc))
956 {
957 if (PREFIX("Bus="))
958 rc = usbRead8(pszValue, 10, &Dev.bBus, &psz);
959 else if (PREFIX("Port="))
960 rc = usbRead8(pszValue, 10, &Dev.bPort, &psz);
961 else if (PREFIX("Spd="))
962 rc = usbReadSpeed(pszValue, &Dev.enmSpeed, &psz);
963 else if (PREFIX("Dev#="))
964 rc = usbRead8(pszValue, 10, &Dev.bDevNum, &psz);
965 else
966 psz = usbReadSkip(psz);
967 psz = RTStrStripL(psz);
968 }
969 break;
970
971 /*
972 * Bandwidth info:
973 * B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd
974 * | | | |__Number of isochronous requests
975 * | | |__Number of interrupt requests
976 * | |__Total Bandwidth allocated to this bus
977 * |__Bandwidth info tag
978 */
979 case 'B':
980 break;
981
982 /*
983 * D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
984 * | | | | | | |__NumberConfigurations
985 * | | | | | |__MaxPacketSize of Default Endpoint
986 * | | | | |__DeviceProtocol
987 * | | | |__DeviceSubClass
988 * | | |__DeviceClass
989 * | |__Device USB version
990 * |__Device info tag #1
991 */
992 case 'D':
993 while (*psz && RT_SUCCESS(rc))
994 {
995 if (PREFIX("Ver="))
996 rc = usbReadBCD(pszValue, 16, &Dev.bcdUSB, &psz);
997 else if (PREFIX("Cls="))
998 {
999 rc = usbRead8(pszValue, 16, &Dev.bDeviceClass, &psz);
1000 if (RT_SUCCESS(rc) && Dev.bDeviceClass == 9 /* HUB */)
1001 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
1002 }
1003 else if (PREFIX("Sub="))
1004 rc = usbRead8(pszValue, 16, &Dev.bDeviceSubClass, &psz);
1005 else if (PREFIX("Prot="))
1006 rc = usbRead8(pszValue, 16, &Dev.bDeviceProtocol, &psz);
1007 //else if (PREFIX("MxPS="))
1008 // rc = usbRead16(pszValue, 10, &Dev.wMaxPacketSize, &psz);
1009 else if (PREFIX("#Cfgs="))
1010 rc = usbRead8(pszValue, 10, &Dev.bNumConfigurations, &psz);
1011 else
1012 psz = usbReadSkip(psz);
1013 psz = RTStrStripL(psz);
1014 }
1015 cHits++;
1016 break;
1017
1018 /*
1019 * P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
1020 * | | | |__Product revision number
1021 * | | |__Product ID code
1022 * | |__Vendor ID code
1023 * |__Device info tag #2
1024 */
1025 case 'P':
1026 while (*psz && RT_SUCCESS(rc))
1027 {
1028 if (PREFIX("Vendor="))
1029 rc = usbRead16(pszValue, 16, &Dev.idVendor, &psz);
1030 else if (PREFIX("ProdID="))
1031 rc = usbRead16(pszValue, 16, &Dev.idProduct, &psz);
1032 else if (PREFIX("Rev="))
1033 rc = usbReadBCD(pszValue, 16, &Dev.bcdDevice, &psz);
1034 else
1035 psz = usbReadSkip(psz);
1036 psz = RTStrStripL(psz);
1037 }
1038 cHits++;
1039 break;
1040
1041 /*
1042 * String.
1043 */
1044 case 'S':
1045 if (PREFIX("Manufacturer="))
1046 rc = usbReadStr(pszValue, &Dev.pszManufacturer);
1047 else if (PREFIX("Product="))
1048 rc = usbReadStr(pszValue, &Dev.pszProduct);
1049 else if (PREFIX("SerialNumber="))
1050 {
1051 rc = usbReadStr(pszValue, &Dev.pszSerialNumber);
1052 if (RT_SUCCESS(rc))
1053 Dev.u64SerialHash = USBLibHashSerial(pszValue);
1054 }
1055 break;
1056
1057 /*
1058 * C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
1059 * | | | | | |__MaxPower in mA
1060 * | | | | |__Attributes
1061 * | | | |__ConfiguratioNumber
1062 * | | |__NumberOfInterfaces
1063 * | |__ "*" indicates the active configuration (others are " ")
1064 * |__Config info tag
1065 */
1066 case 'C':
1067 break;
1068
1069 /*
1070 * I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
1071 * | | | | | | | |__Driver name
1072 * | | | | | | | or "(none)"
1073 * | | | | | | |__InterfaceProtocol
1074 * | | | | | |__InterfaceSubClass
1075 * | | | | |__InterfaceClass
1076 * | | | |__NumberOfEndpoints
1077 * | | |__AlternateSettingNumber
1078 * | |__InterfaceNumber
1079 * |__Interface info tag
1080 */
1081 case 'I':
1082 {
1083 /* Check for thing we don't support. */
1084 while (*psz && RT_SUCCESS(rc))
1085 {
1086 if (PREFIX("Driver="))
1087 {
1088 const char *pszDriver = NULL;
1089 rc = usbReadStr(pszValue, &pszDriver);
1090 if ( !pszDriver
1091 || !*pszDriver
1092 || !strcmp(pszDriver, "(none)")
1093 || !strcmp(pszDriver, "(no driver)"))
1094 /* no driver */;
1095 else if (!strcmp(pszDriver, "hub"))
1096 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
1097 else if (Dev.enmState == USBDEVICESTATE_UNUSED)
1098 Dev.enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1099 RTStrFree((char *)pszDriver);
1100 break; /* last attrib */
1101 }
1102 else if (PREFIX("Cls="))
1103 {
1104 uint8_t bInterfaceClass;
1105 rc = usbRead8(pszValue, 16, &bInterfaceClass, &psz);
1106 if (RT_SUCCESS(rc) && bInterfaceClass == 9 /* HUB */)
1107 Dev.enmState = USBDEVICESTATE_UNSUPPORTED;
1108 }
1109 else
1110 psz = usbReadSkip(psz);
1111 psz = RTStrStripL(psz);
1112 }
1113 break;
1114 }
1115
1116
1117 /*
1118 * E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddms
1119 * | | | | |__Interval (max) between transfers
1120 * | | | |__EndpointMaxPacketSize
1121 * | | |__Attributes(EndpointType)
1122 * | |__EndpointAddress(I=In,O=Out)
1123 * |__Endpoint info tag
1124 */
1125 case 'E':
1126 break;
1127
1128 }
1129#undef PREFIX
1130 } /* parse loop */
1131
1132 /*
1133 * Add the current entry.
1134 */
1135 AssertMsg(cHits >= 3 || cHits == 0, ("cHits=%d\n", cHits));
1136 if (cHits >= 3)
1137 rc = addDeviceToChain(&Dev, &pFirst, &ppNext, rc);
1138
1139 /*
1140 * Success?
1141 */
1142 if (RT_FAILURE(rc))
1143 {
1144 LogFlow(("USBProxyServiceLinux::getDevices: rc=%Rrc\n", rc));
1145 while (pFirst)
1146 {
1147 PUSBDEVICE pFree = pFirst;
1148 pFirst = pFirst->pNext;
1149 freeDevice(pFree);
1150 }
1151 }
1152
1153 /*
1154 * Turn buffering off to detach it from the local buffer and to
1155 * make subsequent rewind() calls work correctly.
1156 */
1157 setvbuf(mStream, NULL, _IONBF, 0);
1158 }
1159 return pFirst;
1160}
1161
1162#ifdef VBOX_USB_WITH_SYSFS
1163
1164/**
1165 * Helper function for extracting the port number on the parent device from
1166 * the sysfs path value.
1167 *
1168 * The sysfs path is a chain of elements separated by forward slashes, and for
1169 * USB devices, the last element in the chain takes the form
1170 * <port>-<port>.[...].<port>[:<config>.<interface>]
1171 * where the first <port> is the port number on the root hub, and the following
1172 * (optional) ones are the port numbers on any other hubs between the device
1173 * and the root hub. The last part (:<config.interface>) is only present for
1174 * interfaces, not for devices. This API should only be called for devices.
1175 * For compatibility with usbfs, which enumerates from zero up, we subtract one
1176 * from the port number.
1177 *
1178 * For root hubs, the last element in the chain takes the form
1179 * usb<hub number>
1180 * and usbfs always returns port number zero.
1181 *
1182 * @returns VBox status. pu8Port is set on success.
1183 * @param pszPath The sysfs path to parse.
1184 * @param pu8Port Where to store the port number.
1185 */
1186static int usbGetPortFromSysfsPath(const char *pszPath, uint8_t *pu8Port)
1187{
1188 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
1189 AssertPtrReturn(pu8Port, VERR_INVALID_POINTER);
1190
1191 /*
1192 * This should not be possible until we get PCs with USB as their primary bus.
1193 * Note: We don't assert this, as we don't expect the caller to validate the
1194 * sysfs path.
1195 */
1196 const char *pszLastComp = strrchr(pszPath, '/');
1197 if (!pszLastComp)
1198 {
1199 Log(("usbGetPortFromSysfsPath(%s): failed [1]\n", pszPath));
1200 return VERR_INVALID_PARAMETER;
1201 }
1202 pszLastComp++; /* skip the slash */
1203
1204 /*
1205 * This API should not be called for interfaces, so the last component
1206 * of the path should not contain a colon. We *do* assert this, as it
1207 * might indicate a caller bug.
1208 */
1209 AssertMsgReturn(strchr(pszLastComp, ':') == NULL, ("%s\n", pszPath), VERR_INVALID_PARAMETER);
1210
1211 /*
1212 * Look for the start of the last number.
1213 */
1214 const char *pchDash = strrchr(pszLastComp, '-');
1215 const char *pchDot = strrchr(pszLastComp, '.');
1216 if (!pchDash && !pchDot)
1217 {
1218 /* No -/. so it must be a root hub. Check that it's usb<something>. */
1219 if (strncmp(pszLastComp, "usb", sizeof("usb") - 1) != 0)
1220 {
1221 Log(("usbGetPortFromSysfsPath(%s): failed [2]\n", pszPath));
1222 return VERR_INVALID_PARAMETER;
1223 }
1224 return VERR_NOT_SUPPORTED;
1225 }
1226 else
1227 {
1228 const char *pszLastPort = pchDot != NULL
1229 ? pchDot + 1
1230 : pchDash + 1;
1231 int rc = RTStrToUInt8Full(pszLastPort, 10, pu8Port);
1232 if (rc != VINF_SUCCESS)
1233 {
1234 Log(("usbGetPortFromSysfsPath(%s): failed [3], rc=%Rrc\n", pszPath, rc));
1235 return VERR_INVALID_PARAMETER;
1236 }
1237 if (*pu8Port == 0)
1238 {
1239 Log(("usbGetPortFromSysfsPath(%s): failed [4]\n", pszPath));
1240 return VERR_INVALID_PARAMETER;
1241 }
1242
1243 /* usbfs compatibility, 0-based port number. */
1244 *pu8Port -= 1;
1245 }
1246 return VINF_SUCCESS;
1247}
1248
1249
1250/**
1251 * Dumps a USBDEVICE structure to the log using LogLevel 3.
1252 * @param pDev The structure to log.
1253 * @todo This is really common code.
1254 */
1255DECLINLINE(void) usbLogDevice(PUSBDEVICE pDev)
1256{
1257 NOREF(pDev);
1258
1259 Log3(("USB device:\n"));
1260 Log3(("Product: %s (%x)\n", pDev->pszProduct, pDev->idProduct));
1261 Log3(("Manufacturer: %s (Vendor ID %x)\n", pDev->pszManufacturer, pDev->idVendor));
1262 Log3(("Serial number: %s (%llx)\n", pDev->pszSerialNumber, pDev->u64SerialHash));
1263 Log3(("Device revision: %d\n", pDev->bcdDevice));
1264 Log3(("Device class: %x\n", pDev->bDeviceClass));
1265 Log3(("Device subclass: %x\n", pDev->bDeviceSubClass));
1266 Log3(("Device protocol: %x\n", pDev->bDeviceProtocol));
1267 Log3(("USB version number: %d\n", pDev->bcdUSB));
1268 Log3(("Device speed: %s\n",
1269 pDev->enmSpeed == USBDEVICESPEED_UNKNOWN ? "unknown"
1270 : pDev->enmSpeed == USBDEVICESPEED_LOW ? "1.5 MBit/s"
1271 : pDev->enmSpeed == USBDEVICESPEED_FULL ? "12 MBit/s"
1272 : pDev->enmSpeed == USBDEVICESPEED_HIGH ? "480 MBit/s"
1273 : pDev->enmSpeed == USBDEVICESPEED_VARIABLE ? "variable"
1274 : "invalid"));
1275 Log3(("Number of configurations: %d\n", pDev->bNumConfigurations));
1276 Log3(("Bus number: %d\n", pDev->bBus));
1277 Log3(("Port number: %d\n", pDev->bPort));
1278 Log3(("Device number: %d\n", pDev->bDevNum));
1279 Log3(("Device state: %s\n",
1280 pDev->enmState == USBDEVICESTATE_UNSUPPORTED ? "unsupported"
1281 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST ? "in use by host"
1282 : pDev->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE ? "in use by host, possibly capturable"
1283 : pDev->enmState == USBDEVICESTATE_UNUSED ? "not in use"
1284 : pDev->enmState == USBDEVICESTATE_HELD_BY_PROXY ? "held by proxy"
1285 : pDev->enmState == USBDEVICESTATE_USED_BY_GUEST ? "used by guest"
1286 : "invalid"));
1287 Log3(("OS device address: %s\n", pDev->pszAddress));
1288}
1289
1290/**
1291 * In contrast to usbReadBCD() this function can handle BCD values without
1292 * a decimal separator. This is necessary for parsing bcdDevice.
1293 * @param pszBuf Pointer to the string buffer.
1294 * @param pu15 Pointer to the return value.
1295 * @returns IPRT status code.
1296 */
1297static int convertSysfsStrToBCD(const char *pszBuf, uint16_t *pu16)
1298{
1299 char *pszNext;
1300 int32_t i32;
1301
1302 pszBuf = RTStrStripL(pszBuf);
1303 int rc = RTStrToInt32Ex(pszBuf, &pszNext, 16, &i32);
1304 if ( RT_FAILURE(rc)
1305 || rc == VWRN_NUMBER_TOO_BIG
1306 || i32 < 0)
1307 return VERR_NUMBER_TOO_BIG;
1308 if (*pszNext == '.')
1309 {
1310 if (i32 > 255)
1311 return VERR_NUMBER_TOO_BIG;
1312 int32_t i32Lo;
1313 rc = RTStrToInt32Ex(pszNext+1, &pszNext, 16, &i32Lo);
1314 if ( RT_FAILURE(rc)
1315 || rc == VWRN_NUMBER_TOO_BIG
1316 || i32Lo > 255
1317 || i32Lo < 0)
1318 return VERR_NUMBER_TOO_BIG;
1319 i32 = (i32 << 8) | i32Lo;
1320 }
1321 if ( i32 > 65535
1322 || (*pszNext != '\0' && *pszNext != ' '))
1323 return VERR_NUMBER_TOO_BIG;
1324
1325 *pu16 = (uint16_t)i32;
1326 return VINF_SUCCESS;
1327}
1328
1329#endif /* VBOX_USB_WITH_SYSFS */
1330
1331/**
1332 * USBProxyService::getDevices() implementation for sysfs.
1333 */
1334PUSBDEVICE USBProxyServiceLinux::getDevicesFromSysfs(void)
1335{
1336#ifdef VBOX_USB_WITH_SYSFS
1337 USBDevInfoUpdateDevices(&mDeviceList);
1338 /* Add each of the devices found to the chain. */
1339 PUSBDEVICE pFirst = NULL;
1340 PUSBDEVICE pLast = NULL;
1341 int rc = VINF_SUCCESS;
1342 USBDeviceInfoList_iterator it;
1343 USBDeviceInfoList_iter_init(&it, USBDevInfoBegin(&mDeviceList));
1344 for (; RT_SUCCESS(rc)
1345 && !USBDeviceInfoList_iter_eq(&it, USBDevInfoEnd(&mDeviceList));
1346 USBDeviceInfoList_iter_incr(&it))
1347 {
1348 USBDEVICE *Dev = (USBDEVICE *)RTMemAllocZ(sizeof(USBDEVICE));
1349 if (!Dev)
1350 rc = VERR_NO_MEMORY;
1351 if (RT_SUCCESS(rc))
1352 {
1353 const char *pszSysfsPath = USBDeviceInfoList_iter_target(&it)->mSysfsPath;
1354
1355 /* Fill in the simple fields */
1356 Dev->enmState = USBDEVICESTATE_UNUSED;
1357 Dev->bBus = RTLinuxSysFsReadIntFile(10, "%s/busnum", pszSysfsPath);
1358 Dev->bDeviceClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceClass", pszSysfsPath);
1359 Dev->bDeviceSubClass = RTLinuxSysFsReadIntFile(16, "%s/bDeviceSubClass", pszSysfsPath);
1360 Dev->bDeviceProtocol = RTLinuxSysFsReadIntFile(16, "%s/bDeviceProtocol", pszSysfsPath);
1361 Dev->bNumConfigurations = RTLinuxSysFsReadIntFile(10, "%s/bNumConfigurations", pszSysfsPath);
1362 Dev->idVendor = RTLinuxSysFsReadIntFile(16, "%s/idVendor", pszSysfsPath);
1363 Dev->idProduct = RTLinuxSysFsReadIntFile(16, "%s/idProduct", pszSysfsPath);
1364 Dev->bDevNum = RTLinuxSysFsReadIntFile(10, "%s/devnum", pszSysfsPath);
1365
1366 /* Now deal with the non-numeric bits. */
1367 char szBuf[1024]; /* Should be larger than anything a sane device
1368 * will need, and insane devices can be unsupported
1369 * until further notice. */
1370 ssize_t cchRead;
1371
1372 /* For simplicity, we just do strcmps on the next one. */
1373 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/speed",
1374 pszSysfsPath);
1375 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1376 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1377 else
1378 Dev->enmSpeed = !strcmp(szBuf, "1.5") ? USBDEVICESPEED_LOW
1379 : !strcmp(szBuf, "12") ? USBDEVICESPEED_FULL
1380 : !strcmp(szBuf, "480") ? USBDEVICESPEED_HIGH
1381 : USBDEVICESPEED_UNKNOWN;
1382
1383 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/version",
1384 pszSysfsPath);
1385 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1386 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1387 else
1388 {
1389 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdUSB);
1390 if (RT_FAILURE(rc))
1391 {
1392 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1393 Dev->bcdUSB = (uint16_t)-1;
1394 }
1395 }
1396
1397 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/bcdDevice",
1398 pszSysfsPath);
1399 if (cchRead <= 0 || (size_t) cchRead == sizeof(szBuf))
1400 Dev->bcdDevice = (uint16_t)-1;
1401 else
1402 {
1403 rc = convertSysfsStrToBCD(szBuf, &Dev->bcdDevice);
1404 if (RT_FAILURE(rc))
1405 Dev->bcdDevice = (uint16_t)-1;
1406 }
1407
1408 /* Now do things that need string duplication */
1409 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/product",
1410 pszSysfsPath);
1411 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1412 {
1413 RTStrPurgeEncoding(szBuf);
1414 Dev->pszProduct = RTStrDup(szBuf);
1415 }
1416
1417 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/serial",
1418 pszSysfsPath);
1419 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1420 {
1421 RTStrPurgeEncoding(szBuf);
1422 Dev->pszSerialNumber = RTStrDup(szBuf);
1423 Dev->u64SerialHash = USBLibHashSerial(szBuf);
1424 }
1425
1426 cchRead = RTLinuxSysFsReadStrFile(szBuf, sizeof(szBuf), "%s/manufacturer",
1427 pszSysfsPath);
1428 if (cchRead > 0 && (size_t) cchRead < sizeof(szBuf))
1429 {
1430 RTStrPurgeEncoding(szBuf);
1431 Dev->pszManufacturer = RTStrDup(szBuf);
1432 }
1433
1434 /* Work out the port number */
1435 if (RT_FAILURE(usbGetPortFromSysfsPath(pszSysfsPath, &Dev->bPort)))
1436 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1437
1438 /* Check the interfaces to see if we can support the device. */
1439 USBInterfaceList_iterator it2;
1440 USBDeviceInfo *udi = USBDeviceInfoList_iter_target(&it);
1441 USBInterfaceList_iter_init(&it2, USBInterfaceList_begin(&udi->mInterfaces));
1442 for (; !USBInterfaceList_iter_eq(&it2, USBInterfaceList_end(&udi->mInterfaces));
1443 USBInterfaceList_iter_incr(&it2))
1444 {
1445 ssize_t cb = RTLinuxSysFsGetLinkDest(szBuf, sizeof(szBuf), "%s/driver",
1446 USBInterfaceList_iter_target(&it2));
1447 if (cb > 0 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED)
1448 Dev->enmState = (strcmp(szBuf, "hub") == 0)
1449 ? USBDEVICESTATE_UNSUPPORTED
1450 : USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1451 if (RTLinuxSysFsReadIntFile(16, "%s/bInterfaceClass",
1452 USBInterfaceList_iter_target(&it2)) == 9 /* hub */)
1453 Dev->enmState = USBDEVICESTATE_UNSUPPORTED;
1454 }
1455
1456 /* We want a copy of the device node and sysfs paths guaranteed not to
1457 * contain double slashes, since we use a double slash as a separator in
1458 * the pszAddress field. */
1459 char szDeviceClean[RTPATH_MAX];
1460 char szSysfsClean[RTPATH_MAX];
1461 char *pszAddress = NULL;
1462 if ( RT_SUCCESS(RTPathReal(USBDeviceInfoList_iter_target(&it)->mDevice, szDeviceClean,
1463 sizeof(szDeviceClean)))
1464 && RT_SUCCESS(RTPathReal(pszSysfsPath, szSysfsClean,
1465 sizeof(szSysfsClean)))
1466 )
1467 RTStrAPrintf(&pszAddress, "sysfs:%s//device:%s", szSysfsClean,
1468 szDeviceClean);
1469 Dev->pszAddress = pszAddress;
1470
1471 /* Work out from the data collected whether we can support this device. */
1472 Dev->enmState = usbDeterminState(Dev);
1473 usbLogDevice(Dev);
1474 }
1475 if ( RT_SUCCESS(rc)
1476 && Dev->enmState != USBDEVICESTATE_UNSUPPORTED
1477 && Dev->pszAddress != NULL
1478 )
1479 {
1480 if (pLast != NULL)
1481 {
1482 pLast->pNext = Dev;
1483 pLast = pLast->pNext;
1484 }
1485 else
1486 pFirst = pLast = Dev;
1487 }
1488 else
1489 freeDevice(Dev);
1490 }
1491 if (RT_FAILURE(rc))
1492 while (pFirst)
1493 {
1494 PUSBDEVICE pNext = pFirst->pNext;
1495 freeDevice(pFirst);
1496 pFirst = pNext;
1497 }
1498
1499 /* Eliminate any duplicates. This was originally a sanity check, but it
1500 * turned out that hal can get confused and return devices twice. */
1501 for (PUSBDEVICE pDev = pFirst; pDev != NULL; pDev = pDev->pNext)
1502 for (PUSBDEVICE pDev2 = pDev; pDev2 != NULL && pDev2->pNext != NULL;
1503 pDev2 = pDev2->pNext)
1504 while ( pDev2->pNext != NULL
1505 && RTStrCmp(pDev->pszAddress, pDev2->pNext->pszAddress) == 0)
1506 {
1507 PUSBDEVICE pDup = pDev2->pNext;
1508 pDev2->pNext = pDup->pNext;
1509 freeDevice(pDup);
1510 }
1511 return pFirst;
1512#else /* !VBOX_USB_WITH_SYSFS */
1513 return NULL;
1514#endif /* !VBOX_USB_WITH_SYSFS */
1515}
1516
1517
1518PUSBDEVICE USBProxyServiceLinux::getDevices(void)
1519{
1520 PUSBDEVICE pDevices;
1521 if (mUsingUsbfsDevices)
1522 pDevices = getDevicesFromUsbfs();
1523 else
1524 pDevices = getDevicesFromSysfs();
1525 return pDevices;
1526}
1527
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