USBProxyService.cpp revision 98f65e540e4b270afc32507e1d95c9a99869eebc
/* $Id$ */
/** @file
* VirtualBox USB Proxy Service (base) class.
*/
/*
* Copyright (C) 2006-2007 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.
*/
#include "USBProxyService.h"
#include "HostUSBDeviceImpl.h"
#include "HostImpl.h"
#include "MachineImpl.h"
#include "VirtualBoxImpl.h"
#include "AutoCaller.h"
#include "Logging.h"
#include <iprt/semaphore.h>
#ifndef VBOX_WITH_VRDP_MEMLEAK_DETECTOR
#endif /* !VBOX_WITH_VRDP_MEMLEAK_DETECTOR */
/**
* Initialize data members.
*/
{
}
/**
* Initialize the object.
*
* Child classes should override and call this method
*
* @returns S_OK on success, or COM error status on fatal error.
*/
{
return S_OK;
}
/**
* Empty destructor.
*/
{
LogFlowThisFunc(("\n"));
mTerminate = true;
}
/**
* Query if the service is active and working.
*
* @returns true if the service is up running.
* @returns false if the service isn't running.
*/
bool USBProxyService::isActive(void)
{
return mThread != NIL_RTTHREAD;
}
/**
* Get last error.
* Can be used to check why the proxy !isActive() upon construction.
*
* @returns VBox status code.
*/
int USBProxyService::getLastError(void)
{
return mLastError;
}
/**
* Get last error message.
* Can be used to check why the proxy !isActive() upon construction as an
* extension to getLastError(). May return a NULL error.
*
* @param
* @returns VBox status code.
*/
{
return S_OK;
}
/**
* We're using the Host object lock.
*
* This is just a temporary measure until all the USB refactoring is
* done, probably... For now it help avoiding deadlocks we don't have
* time to fix.
*
* @returns Lock handle.
*/
{
return mHost->lockHandle();
}
/**
* Gets the collection of USB devices, slave of Host::USBDevices.
*
* This is an interface for the HostImpl::USBDevices property getter.
*
*
* @param aUSBDevices Where to store the pointer to the collection.
*
* @returns COM status code.
*
* @remarks The caller must own the write lock of the host object.
*/
{
return S_OK;
}
/**
* Request capture of a specific device.
*
* This is in an interface for SessionMachine::CaptureUSBDevice(), which is
* an internal worker used by Console::AttachUSBDevice() from the VM process.
*
* When the request is completed, SessionMachine::onUSBDeviceAttach() will
* be called for the given machine object.
*
*
* @param aMachine The machine to attach the device to.
* @param aId The UUID of the USB device to capture and attach.
*
* @returns COM status code and error info.
*
* @remarks This method may operate synchronously as well as asynchronously. In the
* former case it will temporarily abandon locks because of IPC.
*/
{
/*
* Translate the device id into a device object.
*/
if (pHostDevice.isNull())
return setError(E_INVALIDARG,
/*
* Try to capture the device
*/
}
/**
* Notification from VM process about USB device detaching progress.
*
* This is in an interface for SessionMachine::DetachUSBDevice(), which is
* an internal worker used by Console::DetachUSBDevice() from the VM process.
*
* @param aMachine The machine which is sending the notification.
* @param aId The UUID of the USB device is concerns.
* @param aDone \a false for the pre-action notification (necessary
* for advancing the device state to avoid confusing
* the guest).
* \a true for the post-action notification. The device
* will be subjected to all filters except those of
* of \a Machine.
*
* @returns COM status code.
*
* @remarks When \a aDone is \a true this method may end up doing IPC to other
* VMs when running filters. In these cases it will temporarily
* abandon its locks.
*/
{
LogFlowThisFunc(("aMachine=%p{%s} aId={%RTuuid} aDone=%RTbool\n",
aDone));
// get a list of all running machines while we're outside the lock
// (getOpenedMachines requests locks which are incompatible with the lock of the machines list)
/*
* Work the state machine.
*/
LogFlowThisFunc(("id={%RTuuid} state=%s aDone=%RTbool name={%s}\n",
bool fRunFilters = false;
/*
* Run filters if necessary.
*/
&& fRunFilters)
{
Assert(aDone && pHostDevice->getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->getMachine().isNull());
}
return hrc;
}
/**
* Apply filters for the machine to all eligible USB devices.
*
* This is in an interface for SessionMachine::CaptureUSBDevice(), which
* is an internal worker used by Console::AutoCaptureUSBDevices() from the
* VM process at VM startup.
*
* Matching devices will be attached to the VM and may result IPC back
* to the VM process via SessionMachine::onUSBDeviceAttach() depending
* on whether the device needs to be captured or not. If capture is
* required, SessionMachine::onUSBDeviceAttach() will be called
* asynchronously by the USB proxy service thread.
*
* @param aMachine The machine to capture devices for.
*
* @returns COM status code, perhaps with error info.
*
* @remarks Write locks the host object and may temporarily abandon
* its locks to perform IPC.
*/
{
LogFlowThisFunc(("aMachine=%p{%s}\n",
/*
* Make a copy of the list because we might have to exit and
* re-enter the lock protecting it. (This will not make copies
* of any HostUSBDevice objects, only reference them.)
*/
++it)
{
}
return S_OK;
}
/**
* Detach all USB devices currently attached to a VM.
*
* This is in an interface for SessionMachine::DetachAllUSBDevices(), which
* is an internal worker used by Console::powerDown() from the VM process
* at VM startup, and SessionMachine::uninit() at VM abend.
*
* This is, like #detachDeviceFromVM(), normally a two stage journey
* where \a aDone indicates where we are. In addition we may be called
* to clean up VMs that have abended, in which case there will be no
* preparatory call. Filters will be applied to the devices in the final
* call with the risk that we have to do some IPC when attaching them
* to other VMs.
*
* @param aMachine The machine to detach devices from.
*
* @returns COM status code, perhaps with error info.
*
* @remarks Write locks the host object and may temporarily abandon
* its locks to perform IPC.
*/
HRESULT USBProxyService::detachAllDevicesFromVM(SessionMachine *aMachine, bool aDone, bool aAbnormal)
{
// get a list of all running machines while we're outside the lock
// (getOpenedMachines requests locks which are incompatible with the lock of the machines list)
/*
* Make a copy of the device list (not the HostUSBDevice objects, just
* the list) since we may end up performing IPC and temporarily have
* to abandon locks when applying filters.
*/
++It)
{
{
/*
* Same procedure as in detachUSBDevice().
*/
bool fRunFilters = false;
&& fRunFilters)
{
Assert(aDone && pHostDevice->getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->getMachine().isNull());
}
}
}
return S_OK;
}
/**
* Runs all the filters on the specified device.
*
* All filters mean global and active VM, with the exception of those
* belonging to \a aMachine. If a global ignore filter matched or if
* none of the filters matched, the device will be released back to
* the host.
*
* The device calling us here will be in the HeldByProxy, Unused, or
* Capturable state. The caller is aware that locks held might have
* to be abandond because of IPC and that the device might be in
* almost any state upon return.
*
*
* @returns COM status code (only parameter & state checks will fail).
* @param aDevice The USB device to apply filters to.
* @param aIgnoreMachine The machine to ignore filters from (we've just
* detached the device from this machine).
*
* @note The caller is expected to own both the device and Host write locks,
* and be prepared that these locks may be abandond temporarily.
*/
{
/*
* Verify preconditions.
*/
AssertMsgReturn(aDevice->isCapturableOrHeld(), ("{%s} %s\n", aDevice->getName().c_str(), aDevice->getStateName()), E_FAIL);
/*
* Get the lists we'll iterate.
*/
/*
* Run global filters filerts first.
*/
bool fHoldIt = false;
++it)
{
{
if (action == USBDeviceFilterAction_Ignore)
{
/*
* Release the device to the host and we're done.
*/
return S_OK;
}
if (action == USBDeviceFilterAction_Hold)
{
/*
* A device held by the proxy needs to be subjected
* to the machine filters.
*/
fHoldIt = true;
break;
}
}
}
/*
* Run the per-machine filters.
*/
++it)
{
/* Skip the machine the device was just detached from. */
if ( aIgnoreMachine
&& pMachine == aIgnoreMachine)
continue;
/* runMachineFilters takes care of checking the machine state. */
{
return S_OK;
}
}
/*
* No matching machine, so request hold or release depending
* on global filter match.
*/
if (fHoldIt)
aDevice->requestHold();
else
return S_OK;
}
/**
* Runs the USB filters of the machine on the device.
*
* If a match is found we will request capture for VM. This may cause
* us to temporary abandon locks while doing IPC.
*
* @param aMachine Machine whose filters are to be run.
* @param aDevice The USB device in question.
* @returns @c true if the device has been or is being attached to the VM, @c false otherwise.
*
* @note Caller must own the USB and device locks for writing.
* @note Locks aMachine for reading.
*/
bool USBProxyService::runMachineFilters(SessionMachine *aMachine, ComObjPtr<HostUSBDevice> &aDevice)
{
/*
* Validate preconditions.
*/
AssertReturn(aMachine, false);
AssertReturn(isWriteLockOnCurrentThread(), false);
/* Let HostUSBDevice::requestCaptureToVM() validate the state. */
/*
* Do the job.
*/
{
/* try to capture the device */
}
return false;
}
/**
* A filter was inserted / loaded.
*
* @param aFilter Pointer to the inserted filter.
* @return ID of the inserted filter
*/
{
// return non-NULL to fake success.
return (void *)1;
}
/**
* A filter was removed.
*
* @param aId ID of the filter to remove
*/
{
}
/**
* A VM is trying to capture a device, do necessary preperations.
*
* @returns VBox status code.
* @param aDevice The device in question.
*/
{
return VERR_NOT_IMPLEMENTED;
}
/**
* Notification that an async captureDevice() operation completed.
*
* This is used by the proxy to release temporary filters.
*
* @returns VBox status code.
* @param aDevice The device in question.
* @param aSuccess Whether it succeeded or failed.
*/
{
}
/**
* The device is going to be detached from a VM.
*
* @param aDevice The device in question.
*/
{
}
/**
* A VM is releasing a device back to the host.
*
* @returns VBox status code.
* @param aDevice The device in question.
*/
{
return VERR_NOT_IMPLEMENTED;
}
/**
* Notification that an async releaseDevice() operation completed.
*
* This is used by the proxy to release temporary filters.
*
* @returns VBox status code.
* @param aDevice The device in question.
* @param aSuccess Whether it succeeded or failed.
*/
{
}
// Internals
/////////////////////////////////////////////////////////////////////////////
/**
* Starts the service.
*
* @returns VBox status.
*/
int USBProxyService::start(void)
{
int rc = VINF_SUCCESS;
if (mThread == NIL_RTTHREAD)
{
/*
* Force update before starting the poller thread.
*/
{
/*
* Create the poller thread which will look for changes.
*/
mTerminate = false;
if (RT_SUCCESS(rc))
else
}
mLastError = rc;
}
else
return rc;
}
/**
* Stops the service.
*
* @returns VBox status.
*/
int USBProxyService::stop(void)
{
int rc = VINF_SUCCESS;
if (mThread != NIL_RTTHREAD)
{
/*
* Mark the thread for termination and kick it.
*/
ASMAtomicXchgSize(&mTerminate, true);
rc = interruptWait();
/*
* Wait for the thread to finish and then update the state.
*/
if (rc == VERR_INVALID_HANDLE)
rc = VINF_SUCCESS;
if (RT_SUCCESS(rc))
{
mTerminate = false;
}
else
{
mLastError = rc;
}
}
else
LogFlowThisFunc(("not active\n"));
return rc;
}
/**
* The service thread created by start().
*
* @param Thread The thread handle.
* @param pvUser Pointer to the USBProxyService instance.
*/
{
int rc = VINF_SUCCESS;
/*
* Processing loop.
*/
for (;;)
{
break;
if (pThis->mTerminate)
break;
pThis->processChanges();
}
return rc;
}
/**
* First call made on the service thread, use it to do
* thread initialization.
*
* The default implementation in USBProxyService just a dummy stub.
*/
void USBProxyService::serviceThreadInit(void)
{
}
/**
* Last call made on the service thread, use it to do
* thread termination.
*/
void USBProxyService::serviceThreadTerm(void)
{
}
/**
* Wait for a change in the USB devices attached to the host.
*
* The default implementation in USBProxyService just a dummy stub.
*
* @returns VBox status code. VERR_INTERRUPTED and VERR_TIMEOUT are considered
* harmless, while all other error status are fatal.
* @param aMillies Number of milliseconds to wait.
*/
{
}
/**
* Interrupt any wait() call in progress.
*
* The default implementation in USBProxyService just a dummy stub.
*
* @returns VBox status.
*/
int USBProxyService::interruptWait(void)
{
return VERR_NOT_IMPLEMENTED;
}
/**
* Sort a list of USB devices.
*
* @returns Pointer to the head of the sorted doubly linked list.
* @param aDevices Head pointer (can be both singly and doubly linked list).
*/
{
while (pDevices)
{
/* unlink head */
if (pDevices)
/* find location. */
while ( pCur
/* insert (after pCur) */
if (pCur)
{
else
}
else
{
if (pHead)
else
}
}
return pHead;
}
/**
* Process any relevant changes in the attached USB devices.
*
* Except for the first call, this is always running on the service thread.
*/
void USBProxyService::processChanges(void)
{
LogFlowThisFunc(("\n"));
/*
* Get the sorted list of USB devices.
*/
// get a list of all running machines while we're outside the lock
// (getOpenedMachines requests locks which are incompatible with the lock of the machines list)
/*
* Compare previous list with the previous list of devices
* and merge in any changes while notifying Host.
*/
|| pDevices)
{
pHostDevice = *It;
/*
* Assert that the object is still alive (we still reference it in
* the collection and we're the only one who calls uninit() on it.
*/
/*
* properties. All Host callbacks also imply the object is locked.
*/
/*
* Compare.
*/
int iDiff;
if (pHostDevice.isNull())
iDiff = 1;
else
{
if (!pDevices)
iDiff = -1;
else
}
if (!iDiff)
{
/*
* The device still there, update the state and move on. The PUSBDEVICE
* structure is eaten by updateDeviceState / HostUSBDevice::updateState().
*/
bool fRunFilters = false;
It++;
}
else
{
if (iDiff > 0)
{
/*
* Head of pDevices was attached.
*/
Log(("USBProxyService::processChanges: attached %p {%s} %s / %p:{.idVendor=%#06x, .idProduct=%#06x, .pszProduct=\"%s\", .pszManufacturer=\"%s\"}\n",
(HostUSBDevice *)NewObj,
NewObj->getStateName(),
pNew,
pNew->pszManufacturer));
/* Not really necessary to lock here, but make Assert checks happy. */
}
else
{
/*
* Check if the device was actually detached or logically detached
* as the result of a re-enumeration.
*/
if (!pHostDevice->wasActuallyDetached())
It++;
else
{
Log(("USBProxyService::processChanges: detached %p {%s}\n",
/* from now on, the object is no more valid,
* uninitialize to avoid abuse */
pHostDevice->uninit();
}
}
}
} /* while */
LogFlowThisFunc(("returns void\n"));
}
/**
* Get a list of USB device currently attached to the host.
*
* The default implementation in USBProxyService just a dummy stub.
*
* @returns Pointer to a list of USB devices.
* The list nodes are freed individually by calling freeDevice().
*/
{
return NULL;
}
/**
* Performs the required actions when a device has been added.
*
* This means things like running filters and subsequent capturing and
* VM attaching. This may result in IPC and temporary lock abandonment.
*
* @param aDevice The device in question.
* @param aUSBDevice The USB device structure.
*/
{
/*
* Validate preconditions.
*/
LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
(HostUSBDevice *)aDevice,
aDevice->getStateName(),
/*
* Run filters on the device.
*/
if (aDevice->isCapturableOrHeld())
{
}
}
/**
* Remove device notification hook for the OS specific code.
*
* This is means things like
*
* @param aDevice The device in question.
*/
{
/*
* Validate preconditions.
*/
LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
(HostUSBDevice *)aDevice,
aDevice->getStateName(),
/*
* Detach the device from any machine currently using it,
* reset all data and uninitialize the device object.
*/
}
/**
* Implement fake capture, ++.
*
* @returns true if there is a state change.
* @param pDevice The device in question.
* @param pUSBDevice The USB device structure for the last enumeration.
* @param aRunFilters Whether or not to run filters.
*/
bool USBProxyService::updateDeviceStateFake(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
{
*aRunFilters = false;
*aIgnoreMachine = NULL;
AssertReturn(aDevice, false);
/*
* Just hand it to the device, it knows best what needs to be done.
*/
}
/**
* Updates the device state.
*
* This is responsible for calling HostUSBDevice::updateState().
*
* @returns true if there is a state change.
* @param aDevice The device in question.
* @param aUSBDevice The USB device structure for the last enumeration.
* @param aRunFilters Whether or not to run filters.
* @param aIgnoreMachine Machine to ignore when running filters.
*/
bool USBProxyService::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
{
AssertReturn(aDevice, false);
}
/**
* Handle a device which state changed in some siginificant way.
*
* This means things like running filters and subsequent capturing and
* VM attaching. This may result in IPC and temporary lock abandonment.
*
* @param aDevice The device.
* @param pllOpenedMachines list of running session machines (VirtualBox::getOpenedMachines()); if NULL, we don't run filters
* @param aIgnoreMachine Machine to ignore when running filters.
*/
void USBProxyService::deviceChanged(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList *pllOpenedMachines, SessionMachine *aIgnoreMachine)
{
/*
* Validate preconditions.
*/
LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid} aRunFilters=%RTbool aIgnoreMachine=%p\n",
(HostUSBDevice *)aDevice,
aDevice->getStateName(),
/*
* Run filters if requested to do so.
*/
if (pllOpenedMachines)
{
}
}
/**
* Free all the members of a USB device returned by getDevice().
*
* @param pDevice Pointer to the device.
*/
/*static*/ void
{
#ifdef RT_OS_WINDOWS
#elif defined(RT_OS_SOLARIS)
#endif
}
/**
* Free one USB device returned by getDevice().
*
* @param pDevice Pointer to the device.
*/
/*static*/ void
{
}
/**
* Initializes a filter with the data from the specified device.
*
* @param aFilter The filter to fill.
* @param aDevice The device to fill it with.
*/
/*static*/ void
{
int vrc;
vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_CLASS, pDev->bDeviceClass, true); AssertRC(vrc);
vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_SUB_CLASS, pDev->bDeviceSubClass, true); AssertRC(vrc);
vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_PROTOCOL, pDev->bDeviceProtocol, true); AssertRC(vrc);
if (pDev->pszSerialNumber)
{
vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_SERIAL_NUMBER_STR, pDev->pszSerialNumber, true);
}
if (pDev->pszProduct)
{
}
if (pDev->pszManufacturer)
{
}
}
/**
* Searches the list of devices (mDevices) for the given device.
*
*
* @returns Smart pointer to the device on success, NULL otherwise.
* @param aId The UUID of the device we're looking for.
*/
{
++It)
{
break;
}
return Dev;
}
/*static*/
{
"USBProxyService",
false /* aWarning*/,
true /* aLogIt*/);
return rc;
}
/* vi: set tabstop=4 shiftwidth=4 expandtab: */