VirtualBox

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

Last change on this file since 32258 was 32258, checked in by vboxsync, 15 years ago

Main/USB/linux: simplified the vector container and the code using it

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

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