VirtualBox

source: vbox/trunk/src/VBox/HostDrivers/VBoxUSB/win/mon/VBoxUsbFlt.cpp@ 108885

Last change on this file since 108885 was 108885, checked in by vboxsync, 2 weeks ago

VBoxUSBMon: Removed temporary registry key workaround added for bugref:9479

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 64.9 KB
Line 
1/* $Id: VBoxUsbFlt.cpp 108885 2025-04-08 11:51:30Z vboxsync $ */
2/** @file
3 * VBox USB Monitor Device Filtering functionality
4 */
5/*
6 * Copyright (C) 2011-2024 Oracle and/or its affiliates.
7 *
8 * This file is part of VirtualBox base platform packages, as
9 * available from https://www.virtualbox.org.
10 *
11 * This program is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU General Public License
13 * as published by the Free Software Foundation, in version 3 of the
14 * License.
15 *
16 * This program is distributed in the hope that it will be useful, but
17 * WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License
22 * along with this program; if not, see <https://www.gnu.org/licenses>.
23 *
24 * The contents of this file may alternatively be used under the terms
25 * of the Common Development and Distribution License Version 1.0
26 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
27 * in the VirtualBox distribution, in which case the provisions of the
28 * CDDL are applicable instead of those of the GPL.
29 *
30 * You may elect to license modified versions of this file under the
31 * terms and conditions of either the GPL or the CDDL or both.
32 *
33 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
34 */
35
36
37/*********************************************************************************************************************************
38* Header Files *
39*********************************************************************************************************************************/
40#include "VBoxUsbMon.h"
41#include "../cmn/VBoxUsbTool.h"
42
43#include <VBox/cdefs.h>
44#include <VBox/types.h>
45#include <iprt/process.h>
46#include <iprt/assert.h>
47#include <iprt/errcore.h>
48
49#include <iprt/assert.h>
50
51#pragma warning(disable : 4200)
52#include "usbdi.h"
53#pragma warning(default : 4200)
54#include "usbdlib.h"
55#include "VBoxUSBFilterMgr.h"
56#include <VBox/usblib.h>
57#include <devguid.h>
58#include <devpkey.h>
59
60
61/* We should be including ntifs.h but that's not as easy as it sounds. */
62extern "C" {
63NTKERNELAPI PDEVICE_OBJECT IoGetDeviceAttachmentBaseRef(__in PDEVICE_OBJECT DeviceObject);
64}
65
66/*
67 * state transitions:
68 *
69 * (we are not filtering this device )
70 * ADDED --> UNCAPTURED ------------------------------->-
71 * | |
72 * | (we are filtering this device, | (the device is being
73 * | waiting for our device driver | re-plugged to perform
74 * | to pick it up) | capture-uncapture transition)
75 * |-> CAPTURING -------------------------------->|---> REPLUGGING -----
76 * ^ | (device driver picked | |
77 * | | up the device) | (remove cased | (device is removed
78 * | ->---> CAPTURED ---------------------->| by "real" removal | the device info is removed form the list)
79 * | | |------------------->->--> REMOVED
80 * | | |
81 * |-----------<->---> USED_BY_GUEST ------->|
82 * | |
83 * |------------------------<-
84 *
85 * NOTE: the order of enums DOES MATTER!!
86 * Do not blindly modify!! as the code assumes the state is ordered this way.
87 */
88typedef enum
89{
90 VBOXUSBFLT_DEVSTATE_UNKNOWN = 0,
91 VBOXUSBFLT_DEVSTATE_REMOVED,
92 VBOXUSBFLT_DEVSTATE_REPLUGGING,
93 VBOXUSBFLT_DEVSTATE_ADDED,
94 VBOXUSBFLT_DEVSTATE_UNCAPTURED,
95 VBOXUSBFLT_DEVSTATE_CAPTURING,
96 VBOXUSBFLT_DEVSTATE_CAPTURED,
97 VBOXUSBFLT_DEVSTATE_USED_BY_GUEST,
98 VBOXUSBFLT_DEVSTATE_32BIT_HACK = 0x7fffffff
99} VBOXUSBFLT_DEVSTATE;
100
101typedef struct VBOXUSBFLT_DEVICE
102{
103 LIST_ENTRY GlobalLe;
104 /* auxiliary list to be used for gathering devices to be re-plugged
105 * only thread that puts the device to the REPLUGGING state can use this list */
106 LIST_ENTRY RepluggingLe;
107 /* Owning session. Each matched device has an owning session. */
108 struct VBOXUSBFLTCTX *pOwner;
109 /* filter id - if NULL AND device has an owner - the filter is destroyed */
110 uintptr_t uFltId;
111 /* true iff device is filtered with a one-shot filter */
112 bool fIsFilterOneShot;
113 /* true if descriptors could not be read and only inferred from PnP Manager data */
114 bool fInferredDesc;
115 /* The device state. If the non-owner session is requesting the state while the device is grabbed,
116 * the USBDEVICESTATE_USED_BY_HOST is returned. */
117 VBOXUSBFLT_DEVSTATE enmState;
118 volatile uint32_t cRefs;
119 PDEVICE_OBJECT Pdo;
120 uint16_t idVendor;
121 uint16_t idProduct;
122 uint16_t bcdDevice;
123 uint16_t bPort;
124 uint8_t bClass;
125 uint8_t bSubClass;
126 uint8_t bProtocol;
127 char szSerial[MAX_USB_SERIAL_STRING];
128 char szMfgName[MAX_USB_SERIAL_STRING];
129 char szProduct[MAX_USB_SERIAL_STRING];
130 WCHAR szLocationPath[768];
131#if 0
132 char szDrvKeyName[512];
133 BOOLEAN fHighSpeed;
134#endif
135} VBOXUSBFLT_DEVICE, *PVBOXUSBFLT_DEVICE;
136
137#define PVBOXUSBFLT_DEVICE_FROM_LE(_pLe) ( (PVBOXUSBFLT_DEVICE)( ((uint8_t*)(_pLe)) - RT_OFFSETOF(VBOXUSBFLT_DEVICE, GlobalLe) ) )
138#define PVBOXUSBFLT_DEVICE_FROM_REPLUGGINGLE(_pLe) ( (PVBOXUSBFLT_DEVICE)( ((uint8_t*)(_pLe)) - RT_OFFSETOF(VBOXUSBFLT_DEVICE, RepluggingLe) ) )
139#define PVBOXUSBFLTCTX_FROM_LE(_pLe) ( (PVBOXUSBFLTCTX)( ((uint8_t*)(_pLe)) - RT_OFFSETOF(VBOXUSBFLTCTX, ListEntry) ) )
140
141typedef struct VBOXUSBFLT_LOCK
142{
143 KSPIN_LOCK Lock;
144 KIRQL OldIrql;
145} VBOXUSBFLT_LOCK, *PVBOXUSBFLT_LOCK;
146
147#define VBOXUSBFLT_LOCK_INIT() \
148 KeInitializeSpinLock(&g_VBoxUsbFltGlobals.Lock.Lock)
149#define VBOXUSBFLT_LOCK_TERM() do { } while (0)
150#define VBOXUSBFLT_LOCK_ACQUIRE() \
151 KeAcquireSpinLock(&g_VBoxUsbFltGlobals.Lock.Lock, &g_VBoxUsbFltGlobals.Lock.OldIrql);
152#define VBOXUSBFLT_LOCK_RELEASE() \
153 KeReleaseSpinLock(&g_VBoxUsbFltGlobals.Lock.Lock, g_VBoxUsbFltGlobals.Lock.OldIrql);
154
155
156typedef struct VBOXUSBFLT_BLDEV
157{
158 LIST_ENTRY ListEntry;
159 uint16_t idVendor;
160 uint16_t idProduct;
161 uint16_t bcdDevice;
162} VBOXUSBFLT_BLDEV, *PVBOXUSBFLT_BLDEV;
163
164#define PVBOXUSBFLT_BLDEV_FROM_LE(_pLe) ( (PVBOXUSBFLT_BLDEV)( ((uint8_t*)(_pLe)) - RT_OFFSETOF(VBOXUSBFLT_BLDEV, ListEntry) ) )
165
166typedef struct VBOXUSBFLTGLOBALS
167{
168 LIST_ENTRY DeviceList;
169 LIST_ENTRY ContextList;
170 /* devices known to misbehave */
171 LIST_ENTRY BlackDeviceList;
172 VBOXUSBFLT_LOCK Lock;
173} VBOXUSBFLTGLOBALS, *PVBOXUSBFLTGLOBALS;
174static VBOXUSBFLTGLOBALS g_VBoxUsbFltGlobals;
175
176static bool vboxUsbFltBlDevMatchLocked(uint16_t idVendor, uint16_t idProduct, uint16_t bcdDevice)
177{
178 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.BlackDeviceList.Flink;
179 pEntry != &g_VBoxUsbFltGlobals.BlackDeviceList;
180 pEntry = pEntry->Flink)
181 {
182 PVBOXUSBFLT_BLDEV pDev = PVBOXUSBFLT_BLDEV_FROM_LE(pEntry);
183 if (pDev->idVendor != idVendor)
184 continue;
185 if (pDev->idProduct != idProduct)
186 continue;
187 if (pDev->bcdDevice != bcdDevice)
188 continue;
189
190 return true;
191 }
192 return false;
193}
194
195static NTSTATUS vboxUsbFltBlDevAddLocked(uint16_t idVendor, uint16_t idProduct, uint16_t bcdDevice)
196{
197 if (vboxUsbFltBlDevMatchLocked(idVendor, idProduct, bcdDevice))
198 return STATUS_SUCCESS;
199 PVBOXUSBFLT_BLDEV pDev = (PVBOXUSBFLT_BLDEV)VBoxUsbMonMemAllocZ(sizeof (*pDev));
200 if (!pDev)
201 {
202 AssertFailed();
203 return STATUS_INSUFFICIENT_RESOURCES;
204 }
205
206 pDev->idVendor = idVendor;
207 pDev->idProduct = idProduct;
208 pDev->bcdDevice = bcdDevice;
209 InsertHeadList(&g_VBoxUsbFltGlobals.BlackDeviceList, &pDev->ListEntry);
210 return STATUS_SUCCESS;
211}
212
213static void vboxUsbFltBlDevClearLocked()
214{
215 PLIST_ENTRY pNext;
216 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.BlackDeviceList.Flink;
217 pEntry != &g_VBoxUsbFltGlobals.BlackDeviceList;
218 pEntry = pNext)
219 {
220 pNext = pEntry->Flink;
221 VBoxUsbMonMemFree(pEntry);
222 }
223}
224
225static void vboxUsbFltBlDevPopulateWithKnownLocked()
226{
227 /* this one halts when trying to get string descriptors from it */
228 vboxUsbFltBlDevAddLocked(0x5ac, 0x921c, 0x115);
229}
230
231
232DECLINLINE(void) vboxUsbFltDevRetain(PVBOXUSBFLT_DEVICE pDevice)
233{
234 Assert(pDevice->cRefs);
235 ASMAtomicIncU32(&pDevice->cRefs);
236}
237
238static void vboxUsbFltDevDestroy(PVBOXUSBFLT_DEVICE pDevice)
239{
240 Assert(!pDevice->cRefs);
241 Assert(pDevice->enmState == VBOXUSBFLT_DEVSTATE_REMOVED);
242 VBoxUsbMonMemFree(pDevice);
243}
244
245DECLINLINE(void) vboxUsbFltDevRelease(PVBOXUSBFLT_DEVICE pDevice)
246{
247 uint32_t cRefs = ASMAtomicDecU32(&pDevice->cRefs);
248 Assert(cRefs < UINT32_MAX/2);
249 if (!cRefs)
250 {
251 vboxUsbFltDevDestroy(pDevice);
252 }
253}
254
255static void vboxUsbFltDevOwnerSetLocked(PVBOXUSBFLT_DEVICE pDevice, PVBOXUSBFLTCTX pContext, uintptr_t uFltId, bool fIsOneShot)
256{
257 ASSERT_WARN(!pDevice->pOwner, ("device 0x%p has an owner(0x%p)", pDevice, pDevice->pOwner));
258 ++pContext->cActiveFilters;
259 pDevice->pOwner = pContext;
260 pDevice->uFltId = uFltId;
261 pDevice->fIsFilterOneShot = fIsOneShot;
262}
263
264static void vboxUsbFltDevOwnerClearLocked(PVBOXUSBFLT_DEVICE pDevice)
265{
266 ASSERT_WARN(pDevice->pOwner, ("no owner for device 0x%p", pDevice));
267 --pDevice->pOwner->cActiveFilters;
268 ASSERT_WARN(pDevice->pOwner->cActiveFilters < UINT32_MAX/2, ("cActiveFilters (%d)", pDevice->pOwner->cActiveFilters));
269 pDevice->pOwner = NULL;
270 pDevice->uFltId = 0;
271}
272
273static void vboxUsbFltDevOwnerUpdateLocked(PVBOXUSBFLT_DEVICE pDevice, PVBOXUSBFLTCTX pContext, uintptr_t uFltId, bool fIsOneShot)
274{
275 if (pDevice->pOwner != pContext)
276 {
277 if (pDevice->pOwner)
278 vboxUsbFltDevOwnerClearLocked(pDevice);
279 if (pContext)
280 vboxUsbFltDevOwnerSetLocked(pDevice, pContext, uFltId, fIsOneShot);
281 }
282 else if (pContext)
283 {
284 pDevice->uFltId = uFltId;
285 pDevice->fIsFilterOneShot = fIsOneShot;
286 }
287}
288
289static PVBOXUSBFLT_DEVICE vboxUsbFltDevGetLocked(PDEVICE_OBJECT pPdo)
290{
291#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
292 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
293 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
294 pEntry = pEntry->Flink)
295 {
296 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
297 for (PLIST_ENTRY pEntry2 = pEntry->Flink;
298 pEntry2 != &g_VBoxUsbFltGlobals.DeviceList;
299 pEntry2 = pEntry2->Flink)
300 {
301 PVBOXUSBFLT_DEVICE pDevice2 = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry2);
302 ASSERT_WARN( pDevice->idVendor != pDevice2->idVendor
303 || pDevice->idProduct != pDevice2->idProduct
304 || pDevice->bcdDevice != pDevice2->bcdDevice, ("duplicate devices in a list!!"));
305 }
306 }
307#endif
308 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
309 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
310 pEntry = pEntry->Flink)
311 {
312 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
313 ASSERT_WARN( pDevice->enmState == VBOXUSBFLT_DEVSTATE_REPLUGGING
314 || pDevice->enmState == VBOXUSBFLT_DEVSTATE_UNCAPTURED
315 || pDevice->enmState == VBOXUSBFLT_DEVSTATE_CAPTURING
316 || pDevice->enmState == VBOXUSBFLT_DEVSTATE_CAPTURED
317 || pDevice->enmState == VBOXUSBFLT_DEVSTATE_USED_BY_GUEST,
318 ("Invalid device state(%d) for device(0x%p) PDO(0x%p)", pDevice->enmState, pDevice, pDevice->Pdo));
319 if (pDevice->Pdo == pPdo)
320 return pDevice;
321 }
322 return NULL;
323}
324
325static NTSTATUS vboxUsbFltPdoReplug(PDEVICE_OBJECT pDo)
326{
327 LOG(("Replugging PDO(0x%p)", pDo));
328 NTSTATUS Status = VBoxUsbToolIoInternalCtlSendSync(pDo, IOCTL_INTERNAL_USB_CYCLE_PORT, NULL, NULL);
329 ASSERT_WARN(Status == STATUS_SUCCESS, ("replugging PDO(0x%p) failed Status(0x%x)", pDo, Status));
330 LOG(("Replugging PDO(0x%p) done with Status(0x%x)", pDo, Status));
331 return Status;
332}
333
334static bool vboxUsbFltDevCanBeCaptured(PVBOXUSBFLT_DEVICE pDevice)
335{
336 if (pDevice->bClass == USB_DEVICE_CLASS_HUB)
337 {
338 LOG(("device (0x%p), pdo (0x%p) is a hub, can not be captured", pDevice, pDevice->Pdo));
339 return false;
340 }
341 return true;
342}
343
344static PVBOXUSBFLTCTX vboxUsbFltDevMatchLocked(PVBOXUSBFLT_DEVICE pDevice, uintptr_t *puId, bool fRemoveFltIfOneShot, bool *pfFilter, bool *pfIsOneShot)
345{
346 *puId = 0;
347 *pfFilter = false;
348 *pfIsOneShot = false;
349 if (!vboxUsbFltDevCanBeCaptured(pDevice))
350 {
351 LOG(("vboxUsbFltDevCanBeCaptured returned false"));
352 return NULL;
353 }
354
355 USBFILTER DevFlt;
356 USBFilterInit(&DevFlt, USBFILTERTYPE_CAPTURE);
357 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_VENDOR_ID, pDevice->idVendor, true);
358 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_PRODUCT_ID, pDevice->idProduct, true);
359 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_DEVICE_REV, pDevice->bcdDevice, true);
360
361 /* If we could not read a string descriptor, don't set the filter item at all. */
362 if (pDevice->szMfgName[0])
363 USBFilterSetStringExact(&DevFlt, USBFILTERIDX_MANUFACTURER_STR, pDevice->szMfgName, true /*fMustBePresent*/, true /*fPurge*/);
364 if (pDevice->szProduct[0])
365 USBFilterSetStringExact(&DevFlt, USBFILTERIDX_PRODUCT_STR, pDevice->szProduct, true /*fMustBePresent*/, true /*fPurge*/);
366 if (pDevice->szSerial[0])
367 USBFilterSetStringExact(&DevFlt, USBFILTERIDX_SERIAL_NUMBER_STR, pDevice->szSerial, true /*fMustBePresent*/, true /*fPurge*/);
368
369 /* If device descriptor had to be inferred from PnP Manager data, the class/subclass/protocol may be wrong.
370 * When Windows reports CompatibleIDs 'USB\Class_03&SubClass_00&Prot_00', the device descriptor might be
371 * reporting class 3 (HID), *or* the device descriptor might be reporting class 0 (specified by interface)
372 * and the device's interface reporting class 3. Ignore the class/subclass/protocol in such case, since
373 * we are more or less guaranteed to rely on VID/PID anyway.
374 * See @bugref{9479}.
375 */
376 if (pDevice->fInferredDesc)
377 {
378 LOG(("Device descriptor was not read, only inferred; ignoring class/subclass/protocol!"));
379 }
380 else
381 {
382 LOG(("Setting filter class/subclass/protocol %02X/%02X/%02X\n", pDevice->bClass, pDevice->bSubClass, pDevice->bProtocol));
383 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_DEVICE_CLASS, pDevice->bClass, true);
384 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_DEVICE_SUB_CLASS, pDevice->bSubClass, true);
385 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_DEVICE_PROTOCOL, pDevice->bProtocol, true);
386 }
387
388 /* If the port number looks valid, add it to the filter. */
389 if (pDevice->bPort)
390 {
391 LOG(("Setting filter port %04X\n", pDevice->bPort));
392 USBFilterSetNumExact(&DevFlt, USBFILTERIDX_PORT, pDevice->bPort, true);
393 }
394 else
395 LOG(("Port number not known, ignoring!"));
396
397 /* Run filters on the thing. */
398 PVBOXUSBFLTCTX pOwner = VBoxUSBFilterMatchEx(&DevFlt, puId, fRemoveFltIfOneShot, pfFilter, pfIsOneShot);
399 USBFilterDelete(&DevFlt);
400 return pOwner;
401}
402
403static void vboxUsbFltDevStateMarkReplugLocked(PVBOXUSBFLT_DEVICE pDevice)
404{
405 vboxUsbFltDevOwnerUpdateLocked(pDevice, NULL, 0, false);
406 pDevice->enmState = VBOXUSBFLT_DEVSTATE_REPLUGGING;
407}
408
409static bool vboxUsbFltDevStateIsNotFiltered(PVBOXUSBFLT_DEVICE pDevice)
410{
411 return pDevice->enmState == VBOXUSBFLT_DEVSTATE_UNCAPTURED;
412}
413
414static bool vboxUsbFltDevStateIsFiltered(PVBOXUSBFLT_DEVICE pDevice)
415{
416 return pDevice->enmState >= VBOXUSBFLT_DEVSTATE_CAPTURING;
417}
418
419static uint16_t vboxUsbParseHexNumU16(WCHAR **ppStr)
420{
421 WCHAR *pStr = *ppStr;
422 WCHAR wc;
423 uint16_t num = 0;
424 unsigned u;
425
426 for (int i = 0; i < 4; ++i)
427 {
428 if (!*pStr) /* Just in case the string is too short. */
429 break;
430
431 wc = *pStr;
432 u = wc >= 'A' ? wc - 'A' + 10 : wc - '0'; /* Hex digit to number. */
433 num |= u << (12 - 4 * i);
434 pStr++;
435 }
436 *ppStr = pStr;
437
438 return num;
439}
440
441static uint8_t vboxUsbParseHexNumU8(WCHAR **ppStr)
442{
443 WCHAR *pStr = *ppStr;
444 WCHAR wc;
445 uint16_t num = 0;
446 unsigned u;
447
448 for (int i = 0; i < 2; ++i)
449 {
450 if (!*pStr) /* Just in case the string is too short. */
451 break;
452
453 wc = *pStr;
454 u = wc >= 'A' ? wc - 'A' + 10 : wc - '0'; /* Hex digit to number. */
455 num |= u << (4 - 4 * i);
456 pStr++;
457 }
458 *ppStr = pStr;
459
460 return num;
461}
462
463static bool vboxUsbParseHardwareID(WCHAR *pchIdStr, uint16_t *pVid, uint16_t *pPid, uint16_t *pRev)
464{
465#define VID_PREFIX L"USB\\VID_"
466#define PID_PREFIX L"&PID_"
467#define REV_PREFIX L"&REV_"
468
469 *pVid = *pPid = *pRev = 0xFFFF;
470
471 /* The Hardware ID is in the format USB\VID_xxxx&PID_xxxx&REV_xxxx, with 'xxxx'
472 * being 16-bit hexadecimal numbers. The string is coming from the
473 * Windows PnP manager so OEMs should have no opportunity to mess it up.
474 */
475
476 if (wcsncmp(pchIdStr, VID_PREFIX, wcslen(VID_PREFIX)))
477 return false;
478 /* Point to the start of the vendor ID number and parse it. */
479 pchIdStr += wcslen(VID_PREFIX);
480 *pVid = vboxUsbParseHexNumU16(&pchIdStr);
481
482 if (wcsncmp(pchIdStr, PID_PREFIX, wcslen(PID_PREFIX)))
483 return false;
484 /* Point to the start of the product ID number and parse it. */
485 pchIdStr += wcslen(PID_PREFIX);
486 *pPid = vboxUsbParseHexNumU16(&pchIdStr);
487
488 /* The revision might not be there; the Windows documentation is not
489 * entirely clear if it will be always present for USB devices or not.
490 * If it's not there, still consider this a success. */
491 if (wcsncmp(pchIdStr, REV_PREFIX, wcslen(REV_PREFIX)))
492 return true;
493
494 /* Point to the start of the revision number and parse it. */
495 pchIdStr += wcslen(REV_PREFIX);
496 *pRev = vboxUsbParseHexNumU16(&pchIdStr);
497
498 return true;
499#undef VID_PREFIX
500#undef PID_PREFIX
501#undef REV_PREFIX
502}
503
504static bool vboxUsbParseCompatibleIDs(WCHAR *pchIdStr, uint8_t *pClass, uint8_t *pSubClass, uint8_t *pProt)
505{
506#define CLS_PREFIX L"USB\\Class_"
507#define SUB_PREFIX L"&SubClass_"
508#define PRO_PREFIX L"&Prot_"
509
510 *pClass = *pSubClass = *pProt = 0xFF;
511
512 /* The Compatible IDs string is in the format USB\Class_xx&SubClass_xx&Prot_xx,
513 * with 'xx' being 8-bit hexadecimal numbers. Since this string is provided by the
514 * PnP manager and USB devices always report these as part of the basic USB device
515 * descriptor, we assume all three must be present.
516 */
517
518 if (wcsncmp(pchIdStr, CLS_PREFIX, wcslen(CLS_PREFIX)))
519 return false;
520 /* Point to the start of the device class and parse it. */
521 pchIdStr += wcslen(CLS_PREFIX);
522 *pClass = vboxUsbParseHexNumU8(&pchIdStr);
523
524 if (wcsncmp(pchIdStr, SUB_PREFIX, wcslen(SUB_PREFIX)))
525 return false;
526
527 /* Point to the start of the subclass and parse it. */
528 pchIdStr += wcslen(SUB_PREFIX);
529 *pSubClass = vboxUsbParseHexNumU8(&pchIdStr);
530
531 if (wcsncmp(pchIdStr, PRO_PREFIX, wcslen(PRO_PREFIX)))
532 return false;
533
534 /* Point to the start of the protocol and parse it. */
535 pchIdStr += wcslen(PRO_PREFIX);
536 *pProt = vboxUsbParseHexNumU8(&pchIdStr);
537
538 return true;
539#undef CLS_PREFIX
540#undef SUB_PREFIX
541#undef PRO_PREFIX
542}
543
544#define VBOXUSBMON_POPULATE_REQUEST_TIMEOUT_MS 10000
545
546static NTSTATUS vboxUsbFltDevPopulate(PVBOXUSBFLT_DEVICE pDevice, PDEVICE_OBJECT pDo /*, BOOLEAN bPopulateNonFilterProps*/)
547{
548 NTSTATUS Status;
549 USB_TOPOLOGY_ADDRESS TopoAddr;
550 PUSB_DEVICE_DESCRIPTOR pDevDr = 0;
551 ULONG ulResultLen;
552 DEVPROPTYPE type;
553 WCHAR wchPropBuf[256];
554 uint16_t port;
555 bool rc;
556
557 pDevice->Pdo = pDo;
558
559 LOG(("Populating Device(0x%p) for PDO(0x%p)", pDevice, pDo));
560
561 pDevDr = (PUSB_DEVICE_DESCRIPTOR)VBoxUsbMonMemAllocZ(sizeof(*pDevDr));
562 if (pDevDr == NULL)
563 {
564 WARN(("Failed to alloc mem for urb"));
565 return STATUS_INSUFFICIENT_RESOURCES;
566 }
567
568 do
569 {
570 pDevice->fInferredDesc = false;
571 Status = VBoxUsbToolGetDescriptor(pDo, pDevDr, sizeof(*pDevDr), USB_DEVICE_DESCRIPTOR_TYPE, 0, 0, VBOXUSBMON_POPULATE_REQUEST_TIMEOUT_MS);
572 if (!NT_SUCCESS(Status))
573 {
574 uint16_t vid, pid, rev;
575 uint8_t cls, sub, prt;
576
577 WARN(("getting device descriptor failed, Status (0x%x); falling back to IoGetDeviceProperty", Status));
578
579 /* Try falling back to IoGetDevicePropertyData. */
580 Status = IoGetDevicePropertyData(pDo, &DEVPKEY_Device_HardwareIds, LOCALE_NEUTRAL, 0, sizeof(wchPropBuf), wchPropBuf, &ulResultLen, &type);
581 if (!NT_SUCCESS(Status))
582 {
583 /* This just isn't our day. We have no idea what the device is. */
584 WARN(("IoGetDevicePropertyData failed for DEVPKEY_Device_HardwareIds, Status (0x%x)", Status));
585 break;
586 }
587 rc = vboxUsbParseHardwareID(wchPropBuf, &vid, &pid, &rev);
588 if (!rc)
589 {
590 /* This *really* should not happen. */
591 WARN(("Failed to parse Hardware ID"));
592 break;
593 }
594
595 /* Now grab the Compatible IDs to get the class/subclass/protocol. */
596 Status = IoGetDevicePropertyData(pDo, &DEVPKEY_Device_CompatibleIds, LOCALE_NEUTRAL, 0, sizeof(wchPropBuf), wchPropBuf, &ulResultLen, &type);
597 if (!NT_SUCCESS(Status))
598 {
599 /* We really kind of need these. */
600 WARN(("IoGetDevicePropertyData failed for DEVPKEY_Device_CompatibleIds, Status (0x%x)", Status));
601 break;
602 }
603 rc = vboxUsbParseCompatibleIDs(wchPropBuf, &cls, &sub, &prt);
604 if (!rc)
605 {
606 /* This *really* should not happen. */
607 WARN(("Failed to parse Hardware ID"));
608 break;
609 }
610
611 LOG(("Parsed HardwareID: vid=%04X, pid=%04X, rev=%04X, class=%02X, subcls=%02X, prot=%02X", vid, pid, rev, cls, sub, prt));
612 if (vid == 0xFFFF || pid == 0xFFFF)
613 break;
614
615 LOG(("Successfully fell back to IoGetDeviceProperty result"));
616 pDevDr->idVendor = vid;
617 pDevDr->idProduct = pid;
618 pDevDr->bcdDevice = rev;
619 pDevDr->bDeviceClass = cls;
620 pDevDr->bDeviceSubClass = sub;
621 pDevDr->bDeviceProtocol = prt;
622
623 /* The USB device class/subclass/protocol may not be accurate. We have to be careful when comparing
624 * and not take mismatches too seriously.
625 */
626 pDevice->fInferredDesc = true;
627 }
628
629 /* Query the location path. The path is purely a function of the physical device location
630 * and does not change if the device changes, and also does not change depending on
631 * whether the device is captured or not.
632 * NB: We ignore any additional strings and only look at the first one.
633 */
634 Status = IoGetDevicePropertyData(pDo, &DEVPKEY_Device_LocationPaths, LOCALE_NEUTRAL, 0, sizeof(pDevice->szLocationPath), pDevice->szLocationPath, &ulResultLen, &type);
635 if (!NT_SUCCESS(Status))
636 {
637 /* We do need this, but not critically. On Windows 7, we may get STATUS_OBJECT_NAME_NOT_FOUND. */
638 WARN(("IoGetDevicePropertyData failed for DEVPKEY_Device_LocationPaths, Status (0x%x)", Status));
639 }
640 else
641 {
642 LOG_STRW(pDevice->szLocationPath);
643 }
644
645 // Disabled, but could be used as a fallback instead of IoGetDevicePropertyData; it should work even
646 // when this code is entered from the PnP IRP processing path.
647#if 0
648 {
649 HUB_DEVICE_CONFIG_INFO HubInfo;
650
651 memset(&HubInfo, 0, sizeof(HubInfo));
652 HubInfo.Version = 1;
653 HubInfo.Length = sizeof(HubInfo);
654
655 NTSTATUS Status = VBoxUsbToolIoInternalCtlSendSync(pDo, IOCTL_INTERNAL_USB_GET_DEVICE_CONFIG_INFO, &HubInfo, NULL);
656 ASSERT_WARN(Status == STATUS_SUCCESS, ("GET_DEVICE_CONFIG_INFO for PDO(0x%p) failed Status(0x%x)", pDo, Status));
657 LOG(("Querying hub device config info for PDO(0x%p) done with Status(0x%x)", pDo, Status));
658
659 if (Status == STATUS_SUCCESS)
660 {
661 uint16_t vid, pid, rev;
662 uint8_t cls, sub, prt;
663
664 LOG(("Hub flags: %X\n", HubInfo.HubFlags));
665 LOG_STRW(HubInfo.HardwareIds.Buffer);
666 LOG_STRW(HubInfo.CompatibleIds.Buffer);
667 if (HubInfo.DeviceDescription.Buffer)
668 LOG_STRW(HubInfo.DeviceDescription.Buffer);
669
670 rc = vboxUsbParseHardwareID(HubInfo.HardwareIds.Buffer, &pid, &vid, &rev);
671 if (!rc)
672 {
673 /* This *really* should not happen. */
674 WARN(("Failed to parse Hardware ID"));
675 }
676
677 /* The CompatibleID the IOCTL gives is not always the same as what the PnP Manager uses
678 * (thanks, Microsoft). It might look like "USB\DevClass_00&SubClass_00&Prot_00" or like
679 * "USB\USB30_HUB". In such cases, we must consider the class/subclass/protocol
680 * information simply unavailable.
681 */
682 rc = vboxUsbParseCompatibleIDs(HubInfo.CompatibleIds.Buffer, &cls, &sub, &prt);
683 if (!rc)
684 {
685 /* This is unfortunate but not fatal. */
686 WARN(("Failed to parse Compatible ID"));
687 }
688 LOG(("Parsed HardwareID from IOCTL: vid=%04X, pid=%04X, rev=%04X, class=%02X, subcls=%02X, prot=%02X", vid, pid, rev, cls, sub, prt));
689
690 ExFreePool(HubInfo.HardwareIds.Buffer);
691 ExFreePool(HubInfo.CompatibleIds.Buffer);
692 if (HubInfo.DeviceDescription.Buffer)
693 ExFreePool(HubInfo.DeviceDescription.Buffer);
694 }
695 }
696#endif
697
698 /* Query the topology address from the hub driver. This is not trivial to translate to the location
699 * path, but at least we can get the port number this way.
700 */
701 memset(&TopoAddr, 0, sizeof(TopoAddr));
702 Status = VBoxUsbToolIoInternalCtlSendSync(pDo, IOCTL_INTERNAL_USB_GET_TOPOLOGY_ADDRESS, &TopoAddr, NULL);
703 ASSERT_WARN(Status == STATUS_SUCCESS, ("GET_TOPOLOGY_ADDRESS for PDO(0x%p) failed Status(0x%x)", pDo, Status));
704 LOG(("Querying topology address for PDO(0x%p) done with Status(0x%x)", pDo, Status));
705
706 port = 0;
707 if (Status == STATUS_SUCCESS)
708 {
709 uint16_t *pPort = &TopoAddr.RootHubPortNumber;
710
711 /* The last non-zero port number is the one we're looking for. It might be on the
712 * root hub directly, or on some downstream hub.
713 */
714 for (int i = 0; i < RT_ELEMENTS(TopoAddr.HubPortNumber) + 1; ++i) {
715 if (*pPort)
716 port = *pPort;
717 pPort++;
718 }
719 LOG(("PCI bus/dev/fn: %02X:%02X:%02X, parsed port: %u\n", TopoAddr.PciBusNumber, TopoAddr.PciDeviceNumber, TopoAddr.PciFunctionNumber, port));
720 LOG(("RH port: %u, hub ports: %u/%u/%u/%u/%u/%u\n", TopoAddr.RootHubPortNumber, TopoAddr.HubPortNumber[0],
721 TopoAddr.HubPortNumber[1], TopoAddr.HubPortNumber[2], TopoAddr.HubPortNumber[3], TopoAddr.HubPortNumber[4], TopoAddr.HubPortNumber[5]));
722
723 /* In the extremely unlikely case that the port number does not fit into 8 bits, force
724 * it to zero to indicate that we can't use it.
725 */
726 if (port > 255)
727 port = 0;
728 }
729
730 if (vboxUsbFltBlDevMatchLocked(pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice))
731 {
732 WARN(("found a known black list device, vid(0x%x), pid(0x%x), rev(0x%x)", pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice));
733 Status = STATUS_UNSUCCESSFUL;
734 break;
735 }
736
737 LOG(("Device pid=%x vid=%x rev=%x port=%x", pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice, port));
738 pDevice->bPort = port;
739 pDevice->idVendor = pDevDr->idVendor;
740 pDevice->idProduct = pDevDr->idProduct;
741 pDevice->bcdDevice = pDevDr->bcdDevice;
742 pDevice->bClass = pDevDr->bDeviceClass;
743 pDevice->bSubClass = pDevDr->bDeviceSubClass;
744 pDevice->bProtocol = pDevDr->bDeviceProtocol;
745 pDevice->szSerial[0] = 0;
746 pDevice->szMfgName[0] = 0;
747 pDevice->szProduct[0] = 0;
748
749 /* If there are no strings, don't even try to get any string descriptors. */
750 if (pDevDr->iSerialNumber || pDevDr->iManufacturer || pDevDr->iProduct)
751 {
752 int langId;
753
754 Status = VBoxUsbToolGetLangID(pDo, &langId, VBOXUSBMON_POPULATE_REQUEST_TIMEOUT_MS);
755 if (!NT_SUCCESS(Status))
756 {
757 WARN(("reading language ID failed"));
758 if (Status == STATUS_CANCELLED)
759 {
760 WARN(("found a new black list device, vid(0x%x), pid(0x%x), rev(0x%x)", pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice));
761 vboxUsbFltBlDevAddLocked(pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice);
762 Status = STATUS_UNSUCCESSFUL;
763 }
764 break;
765 }
766
767 if (pDevDr->iSerialNumber)
768 {
769 Status = VBoxUsbToolGetStringDescriptor(pDo, pDevice->szSerial, sizeof (pDevice->szSerial), pDevDr->iSerialNumber, langId, VBOXUSBMON_POPULATE_REQUEST_TIMEOUT_MS);
770 if (!NT_SUCCESS(Status))
771 {
772 WARN(("reading serial number failed"));
773 ASSERT_WARN(pDevice->szSerial[0] == '\0', ("serial is not zero!!"));
774 if (Status == STATUS_CANCELLED)
775 {
776 WARN(("found a new black list device, vid(0x%x), pid(0x%x), rev(0x%x)", pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice));
777 vboxUsbFltBlDevAddLocked(pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice);
778 Status = STATUS_UNSUCCESSFUL;
779 break;
780 }
781 LOG(("pretending success.."));
782 Status = STATUS_SUCCESS;
783 }
784 }
785
786 if (pDevDr->iManufacturer)
787 {
788 Status = VBoxUsbToolGetStringDescriptor(pDo, pDevice->szMfgName, sizeof (pDevice->szMfgName), pDevDr->iManufacturer, langId, VBOXUSBMON_POPULATE_REQUEST_TIMEOUT_MS);
789 if (!NT_SUCCESS(Status))
790 {
791 WARN(("reading manufacturer name failed"));
792 ASSERT_WARN(pDevice->szMfgName[0] == '\0', ("szMfgName is not zero!!"));
793 if (Status == STATUS_CANCELLED)
794 {
795 WARN(("found a new black list device, vid(0x%x), pid(0x%x), rev(0x%x)", pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice));
796 vboxUsbFltBlDevAddLocked(pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice);
797 Status = STATUS_UNSUCCESSFUL;
798 break;
799 }
800 LOG(("pretending success.."));
801 Status = STATUS_SUCCESS;
802 }
803 }
804
805 if (pDevDr->iProduct)
806 {
807 Status = VBoxUsbToolGetStringDescriptor(pDo, pDevice->szProduct, sizeof (pDevice->szProduct), pDevDr->iProduct, langId, VBOXUSBMON_POPULATE_REQUEST_TIMEOUT_MS);
808 if (!NT_SUCCESS(Status))
809 {
810 WARN(("reading product name failed"));
811 ASSERT_WARN(pDevice->szProduct[0] == '\0', ("szProduct is not zero!!"));
812 if (Status == STATUS_CANCELLED)
813 {
814 WARN(("found a new black list device, vid(0x%x), pid(0x%x), rev(0x%x)", pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice));
815 vboxUsbFltBlDevAddLocked(pDevDr->idVendor, pDevDr->idProduct, pDevDr->bcdDevice);
816 Status = STATUS_UNSUCCESSFUL;
817 break;
818 }
819 LOG(("pretending success.."));
820 Status = STATUS_SUCCESS;
821 }
822 }
823
824 LOG((": strings: '%s':'%s':'%s' (lang ID %x)",
825 pDevice->szMfgName, pDevice->szProduct, pDevice->szSerial, langId));
826 }
827
828 LOG(("Populating Device(0x%p) for PDO(0x%p) Succeeded", pDevice, pDo));
829 Status = STATUS_SUCCESS;
830 } while (0);
831
832 VBoxUsbMonMemFree(pDevDr);
833 LOG(("Populating Device(0x%p) for PDO(0x%p) Done, Status (0x%x)", pDevice, pDo, Status));
834 return Status;
835}
836
837static bool vboxUsbFltDevCheckReplugLocked(PVBOXUSBFLT_DEVICE pDevice, PVBOXUSBFLTCTX pContext)
838{
839 ASSERT_WARN(pContext, ("context is NULL!"));
840
841 LOG(("Current context is (0x%p)", pContext));
842 LOG(("Current Device owner is (0x%p)", pDevice->pOwner));
843
844 /* check if device is already replugging */
845 if (pDevice->enmState <= VBOXUSBFLT_DEVSTATE_ADDED)
846 {
847 LOG(("Device (0x%p) is already replugging, return..", pDevice));
848 /* it is, do nothing */
849 ASSERT_WARN(pDevice->enmState == VBOXUSBFLT_DEVSTATE_REPLUGGING,
850 ("Device (0x%p) state is NOT REPLUGGING (%d)", pDevice, pDevice->enmState));
851 return false;
852 }
853
854 if (pDevice->pOwner && pContext != pDevice->pOwner)
855 {
856 LOG(("Device (0x%p) is owned by another context(0x%p), current is(0x%p)", pDevice, pDevice->pOwner, pContext));
857 /* this device is owned by another context, we're not allowed to do anything */
858 return false;
859 }
860
861 uintptr_t uId = 0;
862 bool bNeedReplug = false;
863 bool fFilter = false;
864 bool fIsOneShot = false;
865 PVBOXUSBFLTCTX pNewOwner = vboxUsbFltDevMatchLocked(pDevice, &uId,
866 false, /* do not remove a one-shot filter */
867 &fFilter, &fIsOneShot);
868 LOG(("Matching Info: Filter (0x%p), NewOwner(0x%p), fFilter(%d), fIsOneShot(%d)", uId, pNewOwner, (int)fFilter, (int)fIsOneShot));
869 if (pDevice->pOwner && pNewOwner && pDevice->pOwner != pNewOwner)
870 {
871 LOG(("Matching: Device (0x%p) is requested another owner(0x%p), current is(0x%p)", pDevice, pNewOwner, pDevice->pOwner));
872 /* the device is owned by another owner, we can not change the owner here */
873 return false;
874 }
875
876 if (!fFilter)
877 {
878 LOG(("Matching: Device (0x%p) should NOT be filtered", pDevice));
879 /* the device should NOT be filtered, check the current state */
880 if (vboxUsbFltDevStateIsNotFiltered(pDevice))
881 {
882 LOG(("Device (0x%p) is NOT filtered", pDevice));
883 /* no changes */
884 if (fIsOneShot)
885 {
886 ASSERT_WARN(pNewOwner, ("no new owner"));
887 LOG(("Matching: This is a one-shot filter (0x%p), removing..", uId));
888 /* remove a one-shot filter and keep the original filter data */
889 int tmpRc = VBoxUSBFilterRemove(pNewOwner, uId);
890 ASSERT_WARN(RT_SUCCESS(tmpRc), ("remove filter failed, rc (%d)", tmpRc));
891 if (!pDevice->pOwner)
892 {
893 LOG(("Matching: updating the one-shot owner to (0x%p), fltId(0x%p)", pNewOwner, uId));
894 /* update owner for one-shot if the owner is changed (i.e. assigned) */
895 vboxUsbFltDevOwnerUpdateLocked(pDevice, pNewOwner, uId, true);
896 }
897 else
898 {
899 LOG(("Matching: device already has owner (0x%p) assigned", pDevice->pOwner));
900 }
901 }
902 else
903 {
904 LOG(("Matching: This is NOT a one-shot filter (0x%p), newOwner(0x%p)", uId, pNewOwner));
905 if (pNewOwner)
906 {
907 vboxUsbFltDevOwnerUpdateLocked(pDevice, pNewOwner, uId, false);
908 }
909 }
910 }
911 else
912 {
913 LOG(("Device (0x%p) IS filtered", pDevice));
914 /* the device is currently filtered, we should release it only if
915 * 1. device does not have an owner
916 * or
917 * 2. it should be released bue to a one-shot filter
918 * or
919 * 3. it is NOT grabbed by a one-shot filter */
920 if (!pDevice->pOwner || fIsOneShot || !pDevice->fIsFilterOneShot)
921 {
922 LOG(("Matching: Need replug"));
923 bNeedReplug = true;
924 }
925 }
926 }
927 else
928 {
929 LOG(("Matching: Device (0x%p) SHOULD be filtered", pDevice));
930 /* the device should be filtered, check the current state */
931 ASSERT_WARN(uId, ("zero uid"));
932 ASSERT_WARN(pNewOwner, ("zero pNewOwner"));
933 if (vboxUsbFltDevStateIsFiltered(pDevice))
934 {
935 LOG(("Device (0x%p) IS filtered", pDevice));
936 /* the device is filtered */
937 if (pNewOwner == pDevice->pOwner)
938 {
939 LOG(("Device owner match"));
940 /* no changes */
941 if (fIsOneShot)
942 {
943 LOG(("Matching: This is a one-shot filter (0x%p), removing..", uId));
944 /* remove a one-shot filter and keep the original filter data */
945 int tmpRc = VBoxUSBFilterRemove(pNewOwner, uId);
946 ASSERT_WARN(RT_SUCCESS(tmpRc), ("remove filter failed, rc (%d)", tmpRc));
947 }
948 else
949 {
950 LOG(("Matching: This is NOT a one-shot filter (0x%p), Owner(0x%p)", uId, pDevice->pOwner));
951 vboxUsbFltDevOwnerUpdateLocked(pDevice, pDevice->pOwner, uId, false);
952 }
953 }
954 else
955 {
956 ASSERT_WARN(!pDevice->pOwner, ("device should NOT have owner"));
957 LOG(("Matching: Need replug"));
958 /* the device needs to be filtered, but the owner changes, replug needed */
959 bNeedReplug = true;
960 }
961 }
962 else
963 {
964 /* the device is currently NOT filtered,
965 * we should replug it only if
966 * 1. device does not have an owner
967 * or
968 * 2. it should be captured due to a one-shot filter
969 * or
970 * 3. it is NOT released by a one-shot filter */
971 if (!pDevice->pOwner || fIsOneShot || !pDevice->fIsFilterOneShot)
972 {
973 bNeedReplug = true;
974 LOG(("Matching: Need replug"));
975 }
976 }
977 }
978
979 if (bNeedReplug)
980 {
981 LOG(("Matching: Device needs replugging, marking as such"));
982 vboxUsbFltDevStateMarkReplugLocked(pDevice);
983 }
984 else
985 {
986 LOG(("Matching: Device does NOT need replugging"));
987 }
988
989 return bNeedReplug;
990}
991
992static void vboxUsbFltReplugList(PLIST_ENTRY pList)
993{
994 PLIST_ENTRY pNext;
995 for (PLIST_ENTRY pEntry = pList->Flink;
996 pEntry != pList;
997 pEntry = pNext)
998 {
999 pNext = pEntry->Flink;
1000 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_REPLUGGINGLE(pEntry);
1001 LOG(("replugging matched PDO(0x%p), pDevice(0x%p)", pDevice->Pdo, pDevice));
1002 ASSERT_WARN(pDevice->enmState == VBOXUSBFLT_DEVSTATE_REPLUGGING
1003 || pDevice->enmState == VBOXUSBFLT_DEVSTATE_REMOVED,
1004 ("invalid state(0x%x) for device(0x%p)", pDevice->enmState, pDevice));
1005
1006 vboxUsbFltPdoReplug(pDevice->Pdo);
1007 ObDereferenceObject(pDevice->Pdo);
1008 vboxUsbFltDevRelease(pDevice);
1009 }
1010}
1011
1012typedef struct VBOXUSBFLTCHECKWALKER
1013{
1014 PVBOXUSBFLTCTX pContext;
1015} VBOXUSBFLTCHECKWALKER, *PVBOXUSBFLTCHECKWALKER;
1016
1017static DECLCALLBACK(BOOLEAN) vboxUsbFltFilterCheckWalker(PFILE_OBJECT pHubFile,
1018 PDEVICE_OBJECT pHubDo, PVOID pvContext)
1019{
1020 PVBOXUSBFLTCHECKWALKER pData = (PVBOXUSBFLTCHECKWALKER)pvContext;
1021 PVBOXUSBFLTCTX pContext = pData->pContext;
1022
1023 LOG(("Visiting pHubFile(0x%p), pHubDo(0x%p), oContext(0x%p)", pHubFile, pHubDo, pContext));
1024 KIRQL Irql = KeGetCurrentIrql();
1025 ASSERT_WARN(Irql == PASSIVE_LEVEL, ("unexpected IRQL (%d)", Irql));
1026
1027 PDEVICE_RELATIONS pDevRelations = NULL;
1028
1029 NTSTATUS Status = VBoxUsbMonQueryBusRelations(pHubDo, pHubFile, &pDevRelations);
1030 if (Status == STATUS_SUCCESS && pDevRelations)
1031 {
1032 ULONG cReplugPdos = pDevRelations->Count;
1033 LIST_ENTRY ReplugDevList;
1034 InitializeListHead(&ReplugDevList);
1035 for (ULONG k = 0; k < pDevRelations->Count; ++k)
1036 {
1037 PDEVICE_OBJECT pDevObj;
1038
1039 /* Grab the PDO+reference. We won't need the upper layer device object
1040 * anymore, so dereference that right here, and drop the PDO ref later.
1041 */
1042 pDevObj = IoGetDeviceAttachmentBaseRef(pDevRelations->Objects[k]);
1043 LOG(("DevObj=%p, PDO=%p\n", pDevRelations->Objects[k], pDevObj));
1044 ObDereferenceObject(pDevRelations->Objects[k]);
1045 pDevRelations->Objects[k] = pDevObj;
1046
1047 LOG(("Found existing USB PDO 0x%p", pDevObj));
1048 VBOXUSBFLT_LOCK_ACQUIRE();
1049 PVBOXUSBFLT_DEVICE pDevice = vboxUsbFltDevGetLocked(pDevObj);
1050 if (pDevice)
1051 {
1052 LOG(("Found existing device info (0x%p) for PDO 0x%p", pDevice, pDevObj));
1053 bool bReplug = vboxUsbFltDevCheckReplugLocked(pDevice, pContext);
1054 if (bReplug)
1055 {
1056 LOG(("Replug needed for device (0x%p)", pDevice));
1057 InsertHeadList(&ReplugDevList, &pDevice->RepluggingLe);
1058 vboxUsbFltDevRetain(pDevice);
1059 /* do not dereference object since we will use it later */
1060 }
1061 else
1062 {
1063 LOG(("Replug NOT needed for device (0x%p)", pDevice));
1064 ObDereferenceObject(pDevObj);
1065 }
1066
1067 VBOXUSBFLT_LOCK_RELEASE();
1068
1069 pDevRelations->Objects[k] = NULL;
1070 --cReplugPdos;
1071 ASSERT_WARN((uint32_t)cReplugPdos < UINT32_MAX/2, ("cReplugPdos(%d) state broken", cReplugPdos));
1072 continue;
1073 }
1074 VBOXUSBFLT_LOCK_RELEASE();
1075
1076 LOG(("NO device info found for PDO 0x%p", pDevObj));
1077 VBOXUSBFLT_DEVICE Device;
1078 Status = vboxUsbFltDevPopulate(&Device, pDevObj /*, FALSE /* only need filter properties */);
1079 if (NT_SUCCESS(Status))
1080 {
1081 uintptr_t uId = 0;
1082 bool fFilter = false;
1083 bool fIsOneShot = false;
1084 VBOXUSBFLT_LOCK_ACQUIRE();
1085 PVBOXUSBFLTCTX pCtx = vboxUsbFltDevMatchLocked(&Device, &uId,
1086 false, /* do not remove a one-shot filter */
1087 &fFilter, &fIsOneShot);
1088 VBOXUSBFLT_LOCK_RELEASE();
1089 NOREF(pCtx);
1090 LOG(("Matching Info: Filter (0x%p), pCtx(0x%p), fFilter(%d), fIsOneShot(%d)", uId, pCtx, (int)fFilter, (int)fIsOneShot));
1091 if (fFilter)
1092 {
1093 LOG(("Matching: This device SHOULD be filtered"));
1094 /* this device needs to be filtered, but it's not,
1095 * leave the PDO in array to issue a replug request for it
1096 * later on */
1097 continue;
1098 }
1099 }
1100 else
1101 {
1102 WARN(("vboxUsbFltDevPopulate for PDO 0x%p failed with Status 0x%x", pDevObj, Status));
1103 }
1104
1105 LOG(("Matching: This device should NOT be filtered"));
1106 /* this device should not be filtered, and it's not */
1107 ObDereferenceObject(pDevObj);
1108 pDevRelations->Objects[k] = NULL;
1109 --cReplugPdos;
1110 ASSERT_WARN((uint32_t)cReplugPdos < UINT32_MAX/2, ("cReplugPdos is %d", cReplugPdos));
1111 }
1112
1113 LOG(("(%d) non-matched PDOs to be replugged", cReplugPdos));
1114
1115 if (cReplugPdos)
1116 {
1117 for (ULONG k = 0; k < pDevRelations->Count; ++k)
1118 {
1119 if (!pDevRelations->Objects[k])
1120 continue;
1121
1122 Status = vboxUsbFltPdoReplug(pDevRelations->Objects[k]);
1123 ASSERT_WARN(Status == STATUS_SUCCESS, ("vboxUsbFltPdoReplug failed! Status(0x%x)", Status));
1124 ObDereferenceObject(pDevRelations->Objects[k]);
1125 if (!--cReplugPdos)
1126 break;
1127 }
1128
1129 ASSERT_WARN(!cReplugPdos, ("cReplugPdos reached zero!"));
1130 }
1131
1132 vboxUsbFltReplugList(&ReplugDevList);
1133
1134 ExFreePool(pDevRelations);
1135 }
1136 else
1137 {
1138 WARN(("VBoxUsbMonQueryBusRelations failed for hub DO(0x%p), Status(0x%x), pDevRelations(0x%p)",
1139 pHubDo, Status, pDevRelations));
1140 }
1141
1142 LOG(("Done Visiting pHubFile(0x%p), pHubDo(0x%p), oContext(0x%p)", pHubFile, pHubDo, pContext));
1143
1144 return TRUE;
1145}
1146
1147NTSTATUS VBoxUsbFltFilterCheck(PVBOXUSBFLTCTX pContext)
1148{
1149 KIRQL Irql = KeGetCurrentIrql();
1150 ASSERT_WARN(Irql == PASSIVE_LEVEL, ("unexpected IRQL (%d)", Irql));
1151
1152 LOG(("Running filters, Context (0x%p)..", pContext));
1153
1154 VBOXUSBFLTCHECKWALKER Data;
1155 Data.pContext = pContext;
1156 vboxUsbMonHubDevWalk(vboxUsbFltFilterCheckWalker, &Data);
1157
1158 LOG(("DONE Running filters, Context (0x%p)", pContext));
1159
1160 return STATUS_SUCCESS;
1161}
1162
1163NTSTATUS VBoxUsbFltClose(PVBOXUSBFLTCTX pContext)
1164{
1165 LOG(("Closing context(0x%p)", pContext));
1166 LIST_ENTRY ReplugDevList;
1167 InitializeListHead(&ReplugDevList);
1168
1169 ASSERT_WARN(pContext, ("null context"));
1170
1171 KIRQL Irql = KeGetCurrentIrql();
1172 ASSERT_WARN(Irql == PASSIVE_LEVEL, ("irql==(%d)", Irql));
1173
1174 VBOXUSBFLT_LOCK_ACQUIRE();
1175
1176 pContext->bRemoved = TRUE;
1177 RemoveEntryList(&pContext->ListEntry);
1178
1179 LOG(("removing owner filters"));
1180 /* now re-arrange the filters */
1181 /* 1. remove filters */
1182 VBoxUSBFilterRemoveOwner(pContext);
1183
1184 LOG(("enumerating devices.."));
1185 /* 2. check if there are devices owned */
1186 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
1187 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
1188 pEntry = pEntry->Flink)
1189 {
1190 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
1191 if (pDevice->pOwner != pContext)
1192 continue;
1193
1194 LOG(("found device(0x%p), pdo(0x%p), state(%d), filter id(0x%p), oneshot(%d)",
1195 pDevice, pDevice->Pdo, pDevice->enmState, pDevice->uFltId, (int)pDevice->fIsFilterOneShot));
1196 ASSERT_WARN(pDevice->enmState != VBOXUSBFLT_DEVSTATE_ADDED, ("VBOXUSBFLT_DEVSTATE_ADDED state for device(0x%p)", pDevice));
1197 ASSERT_WARN(pDevice->enmState != VBOXUSBFLT_DEVSTATE_REMOVED, ("VBOXUSBFLT_DEVSTATE_REMOVED state for device(0x%p)", pDevice));
1198
1199 vboxUsbFltDevOwnerClearLocked(pDevice);
1200
1201 if (vboxUsbFltDevCheckReplugLocked(pDevice, pContext))
1202 {
1203 LOG(("device needs replug"));
1204 InsertHeadList(&ReplugDevList, &pDevice->RepluggingLe);
1205 /* retain to ensure the device is not removed before we issue a replug */
1206 vboxUsbFltDevRetain(pDevice);
1207 /* keep the PDO alive */
1208 ObReferenceObject(pDevice->Pdo);
1209 }
1210 else
1211 {
1212 LOG(("device does NOT need replug"));
1213 }
1214 }
1215
1216 VBOXUSBFLT_LOCK_RELEASE();
1217
1218 /* this should replug all devices that were either skipped or grabbed due to the context's */
1219 vboxUsbFltReplugList(&ReplugDevList);
1220
1221 LOG(("SUCCESS done context(0x%p)", pContext));
1222 return STATUS_SUCCESS;
1223}
1224
1225NTSTATUS VBoxUsbFltCreate(PVBOXUSBFLTCTX pContext)
1226{
1227 LOG(("Creating context(0x%p)", pContext));
1228 memset(pContext, 0, sizeof (*pContext));
1229 pContext->Process = RTProcSelf();
1230 VBOXUSBFLT_LOCK_ACQUIRE();
1231 InsertHeadList(&g_VBoxUsbFltGlobals.ContextList, &pContext->ListEntry);
1232 VBOXUSBFLT_LOCK_RELEASE();
1233 LOG(("SUCCESS context(0x%p)", pContext));
1234 return STATUS_SUCCESS;
1235}
1236
1237int VBoxUsbFltAdd(PVBOXUSBFLTCTX pContext, PUSBFILTER pFilter, uintptr_t *pId)
1238{
1239 LOG(("adding filter, Context (0x%p)..", pContext));
1240 *pId = 0;
1241 /* LOG the filter details. */
1242 LOG((__FUNCTION__": %s %s %s",
1243 USBFilterGetString(pFilter, USBFILTERIDX_MANUFACTURER_STR) ? USBFilterGetString(pFilter, USBFILTERIDX_MANUFACTURER_STR) : "<null>",
1244 USBFilterGetString(pFilter, USBFILTERIDX_PRODUCT_STR) ? USBFilterGetString(pFilter, USBFILTERIDX_PRODUCT_STR) : "<null>",
1245 USBFilterGetString(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR) ? USBFilterGetString(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR) : "<null>"));
1246#ifdef VBOX_USB_WITH_VERBOSE_LOGGING
1247 LOG(("VBoxUSBClient::addFilter: idVendor=%#x idProduct=%#x bcdDevice=%#x bDeviceClass=%#x bDeviceSubClass=%#x bDeviceProtocol=%#x bBus=%#x bPort=%#x Type%#x",
1248 USBFilterGetNum(pFilter, USBFILTERIDX_VENDOR_ID),
1249 USBFilterGetNum(pFilter, USBFILTERIDX_PRODUCT_ID),
1250 USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_REV),
1251 USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_CLASS),
1252 USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_SUB_CLASS),
1253 USBFilterGetNum(pFilter, USBFILTERIDX_DEVICE_PROTOCOL),
1254 USBFilterGetNum(pFilter, USBFILTERIDX_BUS),
1255 USBFilterGetNum(pFilter, USBFILTERIDX_PORT),
1256 USBFilterGetFilterType(pFilter)));
1257#endif
1258
1259 /* We can't get the bus/port numbers. Ignore them while matching. */
1260 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_BUS, false);
1261 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_PORT, false);
1262
1263 /* We may not be able to reconstruct the class/subclass/protocol if we aren't able to
1264 * read the device descriptor. Don't require these to be present. See also the fInferredDesc flag.
1265 */
1266 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_DEVICE_CLASS, false);
1267 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_DEVICE_SUB_CLASS, false);
1268 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_DEVICE_PROTOCOL, false);
1269
1270 /* We may also be unable to read string descriptors. Often the userland can't read the
1271 * string descriptors either because the device is in a low-power state, but it can happen
1272 * that the userland gets lucky and reads the strings, but by the time we get to read them
1273 * they're inaccessible due to power management. So, don't require the strings to be present.
1274 */
1275 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_MANUFACTURER_STR, false);
1276 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_PRODUCT_STR, false);
1277 USBFilterSetMustBePresent(pFilter, USBFILTERIDX_SERIAL_NUMBER_STR, false);
1278
1279 uintptr_t uId = 0;
1280 VBOXUSBFLT_LOCK_ACQUIRE();
1281 /* Add the filter. */
1282 int rc = VBoxUSBFilterAdd(pFilter, pContext, &uId);
1283 VBOXUSBFLT_LOCK_RELEASE();
1284 if (RT_SUCCESS(rc))
1285 {
1286 LOG(("ADDED filter id 0x%p", uId));
1287 ASSERT_WARN(uId, ("uid is NULL"));
1288#ifdef VBOX_USBMON_WITH_FILTER_AUTOAPPLY
1289 VBoxUsbFltFilterCheck();
1290#endif
1291 }
1292 else
1293 {
1294 WARN(("VBoxUSBFilterAdd failed rc (%d)", rc));
1295 ASSERT_WARN(!uId, ("uid is not NULL"));
1296 }
1297
1298 *pId = uId;
1299 return rc;
1300}
1301
1302int VBoxUsbFltRemove(PVBOXUSBFLTCTX pContext, uintptr_t uId)
1303{
1304 LOG(("removing filter id(0x%p), Context (0x%p)..", pContext, uId));
1305 Assert(uId);
1306
1307 VBOXUSBFLT_LOCK_ACQUIRE();
1308 int rc = VBoxUSBFilterRemove(pContext, uId);
1309 if (!RT_SUCCESS(rc))
1310 {
1311 WARN(("VBoxUSBFilterRemove failed rc (%d)", rc));
1312 VBOXUSBFLT_LOCK_RELEASE();
1313 return rc;
1314 }
1315
1316 LOG(("enumerating devices.."));
1317 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
1318 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
1319 pEntry = pEntry->Flink)
1320 {
1321 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
1322 if (pDevice->fIsFilterOneShot)
1323 {
1324 ASSERT_WARN(!pDevice->uFltId, ("oneshot filter on device(0x%p): unexpected uFltId(%d)", pDevice, pDevice->uFltId));
1325 }
1326
1327 if (pDevice->uFltId != uId)
1328 continue;
1329
1330 ASSERT_WARN(pDevice->pOwner == pContext, ("Device(0x%p) owner(0x%p) not match to (0x%p)", pDevice, pDevice->pOwner, pContext));
1331 if (pDevice->pOwner != pContext)
1332 continue;
1333
1334 LOG(("found device(0x%p), pdo(0x%p), state(%d), filter id(0x%p), oneshot(%d)",
1335 pDevice, pDevice->Pdo, pDevice->enmState, pDevice->uFltId, (int)pDevice->fIsFilterOneShot));
1336 ASSERT_WARN(!pDevice->fIsFilterOneShot, ("device(0x%p) is filtered with a oneshot filter", pDevice));
1337 pDevice->uFltId = 0;
1338 /* clear the fIsFilterOneShot flag to ensure the device is replugged on the next VBoxUsbFltFilterCheck call */
1339 pDevice->fIsFilterOneShot = false;
1340 }
1341 VBOXUSBFLT_LOCK_RELEASE();
1342
1343 LOG(("done enumerating devices"));
1344
1345 if (RT_SUCCESS(rc))
1346 {
1347#ifdef VBOX_USBMON_WITH_FILTER_AUTOAPPLY
1348 VBoxUsbFltFilterCheck();
1349#endif
1350 }
1351 return rc;
1352}
1353
1354static USBDEVICESTATE vboxUsbDevGetUserState(PVBOXUSBFLTCTX pContext, PVBOXUSBFLT_DEVICE pDevice)
1355{
1356 if (vboxUsbFltDevStateIsNotFiltered(pDevice))
1357 return USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1358
1359 /* the device is filtered, or replugging */
1360 if (pDevice->enmState == VBOXUSBFLT_DEVSTATE_REPLUGGING)
1361 {
1362 ASSERT_WARN(!pDevice->pOwner, ("replugging device(0x%p) still has an owner(0x%p)", pDevice, pDevice->pOwner));
1363 ASSERT_WARN(!pDevice->uFltId, ("replugging device(0x%p) still has filter(0x%p)", pDevice, pDevice->uFltId));
1364 /* no user state for this, we should not return it tu the user */
1365 return USBDEVICESTATE_USED_BY_HOST;
1366 }
1367
1368 /* the device is filtered, if owner differs from the context, return as USED_BY_HOST */
1369 ASSERT_WARN(pDevice->pOwner, ("device(0x%p) has noowner", pDevice));
1370 /* the id can be null if a filter is removed */
1371// Assert(pDevice->uFltId);
1372
1373 if (pDevice->pOwner != pContext)
1374 {
1375 LOG(("Device owner differs from the current context, returning used by host"));
1376 return USBDEVICESTATE_USED_BY_HOST;
1377 }
1378
1379 switch (pDevice->enmState)
1380 {
1381 case VBOXUSBFLT_DEVSTATE_UNCAPTURED:
1382 case VBOXUSBFLT_DEVSTATE_CAPTURING:
1383 return USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
1384 case VBOXUSBFLT_DEVSTATE_CAPTURED:
1385 return USBDEVICESTATE_HELD_BY_PROXY;
1386 case VBOXUSBFLT_DEVSTATE_USED_BY_GUEST:
1387 return USBDEVICESTATE_USED_BY_GUEST;
1388 default:
1389 WARN(("unexpected device state(%d) for device(0x%p)", pDevice->enmState, pDevice));
1390 return USBDEVICESTATE_UNSUPPORTED;
1391 }
1392}
1393
1394NTSTATUS VBoxUsbFltGetDevice(PVBOXUSBFLTCTX pContext, HVBOXUSBDEVUSR hDevice, PUSBSUP_GETDEV_MON pInfo)
1395{
1396 if (!hDevice)
1397 return STATUS_INVALID_PARAMETER;
1398
1399 memset (pInfo, 0, sizeof (*pInfo));
1400 VBOXUSBFLT_LOCK_ACQUIRE();
1401 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
1402 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
1403 pEntry = pEntry->Flink)
1404 {
1405 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
1406 Assert(pDevice->enmState != VBOXUSBFLT_DEVSTATE_REMOVED);
1407 Assert(pDevice->enmState != VBOXUSBFLT_DEVSTATE_ADDED);
1408
1409 if (pDevice != hDevice)
1410 continue;
1411
1412 USBDEVICESTATE enmUsrState = vboxUsbDevGetUserState(pContext, pDevice);
1413 pInfo->enmState = enmUsrState;
1414 VBOXUSBFLT_LOCK_RELEASE();
1415 return STATUS_SUCCESS;
1416 }
1417
1418 VBOXUSBFLT_LOCK_RELEASE();
1419
1420 /* We should not get this far with valid input. */
1421 return STATUS_INVALID_PARAMETER;
1422}
1423
1424NTSTATUS VBoxUsbFltPdoAdd(PDEVICE_OBJECT pPdo, BOOLEAN *pbFiltered)
1425{
1426 *pbFiltered = FALSE;
1427 PVBOXUSBFLT_DEVICE pDevice;
1428
1429 /* Find the real PDO+reference. Dereference when we're done with it. Note that
1430 * the input pPdo was not explicitly referenced so we're not dropping its ref.
1431 */
1432 PDEVICE_OBJECT pDevObj = IoGetDeviceAttachmentBaseRef(pPdo);
1433 LOG(("DevObj=%p, real PDO=%p\n", pPdo, pDevObj));
1434 pPdo = pDevObj;
1435
1436 /* first check if device is in the a already */
1437 VBOXUSBFLT_LOCK_ACQUIRE();
1438 pDevice = vboxUsbFltDevGetLocked(pPdo);
1439 if (pDevice)
1440 {
1441 LOG(("found device (0x%p), state(%d) for PDO(0x%p)", pDevice, pDevice->enmState, pPdo));
1442 ASSERT_WARN(pDevice->enmState != VBOXUSBFLT_DEVSTATE_ADDED, ("VBOXUSBFLT_DEVSTATE_ADDED state for device(0x%p)", pDevice));
1443 ASSERT_WARN(pDevice->enmState != VBOXUSBFLT_DEVSTATE_REMOVED, ("VBOXUSBFLT_DEVSTATE_REMOVED state for device(0x%p)", pDevice));
1444 *pbFiltered = pDevice->enmState >= VBOXUSBFLT_DEVSTATE_CAPTURING;
1445 VBOXUSBFLT_LOCK_RELEASE();
1446 ObDereferenceObject(pPdo);
1447 return STATUS_SUCCESS;
1448 }
1449 VBOXUSBFLT_LOCK_RELEASE();
1450 pDevice = (PVBOXUSBFLT_DEVICE)VBoxUsbMonMemAllocZ(sizeof (*pDevice));
1451 if (!pDevice)
1452 {
1453 WARN(("VBoxUsbMonMemAllocZ failed"));
1454 ObDereferenceObject(pPdo);
1455 return STATUS_NO_MEMORY;
1456 }
1457
1458 pDevice->enmState = VBOXUSBFLT_DEVSTATE_ADDED;
1459 pDevice->cRefs = 1;
1460 NTSTATUS Status = vboxUsbFltDevPopulate(pDevice, pPdo /* , TRUE /* need all props */);
1461 if (!NT_SUCCESS(Status))
1462 {
1463 WARN(("vboxUsbFltDevPopulate failed, Status 0x%x", Status));
1464 ObDereferenceObject(pPdo);
1465 VBoxUsbMonMemFree(pDevice);
1466 return Status;
1467 }
1468
1469 uintptr_t uId;
1470 bool fFilter = false;
1471 bool fIsOneShot = false;
1472 PVBOXUSBFLTCTX pCtx;
1473 PVBOXUSBFLT_DEVICE pTmpDev;
1474 VBOXUSBFLT_LOCK_ACQUIRE();
1475 /* (paranoia) re-check the device is still not here */
1476 pTmpDev = vboxUsbFltDevGetLocked(pPdo);
1477
1478 /* Drop the PDO ref, now we won't need it anymore. */
1479 ObDereferenceObject(pPdo);
1480
1481 if (pTmpDev)
1482 {
1483 LOG(("second try: found device (0x%p), state(%d) for PDO(0x%p)", pDevice, pDevice->enmState, pPdo));
1484 ASSERT_WARN(pDevice->enmState != VBOXUSBFLT_DEVSTATE_ADDED, ("second try: VBOXUSBFLT_DEVSTATE_ADDED state for device(0x%p)", pDevice));
1485 ASSERT_WARN(pDevice->enmState != VBOXUSBFLT_DEVSTATE_REMOVED, ("second try: VBOXUSBFLT_DEVSTATE_REMOVED state for device(0x%p)", pDevice));
1486 *pbFiltered = pTmpDev->enmState >= VBOXUSBFLT_DEVSTATE_CAPTURING;
1487 VBOXUSBFLT_LOCK_RELEASE();
1488 VBoxUsbMonMemFree(pDevice);
1489 return STATUS_SUCCESS;
1490 }
1491
1492 LOG(("Created Device 0x%p for PDO 0x%p", pDevice, pPdo));
1493
1494 pCtx = vboxUsbFltDevMatchLocked(pDevice, &uId,
1495 true, /* remove a one-shot filter */
1496 &fFilter, &fIsOneShot);
1497 LOG(("Matching Info: Filter (0x%p), pCtx(0x%p), fFilter(%d), fIsOneShot(%d)", uId, pCtx, (int)fFilter, (int)fIsOneShot));
1498 if (fFilter)
1499 {
1500 LOG(("Created Device 0x%p should be filtered", pDevice));
1501 ASSERT_WARN(pCtx, ("zero ctx"));
1502 ASSERT_WARN(uId, ("zero uId"));
1503 pDevice->enmState = VBOXUSBFLT_DEVSTATE_CAPTURING;
1504 }
1505 else
1506 {
1507 LOG(("Created Device 0x%p should NOT be filtered", pDevice));
1508 ASSERT_WARN(!uId == !pCtx, ("invalid uid(0x%p) - ctx(0x%p) pair", uId, pCtx)); /* either both zero or both not */
1509 pDevice->enmState = VBOXUSBFLT_DEVSTATE_UNCAPTURED;
1510 }
1511
1512 if (pCtx)
1513 vboxUsbFltDevOwnerSetLocked(pDevice, pCtx, fIsOneShot ? 0 : uId, fIsOneShot);
1514
1515 InsertHeadList(&g_VBoxUsbFltGlobals.DeviceList, &pDevice->GlobalLe);
1516
1517 /* do not need to signal anything here -
1518 * going to do that once the proxy device object starts */
1519 VBOXUSBFLT_LOCK_RELEASE();
1520
1521 *pbFiltered = fFilter;
1522
1523 return STATUS_SUCCESS;
1524}
1525
1526BOOLEAN VBoxUsbFltPdoIsFiltered(PDEVICE_OBJECT pPdo)
1527{
1528 VBOXUSBFLT_DEVSTATE enmState = VBOXUSBFLT_DEVSTATE_REMOVED;
1529
1530 /* Find the real PDO+reference. Dereference when we're done with it. Note that
1531 * the input pPdo was not explicitly referenced so we're not dropping its ref.
1532 */
1533 PDEVICE_OBJECT pDevObj = IoGetDeviceAttachmentBaseRef(pPdo);
1534 LOG(("DevObj=%p, real PDO=%p\n", pPdo, pDevObj));
1535 pPdo = pDevObj;
1536
1537 VBOXUSBFLT_LOCK_ACQUIRE();
1538
1539 PVBOXUSBFLT_DEVICE pDevice = vboxUsbFltDevGetLocked(pPdo);
1540 if (pDevice)
1541 enmState = pDevice->enmState;
1542
1543 VBOXUSBFLT_LOCK_RELEASE();
1544 ObDereferenceObject(pPdo);
1545
1546 return enmState >= VBOXUSBFLT_DEVSTATE_CAPTURING;
1547}
1548
1549NTSTATUS VBoxUsbFltPdoRemove(PDEVICE_OBJECT pPdo)
1550{
1551 PVBOXUSBFLT_DEVICE pDevice;
1552 VBOXUSBFLT_DEVSTATE enmOldState;
1553
1554 /* Find the real PDO+reference. Dereference when we're done with it. Note that
1555 * the input pPdo was not explicitly referenced so we're not dropping its ref.
1556 */
1557 PDEVICE_OBJECT pDevObj = IoGetDeviceAttachmentBaseRef(pPdo);
1558 LOG(("DevObj=%p, real PDO=%p\n", pPdo, pDevObj));
1559 pPdo = pDevObj;
1560
1561 VBOXUSBFLT_LOCK_ACQUIRE();
1562 pDevice = vboxUsbFltDevGetLocked(pPdo);
1563 if (pDevice)
1564 {
1565 RemoveEntryList(&pDevice->GlobalLe);
1566 enmOldState = pDevice->enmState;
1567 pDevice->enmState = VBOXUSBFLT_DEVSTATE_REMOVED;
1568 }
1569 VBOXUSBFLT_LOCK_RELEASE();
1570 ObDereferenceObject(pPdo);
1571 if (pDevice)
1572 vboxUsbFltDevRelease(pDevice);
1573 return STATUS_SUCCESS;
1574}
1575
1576HVBOXUSBFLTDEV VBoxUsbFltProxyStarted(PDEVICE_OBJECT pPdo)
1577{
1578 PVBOXUSBFLT_DEVICE pDevice;
1579 VBOXUSBFLT_LOCK_ACQUIRE();
1580
1581 /* NB: The USB proxy (VBoxUSB.sys) passes us the real PDO, not anything above that. */
1582 pDevice = vboxUsbFltDevGetLocked(pPdo);
1583 /*
1584 * Prevent a host crash when vboxUsbFltDevGetLocked fails to locate the matching PDO
1585 * in g_VBoxUsbFltGlobals.DeviceList (see @bugref{6509}).
1586 */
1587 if (pDevice == NULL)
1588 {
1589 WARN(("failed to get device for PDO(0x%p)", pPdo));
1590 }
1591 else if (pDevice->enmState == VBOXUSBFLT_DEVSTATE_CAPTURING)
1592 {
1593 pDevice->enmState = VBOXUSBFLT_DEVSTATE_CAPTURED;
1594 LOG(("The proxy notified proxy start for the captured device 0x%p", pDevice));
1595 vboxUsbFltDevRetain(pDevice);
1596 }
1597 else
1598 {
1599 WARN(("invalid state, %d", pDevice->enmState));
1600 pDevice = NULL;
1601 }
1602 VBOXUSBFLT_LOCK_RELEASE();
1603 return pDevice;
1604}
1605
1606void VBoxUsbFltProxyStopped(HVBOXUSBFLTDEV hDev)
1607{
1608 PVBOXUSBFLT_DEVICE pDevice = (PVBOXUSBFLT_DEVICE)hDev;
1609 /*
1610 * Prevent a host crash when VBoxUsbFltProxyStarted fails, returning NULL.
1611 * See @bugref{6509}.
1612 */
1613 if (pDevice == NULL)
1614 {
1615 WARN(("VBoxUsbFltProxyStopped called with NULL device pointer"));
1616 return;
1617 }
1618 VBOXUSBFLT_LOCK_ACQUIRE();
1619 if (pDevice->enmState == VBOXUSBFLT_DEVSTATE_CAPTURED
1620 || pDevice->enmState == VBOXUSBFLT_DEVSTATE_USED_BY_GUEST)
1621 {
1622 /* this is due to the device being physically removed */
1623 LOG(("The proxy notified proxy stop for the captured device 0x%p, current state %d", pDevice, pDevice->enmState));
1624 pDevice->enmState = VBOXUSBFLT_DEVSTATE_CAPTURING;
1625 }
1626 else
1627 {
1628 if (pDevice->enmState != VBOXUSBFLT_DEVSTATE_REPLUGGING)
1629 {
1630 WARN(("invalid state, %d", pDevice->enmState));
1631 }
1632 }
1633 VBOXUSBFLT_LOCK_RELEASE();
1634
1635 vboxUsbFltDevRelease(pDevice);
1636}
1637
1638
1639static NTSTATUS vboxUsbFltRegKeyQuery(PWSTR ValueName, ULONG ValueType, PVOID ValueData, ULONG ValueLength, PVOID Context, PVOID EntryContext)
1640{
1641 NTSTATUS Status = STATUS_SUCCESS;
1642
1643 RT_NOREF(ValueName, Context);
1644 if ( ValueType == REG_DWORD
1645 && ValueLength == sizeof(ULONG))
1646 *(ULONG *)EntryContext = *(ULONG *)ValueData;
1647 else
1648 Status = STATUS_OBJECT_TYPE_MISMATCH;
1649
1650 return Status;
1651}
1652
1653
1654NTSTATUS VBoxUsbFltInit()
1655{
1656 int rc = VBoxUSBFilterInit();
1657 if (RT_FAILURE(rc))
1658 {
1659 WARN(("VBoxUSBFilterInit failed, rc (%d)", rc));
1660 return STATUS_UNSUCCESSFUL;
1661 }
1662
1663 memset(&g_VBoxUsbFltGlobals, 0, sizeof (g_VBoxUsbFltGlobals));
1664 InitializeListHead(&g_VBoxUsbFltGlobals.DeviceList);
1665 InitializeListHead(&g_VBoxUsbFltGlobals.ContextList);
1666 InitializeListHead(&g_VBoxUsbFltGlobals.BlackDeviceList);
1667 vboxUsbFltBlDevPopulateWithKnownLocked();
1668 VBOXUSBFLT_LOCK_INIT();
1669
1670 return STATUS_SUCCESS;
1671}
1672
1673NTSTATUS VBoxUsbFltTerm()
1674{
1675 bool bBusy = false;
1676 VBOXUSBFLT_LOCK_ACQUIRE();
1677 do
1678 {
1679 if (!IsListEmpty(&g_VBoxUsbFltGlobals.ContextList))
1680 {
1681 AssertFailed();
1682 bBusy = true;
1683 break;
1684 }
1685
1686 PLIST_ENTRY pNext = NULL;
1687 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
1688 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
1689 pEntry = pNext)
1690 {
1691 pNext = pEntry->Flink;
1692 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
1693 Assert(!pDevice->uFltId);
1694 Assert(!pDevice->pOwner);
1695 if (pDevice->cRefs != 1)
1696 {
1697 AssertFailed();
1698 bBusy = true;
1699 break;
1700 }
1701 }
1702 } while (0);
1703
1704 VBOXUSBFLT_LOCK_RELEASE()
1705
1706 if (bBusy)
1707 {
1708 return STATUS_DEVICE_BUSY;
1709 }
1710
1711 for (PLIST_ENTRY pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink;
1712 pEntry != &g_VBoxUsbFltGlobals.DeviceList;
1713 pEntry = g_VBoxUsbFltGlobals.DeviceList.Flink)
1714 {
1715 RemoveEntryList(pEntry);
1716 PVBOXUSBFLT_DEVICE pDevice = PVBOXUSBFLT_DEVICE_FROM_LE(pEntry);
1717 pDevice->enmState = VBOXUSBFLT_DEVSTATE_REMOVED;
1718 vboxUsbFltDevRelease(pDevice);
1719 }
1720
1721 vboxUsbFltBlDevClearLocked();
1722
1723 VBOXUSBFLT_LOCK_TERM();
1724
1725 VBoxUSBFilterTerm();
1726
1727 return STATUS_SUCCESS;
1728}
1729
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