VirtualBox

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

Last change on this file since 98351 was 98292, checked in by vboxsync, 23 months ago

Main/src-server: rc -> hrc/vrc. Enabled scm rc checks. bugref:10223

  • 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 98292 2023-01-25 01:14:53Z 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 * @returns true if there is a state change.
647 * @param aDevice The device in question.
648 * @param aUSBDevice The USB device structure for the last enumeration.
649 * @param fFakeUpdate Flag whether to fake updating state.
650 */
651void USBProxyService::i_updateDeviceState(ComObjPtr<HostUSBDevice> &aDevice, PUSBDEVICE aUSBDevice, bool fFakeUpdate)
652{
653 AssertReturnVoid(aDevice);
654 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
655
656 bool fRunFilters = false;
657 SessionMachine *pIgnoreMachine = NULL;
658 bool fDevChanged = false;
659 if (fFakeUpdate)
660 fDevChanged = aDevice->i_updateStateFake(aUSBDevice, &fRunFilters, &pIgnoreMachine);
661 else
662 fDevChanged = aDevice->i_updateState(aUSBDevice, &fRunFilters, &pIgnoreMachine);
663
664 if (fDevChanged)
665 deviceChanged(aDevice, fRunFilters, pIgnoreMachine);
666}
667
668
669/**
670 * Handle a device which state changed in some significant way.
671 *
672 * This means things like running filters and subsequent capturing and
673 * VM attaching. This may result in IPC and temporary lock abandonment.
674 *
675 * @param aDevice The device.
676 * @param fRunFilters Flag whether to run filters.
677 * @param aIgnoreMachine Machine to ignore when running filters.
678 */
679void USBProxyService::deviceChanged(ComObjPtr<HostUSBDevice> &aDevice, bool fRunFilters,
680 SessionMachine *aIgnoreMachine)
681{
682 /*
683 * Validate preconditions.
684 */
685 AssertReturnVoid(!isWriteLockOnCurrentThread());
686 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
687 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
688 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid} aRunFilters=%RTbool aIgnoreMachine=%p\n",
689 (HostUSBDevice *)aDevice,
690 aDevice->i_getName().c_str(),
691 aDevice->i_getStateName(),
692 aDevice->i_getId().raw(),
693 fRunFilters,
694 aIgnoreMachine));
695 devLock.release();
696
697 /*
698 * Run filters if requested to do so.
699 */
700 if (fRunFilters)
701 {
702 SessionMachinesList llOpenedMachines;
703 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
704 HRESULT hrc = runAllFiltersOnDevice(aDevice, llOpenedMachines, aIgnoreMachine);
705 AssertComRC(hrc);
706 }
707}
708
709
710/**
711 * Runs all the filters on the specified device.
712 *
713 * All filters mean global and active VM, with the exception of those
714 * belonging to \a aMachine. If a global ignore filter matched or if
715 * none of the filters matched, the device will be released back to
716 * the host.
717 *
718 * The device calling us here will be in the HeldByProxy, Unused, or
719 * Capturable state. The caller is aware that locks held might have
720 * to be abandond because of IPC and that the device might be in
721 * almost any state upon return.
722 *
723 *
724 * @returns COM status code (only parameter & state checks will fail).
725 * @param aDevice The USB device to apply filters to.
726 * @param llOpenedMachines The list of opened machines.
727 * @param aIgnoreMachine The machine to ignore filters from (we've just
728 * detached the device from this machine).
729 *
730 * @note The caller is expected to own no locks.
731 */
732HRESULT USBProxyService::runAllFiltersOnDevice(ComObjPtr<HostUSBDevice> &aDevice,
733 SessionMachinesList &llOpenedMachines,
734 SessionMachine *aIgnoreMachine)
735{
736 LogFlowThisFunc(("{%s} ignoring=%p\n", aDevice->i_getName().c_str(), aIgnoreMachine));
737
738 /*
739 * Verify preconditions.
740 */
741 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
742 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), E_FAIL);
743
744 /*
745 * Get the lists we'll iterate.
746 */
747 Host::USBDeviceFilterList globalFilters;
748 mHost->i_getUSBFilters(&globalFilters);
749
750 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
751 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
752 AssertMsgReturn(aDevice->i_isCapturableOrHeld(), ("{%s} %s\n", aDevice->i_getName().c_str(),
753 aDevice->i_getStateName()), E_FAIL);
754
755 /*
756 * Run global filters filters first.
757 */
758 bool fHoldIt = false;
759 for (Host::USBDeviceFilterList::const_iterator it = globalFilters.begin();
760 it != globalFilters.end();
761 ++it)
762 {
763 AutoWriteLock filterLock(*it COMMA_LOCKVAL_SRC_POS);
764 const HostUSBDeviceFilter::BackupableUSBDeviceFilterData &data = (*it)->i_getData();
765 if (aDevice->i_isMatch(data))
766 {
767 USBDeviceFilterAction_T action = USBDeviceFilterAction_Null;
768 (*it)->COMGETTER(Action)(&action);
769 if (action == USBDeviceFilterAction_Ignore)
770 {
771 /*
772 * Release the device to the host and we're done.
773 */
774 filterLock.release();
775 devLock.release();
776 alock.release();
777 aDevice->i_requestReleaseToHost();
778 return S_OK;
779 }
780 if (action == USBDeviceFilterAction_Hold)
781 {
782 /*
783 * A device held by the proxy needs to be subjected
784 * to the machine filters.
785 */
786 fHoldIt = true;
787 break;
788 }
789 AssertMsgFailed(("action=%d\n", action));
790 }
791 }
792 globalFilters.clear();
793
794 /*
795 * Run the per-machine filters.
796 */
797 for (SessionMachinesList::const_iterator it = llOpenedMachines.begin();
798 it != llOpenedMachines.end();
799 ++it)
800 {
801 ComObjPtr<SessionMachine> pMachine = *it;
802
803 /* Skip the machine the device was just detached from. */
804 if ( aIgnoreMachine
805 && pMachine == aIgnoreMachine)
806 continue;
807
808 /* runMachineFilters takes care of checking the machine state. */
809 devLock.release();
810 alock.release();
811 if (runMachineFilters(pMachine, aDevice))
812 {
813 LogFlowThisFunc(("{%s} attached to %p\n", aDevice->i_getName().c_str(), (void *)pMachine));
814 return S_OK;
815 }
816 alock.acquire();
817 devLock.acquire();
818 }
819
820 /*
821 * No matching machine, so request hold or release depending
822 * on global filter match.
823 */
824 devLock.release();
825 alock.release();
826 if (fHoldIt)
827 aDevice->i_requestHold();
828 else
829 aDevice->i_requestReleaseToHost();
830 return S_OK;
831}
832
833
834/**
835 * Runs the USB filters of the machine on the device.
836 *
837 * If a match is found we will request capture for VM. This may cause
838 * us to temporary abandon locks while doing IPC.
839 *
840 * @param aMachine Machine whose filters are to be run.
841 * @param aDevice The USB device in question.
842 * @returns @c true if the device has been or is being attached to the VM, @c false otherwise.
843 *
844 * @note Locks several objects temporarily for reading or writing.
845 */
846bool USBProxyService::runMachineFilters(SessionMachine *aMachine, ComObjPtr<HostUSBDevice> &aDevice)
847{
848 LogFlowThisFunc(("{%s} aMachine=%p \n", aDevice->i_getName().c_str(), aMachine));
849
850 /*
851 * Validate preconditions.
852 */
853 AssertReturn(aMachine, false);
854 AssertReturn(!isWriteLockOnCurrentThread(), false);
855 AssertReturn(!aMachine->isWriteLockOnCurrentThread(), false);
856 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
857 /* Let HostUSBDevice::requestCaptureToVM() validate the state. */
858
859 /*
860 * Do the job.
861 */
862 ULONG ulMaskedIfs;
863 if (aMachine->i_hasMatchingUSBFilter(aDevice, &ulMaskedIfs))
864 {
865 /* try to capture the device */
866 HRESULT hrc = aDevice->i_requestCaptureForVM(aMachine, false /* aSetError */, Utf8Str(), ulMaskedIfs);
867 return SUCCEEDED(hrc)
868 || hrc == E_UNEXPECTED /* bad device state, give up */;
869 }
870
871 return false;
872}
873
874
875/**
876 * Searches the list of devices (mDevices) for the given device.
877 *
878 *
879 * @returns Smart pointer to the device on success, NULL otherwise.
880 * @param aId The UUID of the device we're looking for.
881 */
882ComObjPtr<HostUSBDevice> USBProxyService::findDeviceById(IN_GUID aId)
883{
884 Guid Id(aId);
885 ComObjPtr<HostUSBDevice> Dev;
886 for (HostUSBDeviceList::iterator it = mDevices.begin();
887 it != mDevices.end();
888 ++it)
889 if ((*it)->i_getId() == Id)
890 {
891 Dev = (*it);
892 break;
893 }
894
895 return Dev;
896}
897
898/**
899 * Creates a new USB device source.
900 *
901 * @returns COM status code.
902 * @param aBackend The backend to use.
903 * @param aId The ID of the source.
904 * @param aAddress The backend specific address.
905 * @param aPropertyNames Vector of optional property keys the backend supports.
906 * @param aPropertyValues Vector of optional property values the backend supports.
907 * @param fLoadingSettings Flag whether the USB device source is created while the
908 * settings are loaded or through the Main API.
909 */
910HRESULT USBProxyService::createUSBDeviceSource(const com::Utf8Str &aBackend, const com::Utf8Str &aId,
911 const com::Utf8Str &aAddress, const std::vector<com::Utf8Str> &aPropertyNames,
912 const std::vector<com::Utf8Str> &aPropertyValues,
913 bool fLoadingSettings)
914{
915 HRESULT hrc = S_OK;
916
917 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
918
919 /** @todo */
920 NOREF(aPropertyNames);
921 NOREF(aPropertyValues);
922
923 /* Check whether the ID is used first. */
924 for (USBProxyBackendList::iterator it = mBackends.begin();
925 it != mBackends.end();
926 ++it)
927 {
928 USBProxyBackend *pUsbProxyBackend = *it;
929
930 if (aId.equals(pUsbProxyBackend->i_getId()))
931 return setError(VBOX_E_OBJECT_IN_USE,
932 tr("The USB device source \"%s\" exists already"), aId.c_str());
933 }
934
935 /* Create appropriate proxy backend. */
936 if (aBackend.equalsIgnoreCase("USBIP"))
937 {
938 ComObjPtr<USBProxyBackendUsbIp> UsbProxyBackend;
939
940 UsbProxyBackend.createObject();
941 int vrc = UsbProxyBackend->init(this, aId, aAddress, fLoadingSettings);
942 if (RT_FAILURE(vrc))
943 hrc = setError(E_FAIL,
944 tr("Creating the USB device source \"%s\" using backend \"%s\" failed with %Rrc"),
945 aId.c_str(), aBackend.c_str(), vrc);
946 else
947 mBackends.push_back(static_cast<ComObjPtr<USBProxyBackend> >(UsbProxyBackend));
948 }
949 else
950 hrc = setError(VBOX_E_OBJECT_NOT_FOUND,
951 tr("The USB backend \"%s\" is not supported"), aBackend.c_str());
952
953 return hrc;
954}
955
956/*static*/
957HRESULT USBProxyService::setError(HRESULT aResultCode, const char *aText, ...)
958{
959 va_list va;
960 va_start(va, aText);
961 HRESULT hrc = VirtualBoxBase::setErrorInternalV(aResultCode,
962 COM_IIDOF(IHost),
963 "USBProxyService",
964 aText, va,
965 false /* aWarning*/,
966 true /* aLogIt*/);
967 va_end(va);
968 return hrc;
969}
970
971/* 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