VirtualBox

source: vbox/trunk/src/VBox/Main/USBProxyService.cpp@ 33060

Last change on this file since 33060 was 32056, checked in by vboxsync, 14 years ago

Applied a simple memory leak detector to libjpeg and VBoxC (Windows host only), the code completely disabled by default.

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