USBProxyServiceLinux.cpp revision a0c1e203edd9781c6d0f7560e37dbc729fef5991
/* $Id$ */
/** @file
* VirtualBox USB Proxy Service, Linux Specialization.
*/
/*
* Copyright (C) 2006-2010 Oracle Corporation
*
* This file is part of VirtualBox Open Source Edition (OSE), as
* available from http://www.virtualbox.org. This file is free software;
* General Public License (GPL) as published by the Free Software
* Foundation, in version 2 as it comes in the "COPYING" file of the
* VirtualBox OSE distribution. VirtualBox OSE is distributed in the
* hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
*/
/*******************************************************************************
* Header Files *
*******************************************************************************/
#include "USBProxyService.h"
#include "Logging.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#ifdef VBOX_WITH_LINUX_COMPILER_H
# include <linux/compiler.h>
#endif
#include <linux/usbdevice_fs.h>
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/** Suffix translation. */
typedef struct USBSUFF
{
char szSuff[4];
unsigned cchSuff;
unsigned uMul;
unsigned uDiv;
/*******************************************************************************
* Global Variables *
*******************************************************************************/
/**
* Suffixes for the endpoint polling interval.
*/
static const USBSUFF s_aIntervalSuff[] =
{
{ "ms", 2, 1, 0 },
{ "us", 2, 1, 1000 },
{ "ns", 2, 1, 1000000 },
{ "s", 1, 1000, 0 },
{ "", 0, 0, 0 } /* term */
};
/**
* Initialize data members.
*/
USBProxyServiceLinux::USBProxyServiceLinux(Host *aHost, const char *aUsbfsRoot /* = "/proc/bus/usb" */)
mWakeupPipeW(NIL_RTFILE), mUsbfsRoot(aUsbfsRoot), mUsingUsbfsDevices(true /* see init */), mUdevPolls(0)
{
}
/**
* Initializes the object (called right after construction).
*
* @returns S_OK on success and non-fatal failures, some COM error otherwise.
*/
{
/*
* Call the superclass method first.
*/
/*
* We have two methods available for getting host USB device data - using
* settings and an environment variable; if the default is not available
* we fall back to the second.
* In the event of both failing, the error from the second method tried
* will be presented to the user.
*/
#ifdef VBOX_WITH_SYSFS_BY_DEFAULT
mUsingUsbfsDevices = false;
#else
mUsingUsbfsDevices = true;
#endif
if (pszUsbFromEnv)
{
{
LogRel(("Default USB access method set to \"usbfs\" from environment\n"));
mUsingUsbfsDevices = true;
}
{
LogRel(("Default USB method set to \"sysfs\" from environment\n"));
mUsingUsbfsDevices = false;
}
else
LogRel(("Invalid VBOX_USB environment variable setting \"%s\"\n",
}
if (RT_FAILURE(rc))
{
/* For the day when we have VBoxSVC release logging... */
LogRel(("Failed to initialise host USB using %s\n",
}
: "Failed to initialise host USB using %s\n",
mLastError = rc;
return S_OK;
}
/**
* Initializiation routine for the usbfs based operation.
*
* @returns iprt status code.
*/
int USBProxyServiceLinux::initUsbfs(void)
{
/*
* Open the devices file.
*/
int rc;
char *pszDevices;
if (pszDevices)
{
if (RT_SUCCESS(rc))
{
/*
* Check that we're actually on the usbfs.
*/
{
{
int pipes[2];
{
mWakeupPipeR = pipes[0];
if (mStream)
{
/*
* Start the poller thread.
*/
if (RT_SUCCESS(rc))
{
LogFlowThisFunc(("returns successfully - mFile=%d mStream=%p mWakeupPipeR/W=%d/%d\n",
/*
* Turn buffering off to work around rewind() problems, see getDevices().
*/
return VINF_SUCCESS;
}
mFile = NIL_RTFILE;
}
else
{
}
}
else
{
}
}
else
{
Log(("USBProxyServiceLinux::USBProxyServiceLinux: StFS.f_type=%d expected=%d\n", StFS.f_type, USBDEVICE_SUPER_MAGIC));
}
}
else
{
}
mFile = NIL_RTFILE;
}
}
else
{
rc = VERR_NO_MEMORY;
Log(("USBProxyServiceLinux::USBProxyServiceLinux: out of memory!\n"));
}
return rc;
}
/**
* Initializiation routine for the sysfs based operation.
*
* @returns iprt status code
*/
int USBProxyServiceLinux::initSysfs(void)
{
#ifdef VBOX_USB_WITH_SYSFS
if (!VBoxMainUSBDevInfoInit(&mDeviceList))
return VERR_NO_MEMORY;
else if (rc == VERR_NOT_SUPPORTED)
/* This can legitimately happen if hal or DBus are not running, but of
* course we can't start in this case. */
rc = VINF_SUCCESS;
return rc;
#else /* !VBOX_USB_WITH_SYSFS */
return VERR_NOT_IMPLEMENTED;
#endif /* !VBOX_USB_WITH_SYSFS */
}
/**
* Stop all service threads and free the device chain.
*/
{
LogFlowThisFunc(("\n"));
/*
* Stop the service.
*/
if (isActive())
stop();
/*
* Free resources.
*/
/* (No extra work for !mUsingUsbfsDevices.) */
}
/**
* If any Usbfs-releated resources are currently allocated, then free them
* and mark them as freed.
*/
{
/*
* Free resources.
*/
if (mStream)
{
mFile = NIL_RTFILE;
}
else if (mFile != NIL_RTFILE)
{
mFile = NIL_RTFILE;
}
if (mWakeupPipeR != NIL_RTFILE)
if (mWakeupPipeW != NIL_RTFILE)
}
{
/*
* Don't think we need to do anything when the device is held... fake it.
*/
return VINF_SUCCESS;
}
{
/*
* We're not really holding it atm., just fake it.
*/
return VINF_SUCCESS;
}
bool USBProxyServiceLinux::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
{
LogRel(("USBProxy: Device %04x:%04x (%s) has become accessible.\n",
}
/**
* A device was added, we need to adjust mUdevPolls.
*
* See USBProxyService::deviceAdded for details.
*/
void USBProxyServiceLinux::deviceAdded(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList &llOpenedMachines, PUSBDEVICE aUSBDevice)
{
{
LogRel(("USBProxy: Device %04x:%04x (%s) isn't accessible. giving udev a few seconds to fix this...\n",
}
}
{
int rc;
if (mUsingUsbfsDevices)
else
return rc;
}
/** String written to the wakeup pipe. */
#define WAKE_UP_STRING "WakeUp!"
/** Length of the string written. */
{
/* Cap the wait interval if we're polling for udevd changing device permissions. */
{
mUdevPolls--;
aMillies = 500;
}
if (rc == 0)
return VERR_TIMEOUT;
if (rc > 0)
{
/* drain the pipe */
{
char szBuf[WAKE_UP_STRING_LEN];
}
return VINF_SUCCESS;
}
return RTErrConvertFromErrno(errno);
}
{
#ifdef VBOX_USB_WITH_SYSFS
if (rc == VERR_TRY_AGAIN)
{
rc = VINF_SUCCESS;
}
return rc;
#else /* !VBOX_USB_WITH_SYSFS */
#endif /* !VBOX_USB_WITH_SYSFS */
}
int USBProxyServiceLinux::interruptWait(void)
{
#ifdef VBOX_USB_WITH_SYSFS
if (!mUsingUsbfsDevices)
{
LogFlowFunc(("Returning VINF_SUCCESS\n"));
return VINF_SUCCESS;
}
#endif /* VBOX_USB_WITH_SYSFS */
if (RT_SUCCESS(rc))
return rc;
}
/**
* "reads" the number suffix. It's more like validating it and
* skipping the necessary number of chars.
*/
static int usbReadSkipSuffix(char **ppszNext)
{
{
/* skip unit */
pszNext += 2;
pszNext += 2;
/* skip parenthesis */
if (*pszNext == '(')
{
if (!pszNext++)
{
return VERR_PARSE_ERROR;
}
}
/* blank or end of the line. */
{
return VERR_PARSE_ERROR;
}
/* it's ok. */
}
return VINF_SUCCESS;
}
/**
* Reads a USB number returning the number and the position of the next character to parse.
*/
static int usbReadNum(const char *pszValue, unsigned uBase, uint32_t u32Mask, PCUSBSUFF paSuffs, void *pvNum, char **ppszNext)
{
/*
* Initialize return value to zero and strip leading spaces.
*/
switch (u32Mask)
{
}
if (*pszValue)
{
/*
* Try convert the number.
*/
char *pszNext;
{
return VERR_NO_DATA;
}
/*
* Check the range.
*/
{
return VERR_OUT_OF_RANGE;
}
/*
* Validate and skip stuff following the number.
*/
if (paSuffs)
{
{
{
{
else
break;
}
}
}
}
else
{
if (RT_FAILURE(rc))
return rc;
}
/*
* Set the value.
*/
switch (u32Mask)
{
}
}
return VINF_SUCCESS;
}
{
}
{
}
#if 0
static int usbRead16Suff(const char *pszValue, unsigned uBase, PCUSBSUFF paSuffs, uint16_t *pu16, char **ppszNext)
{
}
#endif
/**
* Reads a USB BCD number returning the number and the position of the next character to parse.
* The returned number contains the integer part in the high byte and the decimal part in the low byte.
*/
{
/*
* Initialize return value to zero and strip leading spaces.
*/
*pu16 = 0;
if (*pszValue)
{
/*
* Try convert the number.
*/
/* integer part */
char *pszNext;
{
return VERR_NO_DATA;
}
if (u32Int & ~0xff)
{
return VERR_OUT_OF_RANGE;
}
/* skip dot and read decimal part */
if (*pszNext != '.')
{
return VERR_PARSE_ERROR;
}
{
return VERR_NO_DATA;
}
if (u32Dec & ~0xff)
{
return VERR_OUT_OF_RANGE;
}
/*
* Validate and skip stuff following the number.
*/
if (RT_FAILURE(rc))
return rc;
/*
* Set the value.
*/
}
return VINF_SUCCESS;
}
/**
* Reads a string, i.e. allocates memory and copies it.
*
* We assume that a string is pure ASCII, if that's not the case
* tell me how to figure out the codeset please.
*/
{
if (*ppsz)
if (*ppsz)
return VINF_SUCCESS;
return VERR_NO_MEMORY;
}
/**
* Skips the current property.
*/
static char *usbReadSkip(char *pszValue)
{
if (psz)
if (!psz)
psz--;
return psz;
}
/**
* Determine the USB speed.
*/
{
/* verified with Linux 2.4.0 ... Linux 2.6.25 */
else
pszValue++;
return VINF_SUCCESS;
}
/**
* Compare a prefix and returns pointer to the char following it if it matches.
*/
{
return NULL;
}
/**
* Does some extra checks to improve the detected device state.
*
* We cannot distinguish between USED_BY_HOST_CAPTURABLE and
* USED_BY_GUEST, HELD_BY_PROXY all that well and it shouldn't be
* necessary either.
*
* We will however, distinguish between the device we have permissions
* to open and those we don't. This is necessary for two reasons.
*
* Firstly, because it's futile to even attempt opening a device which we
* don't have access to, it only serves to confuse the user. (That said,
* it might also be a bit confusing for the user to see that a USB device
* is grayed out with no further explanation, and no way of generating an
* error hinting at why this is the case.)
*
* Secondly and more importantly, we're racing against udevd with respect
* to permissions and group settings on newly plugged devices. When we
* detect a new device that we cannot access we will poll on it for a few
* seconds to give udevd time to fix it. The polling is actually triggered
* in the 'new device' case in the compare loop.
*
* The USBDEVICESTATE_USED_BY_HOST state is only used for this no-access
* case, while USBDEVICESTATE_UNSUPPORTED is only used in the 'hub' case.
* When it's neither of these, we set USBDEVICESTATE_UNUSED or
* USBDEVICESTATE_USED_BY_HOST_CAPTURABLE depending on whether there is
* a driver associated with any of the interfaces.
*
* All except the access check and a special idVendor == 0 precaution
* is handled at parse time.
*
* @returns The adjusted state.
* @param pDevice The device.
*/
{
/*
* If it's already flagged as unsupported, there is nothing to do.
*/
if (enmState == USBDEVICESTATE_UNSUPPORTED)
return USBDEVICESTATE_UNSUPPORTED;
/*
* Root hubs and similar doesn't have any vendor id, just
* refuse these device.
*/
return USBDEVICESTATE_UNSUPPORTED;
/*
* Check if we've got access to the device, if we haven't flag
* it as used-by-host.
*/
#ifndef VBOX_USB_WITH_SYSFS
#else
/* We can't do much with the device without an address. */
return USBDEVICESTATE_UNSUPPORTED;
: pDevice->pszAddress;
#endif
return USBDEVICESTATE_USED_BY_HOST;
#ifdef VBOX_USB_WITH_SYSFS
/**
* @todo Check that any other essential fields are present and mark as
* invalid if not. Particularly to catch the case where the device was
* unplugged while we were reading in its properties.
*/
#endif
return enmState;
}
/** Just a worker for USBProxyServiceLinux::getDevices that avoids some code duplication. */
int USBProxyServiceLinux::addDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, int rc)
{
/* usbDeterminState requires the address. */
if (pDevNew)
{
RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", mUsbfsRoot.c_str(), pDevNew->bBus, pDevNew->bDevNum);
if (pDevNew->pszAddress)
{
{
if (*pppNext)
else
}
else
}
else
{
rc = VERR_NO_MEMORY;
}
}
else
{
rc = VERR_NO_MEMORY;
}
return rc;
}
/**
* USBProxyService::getDevices() implementation for usbfs.
*/
{
if (mStream)
{
int cHits = 0;
char szLine[1024];
/*
* Rewind the stream and make 100% sure we flush the buffer.
*
* We've had trouble with rewind() messing up on buffered streams when attaching
* device clusters such as the Bloomberg keyboard. Therefor the stream is now
* without a permanent buffer (see the constructor) and we'll employ a temporary
* stack buffer while parsing the file (speed).
*/
char szBuf[1024];
int rc = VINF_SUCCESS;
while ( RT_SUCCESS(rc)
{
char *psz;
char *pszValue;
/* validate and remove the trailing newline. */
{
continue;
}
/* strip */
if (!*psz)
continue;
/*
* Interpret the line.
* (Ordered by normal occurence.)
*/
continue;
switch (ch)
{
/*
* T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd
* | | | | | | | | |__MaxChildren
* | | | | | | | |__Device Speed in Mbps
* | | | | | | |__DeviceNumber
* | | | | | |__Count of devices at this level
* | | | |__Parent DeviceNumber
* | | |__Level in topology for this bus
* | |__Bus number
* |__Topology info tag
*/
case 'T':
/* add */
if (cHits >= 3)
else
/* Reset device state */
cHits = 1;
/* parse the line. */
{
if (PREFIX("Bus="))
else if (PREFIX("Port="))
else if (PREFIX("Spd="))
else if (PREFIX("Dev#="))
else
}
break;
/*
* Bandwidth info:
* | | | |__Number of isochronous requests
* | | |__Number of interrupt requests
* | |__Total Bandwidth allocated to this bus
* |__Bandwidth info tag
*/
case 'B':
break;
/*
* D: Ver=x.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd
* | | | | | | |__NumberConfigurations
* | | | | | |__MaxPacketSize of Default Endpoint
* | | | | |__DeviceProtocol
* | | | |__DeviceSubClass
* | | |__DeviceClass
* | |__Device USB version
* |__Device info tag #1
*/
case 'D':
{
if (PREFIX("Ver="))
else if (PREFIX("Cls="))
{
}
else if (PREFIX("Sub="))
else if (PREFIX("Prot="))
//else if (PREFIX("MxPS="))
// rc = usbRead16(pszValue, 10, &Dev.wMaxPacketSize, &psz);
else if (PREFIX("#Cfgs="))
else
}
cHits++;
break;
/*
* P: Vendor=xxxx ProdID=xxxx Rev=xx.xx
* | | | |__Product revision number
* | | |__Product ID code
* | |__Vendor ID code
* |__Device info tag #2
*/
case 'P':
{
if (PREFIX("Vendor="))
else if (PREFIX("ProdID="))
else if (PREFIX("Rev="))
else
}
cHits++;
break;
/*
* String.
*/
case 'S':
if (PREFIX("Manufacturer="))
else if (PREFIX("Product="))
else if (PREFIX("SerialNumber="))
{
if (RT_SUCCESS(rc))
}
break;
/*
* C:* #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA
* | | | | | |__MaxPower in mA
* | | | | |__Attributes
* | | | |__ConfiguratioNumber
* | | |__NumberOfInterfaces
* | |__ "*" indicates the active configuration (others are " ")
* |__Config info tag
*/
case 'C':
break;
/*
* I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=ssss
* | | | | | | | |__Driver name
* | | | | | | | or "(none)"
* | | | | | | |__InterfaceProtocol
* | | | | | |__InterfaceSubClass
* | | | | |__InterfaceClass
* | | | |__NumberOfEndpoints
* | | |__AlternateSettingNumber
* | |__InterfaceNumber
* |__Interface info tag
*/
case 'I':
{
/* Check for thing we don't support. */
{
if (PREFIX("Driver="))
{
if ( !pszDriver
|| !*pszDriver
/* no driver */;
break; /* last attrib */
}
else if (PREFIX("Cls="))
{
}
else
}
break;
}
/*
* E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=dddms
* | | | | |__Interval (max) between transfers
* | | | |__EndpointMaxPacketSize
* | | |__Attributes(EndpointType)
* | |__EndpointAddress(I=In,O=Out)
* |__Endpoint info tag
*/
case 'E':
break;
}
} /* parse loop */
/*
* Add the current entry.
*/
if (cHits >= 3)
/*
* Success?
*/
if (RT_FAILURE(rc))
{
while (pFirst)
{
}
}
/*
* Turn buffering off to detach it from the local buffer and to
* make subsequent rewind() calls work correctly.
*/
}
return pFirst;
}
#ifdef VBOX_USB_WITH_SYSFS
/**
* Helper function for extracting the port number on the parent device from
* the sysfs path value.
*
* The sysfs path is a chain of elements separated by forward slashes, and for
* USB devices, the last element in the chain takes the form
* <port>-<port>.[...].<port>[:<config>.<interface>]
* where the first <port> is the port number on the root hub, and the following
* (optional) ones are the port numbers on any other hubs between the device
* and the root hub. The last part (:<config.interface>) is only present for
* interfaces, not for devices. This API should only be called for devices.
* For compatibility with usbfs, which enumerates from zero up, we subtract one
* from the port number.
*
* For root hubs, the last element in the chain takes the form
* usb<hub number>
* and usbfs always returns port number zero.
*
* @returns VBox status. pu8Port is set on success.
* @param pszPath The sysfs path to parse.
* @param pu8Port Where to store the port number.
*/
{
/*
* This should not be possible until we get PCs with USB as their primary bus.
* Note: We don't assert this, as we don't expect the caller to validate the
* sysfs path.
*/
if (!pszLastComp)
{
return VERR_INVALID_PARAMETER;
}
pszLastComp++; /* skip the slash */
/*
* This API should not be called for interfaces, so the last component
* of the path should not contain a colon. We *do* assert this, as it
* might indicate a caller bug.
*/
/*
* Look for the start of the last number.
*/
{
/* No -/. so it must be a root hub. Check that it's usb<something>. */
{
return VERR_INVALID_PARAMETER;
}
return VERR_NOT_SUPPORTED;
}
else
{
? pchDot + 1
: pchDash + 1;
if (rc != VINF_SUCCESS)
{
return VERR_INVALID_PARAMETER;
}
if (*pu8Port == 0)
{
return VERR_INVALID_PARAMETER;
}
/* usbfs compatibility, 0-based port number. */
*pu8Port -= 1;
}
return VINF_SUCCESS;
}
/**
* Dumps a USBDEVICE structure to the log using LogLevel 3.
* @param pDev The structure to log.
* @todo This is really common code.
*/
{
Log3(("USB device:\n"));
Log3(("Device speed: %s\n",
: "invalid"));
Log3(("Device state: %s\n",
: "invalid"));
}
/**
* In contrast to usbReadBCD() this function can handle BCD values without
* a decimal separator. This is necessary for parsing bcdDevice.
* @param pszBuf Pointer to the string buffer.
* @param pu15 Pointer to the return value.
* @returns IPRT status code.
*/
{
char *pszNext;
if ( RT_FAILURE(rc)
|| rc == VWRN_NUMBER_TOO_BIG
|| i32 < 0)
return VERR_NUMBER_TOO_BIG;
if (*pszNext == '.')
{
if (i32 > 255)
return VERR_NUMBER_TOO_BIG;
if ( RT_FAILURE(rc)
|| rc == VWRN_NUMBER_TOO_BIG
|| i32Lo > 255
|| i32Lo < 0)
return VERR_NUMBER_TOO_BIG;
}
if ( i32 > 65535
return VERR_NUMBER_TOO_BIG;
return VINF_SUCCESS;
}
#endif /* VBOX_USB_WITH_SYSFS */
/**
* USBProxyService::getDevices() implementation for sysfs.
*/
{
#ifdef VBOX_USB_WITH_SYSFS
/* Add each of the devices found to the chain. */
for (; RT_SUCCESS(rc)
{
if (!Dev)
rc = VERR_NO_MEMORY;
if (RT_SUCCESS(rc))
{
/* Fill in the simple fields */
/* Now deal with the non-numeric bits. */
* will need, and insane devices can be unsupported
* until further notice. */
/* For simplicity, we just do strcmps on the next one. */
else
else
{
if (RT_FAILURE(rc))
{
}
}
else
{
if (RT_FAILURE(rc))
}
/* Now do things that need string duplication */
{
}
{
}
{
}
/* Work out the port number */
/* Check the interfaces to see if we can support the device. */
char *pszIf;
{
pszIf);
}
/* We want a copy of the device node and sysfs paths guaranteed not to
* contain double slashes, since we use a double slash as a separator in
* the pszAddress field. */
char szDeviceClean[RTPATH_MAX];
char szSysfsClean[RTPATH_MAX];
char *pszAddress = NULL;
sizeof(szDeviceClean)))
sizeof(szSysfsClean)))
)
/* Work out from the data collected whether we can support this device. */
}
if ( RT_SUCCESS(rc)
)
{
{
}
else
}
else
}
if (RT_FAILURE(rc))
while (pFirst)
{
}
/* Eliminate any duplicates. This was originally a sanity check, but it
* turned out that hal can get confused and return devices twice. */
{
}
return pFirst;
#else /* !VBOX_USB_WITH_SYSFS */
return NULL;
#endif /* !VBOX_USB_WITH_SYSFS */
}
{
if (mUsingUsbfsDevices)
else
return pDevices;
}