VirtualBox

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

Last change on this file since 51425 was 51092, checked in by vboxsync, 11 years ago

6813 src-client/MachineDebuggerImpl.cpp + various formatting changes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 38.0 KB
Line 
1/* $Id: USBProxyService.cpp 51092 2014-04-16 17:57:25Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Service (base) class.
4 */
5
6/*
7 * Copyright (C) 2006-2012 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
36/**
37 * Initialize data members.
38 */
39USBProxyService::USBProxyService(Host *aHost)
40 : mHost(aHost), mThread(NIL_RTTHREAD), mTerminate(false), mLastError(VINF_SUCCESS), mDevices()
41{
42 LogFlowThisFunc(("aHost=%p\n", aHost));
43}
44
45
46/**
47 * Stub needed as long as the class isn't virtual
48 */
49HRESULT USBProxyService::init(void)
50{
51 return S_OK;
52}
53
54
55/**
56 * Empty destructor.
57 */
58USBProxyService::~USBProxyService()
59{
60 LogFlowThisFunc(("\n"));
61 Assert(mThread == NIL_RTTHREAD);
62 mDevices.clear();
63 mTerminate = true;
64 mHost = NULL;
65}
66
67
68/**
69 * Query if the service is active and working.
70 *
71 * @returns true if the service is up running.
72 * @returns false if the service isn't running.
73 */
74bool USBProxyService::isActive(void)
75{
76 return mThread != NIL_RTTHREAD;
77}
78
79
80/**
81 * Get last error.
82 * Can be used to check why the proxy !isActive() upon construction.
83 *
84 * @returns VBox status code.
85 */
86int USBProxyService::getLastError(void)
87{
88 return mLastError;
89}
90
91
92/**
93 * Get last error message.
94 * Can be used to check why the proxy !isActive() upon construction as an
95 * extension to getLastError(). May return a NULL error.
96 *
97 * @param
98 * @returns VBox status code.
99 */
100HRESULT USBProxyService::getLastErrorMessage(BSTR *aError)
101{
102 AssertPtrReturn(aError, E_POINTER);
103 mLastErrorMessage.cloneTo(aError);
104 return S_OK;
105}
106
107
108/**
109 * We're using the Host object lock.
110 *
111 * This is just a temporary measure until all the USB refactoring is
112 * done, probably... For now it help avoiding deadlocks we don't have
113 * time to fix.
114 *
115 * @returns Lock handle.
116 */
117RWLockHandle *USBProxyService::lockHandle() const
118{
119 return mHost->lockHandle();
120}
121
122
123/**
124 * Gets the collection of USB devices, slave of Host::USBDevices.
125 *
126 * This is an interface for the HostImpl::USBDevices property getter.
127 *
128 *
129 * @param aUSBDevices Where to store the pointer to the collection.
130 *
131 * @returns COM status code.
132 *
133 * @remarks The caller must own the write lock of the host object.
134 */
135HRESULT USBProxyService::getDeviceCollection(ComSafeArrayOut(IHostUSBDevice *, aUSBDevices))
136{
137 AssertReturn(isWriteLockOnCurrentThread(), E_FAIL);
138 CheckComArgOutSafeArrayPointerValid(aUSBDevices);
139
140 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
141
142 SafeIfaceArray<IHostUSBDevice> Collection(mDevices);
143 Collection.detachTo(ComSafeArrayOutArg(aUSBDevices));
144
145 return S_OK;
146}
147
148
149/**
150 * Request capture of a specific device.
151 *
152 * This is in an interface for SessionMachine::CaptureUSBDevice(), which is
153 * an internal worker used by Console::AttachUSBDevice() from the VM process.
154 *
155 * When the request is completed, SessionMachine::onUSBDeviceAttach() will
156 * be called for the given machine object.
157 *
158 *
159 * @param aMachine The machine to attach the device to.
160 * @param aId The UUID of the USB device to capture and attach.
161 *
162 * @returns COM status code and error info.
163 *
164 * @remarks This method may operate synchronously as well as asynchronously. In the
165 * former case it will temporarily abandon locks because of IPC.
166 */
167HRESULT USBProxyService::captureDeviceForVM(SessionMachine *aMachine, IN_GUID aId)
168{
169 ComAssertRet(aMachine, E_INVALIDARG);
170 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
171
172 /*
173 * Translate the device id into a device object.
174 */
175 ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId);
176 if (pHostDevice.isNull())
177 return setError(E_INVALIDARG,
178 tr("The USB device with UUID {%RTuuid} is not currently attached to the host"), Guid(aId).raw());
179
180 /*
181 * Try to capture the device
182 */
183 alock.release();
184 return pHostDevice->i_requestCaptureForVM(aMachine, true /* aSetError */);
185}
186
187
188/**
189 * Notification from VM process about USB device detaching progress.
190 *
191 * This is in an interface for SessionMachine::DetachUSBDevice(), which is
192 * an internal worker used by Console::DetachUSBDevice() from the VM process.
193 *
194 * @param aMachine The machine which is sending the notification.
195 * @param aId The UUID of the USB device is concerns.
196 * @param aDone \a false for the pre-action notification (necessary
197 * for advancing the device state to avoid confusing
198 * the guest).
199 * \a true for the post-action notification. The device
200 * will be subjected to all filters except those of
201 * of \a Machine.
202 *
203 * @returns COM status code.
204 *
205 * @remarks When \a aDone is \a true this method may end up doing IPC to other
206 * VMs when running filters. In these cases it will temporarily
207 * abandon its locks.
208 */
209HRESULT USBProxyService::detachDeviceFromVM(SessionMachine *aMachine, IN_GUID aId, bool aDone)
210{
211 LogFlowThisFunc(("aMachine=%p{%s} aId={%RTuuid} aDone=%RTbool\n",
212 aMachine,
213 aMachine->getName().c_str(),
214 Guid(aId).raw(),
215 aDone));
216
217 // get a list of all running machines while we're outside the lock
218 // (getOpenedMachines requests locks which are incompatible with the lock of the machines list)
219 SessionMachinesList llOpenedMachines;
220 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
221
222 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
223
224 ComObjPtr<HostUSBDevice> pHostDevice = findDeviceById(aId);
225 ComAssertRet(!pHostDevice.isNull(), E_FAIL);
226 AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
227
228 /*
229 * Work the state machine.
230 */
231 LogFlowThisFunc(("id={%RTuuid} state=%s aDone=%RTbool name={%s}\n",
232 pHostDevice->i_getId().raw(), pHostDevice->i_getStateName(), aDone, pHostDevice->i_getName().c_str()));
233 bool fRunFilters = false;
234 HRESULT hrc = pHostDevice->i_onDetachFromVM(aMachine, aDone, &fRunFilters);
235
236 /*
237 * Run filters if necessary.
238 */
239 if ( SUCCEEDED(hrc)
240 && fRunFilters)
241 {
242 Assert(aDone && pHostDevice->i_getUnistate() == kHostUSBDeviceState_HeldByProxy && pHostDevice->i_getMachine().isNull());
243 devLock.release();
244 alock.release();
245 HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine);
246 ComAssertComRC(hrc2);
247 }
248 return hrc;
249}
250
251
252/**
253 * Apply filters for the machine to all eligible USB devices.
254 *
255 * This is in an interface for SessionMachine::CaptureUSBDevice(), which
256 * is an internal worker used by Console::AutoCaptureUSBDevices() from the
257 * VM process at VM startup.
258 *
259 * Matching devices will be attached to the VM and may result IPC back
260 * to the VM process via SessionMachine::onUSBDeviceAttach() depending
261 * on whether the device needs to be captured or not. If capture is
262 * required, SessionMachine::onUSBDeviceAttach() will be called
263 * asynchronously by the USB proxy service thread.
264 *
265 * @param aMachine The machine to capture devices for.
266 *
267 * @returns COM status code, perhaps with error info.
268 *
269 * @remarks Temporarily locks this object, the machine object and some USB
270 * device, and the called methods will lock similar objects.
271 */
272HRESULT USBProxyService::autoCaptureDevicesForVM(SessionMachine *aMachine)
273{
274 LogFlowThisFunc(("aMachine=%p{%s}\n",
275 aMachine,
276 aMachine->getName().c_str()));
277
278 /*
279 * Make a copy of the list because we cannot hold the lock protecting it.
280 * (This will not make copies of any HostUSBDevice objects, only reference them.)
281 */
282 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
283 HostUSBDeviceList ListCopy = mDevices;
284 alock.release();
285
286 for (HostUSBDeviceList::iterator it = ListCopy.begin();
287 it != ListCopy.end();
288 ++it)
289 {
290 ComObjPtr<HostUSBDevice> device = *it;
291 AutoReadLock devLock(device COMMA_LOCKVAL_SRC_POS);
292 if ( device->i_getUnistate() == kHostUSBDeviceState_HeldByProxy
293 || device->i_getUnistate() == kHostUSBDeviceState_Unused
294 || device->i_getUnistate() == kHostUSBDeviceState_Capturable)
295 {
296 devLock.release();
297 runMachineFilters(aMachine, device);
298 }
299 }
300
301 return S_OK;
302}
303
304
305/**
306 * Detach all USB devices currently attached to a VM.
307 *
308 * This is in an interface for SessionMachine::DetachAllUSBDevices(), which
309 * is an internal worker used by Console::powerDown() from the VM process
310 * at VM startup, and SessionMachine::uninit() at VM abend.
311 *
312 * This is, like #detachDeviceFromVM(), normally a two stage journey
313 * where \a aDone indicates where we are. In addition we may be called
314 * to clean up VMs that have abended, in which case there will be no
315 * preparatory call. Filters will be applied to the devices in the final
316 * call with the risk that we have to do some IPC when attaching them
317 * to other VMs.
318 *
319 * @param aMachine The machine to detach devices from.
320 *
321 * @returns COM status code, perhaps with error info.
322 *
323 * @remarks Write locks the host object and may temporarily abandon
324 * its locks to perform IPC.
325 */
326HRESULT USBProxyService::detachAllDevicesFromVM(SessionMachine *aMachine, bool aDone, bool aAbnormal)
327{
328 // get a list of all running machines while we're outside the lock
329 // (getOpenedMachines requests locks which are incompatible with the host object lock)
330 SessionMachinesList llOpenedMachines;
331 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
332
333 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
334
335 /*
336 * Make a copy of the device list (not the HostUSBDevice objects, just
337 * the list) since we may end up performing IPC and temporarily have
338 * to abandon locks when applying filters.
339 */
340 HostUSBDeviceList ListCopy = mDevices;
341
342 for (HostUSBDeviceList::iterator it = ListCopy.begin();
343 it != ListCopy.end();
344 ++it)
345 {
346 ComObjPtr<HostUSBDevice> pHostDevice = *it;
347 AutoWriteLock devLock(pHostDevice COMMA_LOCKVAL_SRC_POS);
348 if (pHostDevice->i_getMachine() == aMachine)
349 {
350 /*
351 * Same procedure as in detachUSBDevice().
352 */
353 bool fRunFilters = false;
354 HRESULT hrc = pHostDevice->i_onDetachFromVM(aMachine, aDone, &fRunFilters, aAbnormal);
355 if ( SUCCEEDED(hrc)
356 && fRunFilters)
357 {
358 Assert(aDone && pHostDevice->i_getUnistate() ==
359 kHostUSBDeviceState_HeldByProxy && pHostDevice->i_getMachine().isNull());
360 devLock.release();
361 alock.release();
362 HRESULT hrc2 = runAllFiltersOnDevice(pHostDevice, llOpenedMachines, aMachine);
363 ComAssertComRC(hrc2);
364 alock.acquire();
365 }
366 }
367 }
368
369 return S_OK;
370}
371
372
373/**
374 * Runs all the filters on the specified device.
375 *
376 * All filters mean global and active VM, with the exception of those
377 * belonging to \a aMachine. If a global ignore filter matched or if
378 * none of the filters matched, the device will be released back to
379 * the host.
380 *
381 * The device calling us here will be in the HeldByProxy, Unused, or
382 * Capturable state. The caller is aware that locks held might have
383 * to be abandond because of IPC and that the device might be in
384 * almost any state upon return.
385 *
386 *
387 * @returns COM status code (only parameter & state checks will fail).
388 * @param aDevice The USB device to apply filters to.
389 * @param aIgnoreMachine The machine to ignore filters from (we've just
390 * detached the device from this machine).
391 *
392 * @note The caller is expected to own no locks.
393 */
394HRESULT USBProxyService::runAllFiltersOnDevice(ComObjPtr<HostUSBDevice> &aDevice,
395 SessionMachinesList &llOpenedMachines,
396 SessionMachine *aIgnoreMachine)
397{
398 LogFlowThisFunc(("{%s} ignoring=%p\n", aDevice->i_getName().c_str(), aIgnoreMachine));
399
400 /*
401 * Verify preconditions.
402 */
403 AssertReturn(!isWriteLockOnCurrentThread(), E_FAIL);
404 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), E_FAIL);
405 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
406 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
407 AssertMsgReturn(aDevice->i_isCapturableOrHeld(), ("{%s} %s\n", aDevice->i_getName().c_str(),
408 aDevice->i_getStateName()), E_FAIL);
409
410 /*
411 * Get the lists we'll iterate.
412 */
413 Host::USBDeviceFilterList globalFilters;
414
415 mHost->i_getUSBFilters(&globalFilters);
416
417 /*
418 * Run global filters filters first.
419 */
420 bool fHoldIt = false;
421 for (Host::USBDeviceFilterList::const_iterator it = globalFilters.begin();
422 it != globalFilters.end();
423 ++it)
424 {
425 AutoWriteLock filterLock(*it COMMA_LOCKVAL_SRC_POS);
426 const HostUSBDeviceFilter::Data &data = (*it)->i_getData();
427 if (aDevice->i_isMatch(data))
428 {
429 USBDeviceFilterAction_T action = USBDeviceFilterAction_Null;
430 (*it)->COMGETTER(Action)(&action);
431 if (action == USBDeviceFilterAction_Ignore)
432 {
433 /*
434 * Release the device to the host and we're done.
435 */
436 filterLock.release();
437 devLock.release();
438 alock.release();
439 aDevice->i_requestReleaseToHost();
440 return S_OK;
441 }
442 if (action == USBDeviceFilterAction_Hold)
443 {
444 /*
445 * A device held by the proxy needs to be subjected
446 * to the machine filters.
447 */
448 fHoldIt = true;
449 break;
450 }
451 AssertMsgFailed(("action=%d\n", action));
452 }
453 }
454 globalFilters.clear();
455
456 /*
457 * Run the per-machine filters.
458 */
459 for (SessionMachinesList::const_iterator it = llOpenedMachines.begin();
460 it != llOpenedMachines.end();
461 ++it)
462 {
463 ComObjPtr<SessionMachine> pMachine = *it;
464
465 /* Skip the machine the device was just detached from. */
466 if ( aIgnoreMachine
467 && pMachine == aIgnoreMachine)
468 continue;
469
470 /* runMachineFilters takes care of checking the machine state. */
471 devLock.release();
472 alock.release();
473 if (runMachineFilters(pMachine, aDevice))
474 {
475 LogFlowThisFunc(("{%s} attached to %p\n", aDevice->i_getName().c_str(), (void *)pMachine));
476 return S_OK;
477 }
478 alock.acquire();
479 devLock.acquire();
480 }
481
482 /*
483 * No matching machine, so request hold or release depending
484 * on global filter match.
485 */
486 devLock.release();
487 alock.release();
488 if (fHoldIt)
489 aDevice->i_requestHold();
490 else
491 aDevice->i_requestReleaseToHost();
492 return S_OK;
493}
494
495
496/**
497 * Runs the USB filters of the machine on the device.
498 *
499 * If a match is found we will request capture for VM. This may cause
500 * us to temporary abandon locks while doing IPC.
501 *
502 * @param aMachine Machine whose filters are to be run.
503 * @param aDevice The USB device in question.
504 * @returns @c true if the device has been or is being attached to the VM, @c false otherwise.
505 *
506 * @note Locks several objects temporarily for reading or writing.
507 */
508bool USBProxyService::runMachineFilters(SessionMachine *aMachine, ComObjPtr<HostUSBDevice> &aDevice)
509{
510 LogFlowThisFunc(("{%s} aMachine=%p \n", aDevice->i_getName().c_str(), aMachine));
511
512 /*
513 * Validate preconditions.
514 */
515 AssertReturn(aMachine, false);
516 AssertReturn(!isWriteLockOnCurrentThread(), false);
517 AssertReturn(!aMachine->isWriteLockOnCurrentThread(), false);
518 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
519 /* Let HostUSBDevice::requestCaptureToVM() validate the state. */
520
521 /*
522 * Do the job.
523 */
524 ULONG ulMaskedIfs;
525 if (aMachine->hasMatchingUSBFilter(aDevice, &ulMaskedIfs))
526 {
527 /* try to capture the device */
528 HRESULT hrc = aDevice->i_requestCaptureForVM(aMachine, false /* aSetError */, ulMaskedIfs);
529 return SUCCEEDED(hrc)
530 || hrc == E_UNEXPECTED /* bad device state, give up */;
531 }
532
533 return false;
534}
535
536
537/**
538 * A filter was inserted / loaded.
539 *
540 * @param aFilter Pointer to the inserted filter.
541 * @return ID of the inserted filter
542 */
543void *USBProxyService::insertFilter(PCUSBFILTER aFilter)
544{
545 // return non-NULL to fake success.
546 NOREF(aFilter);
547 return (void *)1;
548}
549
550
551/**
552 * A filter was removed.
553 *
554 * @param aId ID of the filter to remove
555 */
556void USBProxyService::removeFilter(void *aId)
557{
558 NOREF(aId);
559}
560
561
562/**
563 * A VM is trying to capture a device, do necessary preparations.
564 *
565 * @returns VBox status code.
566 * @param aDevice The device in question.
567 */
568int USBProxyService::captureDevice(HostUSBDevice *aDevice)
569{
570 NOREF(aDevice);
571 return VERR_NOT_IMPLEMENTED;
572}
573
574
575/**
576 * Notification that an async captureDevice() operation completed.
577 *
578 * This is used by the proxy to release temporary filters.
579 *
580 * @returns VBox status code.
581 * @param aDevice The device in question.
582 * @param aSuccess Whether it succeeded or failed.
583 */
584void USBProxyService::captureDeviceCompleted(HostUSBDevice *aDevice, bool aSuccess)
585{
586 NOREF(aDevice);
587 NOREF(aSuccess);
588}
589
590
591/**
592 * The device is going to be detached from a VM.
593 *
594 * @param aDevice The device in question.
595 *
596 * @todo unused
597 */
598void USBProxyService::detachingDevice(HostUSBDevice *aDevice)
599{
600 NOREF(aDevice);
601}
602
603
604/**
605 * A VM is releasing a device back to the host.
606 *
607 * @returns VBox status code.
608 * @param aDevice The device in question.
609 */
610int USBProxyService::releaseDevice(HostUSBDevice *aDevice)
611{
612 NOREF(aDevice);
613 return VERR_NOT_IMPLEMENTED;
614}
615
616
617/**
618 * Notification that an async releaseDevice() operation completed.
619 *
620 * This is used by the proxy to release temporary filters.
621 *
622 * @returns VBox status code.
623 * @param aDevice The device in question.
624 * @param aSuccess Whether it succeeded or failed.
625 */
626void USBProxyService::releaseDeviceCompleted(HostUSBDevice *aDevice, bool aSuccess)
627{
628 NOREF(aDevice);
629 NOREF(aSuccess);
630}
631
632
633// Internals
634/////////////////////////////////////////////////////////////////////////////
635
636
637/**
638 * Starts the service.
639 *
640 * @returns VBox status.
641 */
642int USBProxyService::start(void)
643{
644 int rc = VINF_SUCCESS;
645 if (mThread == NIL_RTTHREAD)
646 {
647 /*
648 * Force update before starting the poller thread.
649 */
650 rc = wait(0);
651 if (rc == VERR_TIMEOUT || rc == VERR_INTERRUPTED || RT_SUCCESS(rc))
652 {
653 processChanges();
654
655 /*
656 * Create the poller thread which will look for changes.
657 */
658 mTerminate = false;
659 rc = RTThreadCreate(&mThread, USBProxyService::serviceThread, this,
660 0, RTTHREADTYPE_INFREQUENT_POLLER, RTTHREADFLAGS_WAITABLE, "USBPROXY");
661 AssertRC(rc);
662 if (RT_SUCCESS(rc))
663 LogFlowThisFunc(("started mThread=%RTthrd\n", mThread));
664 else
665 mThread = NIL_RTTHREAD;
666 }
667 mLastError = rc;
668 }
669 else
670 LogFlowThisFunc(("already running, mThread=%RTthrd\n", mThread));
671 return rc;
672}
673
674
675/**
676 * Stops the service.
677 *
678 * @returns VBox status.
679 */
680int USBProxyService::stop(void)
681{
682 int rc = VINF_SUCCESS;
683 if (mThread != NIL_RTTHREAD)
684 {
685 /*
686 * Mark the thread for termination and kick it.
687 */
688 ASMAtomicXchgSize(&mTerminate, true);
689 rc = interruptWait();
690 AssertRC(rc);
691
692 /*
693 * Wait for the thread to finish and then update the state.
694 */
695 rc = RTThreadWait(mThread, 60000, NULL);
696 if (rc == VERR_INVALID_HANDLE)
697 rc = VINF_SUCCESS;
698 if (RT_SUCCESS(rc))
699 {
700 LogFlowThisFunc(("stopped mThread=%RTthrd\n", mThread));
701 mThread = NIL_RTTHREAD;
702 mTerminate = false;
703 }
704 else
705 {
706 AssertRC(rc);
707 mLastError = rc;
708 }
709 }
710 else
711 LogFlowThisFunc(("not active\n"));
712
713 return rc;
714}
715
716
717/**
718 * The service thread created by start().
719 *
720 * @param Thread The thread handle.
721 * @param pvUser Pointer to the USBProxyService instance.
722 */
723/*static*/ DECLCALLBACK(int) USBProxyService::serviceThread(RTTHREAD /* Thread */, void *pvUser)
724{
725 USBProxyService *pThis = (USBProxyService *)pvUser;
726 LogFlowFunc(("pThis=%p\n", pThis));
727 pThis->serviceThreadInit();
728 int rc = VINF_SUCCESS;
729
730 /*
731 * Processing loop.
732 */
733 for (;;)
734 {
735 rc = pThis->wait(RT_INDEFINITE_WAIT);
736 if (RT_FAILURE(rc) && rc != VERR_INTERRUPTED && rc != VERR_TIMEOUT)
737 break;
738 if (pThis->mTerminate)
739 break;
740 pThis->processChanges();
741 }
742
743 pThis->serviceThreadTerm();
744 LogFlowFunc(("returns %Rrc\n", rc));
745 return rc;
746}
747
748
749/**
750 * First call made on the service thread, use it to do
751 * thread initialization.
752 *
753 * The default implementation in USBProxyService just a dummy stub.
754 */
755void USBProxyService::serviceThreadInit(void)
756{
757}
758
759
760/**
761 * Last call made on the service thread, use it to do
762 * thread termination.
763 */
764void USBProxyService::serviceThreadTerm(void)
765{
766}
767
768
769/**
770 * Wait for a change in the USB devices attached to the host.
771 *
772 * The default implementation in USBProxyService just a dummy stub.
773 *
774 * @returns VBox status code. VERR_INTERRUPTED and VERR_TIMEOUT are considered
775 * harmless, while all other error status are fatal.
776 * @param aMillies Number of milliseconds to wait.
777 */
778int USBProxyService::wait(RTMSINTERVAL aMillies)
779{
780 return RTThreadSleep(RT_MIN(aMillies, 250));
781}
782
783
784/**
785 * Interrupt any wait() call in progress.
786 *
787 * The default implementation in USBProxyService just a dummy stub.
788 *
789 * @returns VBox status.
790 */
791int USBProxyService::interruptWait(void)
792{
793 return VERR_NOT_IMPLEMENTED;
794}
795
796
797/**
798 * Sort a list of USB devices.
799 *
800 * @returns Pointer to the head of the sorted doubly linked list.
801 * @param aDevices Head pointer (can be both singly and doubly linked list).
802 */
803static PUSBDEVICE sortDevices(PUSBDEVICE pDevices)
804{
805 PUSBDEVICE pHead = NULL;
806 PUSBDEVICE pTail = NULL;
807 while (pDevices)
808 {
809 /* unlink head */
810 PUSBDEVICE pDev = pDevices;
811 pDevices = pDev->pNext;
812 if (pDevices)
813 pDevices->pPrev = NULL;
814
815 /* find location. */
816 PUSBDEVICE pCur = pTail;
817 while ( pCur
818 && HostUSBDevice::i_compare(pCur, pDev) > 0)
819 pCur = pCur->pPrev;
820
821 /* insert (after pCur) */
822 pDev->pPrev = pCur;
823 if (pCur)
824 {
825 pDev->pNext = pCur->pNext;
826 pCur->pNext = pDev;
827 if (pDev->pNext)
828 pDev->pNext->pPrev = pDev;
829 else
830 pTail = pDev;
831 }
832 else
833 {
834 pDev->pNext = pHead;
835 if (pHead)
836 pHead->pPrev = pDev;
837 else
838 pTail = pDev;
839 pHead = pDev;
840 }
841 }
842
843 LogFlowFuncLeave();
844 return pHead;
845}
846
847
848/**
849 * Process any relevant changes in the attached USB devices.
850 *
851 * Except for the first call, this is always running on the service thread.
852 */
853void USBProxyService::processChanges(void)
854{
855 LogFlowThisFunc(("\n"));
856
857 /*
858 * Get the sorted list of USB devices.
859 */
860 PUSBDEVICE pDevices = getDevices();
861 pDevices = sortDevices(pDevices);
862
863 // get a list of all running machines while we're outside the lock
864 // (getOpenedMachines requests higher priority locks)
865 SessionMachinesList llOpenedMachines;
866 mHost->i_parent()->i_getOpenedMachines(llOpenedMachines);
867
868 AutoWriteLock alock(this COMMA_LOCKVAL_SRC_POS);
869
870 /*
871 * Compare previous list with the new list of devices
872 * and merge in any changes while notifying Host.
873 */
874 HostUSBDeviceList::iterator it = this->mDevices.begin();
875 while ( it != mDevices.end()
876 || pDevices)
877 {
878 ComObjPtr<HostUSBDevice> pHostDevice;
879
880 if (it != mDevices.end())
881 pHostDevice = *it;
882
883 /*
884 * Assert that the object is still alive (we still reference it in
885 * the collection and we're the only one who calls uninit() on it.
886 */
887 AutoCaller devCaller(pHostDevice.isNull() ? NULL : pHostDevice);
888 AssertComRC(devCaller.rc());
889
890 /*
891 * Lock the device object since we will read/write its
892 * properties. All Host callbacks also imply the object is locked.
893 */
894 AutoWriteLock devLock(pHostDevice.isNull() ? NULL : pHostDevice
895 COMMA_LOCKVAL_SRC_POS);
896
897 /*
898 * Compare.
899 */
900 int iDiff;
901 if (pHostDevice.isNull())
902 iDiff = 1;
903 else
904 {
905 if (!pDevices)
906 iDiff = -1;
907 else
908 iDiff = pHostDevice->i_compare(pDevices);
909 }
910 if (!iDiff)
911 {
912 /*
913 * The device still there, update the state and move on. The PUSBDEVICE
914 * structure is eaten by updateDeviceState / HostUSBDevice::updateState().
915 */
916 PUSBDEVICE pCur = pDevices;
917 pDevices = pDevices->pNext;
918 pCur->pPrev = pCur->pNext = NULL;
919
920 bool fRunFilters = false;
921 SessionMachine *pIgnoreMachine = NULL;
922 devLock.release();
923 alock.release();
924 if (updateDeviceState(pHostDevice, pCur, &fRunFilters, &pIgnoreMachine))
925 deviceChanged(pHostDevice,
926 (fRunFilters ? &llOpenedMachines : NULL),
927 pIgnoreMachine);
928 alock.acquire();
929 it++;
930 }
931 else
932 {
933 if (iDiff > 0)
934 {
935 /*
936 * Head of pDevices was attached.
937 */
938 PUSBDEVICE pNew = pDevices;
939 pDevices = pDevices->pNext;
940 pNew->pPrev = pNew->pNext = NULL;
941
942 ComObjPtr<HostUSBDevice> NewObj;
943 NewObj.createObject();
944 NewObj->init(pNew, this);
945 Log(("USBProxyService::processChanges: attached %p {%s} %s / %p:{.idVendor=%#06x, .idProduct=%#06x, .pszProduct=\"%s\", .pszManufacturer=\"%s\"}\n",
946 (HostUSBDevice *)NewObj,
947 NewObj->i_getName().c_str(),
948 NewObj->i_getStateName(),
949 pNew,
950 pNew->idVendor,
951 pNew->idProduct,
952 pNew->pszProduct,
953 pNew->pszManufacturer));
954
955 mDevices.insert(it, NewObj);
956
957 devLock.release();
958 alock.release();
959 deviceAdded(NewObj, llOpenedMachines, pNew);
960 alock.acquire();
961 }
962 else
963 {
964 /*
965 * Check if the device was actually detached or logically detached
966 * as the result of a re-enumeration.
967 */
968 if (!pHostDevice->i_wasActuallyDetached())
969 it++;
970 else
971 {
972 it = mDevices.erase(it);
973 devLock.release();
974 alock.release();
975 deviceRemoved(pHostDevice);
976 Log(("USBProxyService::processChanges: detached %p {%s}\n",
977 (HostUSBDevice *)pHostDevice,
978 pHostDevice->i_getName().c_str()));
979
980 /* from now on, the object is no more valid,
981 * uninitialize to avoid abuse */
982 devCaller.release();
983 pHostDevice->uninit();
984 alock.acquire();
985 }
986 }
987 }
988 } /* while */
989
990 LogFlowThisFunc(("returns void\n"));
991}
992
993
994/**
995 * Get a list of USB device currently attached to the host.
996 *
997 * The default implementation in USBProxyService just a dummy stub.
998 *
999 * @returns Pointer to a list of USB devices.
1000 * The list nodes are freed individually by calling freeDevice().
1001 */
1002PUSBDEVICE USBProxyService::getDevices(void)
1003{
1004 return NULL;
1005}
1006
1007
1008/**
1009 * Performs the required actions when a device has been added.
1010 *
1011 * This means things like running filters and subsequent capturing and
1012 * VM attaching. This may result in IPC and temporary lock abandonment.
1013 *
1014 * @param aDevice The device in question.
1015 * @param aUSBDevice The USB device structure.
1016 */
1017void USBProxyService::deviceAdded(ComObjPtr<HostUSBDevice> &aDevice,
1018 SessionMachinesList &llOpenedMachines,
1019 PUSBDEVICE aUSBDevice)
1020{
1021 /*
1022 * Validate preconditions.
1023 */
1024 AssertReturnVoid(!isWriteLockOnCurrentThread());
1025 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
1026 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
1027 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
1028 (HostUSBDevice *)aDevice,
1029 aDevice->i_getName().c_str(),
1030 aDevice->i_getStateName(),
1031 aDevice->i_getId().raw()));
1032
1033 /*
1034 * Run filters on the device.
1035 */
1036 if (aDevice->i_isCapturableOrHeld())
1037 {
1038 devLock.release();
1039 HRESULT rc = runAllFiltersOnDevice(aDevice, llOpenedMachines, NULL /* aIgnoreMachine */);
1040 AssertComRC(rc);
1041 }
1042
1043 NOREF(aUSBDevice);
1044}
1045
1046
1047/**
1048 * Remove device notification hook for the OS specific code.
1049 *
1050 * This is means things like
1051 *
1052 * @param aDevice The device in question.
1053 */
1054void USBProxyService::deviceRemoved(ComObjPtr<HostUSBDevice> &aDevice)
1055{
1056 /*
1057 * Validate preconditions.
1058 */
1059 AssertReturnVoid(!isWriteLockOnCurrentThread());
1060 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
1061 AutoWriteLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
1062 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid}\n",
1063 (HostUSBDevice *)aDevice,
1064 aDevice->i_getName().c_str(),
1065 aDevice->i_getStateName(),
1066 aDevice->i_getId().raw()));
1067
1068 /*
1069 * Detach the device from any machine currently using it,
1070 * reset all data and uninitialize the device object.
1071 */
1072 devLock.release();
1073 aDevice->i_onPhysicalDetached();
1074}
1075
1076
1077/**
1078 * Implement fake capture, ++.
1079 *
1080 * @returns true if there is a state change.
1081 * @param pDevice The device in question.
1082 * @param pUSBDevice The USB device structure for the last enumeration.
1083 * @param aRunFilters Whether or not to run filters.
1084 */
1085bool USBProxyService::updateDeviceStateFake(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters,
1086 SessionMachine **aIgnoreMachine)
1087{
1088 *aRunFilters = false;
1089 *aIgnoreMachine = NULL;
1090 AssertReturn(aDevice, false);
1091 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
1092
1093 /*
1094 * Just hand it to the device, it knows best what needs to be done.
1095 */
1096 return aDevice->i_updateStateFake(aUSBDevice, aRunFilters, aIgnoreMachine);
1097}
1098
1099
1100/**
1101 * Updates the device state.
1102 *
1103 * This is responsible for calling HostUSBDevice::updateState().
1104 *
1105 * @returns true if there is a state change.
1106 * @param aDevice The device in question.
1107 * @param aUSBDevice The USB device structure for the last enumeration.
1108 * @param aRunFilters Whether or not to run filters.
1109 * @param aIgnoreMachine Machine to ignore when running filters.
1110 */
1111bool USBProxyService::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters,
1112 SessionMachine **aIgnoreMachine)
1113{
1114 AssertReturn(aDevice, false);
1115 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
1116
1117 return aDevice->i_updateState(aUSBDevice, aRunFilters, aIgnoreMachine);
1118}
1119
1120
1121/**
1122 * Handle a device which state changed in some significant way.
1123 *
1124 * This means things like running filters and subsequent capturing and
1125 * VM attaching. This may result in IPC and temporary lock abandonment.
1126 *
1127 * @param aDevice The device.
1128 * @param pllOpenedMachines list of running session machines (VirtualBox::getOpenedMachines()); if NULL, we don't run filters
1129 * @param aIgnoreMachine Machine to ignore when running filters.
1130 */
1131void USBProxyService::deviceChanged(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList *pllOpenedMachines,
1132 SessionMachine *aIgnoreMachine)
1133{
1134 /*
1135 * Validate preconditions.
1136 */
1137 AssertReturnVoid(!isWriteLockOnCurrentThread());
1138 AssertReturnVoid(!aDevice->isWriteLockOnCurrentThread());
1139 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
1140 LogFlowThisFunc(("aDevice=%p name={%s} state=%s id={%RTuuid} aRunFilters=%RTbool aIgnoreMachine=%p\n",
1141 (HostUSBDevice *)aDevice,
1142 aDevice->i_getName().c_str(),
1143 aDevice->i_getStateName(),
1144 aDevice->i_getId().raw(),
1145 (pllOpenedMachines != NULL), // used to be "bool aRunFilters"
1146 aIgnoreMachine));
1147 devLock.release();
1148
1149 /*
1150 * Run filters if requested to do so.
1151 */
1152 if (pllOpenedMachines)
1153 {
1154 HRESULT rc = runAllFiltersOnDevice(aDevice, *pllOpenedMachines, aIgnoreMachine);
1155 AssertComRC(rc);
1156 }
1157}
1158
1159
1160
1161/**
1162 * Free all the members of a USB device returned by getDevice().
1163 *
1164 * @param pDevice Pointer to the device.
1165 */
1166/*static*/ void
1167USBProxyService::freeDeviceMembers(PUSBDEVICE pDevice)
1168{
1169 RTStrFree((char *)pDevice->pszManufacturer);
1170 pDevice->pszManufacturer = NULL;
1171 RTStrFree((char *)pDevice->pszProduct);
1172 pDevice->pszProduct = NULL;
1173 RTStrFree((char *)pDevice->pszSerialNumber);
1174 pDevice->pszSerialNumber = NULL;
1175
1176 RTStrFree((char *)pDevice->pszAddress);
1177 pDevice->pszAddress = NULL;
1178#ifdef RT_OS_WINDOWS
1179 RTStrFree(pDevice->pszAltAddress);
1180 pDevice->pszAltAddress = NULL;
1181 RTStrFree(pDevice->pszHubName);
1182 pDevice->pszHubName = NULL;
1183#elif defined(RT_OS_SOLARIS)
1184 RTStrFree(pDevice->pszDevicePath);
1185 pDevice->pszDevicePath = NULL;
1186#endif
1187}
1188
1189
1190/**
1191 * Free one USB device returned by getDevice().
1192 *
1193 * @param pDevice Pointer to the device.
1194 */
1195/*static*/ void
1196USBProxyService::freeDevice(PUSBDEVICE pDevice)
1197{
1198 freeDeviceMembers(pDevice);
1199 RTMemFree(pDevice);
1200}
1201
1202
1203/**
1204 * Initializes a filter with the data from the specified device.
1205 *
1206 * @param aFilter The filter to fill.
1207 * @param aDevice The device to fill it with.
1208 */
1209/*static*/ void
1210USBProxyService::initFilterFromDevice(PUSBFILTER aFilter, HostUSBDevice *aDevice)
1211{
1212 PCUSBDEVICE pDev = aDevice->mUsb;
1213 int vrc;
1214
1215 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_VENDOR_ID, pDev->idVendor, true); AssertRC(vrc);
1216 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_PRODUCT_ID, pDev->idProduct, true); AssertRC(vrc);
1217 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_REV, pDev->bcdDevice, true); AssertRC(vrc);
1218 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_CLASS, pDev->bDeviceClass, true); AssertRC(vrc);
1219 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_SUB_CLASS, pDev->bDeviceSubClass, true); AssertRC(vrc);
1220 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_DEVICE_PROTOCOL, pDev->bDeviceProtocol, true); AssertRC(vrc);
1221 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_PORT, pDev->bPort, true); AssertRC(vrc);
1222 vrc = USBFilterSetNumExact(aFilter, USBFILTERIDX_BUS, pDev->bBus, true); AssertRC(vrc);
1223 if (pDev->pszSerialNumber)
1224 {
1225 vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_SERIAL_NUMBER_STR, pDev->pszSerialNumber, true);
1226 AssertRC(vrc);
1227 }
1228 if (pDev->pszProduct)
1229 {
1230 vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_PRODUCT_STR, pDev->pszProduct, true);
1231 AssertRC(vrc);
1232 }
1233 if (pDev->pszManufacturer)
1234 {
1235 vrc = USBFilterSetStringExact(aFilter, USBFILTERIDX_MANUFACTURER_STR, pDev->pszManufacturer, true);
1236 AssertRC(vrc);
1237 }
1238}
1239
1240
1241/**
1242 * Searches the list of devices (mDevices) for the given device.
1243 *
1244 *
1245 * @returns Smart pointer to the device on success, NULL otherwise.
1246 * @param aId The UUID of the device we're looking for.
1247 */
1248ComObjPtr<HostUSBDevice> USBProxyService::findDeviceById(IN_GUID aId)
1249{
1250 Guid Id(aId);
1251 ComObjPtr<HostUSBDevice> Dev;
1252 for (HostUSBDeviceList::iterator it = mDevices.begin();
1253 it != mDevices.end();
1254 ++it)
1255 if ((*it)->i_getId() == Id)
1256 {
1257 Dev = (*it);
1258 break;
1259 }
1260
1261 return Dev;
1262}
1263
1264/*static*/
1265HRESULT USBProxyService::setError(HRESULT aResultCode, const char *aText, ...)
1266{
1267 va_list va;
1268 va_start(va, aText);
1269 HRESULT rc = VirtualBoxBase::setErrorInternal(aResultCode,
1270 COM_IIDOF(IHost),
1271 "USBProxyService",
1272 Utf8StrFmt(aText, va),
1273 false /* aWarning*/,
1274 true /* aLogIt*/);
1275 va_end(va);
1276 return rc;
1277}
1278
1279/* vi: set tabstop=4 shiftwidth=4 expandtab: */
Note: See TracBrowser for help on using the repository browser.

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