VirtualBox

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

Last change on this file since 103491 was 99739, checked in by vboxsync, 18 months ago

*: doxygen corrections (mostly about removing @returns from functions returning void).

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