USBGetDevices.cpp revision 533aa06616e58c5be91f0482c05d785427a5bca3
/* $Id$ */
/** @file
* VirtualBox Linux host USB device enumeration.
*/
/*
* 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 "USBGetDevices.h"
#include "vector.h"
#ifdef VBOX_WITH_LINUX_COMPILER_H
# include <linux/compiler.h>
#endif
#include <linux/usbdevice_fs.h>
#include <dirent.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
/*******************************************************************************
* Structures and Typedefs *
*******************************************************************************/
/** Suffix translation. */
typedef struct USBSUFF
{
char szSuff[4];
unsigned cchSuff;
unsigned uMul;
unsigned uDiv;
/** Structure describing a host USB device */
typedef struct USBDeviceInfo
{
/** The device node of the device. */
char *mDevice;
/** The system identifier of the device. Specific to the probing
* method. */
char *mSysfsPath;
/** List of interfaces as sysfs paths */
VECTOR_PTR(char *) mvecpszInterfaces;
/*******************************************************************************
* 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 */
};
/**
* "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 Utf8 and if that's not the case
* (pre-2.6.32-kernels used Latin-1, but so few devices return non-ASCII that
* this usually goes unnoticed) then we mercilessly force it to be so.
*/
{
char *psz;
if (*ppsz)
if (psz)
{
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. */
static int addDeviceToChain(PUSBDEVICE pDev, PUSBDEVICE *ppFirst, PUSBDEVICE **pppNext, const char *pcszUsbfsRoot, bool testfs, int rc)
{
/* usbDeterminState requires the address. */
if (pDevNew)
{
RTStrAPrintf((char **)&pDevNew->pszAddress, "%s/%03d/%03d", pcszUsbfsRoot, pDevNew->bBus, pDevNew->bDevNum);
if (pDevNew->pszAddress)
{
{
if (*pppNext)
else
}
else
}
else
{
rc = VERR_NO_MEMORY;
}
}
else
{
rc = VERR_NO_MEMORY;
}
return rc;
}
{
char *pszPath;
if (!pszPath)
return VERR_NO_MEMORY;
if (!pFile)
return RTErrConvertFromErrno(errno);
return VINF_SUCCESS;
}
/**
* USBProxyService::getDevices() implementation for usbfs. The @a testfs flag
* tells the function to return information about unsupported devices as well.
* This is used as a sanity test to check that a devices file is really what
* we expect.
*/
{
int rc;
if (RT_SUCCESS(rc))
{
int cHits = 0;
char szLine[1024];
/* Set close on exit and hope no one is racing us. */
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 occurrence.)
*/
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)
{
}
}
}
if (RT_FAILURE(rc))
return pFirst;
}
#ifdef VBOX_USB_WITH_SYSFS
{
}
const char *aSystemID)
{
{
return 0;
}
return 1;
}
#define USBDEVICE_MAJOR 189
/** Calculate the bus (a.k.a root hub) number of a USB device from it's sysfs
* path. sysfs nodes representing root hubs have file names of the form
* usb<n>, where n is the bus number; other devices start with that number.
* See [http://www.linux-usb.org/FAQ.html#i6] and
* equivalent information about usbfs.
* @returns a bus number greater than 0 on success or 0 on failure.
*/
static unsigned usbGetBusFromSysfsPath(const char *pcszPath)
{
if (!pcszFile)
return 0;
if ( !bus
return bus;
}
/** Calculate the device number of a USB device. See
{
AssertReturn(bus > 0, 0);
AssertReturn(device > 0, 0);
}
/**
* interface add an element for the device to @a pvecDevInfo.
*/
static int addIfDevice(const char *pcszDevicesRoot,
const char *pcszNode,
{
if (!pcszFile)
return VERR_INVALID_PARAMETER;
return VINF_SUCCESS;
if (!bus)
return VINF_SUCCESS;
if (!devnum)
return VINF_SUCCESS;
char szDevPath[RTPATH_MAX];
"%s/%.3d/%.3d",
if (cchDevPath < 0)
return VINF_SUCCESS;
&info)))
return VINF_SUCCESS;
return VERR_NO_MEMORY;
}
/** The logic for testing whether a sysfs address corresponds to an
* interface of a device. Both must be referenced by their canonical
* sysfs paths. This is not tested, as the test requires file-system
* interaction. */
{
/* If this passes, pcszIface is at least cchDev long */
return false;
/* If this passes, pcszIface is longer than cchDev */
return false;
/* In sysfs an interface is an immediate subdirectory of the device */
return false;
/* And it always has a colon in its name */
return false;
/* And hopefully we have now elimitated everything else */
return true;
}
#ifdef DEBUG
# ifdef __cplusplus
/** Unit test the logic in muiIsAnInterfaceOf in debug builds. */
class testIsAnInterfaceOf
{
public:
{
}
};
# endif /* __cplusplus */
#endif /* DEBUG */
/**
* device. To be used with getDeviceInfoFromSysfs().
*/
{
return VINF_SUCCESS;
if (pszDup)
char *, pszDup)))
return VINF_SUCCESS;
return VERR_NO_MEMORY;
}
/** Helper for readFilePaths(). Adds the entries from the open directory
* @a pDir to the vector @a pvecpchDevs using either the full path or the
* realpath() and skipping hidden files and files on which realpath() fails. */
VECTOR_PTR(char *) *pvecpchDevs)
{
{
continue;
return RTErrConvertFromErrno(errno);
return RTErrConvertFromErrno(errno);
if (!pszPath)
return VERR_NO_MEMORY;
return rc;
}
return RTErrConvertFromErrno(err);
}
/**
* Dump the names of a directory's entries into a vector of char pointers.
*
* @returns zero on success or (positive) posix error value.
* @param pcszPath the path to dump.
* @param pvecpchDevs an empty vector of char pointers - must be cleaned up
* by the caller even on failure.
* @param withRealPath whether to canonicalise the filename with realpath
*/
{
int rc;
if (!pDir)
return RTErrConvertFromErrno(errno);
return rc;
}
/**
* Logic for USBSysfsEnumerateHostDevices.
* @param pvecDevInfo vector of device information structures to add device
* information to
* @param pvecpchDevs empty scratch vector which will be freed by the caller,
* to simplify exit logic
*/
static int doSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
VECTOR_PTR(char *) *pvecpchDevs)
{
char **ppszEntry;
int rc;
if (RT_FAILURE(rc))
return rc;
pvecDevInfo)))
return rc;
return rc;
return VINF_SUCCESS;
}
static int USBSysfsEnumerateHostDevices(const char *pcszDevicesRoot,
{
VECTOR_PTR(char *) vecpchDevs;
int rc = VERR_NOT_IMPLEMENTED;
LogFlowFunc(("entered\n"));
&vecpchDevs);
return rc;
}
/**
* 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 */
{
int 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 **ppszIf;
{
*ppszIf);
}
/* We use a double slash as a separator in the pszAddress field. This is
* alright as the two paths can't contain a slash due to the way we build
* them. */
char *pszAddress = NULL;
/* Work out from the data collected whether we can support this device. */
}
/**
* USBProxyService::getDevices() implementation for sysfs.
*/
{
#ifdef VBOX_USB_WITH_SYSFS
/* Add each of the devices found to the chain. */
int rc;
if (RT_FAILURE(rc))
return NULL;
{
if (!Dev)
rc = VERR_NO_MEMORY;
if (RT_SUCCESS(rc))
{
}
if ( RT_SUCCESS(rc)
|| testfs)
)
{
{
}
else
}
else
if (RT_FAILURE(rc))
break;
}
if (RT_FAILURE(rc))
return pFirst;
#else /* !VBOX_USB_WITH_SYSFS */
return NULL;
#endif /* !VBOX_USB_WITH_SYSFS */
}
#ifdef UNIT_TEST
/* Set up mock functions for USBProxyLinuxCheckDeviceRoot - here dlsym and close
* for the inotify presence check. */
static int testInotifyInitGood(void) { return 0; }
static int testInotifyInitBad(void) { return -1; }
static bool s_fHaveInotifyLibC = true;
static bool s_fHaveInotifyKernel = true;
{
if (!s_fHaveInotifyLibC)
return NULL;
if (s_fHaveInotifyKernel)
return (void *)testInotifyInitGood;
return (void *)testInotifyInitBad;
}
{
}
# define close(a) do {} while(0)
#endif
/** Is inotify available and working on this system? This is a requirement
* for using USB with sysfs */
static bool inotifyAvailable(void)
{
int (*inotify_init)(void);
if (!inotify_init)
return false;
int fd = inotify_init();
if (fd == -1)
return false;
return true;
}
#ifdef UNIT_TEST
#endif
#ifdef UNIT_TEST
/** Unit test list of usbfs addresses of connected devices. */
static const char **s_pacszUsbfsDeviceAddresses = NULL;
{
const char **pcsz;
{
if (pNext)
{
return NULL;
}
if (pTail)
else
}
return pList;
}
# define getDevicesFromUsbfs testGetUsbfsDevices
void TestUSBSetAvailableUsbfsDevices(const char **pacszDeviceAddresses)
{
}
/** Unit test list of files reported as accessible by access(3). We only do
* accessible or not accessible. */
static const char **s_pacszAccessibleFiles = NULL;
{
const char **pcsz;
return 0;
return -1;
}
# define access testAccess
void TestUSBSetAccessibleFiles(const char **pacszAccessibleFiles)
{
}
#endif
{
bool fOK = false;
if (!fIsDeviceNodes) /* usbfs */
{
{
fOK = true;
if (pDevices)
{
fOK = false;
}
}
}
else /* device nodes */
fOK = true;
return fOK;
}
#ifdef UNIT_TEST
#endif
bool fUseSysfs)
{
if (!fUseSysfs)
return getDevicesFromUsbfs(pcszDevicesRoot, false);
else
return getDevicesFromSysfs(pcszDevicesRoot, false);
}