VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/USBProxyService.cpp@ 65088

Last change on this file since 65088 was 65088, checked in by vboxsync, 8 years ago

Main: doxygen fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 30.5 KB
Line 
1/* $Id: USBProxyService.cpp 65088 2017-01-03 20:52:49Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Service (base) class.
4 */
5
6/*
7 * Copyright (C) 2006-2016 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#include "USBProxyService.h"
19#include "HostUSBDeviceImpl.h"
20#include "HostImpl.h"
21#include "MachineImpl.h"
22#include "VirtualBoxImpl.h"
23
24#include "AutoCaller.h"
25#include "Logging.h"
26
27#include <VBox/com/array.h>
28#include <VBox/err.h>
29#include <iprt/asm.h>
30#include <iprt/semaphore.h>
31#include <iprt/thread.h>
32#include <iprt/mem.h>
33#include <iprt/string.h>
34
35/** Pair of a USB proxy backend and the opaque filter data assigned by the backend. */
36typedef std::pair<ComObjPtr<USBProxyBackend> , void *> USBFilterPair;
37/** List of USB filter pairs. */
38typedef std::list<USBFilterPair> USBFilterList;
39
40/**
41 * Data for a USB device filter.
42 */
43struct USBFilterData
44{
45 USBFilterData()
46 : llUsbFilters()
47 { }
48
49 USBFilterList llUsbFilters;
50};
51
52/**
53 * Initialize data members.
54 */
55USBProxyService::USBProxyService(Host *aHost)
56 : mHost(aHost), mDevices(), mBackends()
57{
58 LogFlowThisFunc(("aHost=%p\n", aHost));
59}
60
61
62/**
63 * Stub needed as long as the class isn't virtual
64 */
65HRESULT USBProxyService::init(void)
66{
67# if defined(RT_OS_DARWIN)
68 ComObjPtr<USBProxyBackendDarwin> UsbProxyBackendHost;
69# elif defined(RT_OS_LINUX)
70 ComObjPtr<USBProxyBackendLinux> UsbProxyBackendHost;
71# elif defined(RT_OS_OS2)
72 ComObjPtr<USBProxyBackendOs2> UsbProxyBackendHost;
73# elif defined(RT_OS_SOLARIS)
74 ComObjPtr<USBProxyBackendSolaris> UsbProxyBackendHost;
75# elif defined(RT_OS_WINDOWS)
76 ComObjPtr<USBProxyBackendWindows> UsbProxyBackendHost;
77# elif defined(RT_OS_FREEBSD)
78 ComObjPtr<USBProxyBackendFreeBSD> UsbProxyBackendHost;
79# else
80 ComObjPtr<USBProxyBackend> UsbProxyBackendHost;
81# endif
82 UsbProxyBackendHost.createObject();
83 int vrc = UsbProxyBackendHost->init(this, Utf8Str("host"), Utf8Str(""));
84 if (RT_FAILURE(vrc))
85 {
86 mLastError = vrc;
87 }
88 else
89 mBackends.push_back(static_cast<ComObjPtr<USBProxyBackend> >(UsbProxyBackendHost));
90
91 return S_OK;
92}
93
94
95/**
96 * Empty destructor.
97 */
98USBProxyService::~USBProxyService()
99{
100 LogFlowThisFunc(("\n"));
101 while (!mBackends.empty())
102 mBackends.pop_front();
103
104 mDevices.clear();
105 mBackends.clear();
106 mHost = NULL;
107}
108
109
110/**
111 * Query if the service is active and working.
112 *
113 * @returns true if the service is up running.
114 * @returns false if the service isn't running.
115 */
116bool USBProxyService::isActive(void)
117{
118 return mBackends.size() > 0;
119}
120
121
122/**
123 * Get last error.
124 * Can be used to check why the proxy !isActive() upon construction.
125 *
126 * @returns VBox status code.
127 */
128int USBProxyService::getLastError(void)
129{
130 return mLastError;
131}
132
133
134/**
135 * We're using the Host object lock.
136 *
137 * This is just a temporary measure until all the USB refactoring is
138 * done, probably... For now it help avoiding deadlocks we don't have
139 * time to fix.
140 *
141 * @returns Lock handle.
142 */
143RWLockHandle *USBProxyService::lockHandle() const
144{
145 return mHost->lockHandle();
146}
147
148
149void *USBProxyService::insertFilter(PCUSBFILTER aFilter)
150{
151 USBFilterData *pFilterData = new USBFilterData();
152
153 for (USBProxyBackendList::iterator it = mBackends.begin();
154 it != mBackends.end();
155 ++it)
156 {
157 ComObjPtr<USBProxyBackend> pUsbProxyBackend = *it;
158 void *pvId = pUsbProxyBackend->insertFilter(aFilter);
159
160 pFilterData->llUsbFilters.push_back(USBFilterPair(pUsbProxyBackend, pvId));
161 }
162
163 return pFilterData;
164}
165
166void USBProxyService::removeFilter(void *aId)
167{
168 USBFilterData *pFilterData = (USBFilterData *)aId;
169
170 for (USBFilterList::iterator it = pFilterData->llUsbFilters.begin();
171 it != pFilterData->llUsbFilters.end();
172 ++it)
173 {
174 ComObjPtr<USBProxyBackend> pUsbProxyBackend = it->first;
175 pUsbProxyBackend->removeFilter(it->second);
176 }
177
178 pFilterData->llUsbFilters.clear();
179 delete pFilterData;
180}
181
182/**
183 * Gets the collection of USB devices, slave of Host::USBDevices.
184 *
185 * This is an interface for the HostImpl::USBDevices property getter.
186 *
187 *
188 * @param aUSBDevices Where to store the pointer to the collection.
189 *
190 * @returns COM status code.
191 *
192 * @remarks The caller must own the write lock of the host object.
193 */
194HRESULT USBProxyService::getDeviceCollection(std::vector<ComPtr<IHostUSBDevice> > &aUSBDevices)
195{
196 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
197
198 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
199
200 aUSBDevices.resize(mDevices.size());
201 size_t i = 0;
202 for (HostUSBDeviceList::const_iterator it = mDevices.begin(); it != mDevices.end(); ++it, ++i)
203 aUSBDevices[i] = *it;
204
205 return S_OK;
206}
207
208
209HRESULT USBProxyService::addUSBDeviceSource(const com::Utf8Str &aBackend, const com::Utf8Str &aId, const com::Utf8Str &aAddress,
210 const std::vector<com::Utf8Str> &aPropertyNames, const std::vector<com::Utf8Str> &aPropertyValues)
211{
212 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
213
214 HRESULT hrc = createUSBDeviceSource(aBackend, aId, aAddress, aPropertyNames, aPropertyValues);
215 if (SUCCEEDED(hrc))
216 {
217 alock.release();
218 AutoWriteLock vboxLock(mHost->i_parent() COMMA_LOCKVAL_SRC_POS);
219 return mHost->i_parent()->i_saveSettings();
220 }
221
222 return hrc;
223}
224
225HRESULT USBProxyService::removeUSBDeviceSource(const com::Utf8Str &aId)
226{
227 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
228
229 for (USBProxyBackendList::iterator it = mBackends.begin();
230 it != mBackends.end();
231 ++it)
232 {
233 ComObjPtr<USBProxyBackend> UsbProxyBackend = *it;
234
235 if (aId.equals(UsbProxyBackend->i_getId()))
236 {
237 mBackends.erase(it);
238
239 /*
240 * The proxy backend uninit method will be called when the pointer goes
241 * out of scope.
242 */
243
244 alock.release();
245 AutoWriteLock vboxLock(mHost->i_parent() COMMA_LOCKVAL_SRC_POS);
246 return mHost->i_parent()->i_saveSettings();
247 }
248 }
249
250 return setError(VBOX_E_OBJECT_NOT_FOUND,
251 tr("The USB device source \"%s\" could not be found"), aId.c_str());
252}
253
254/**
255 * Request capture of a specific device.
256 *
257 * This is in an interface for SessionMachine::CaptureUSBDevice(), which is
258 * an internal worker used by Console::AttachUSBDevice() from the VM process.
259 *
260 * When the request is completed, SessionMachine::onUSBDeviceAttach() will
261 * be called for the given machine object.
262 *
263 *
264 * @param aMachine The machine to attach the device to.
265 * @param aId The UUID of the USB device to capture and attach.
266 * @param aCaptureFilename
267 *
268 * @returns COM status code and error info.
269 *
270 * @remarks This method may operate synchronously as well as asynchronously. In the
271 * former case it will temporarily abandon locks because of IPC.
272 */
273HRESULT USBProxyService::captureDeviceForVM(SessionMachine *aMachine, IN_GUID aId, const com::Utf8Str &aCaptureFilename)
274{
275 ComAssertRet(aMachine, E_INVALIDARG);
276 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
277
278 /*
279 * Translate the device id into a device object.
280 */
281 ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId);
282 if (pHostDevice.isNull())
283 return setError(E_INVALIDARG,
284 tr("The USB device with UUID {%RTuuid} is not currently attached to the host"), Guid(aId).raw());
285
286 /*
287 * Try to capture the device
288 */
289 alock.release();
290 return pHostDevice->i_requestCaptureForVM(aMachine, true /* aSetError */, aCaptureFilename);
291}
292
293
294/**
295 * Notification from VM process about USB device detaching progress.
296 *
297 * This is in an interface for SessionMachine::DetachUSBDevice(), which is
298 * an internal worker used by Console::DetachUSBDevice() from the VM process.
299 *
300 * @param aMachine The machine which is sending the notification.
301 * @param aId The UUID of the USB device is concerns.
302 * @param aDone \a false for the pre-action notification (necessary
303 * for advancing the device state to avoid confusing
304 * the guest).
305 * \a true for the post-action notification. The device
306 * will be subjected to all filters except those of
307 * of \a Machine.
308 *
309 * @returns COM status code.
310 *
311 * @remarks When \a aDone is \a true this method may end up doing IPC to other
312 * VMs when running filters. In these cases it will temporarily
313 * abandon its locks.
314 */
315HRESULT USBProxyService::detachDeviceFromVM(SessionMachine *aMachine, IN_GUID aId, bool aDone)
316{
317 LogFlowThisFunc(("aMachine=%p{%s} aId={%RTuuid} aDone=%RTbool\n",
318 aMachine,
319 aMachine->i_getName().c_str(),
320 Guid(aId).raw(),
321 aDone));
322
323 // get a list of all running machines while we're outside the lock
324 // (getOpenedMachines requests locks which are incompatible with the lock of the machines list)
325 SessionMachinesList llOpenedMachines;
326 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
327
328 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
329
330 ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId);
331 ComAssertRet(!pHostDevice.isNull(), E_FAIL);
332 AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
333
334 /*
335 * Work the state machine.
336 */
337 LogFlowThisFunc(("id={%RTuuid} state=%s aDone=%RTbool name={%s}\n",
338 pHostDevice->i_getId().raw(), pHostDevice->i_getStateName(), aDone, pHostDevice->i_getName().c_str()));
339 bool fRunFilters = false;
340 HRESULT hrc = pHostDevice->i_onDetachFromVM(aMachine, aDone, &fRunFilters);
341
342 /*
343 * Run filters if necessary.
344 */
345 if ( SUCCEEDED(hrc)
346 && fRunFilters)
347 {
348 Assert(aDone && pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->i_getMachine().isNull());
349 devLock.release();
350 alock.release();
351 HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine);
352 ComAssertComRC(hrc2);
353 }
354 return hrc;
355}
356
357
358/**
359 * Apply filters for the machine to all eligible USB devices.
360 *
361 * This is in an interface for SessionMachine::CaptureUSBDevice(), which
362 * is an internal worker used by Console::AutoCaptureUSBDevices() from the
363 * VM process at VM startup.
364 *
365 * Matching devices will be attached to the VM and may result IPC back
366 * to the VM process via SessionMachine::onUSBDeviceAttach() depending
367 * on whether the device needs to be captured or not. If capture is
368 * required, SessionMachine::onUSBDeviceAttach() will be called
369 * asynchronously by the USB proxy service thread.
370 *
371 * @param aMachine The machine to capture devices for.
372 *
373 * @returns COM status code, perhaps with error info.
374 *
375 * @remarks Temporarily locks this object, the machine object and some USB
376 * device, and the called methods will lock similar objects.
377 */
378HRESULT USBProxyService::autoCaptureDevicesForVM(SessionMachine *aMachine)
379{
380 LogFlowThisFunc(("aMachine=%p{%s}\n",
381 aMachine,
382 aMachine->i_getName().c_str()));
383
384 /*
385 * Make a copy of the list because we cannot hold the lock protecting it.
386 * (This will not make copies of any HostUSBDevice objects, only reference them.)
387 */
388 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
389 HostUSBDeviceList ListCopy = mDevices;
390 alock.release();
391
392 for (HostUSBDeviceList::iterator it = ListCopy.begin();
393 it != ListCopy.end();
394 ++it)
395 {
396 ComObjPtr<HostUSBDevice> pHostDevice = *it;
397 AutoReadLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
398 if ( pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy
399 || pHostDevice->i_getUnistate() == kHostUSBDeviceState_Unused
400 || pHostDevice->i_getUnistate() == kHostUSBDeviceState_Capturable)
401 {
402 devLock.release();
403 runMachineFilters(aMachine, pHostDevice);
404 }
405 }
406
407 return S_OK;
408}
409
410
411/**
412 * Detach all USB devices currently attached to a VM.
413 *
414 * This is in an interface for SessionMachine::DetachAllUSBDevices(), which
415 * is an internal worker used by Console::powerDown() from the VM process
416 * at VM startup, and SessionMachine::uninit() at VM abend.
417 *
418 * This is, like #detachDeviceFromVM(), normally a two stage journey
419 * where \a aDone indicates where we are. In addition we may be called
420 * to clean up VMs that have abended, in which case there will be no
421 * preparatory call. Filters will be applied to the devices in the final
422 * call with the risk that we have to do some IPC when attaching them
423 * to other VMs.
424 *
425 * @param aMachine The machine to detach devices from.
426 * @param aDone
427 * @param aAbnormal
428 *
429 * @returns COM status code, perhaps with error info.
430 *
431 * @remarks Write locks the host object and may temporarily abandon
432 * its locks to perform IPC.
433 */
434HRESULT USBProxyService::detachAllDevicesFromVM(SessionMachine *aMachine, bool aDone, bool aAbnormal)
435{
436 // get a list of all running machines while we're outside the lock
437 // (getOpenedMachines requests locks which are incompatible with the host object lock)
438 SessionMachinesList llOpenedMachines;
439 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
440
441 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
442
443 /*
444 * Make a copy of the device list (not the HostUSBDevice objects, just
445 * the list) since we may end up performing IPC and temporarily have
446 * to abandon locks when applying filters.
447 */
448 HostUSBDeviceList ListCopy = mDevices;
449
450 for (HostUSBDeviceList::iterator it = ListCopy.begin();
451 it != ListCopy.end();
452 ++it)
453 {
454 ComObjPtr<HostUSBDevice> pHostDevice = *it;
455 AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
456 if (pHostDevice->i_getMachine() == aMachine)
457 {
458 /*
459 * Same procedure as in detachUSBDevice().
460 */
461 bool fRunFilters = false;
462 HRESULT hrc = pHostDevice->i_onDetachFromVM(aMachine, aDone, &fRunFilters, aAbnormal);
463 if ( SUCCEEDED(hrc)
464 && fRunFilters)
465 {
466 Assert( aDone
467 && pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy
468 && pHostDevice->i_getMachine().isNull());
469 devLock.release();
470 alock.release();
471 HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine);
472 ComAssertComRC(hrc2);
473 alock.acquire();
474 }
475 }
476 }
477
478 return S_OK;
479}
480
481
482// Internals
483/////////////////////////////////////////////////////////////////////////////
484
485
486/**
487 * Loads the given settings and constructs the additional USB device sources.
488 *
489 * @returns COM status code.
490 * @param llUSBDeviceSources The list of additional device sources.
491 */
492HRESULT USBProxyService::i_loadSettings(const settings::USBDeviceSourcesList &llUSBDeviceSources)
493{
494 HRESULT hrc = S_OK;
495
496 for (settings::USBDeviceSourcesList::const_iterator it = llUSBDeviceSources.begin();
497 it != llUSBDeviceSources.end() && SUCCEEDED(hrc);
498 ++it)
499 {
500 std::vector<com::Utf8Str> vecPropNames, vecPropValues;
501 const settings::USBDeviceSource &src = *it;
502 hrc = createUSBDeviceSource(src.strBackend, src.strName, src.strAddress, vecPropNames, vecPropValues);
503 }
504
505 return hrc;
506}
507
508/**
509 * Saves the additional device sources in the given settings.
510 *
511 * @returns COM status code.
512 * @param llUSBDeviceSources The list of additional device sources.
513 */
514HRESULT USBProxyService::i_saveSettings(settings::USBDeviceSourcesList &llUSBDeviceSources)
515{
516 for (USBProxyBackendList::iterator it = mBackends.begin();
517 it != mBackends.end();
518 ++it)
519 {
520 USBProxyBackend *pUsbProxyBackend = *it;
521
522 /* Host backends are not saved as they are always created during startup. */
523 if (!pUsbProxyBackend->i_getBackend().equals("host"))
524 {
525 settings::USBDeviceSource src;
526
527 src.strBackend = pUsbProxyBackend->i_getBackend();
528 src.strName = pUsbProxyBackend->i_getId();
529 src.strAddress = pUsbProxyBackend->i_getAddress();
530
531 llUSBDeviceSources.push_back(src);
532 }
533 }
534
535 return S_OK;
536}
537
538/**
539 * Performs the required actions when a device has been added.
540 *
541 * This means things like running filters and subsequent capturing and
542 * VM attaching. This may result in IPC and temporary lock abandonment.
543 *
544 * @param aDevice The device in question.
545 * @param aUSBDevice The USB device structure.
546 */
547void USBProxyService::i_deviceAdded(ComObjPtr<HostUSBDevice> &aDevice,
548 PUSBDEVICE pDev)
549{
550 /*
551 * Validate preconditions.
552 */
553 AssertReturnVoid(!isWriteLockOnCurrentThread());
554 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
555 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
556 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
557 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
558 (HostUSBDevice *)aDevice,
559 aDevice->i_getName().c_str(),
560 aDevice->i_getStateName(),
561 aDevice->i_getId().raw()));
562
563 /* Add to our list. */
564 HostUSBDeviceList::iterator it = mDevices.begin();
565 while (it != mDevices.end())
566 {
567 ComObjPtr<HostUSBDevice> pHostDevice = *it;
568
569 /* Assert that the object is still alive. */
570 AutoCaller devCaller(pHostDevice);
571 AssertComRC(devCaller.rc());
572
573 AutoWriteLock curLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
574 if ( pHostDevice->i_getUsbProxyBackend() == aDevice->i_getUsbProxyBackend()
575 && pHostDevice->i_compare(pDev) < 0)
576 break;
577
578 it++;
579 }
580
581 mDevices.insert(it, aDevice);
582
583 /*
584 * Run filters on the device.
585 */
586 if (aDevice->i_isCapturableOrHeld())
587 {
588 devLock.release();
589 alock.release();
590 SessionMachinesList llOpenedMachines;
591 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
592 HRESULT rc = runAllFiltersOnDevice(aDevice, llOpenedMachines, NULL /* aIgnoreMachine */);
593 AssertComRC(rc);
594 }
595}
596
597/**
598 * Remove device notification hook for the USB proxy service.
599 *
600 * @param aDevice The device in question.
601 */
602void USBProxyService::i_deviceRemoved(ComObjPtr<HostUSBDevice> &aDevice)
603{
604 /*
605 * Validate preconditions.
606 */
607 AssertReturnVoid(!isWriteLockOnCurrentThread());
608 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
609 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
610 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
611 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
612 (HostUSBDevice *)aDevice,
613 aDevice->i_getName().c_str(),
614 aDevice->i_getStateName(),
615 aDevice->i_getId().raw()));
616
617 mDevices.remove(aDevice);
618
619 /*
620 * Detach the device from any machine currently using it,
621 * reset all data and uninitialize the device object.
622 */
623 devLock.release();
624 alock.release();
625 aDevice->i_onPhysicalDetached();
626}
627
628/**
629 * Updates the device state.
630 *
631 * This is responsible for calling HostUSBDevice::updateState().
632 *
633 * @returns true if there is a state change.
634 * @param aDevice The device in question.
635 * @param aUSBDevice The USB device structure for the last enumeration.
636 * @param fFakeUpdate Flag whether to fake updating state.
637 */
638void USBProxyService::i_updateDeviceState(ComObjPtr<HostUSBDevice> &aDevice, PUSBDEVICE aUSBDevice, bool fFakeUpdate)
639{
640 AssertReturnVoid(aDevice);
641 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
642
643 bool fRunFilters = false;
644 SessionMachine *pIgnoreMachine = NULL;
645 bool fDevChanged = false;
646 if (fFakeUpdate)
647 fDevChanged = aDevice->i_updateStateFake(aUSBDevice, &fRunFilters, &pIgnoreMachine);
648 else
649 fDevChanged = aDevice->i_updateState(aUSBDevice, &fRunFilters, &pIgnoreMachine);
650
651 if (fDevChanged)
652 deviceChanged(aDevice, fRunFilters, pIgnoreMachine);
653}
654
655
656/**
657 * Handle a device which state changed in some significant way.
658 *
659 * This means things like running filters and subsequent capturing and
660 * VM attaching. This may result in IPC and temporary lock abandonment.
661 *
662 * @param aDevice The device.
663 * @param fRunFilters Flag whether to run filters.
664 * @param aIgnoreMachine Machine to ignore when running filters.
665 */
666void USBProxyService::deviceChanged(ComObjPtr<HostUSBDevice> &aDevice, bool fRunFilters,
667 SessionMachine *aIgnoreMachine)
668{
669 /*
670 * Validate preconditions.
671 */
672 AssertReturnVoid(!isWriteLockOnCurrentThread());
673 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
674 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
675 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid} aRunFilters=%RTbool aIgnoreMachine=%p\n",
676 (HostUSBDevice *)aDevice,
677 aDevice->i_getName().c_str(),
678 aDevice->i_getStateName(),
679 aDevice->i_getId().raw(),
680 fRunFilters,
681 aIgnoreMachine));
682 devLock.release();
683
684 /*
685 * Run filters if requested to do so.
686 */
687 if (fRunFilters)
688 {
689 SessionMachinesList llOpenedMachines;
690 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
691 HRESULT rc = runAllFiltersOnDevice(aDevice, llOpenedMachines, aIgnoreMachine);
692 AssertComRC(rc);
693 }
694}
695
696
697/**
698 * Runs all the filters on the specified device.
699 *
700 * All filters mean global and active VM, with the exception of those
701 * belonging to \a aMachine. If a global ignore filter matched or if
702 * none of the filters matched, the device will be released back to
703 * the host.
704 *
705 * The device calling us here will be in the HeldByProxy, Unused, or
706 * Capturable state. The caller is aware that locks held might have
707 * to be abandond because of IPC and that the device might be in
708 * almost any state upon return.
709 *
710 *
711 * @returns COM status code (only parameter & state checks will fail).
712 * @param aDevice The USB device to apply filters to.
713 * @param aIgnoreMachine The machine to ignore filters from (we've just
714 * detached the device from this machine).
715 *
716 * @note The caller is expected to own no locks.
717 */
718HRESULT USBProxyService::runAllFiltersOnDevice(ComObjPtr<HostUSBDevice> &aDevice,
719 SessionMachinesList &llOpenedMachines,
720 SessionMachine *aIgnoreMachine)
721{
722 LogFlowThisFunc(("{%s} ignoring=%p\n", aDevice->i_getName().c_str(), aIgnoreMachine));
723
724 /*
725 * Verify preconditions.
726 */
727 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
728 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), E_FAIL);
729
730 /*
731 * Get the lists we'll iterate.
732 */
733 Host::USBDeviceFilterList globalFilters;
734 mHost->i_getUSBFilters(&globalFilters);
735
736 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
737 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
738 AssertMsgReturn(aDevice->i_isCapturableOrHeld(), ("{%s} %s\n", aDevice->i_getName().c_str(),
739 aDevice->i_getStateName()), E_FAIL);
740
741 /*
742 * Run global filters filters first.
743 */
744 bool fHoldIt = false;
745 for (Host::USBDeviceFilterList::const_iterator it = globalFilters.begin();
746 it != globalFilters.end();
747 ++it)
748 {
749 AutoWriteLock filterLock(*it COMMA_LOCKVAL_SRC_POS);
750 const HostUSBDeviceFilter::BackupableUSBDeviceFilterData &data = (*it)->i_getData();
751 if (aDevice->i_isMatch(data))
752 {
753 USBDeviceFilterAction_T action = USBDeviceFilterAction_Null;
754 (*it)->COMGETTER(Action)(&action);
755 if (action == USBDeviceFilterAction_Ignore)
756 {
757 /*
758 * Release the device to the host and we're done.
759 */
760 filterLock.release();
761 devLock.release();
762 alock.release();
763 aDevice->i_requestReleaseToHost();
764 return S_OK;
765 }
766 if (action == USBDeviceFilterAction_Hold)
767 {
768 /*
769 * A device held by the proxy needs to be subjected
770 * to the machine filters.
771 */
772 fHoldIt = true;
773 break;
774 }
775 AssertMsgFailed(("action=%d\n", action));
776 }
777 }
778 globalFilters.clear();
779
780 /*
781 * Run the per-machine filters.
782 */
783 for (SessionMachinesList::const_iterator it = llOpenedMachines.begin();
784 it != llOpenedMachines.end();
785 ++it)
786 {
787 ComObjPtr<SessionMachine> pMachine = *it;
788
789 /* Skip the machine the device was just detached from. */
790 if ( aIgnoreMachine
791 && pMachine == aIgnoreMachine)
792 continue;
793
794 /* runMachineFilters takes care of checking the machine state. */
795 devLock.release();
796 alock.release();
797 if (runMachineFilters(pMachine, aDevice))
798 {
799 LogFlowThisFunc(("{%s} attached to %p\n", aDevice->i_getName().c_str(), (void *)pMachine));
800 return S_OK;
801 }
802 alock.acquire();
803 devLock.acquire();
804 }
805
806 /*
807 * No matching machine, so request hold or release depending
808 * on global filter match.
809 */
810 devLock.release();
811 alock.release();
812 if (fHoldIt)
813 aDevice->i_requestHold();
814 else
815 aDevice->i_requestReleaseToHost();
816 return S_OK;
817}
818
819
820/**
821 * Runs the USB filters of the machine on the device.
822 *
823 * If a match is found we will request capture for VM. This may cause
824 * us to temporary abandon locks while doing IPC.
825 *
826 * @param aMachine Machine whose filters are to be run.
827 * @param aDevice The USB device in question.
828 * @returns @c true if the device has been or is being attached to the VM, @c false otherwise.
829 *
830 * @note Locks several objects temporarily for reading or writing.
831 */
832bool USBProxyService::runMachineFilters(SessionMachine *aMachine, ComObjPtr<HostUSBDevice> &aDevice)
833{
834 LogFlowThisFunc(("{%s} aMachine=%p \n", aDevice->i_getName().c_str(), aMachine));
835
836 /*
837 * Validate preconditions.
838 */
839 AssertReturn(aMachine, false);
840 AssertReturn(!isWriteLockOnCurrentThread(), false);
841 AssertReturn(!aMachine->isWriteLockOnCurrentThread(), false);
842 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
843 /* Let HostUSBDevice::requestCaptureToVM() validate the state. */
844
845 /*
846 * Do the job.
847 */
848 ULONG ulMaskedIfs;
849 if (aMachine->i_hasMatchingUSBFilter(aDevice, &ulMaskedIfs))
850 {
851 /* try to capture the device */
852 HRESULT hrc = aDevice->i_requestCaptureForVM(aMachine, false /* aSetError */, Utf8Str(), ulMaskedIfs);
853 return SUCCEEDED(hrc)
854 || hrc == E_UNEXPECTED /* bad device state, give up */;
855 }
856
857 return false;
858}
859
860
861/**
862 * Searches the list of devices (mDevices) for the given device.
863 *
864 *
865 * @returns Smart pointer to the device on success, NULL otherwise.
866 * @param aId The UUID of the device we're looking for.
867 */
868ComObjPtr<HostUSBDevice> USBProxyService::findDeviceById(IN_GUID aId)
869{
870 Guid Id(aId);
871 ComObjPtr<HostUSBDevice> Dev;
872 for (HostUSBDeviceList::iterator it = mDevices.begin();
873 it != mDevices.end();
874 ++it)
875 if ((*it)->i_getId() == Id)
876 {
877 Dev = (*it);
878 break;
879 }
880
881 return Dev;
882}
883
884/**
885 * Creates a new USB device source.
886 *
887 * @returns COM status code.
888 * @param aBackend The backend to use.
889 * @param aId The ID of the source.
890 * @param aAddress The backend specific address.
891 * @param aPropertyNames Vector of optional property keys the backend supports.
892 * @param aPropertyValues Vector of optional property values the backend supports.
893 */
894HRESULT USBProxyService::createUSBDeviceSource(const com::Utf8Str &aBackend, const com::Utf8Str &aId,
895 const com::Utf8Str &aAddress, const std::vector<com::Utf8Str> &aPropertyNames,
896 const std::vector<com::Utf8Str> &aPropertyValues)
897{
898 HRESULT hrc = S_OK;
899
900 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
901
902 /** @todo */
903 NOREF(aPropertyNames);
904 NOREF(aPropertyValues);
905
906 /* Check whether the ID is used first. */
907 for (USBProxyBackendList::iterator it = mBackends.begin();
908 it != mBackends.end();
909 ++it)
910 {
911 USBProxyBackend *pUsbProxyBackend = *it;
912
913 if (aId.equals(pUsbProxyBackend->i_getId()))
914 return setError(VBOX_E_OBJECT_IN_USE,
915 tr("The USB device source \"%s\" exists already"), aId.c_str());
916 }
917
918 /* Create appropriate proxy backend. */
919 if (aBackend.equalsIgnoreCase("USBIP"))
920 {
921 ComObjPtr<USBProxyBackendUsbIp> UsbProxyBackend;
922
923 UsbProxyBackend.createObject();
924 int vrc = UsbProxyBackend->init(this, aId, aAddress);
925 if (RT_FAILURE(vrc))
926 hrc = setError(E_FAIL,
927 tr("Creating the USB device source \"%s\" using backend \"%s\" failed with %Rrc"),
928 aId.c_str(), aBackend.c_str(), vrc);
929 else
930 mBackends.push_back(static_cast<ComObjPtr<USBProxyBackend> >(UsbProxyBackend));
931 }
932 else
933 hrc = setError(VBOX_E_OBJECT_NOT_FOUND,
934 tr("The USB backend \"%s\" is not supported"), aBackend.c_str());
935
936 return hrc;
937}
938
939/*static*/
940HRESULT USBProxyService::setError(HRESULT aResultCode, const char *aText, ...)
941{
942 va_list va;
943 va_start(va, aText);
944 HRESULT rc = VirtualBoxBase::setErrorInternal(aResultCode,
945 COM_IIDOF(IHost),
946 "USBProxyService",
947 Utf8StrFmt(aText, va),
948 false /* aWarning*/,
949 true /* aLogIt*/);
950 va_end(va);
951 return rc;
952}
953
954/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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