VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/linux/USBProxyServiceLinux.cpp@ 36993

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

Main/linux/USB: unit tests for the code changed in r71554 and r71557

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 13.9 KB
Line 
1/* $Id: USBProxyServiceLinux.cpp 36993 2011-05-06 21:53:21Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Service, Linux Specialization.
4 */
5
6/*
7 * Copyright (C) 2006-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.215389.xyz. 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
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#include "USBProxyService.h"
23#include "USBGetDevices.h"
24#include "Logging.h"
25
26#include <VBox/usb.h>
27#include <VBox/usblib.h>
28#include <VBox/err.h>
29
30#include <iprt/string.h>
31#include <iprt/alloc.h>
32#include <iprt/assert.h>
33#include <iprt/ctype.h>
34#include <iprt/dir.h>
35#include <iprt/env.h>
36#include <iprt/file.h>
37#include <iprt/err.h>
38#include <iprt/mem.h>
39#include <iprt/param.h>
40#include <iprt/path.h>
41#include <iprt/stream.h>
42#include <iprt/linux/sysfs.h>
43
44#include <stdlib.h>
45#include <string.h>
46#include <stdio.h>
47#include <errno.h>
48#include <fcntl.h>
49#include <unistd.h>
50#include <sys/statfs.h>
51#include <sys/poll.h>
52#ifdef VBOX_WITH_LINUX_COMPILER_H
53# include <linux/compiler.h>
54#endif
55#include <linux/usbdevice_fs.h>
56
57
58/**
59 * Initialize data members.
60 */
61USBProxyServiceLinux::USBProxyServiceLinux(Host *aHost)
62 : USBProxyService(aHost), mFile(NIL_RTFILE), mWakeupPipeR(NIL_RTFILE),
63 mWakeupPipeW(NIL_RTFILE), mUsingUsbfsDevices(true /* see init */),
64 mUdevPolls(0), mpWaiter(NULL)
65#ifdef UNIT_TEST
66 , mpcszTestUsbfsRoot(NULL), mfTestUsbfsAccessible(false),
67 mpcszTestDevicesRoot(NULL), mfTestDevicesAccessible(false),
68 mrcTestMethodInitResult(VINF_SUCCESS), mpcszTestEnvUsb(NULL),
69 mpcszTestEnvUsbRoot(NULL)
70#endif
71{
72 LogFlowThisFunc(("aHost=%p\n", aHost));
73}
74
75#ifdef UNIT_TEST
76/* For testing we redefine anything that accesses the outside world to
77 * return test values. */
78# define RTEnvGet(a) \
79 ( !RTStrCmp(a, "VBOX_USB") ? mpcszTestEnvUsb \
80 : !RTStrCmp(a, "VBOX_USB_ROOT") ? mpcszTestEnvUsbRoot \
81 : NULL)
82# define USBProxyLinuxCheckDeviceRoot(pcszPath, fUseNodes) \
83 ( ((fUseNodes) && mfTestDevicesAccessible \
84 && !RTStrCmp(pcszPath, mpcszTestDevicesRoot)) \
85 || (!(fUseNodes) && mfTestUsbfsAccessible \
86 && !RTStrCmp(pcszPath, mpcszTestUsbfsRoot)))
87# define RTDirExists(pcszDir) \
88 ( (pcszDir) \
89 && ( !RTStrCmp(pcszDir, mpcszTestDevicesRoot) \
90 || !RTStrCmp(pcszDir, mpcszTestUsbfsRoot)))
91# define RTFileExists(pcszFile) \
92 ( (pcszFile) \
93 && mpcszTestUsbfsRoot \
94 && !RTStrNCmp(pcszFile, mpcszTestUsbfsRoot, strlen(mpcszTestUsbfsRoot)) \
95 && !RTStrCmp(pcszFile + strlen(mpcszTestUsbfsRoot), "/devices"))
96#endif
97
98/**
99 * Initializes the object (called right after construction).
100 *
101 * @returns S_OK on success and non-fatal failures, some COM error otherwise.
102 */
103HRESULT USBProxyServiceLinux::init(void)
104{
105 /*
106 * Call the superclass method first.
107 */
108 HRESULT hrc = USBProxyService::init();
109 AssertComRCReturn(hrc, hrc);
110
111 /*
112 * We have two methods available for getting host USB device data - using
113 * USBFS and using sysfs. The default choice is sysfs; if that is not
114 * available we fall back to USBFS.
115 * In the event of both failing, an appropriate error will be returned.
116 */
117 bool fUseSysfs;
118 const char *pcszUsbFromEnv = RTEnvGet("VBOX_USB");
119 const char *pcszUsbRoot = NULL;
120 if (pcszUsbFromEnv)
121 {
122 bool fValidVBoxUSB = true;
123
124 pcszUsbRoot = RTEnvGet("VBOX_USB_ROOT");
125 if (!RTStrICmp(pcszUsbFromEnv, "USBFS"))
126 {
127 LogRel(("Default USB access method set to \"usbfs\" from environment\n"));
128 fUseSysfs = false;
129 }
130 else if (!RTStrICmp(pcszUsbFromEnv, "SYSFS"))
131 {
132 LogRel(("Default USB method set to \"sysfs\" from environment\n"));
133 fUseSysfs = true;
134 }
135 else
136 {
137 LogRel(("Invalid VBOX_USB environment variable setting \"%s\"\n",
138 pcszUsbFromEnv));
139 fValidVBoxUSB = false;
140 }
141 if (!fValidVBoxUSB && pcszUsbRoot)
142 pcszUsbRoot = NULL;
143 }
144 if (!pcszUsbRoot)
145 {
146 if (USBProxyLinuxCheckDeviceRoot("/dev/vboxusb", true))
147 {
148 fUseSysfs = true;
149 pcszUsbRoot = "/dev/vboxusb";
150 }
151 else if (USBProxyLinuxCheckDeviceRoot("/proc/bus/usb", false))
152 {
153 fUseSysfs = false;
154 pcszUsbRoot = "/proc/bus/usb";
155 }
156 }
157 if (pcszUsbRoot)
158 {
159 mUsingUsbfsDevices = !fUseSysfs;
160 mDevicesRoot = pcszUsbRoot;
161#ifndef UNIT_TEST /* Hack for now */
162 int rc = mUsingUsbfsDevices ? initUsbfs() : initSysfs();
163#else
164 int rc = mrcTestMethodInitResult;
165#endif
166 /* For the day when we have VBoxSVC release logging... */
167 LogRel((RT_SUCCESS(rc) ? "Successfully initialised host USB using %s\n"
168 : "Failed to initialise host USB using %s\n",
169 mUsingUsbfsDevices ? "USBFS" : "sysfs"));
170 mLastError = rc;
171 }
172 else
173 mLastError = RTDirExists("/dev/vboxusb") ? VERR_VUSB_USB_DEVICE_PERMISSION
174 : RTFileExists("/proc/bus/usb/devices") ? VERR_VUSB_USBFS_PERMISSION
175 : VERR_NOT_FOUND;
176 return S_OK;
177}
178
179#ifdef UNIT_TEST
180# undef RTEnvGet
181# undef USBProxyLinuxCheckDeviceRoot
182# undef RTDirExists
183# undef RTFileExists
184#endif
185
186/**
187 * Initialization routine for the usbfs based operation.
188 *
189 * @returns iprt status code.
190 */
191int USBProxyServiceLinux::initUsbfs(void)
192{
193 Assert(mUsingUsbfsDevices);
194
195 /*
196 * Open the devices file.
197 */
198 int rc;
199 char *pszDevices = RTPathJoinA(mDevicesRoot.c_str(), "devices");
200 if (pszDevices)
201 {
202 rc = RTFileOpen(&mFile, pszDevices, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_NONE);
203 if (RT_SUCCESS(rc))
204 {
205 int pipes[2];
206 if (!pipe(pipes))
207 {
208 /* Set close on exec (race here!) */
209 if ( fcntl(pipes[0], F_SETFD, FD_CLOEXEC) >= 0
210 && fcntl(pipes[1], F_SETFD, FD_CLOEXEC) >= 0)
211 {
212 mWakeupPipeR = pipes[0];
213 mWakeupPipeW = pipes[1];
214 /*
215 * Start the poller thread.
216 */
217 rc = start();
218 if (RT_SUCCESS(rc))
219 {
220 RTStrFree(pszDevices);
221 LogFlowThisFunc(("returns successfully - mWakeupPipeR/W=%d/%d\n",
222 mWakeupPipeR, mWakeupPipeW));
223 return VINF_SUCCESS;
224 }
225
226 RTFileClose(mWakeupPipeR);
227 RTFileClose(mWakeupPipeW);
228 mWakeupPipeW = mWakeupPipeR = NIL_RTFILE;
229 }
230 else
231 {
232 rc = RTErrConvertFromErrno(errno);
233 Log(("USBProxyServiceLinux::USBProxyServiceLinux: fcntl failed, errno=%d\n", errno));
234 close(pipes[0]);
235 close(pipes[1]);
236 }
237 }
238 else
239 {
240 rc = RTErrConvertFromErrno(errno);
241 Log(("USBProxyServiceLinux::USBProxyServiceLinux: pipe failed, errno=%d\n", errno));
242 }
243 RTFileClose(mFile);
244 }
245
246 RTStrFree(pszDevices);
247 }
248 else
249 {
250 rc = VERR_NO_MEMORY;
251 Log(("USBProxyServiceLinux::USBProxyServiceLinux: out of memory!\n"));
252 }
253
254 LogFlowThisFunc(("returns failure!!! (rc=%Rrc)\n", rc));
255 return rc;
256}
257
258
259/**
260 * Initialization routine for the sysfs based operation.
261 *
262 * @returns iprt status code
263 */
264int USBProxyServiceLinux::initSysfs(void)
265{
266 Assert(!mUsingUsbfsDevices);
267
268#ifdef VBOX_USB_WITH_SYSFS
269 try
270 {
271 mpWaiter = new VBoxMainHotplugWaiter(mDevicesRoot.c_str());
272 }
273 catch(std::bad_alloc &e)
274 {
275 return VERR_NO_MEMORY;
276 }
277 int rc = mpWaiter->getStatus();
278 if (RT_SUCCESS(rc) || rc == VERR_TIMEOUT || rc == VERR_TRY_AGAIN)
279 rc = start();
280 else if (rc == VERR_NOT_SUPPORTED)
281 /* This can legitimately happen if hal or DBus are not running, but of
282 * course we can't start in this case. */
283 rc = VINF_SUCCESS;
284 return rc;
285
286#else /* !VBOX_USB_WITH_SYSFS */
287 return VERR_NOT_IMPLEMENTED;
288#endif /* !VBOX_USB_WITH_SYSFS */
289}
290
291
292/**
293 * Stop all service threads and free the device chain.
294 */
295USBProxyServiceLinux::~USBProxyServiceLinux()
296{
297 LogFlowThisFunc(("\n"));
298
299 /*
300 * Stop the service.
301 */
302 if (isActive())
303 stop();
304
305 /*
306 * Free resources.
307 */
308 doUsbfsCleanupAsNeeded();
309#ifdef VBOX_USB_WITH_SYSFS
310 if (mpWaiter)
311 delete mpWaiter;
312#endif
313}
314
315
316/**
317 * If any Usbfs-related resources are currently allocated, then free them
318 * and mark them as freed.
319 */
320void USBProxyServiceLinux::doUsbfsCleanupAsNeeded()
321{
322 /*
323 * Free resources.
324 */
325 if (mFile != NIL_RTFILE)
326 {
327 RTFileClose(mFile);
328 mFile = NIL_RTFILE;
329 }
330
331 if (mWakeupPipeR != NIL_RTFILE)
332 RTFileClose(mWakeupPipeR);
333 if (mWakeupPipeW != NIL_RTFILE)
334 RTFileClose(mWakeupPipeW);
335 mWakeupPipeW = mWakeupPipeR = NIL_RTFILE;
336}
337
338
339int USBProxyServiceLinux::captureDevice(HostUSBDevice *aDevice)
340{
341 Log(("USBProxyServiceLinux::captureDevice: %p {%s}\n", aDevice, aDevice->getName().c_str()));
342 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
343 AssertReturn(aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
344
345 /*
346 * Don't think we need to do anything when the device is held... fake it.
347 */
348 Assert(aDevice->getUnistate() == kHostUSBDeviceState_Capturing);
349 interruptWait();
350
351 return VINF_SUCCESS;
352}
353
354
355int USBProxyServiceLinux::releaseDevice(HostUSBDevice *aDevice)
356{
357 Log(("USBProxyServiceLinux::releaseDevice: %p\n", aDevice));
358 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
359 AssertReturn(aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
360
361 /*
362 * We're not really holding it atm., just fake it.
363 */
364 Assert(aDevice->getUnistate() == kHostUSBDeviceState_ReleasingToHost);
365 interruptWait();
366
367 return VINF_SUCCESS;
368}
369
370
371bool USBProxyServiceLinux::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters, SessionMachine **aIgnoreMachine)
372{
373 if ( aUSBDevice->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
374 && aDevice->mUsb->enmState == USBDEVICESTATE_USED_BY_HOST)
375 LogRel(("USBProxy: Device %04x:%04x (%s) has become accessible.\n",
376 aUSBDevice->idVendor, aUSBDevice->idProduct, aUSBDevice->pszAddress));
377 return updateDeviceStateFake(aDevice, aUSBDevice, aRunFilters, aIgnoreMachine);
378}
379
380
381/**
382 * A device was added, we need to adjust mUdevPolls.
383 *
384 * See USBProxyService::deviceAdded for details.
385 */
386void USBProxyServiceLinux::deviceAdded(ComObjPtr<HostUSBDevice> &aDevice, SessionMachinesList &llOpenedMachines, PUSBDEVICE aUSBDevice)
387{
388 if (aUSBDevice->enmState == USBDEVICESTATE_USED_BY_HOST)
389 {
390 LogRel(("USBProxy: Device %04x:%04x (%s) isn't accessible. giving udev a few seconds to fix this...\n",
391 aUSBDevice->idVendor, aUSBDevice->idProduct, aUSBDevice->pszAddress));
392 mUdevPolls = 10; /* (10 * 500ms = 5s) */
393 }
394
395 USBProxyService::deviceAdded(aDevice, llOpenedMachines, aUSBDevice);
396}
397
398
399int USBProxyServiceLinux::wait(RTMSINTERVAL aMillies)
400{
401 int rc;
402 if (mUsingUsbfsDevices)
403 rc = waitUsbfs(aMillies);
404 else
405 rc = waitSysfs(aMillies);
406 return rc;
407}
408
409
410/** String written to the wakeup pipe. */
411#define WAKE_UP_STRING "WakeUp!"
412/** Length of the string written. */
413#define WAKE_UP_STRING_LEN ( sizeof(WAKE_UP_STRING) - 1 )
414
415int USBProxyServiceLinux::waitUsbfs(RTMSINTERVAL aMillies)
416{
417 struct pollfd PollFds[2];
418
419 /* Cap the wait interval if we're polling for udevd changing device permissions. */
420 if (aMillies > 500 && mUdevPolls > 0)
421 {
422 mUdevPolls--;
423 aMillies = 500;
424 }
425
426 memset(&PollFds, 0, sizeof(PollFds));
427 PollFds[0].fd = mFile;
428 PollFds[0].events = POLLIN;
429 PollFds[1].fd = mWakeupPipeR;
430 PollFds[1].events = POLLIN | POLLERR | POLLHUP;
431
432 int rc = poll(&PollFds[0], 2, aMillies);
433 if (rc == 0)
434 return VERR_TIMEOUT;
435 if (rc > 0)
436 {
437 /* drain the pipe */
438 if (PollFds[1].revents & POLLIN)
439 {
440 char szBuf[WAKE_UP_STRING_LEN];
441 rc = RTFileRead(mWakeupPipeR, szBuf, sizeof(szBuf), NULL);
442 AssertRC(rc);
443 }
444 return VINF_SUCCESS;
445 }
446 return RTErrConvertFromErrno(errno);
447}
448
449
450int USBProxyServiceLinux::waitSysfs(RTMSINTERVAL aMillies)
451{
452#ifdef VBOX_USB_WITH_SYSFS
453 int rc = mpWaiter->Wait(aMillies);
454 if (rc == VERR_TRY_AGAIN)
455 {
456 RTThreadYield();
457 rc = VINF_SUCCESS;
458 }
459 return rc;
460#else /* !VBOX_USB_WITH_SYSFS */
461 return USBProxyService::wait(aMillies);
462#endif /* !VBOX_USB_WITH_SYSFS */
463}
464
465
466int USBProxyServiceLinux::interruptWait(void)
467{
468#ifdef VBOX_USB_WITH_SYSFS
469 LogFlowFunc(("mUsingUsbfsDevices=%d\n", mUsingUsbfsDevices));
470 if (!mUsingUsbfsDevices)
471 {
472 mpWaiter->Interrupt();
473 LogFlowFunc(("Returning VINF_SUCCESS\n"));
474 return VINF_SUCCESS;
475 }
476#endif /* VBOX_USB_WITH_SYSFS */
477 int rc = RTFileWrite(mWakeupPipeW, WAKE_UP_STRING, WAKE_UP_STRING_LEN, NULL);
478 if (RT_SUCCESS(rc))
479 RTFileFlush(mWakeupPipeW);
480 LogFlowFunc(("returning %Rrc\n", rc));
481 return rc;
482}
483
484
485PUSBDEVICE USBProxyServiceLinux::getDevices(void)
486{
487 return USBProxyLinuxGetDevices(mDevicesRoot.c_str(), !mUsingUsbfsDevices);
488}
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