VirtualBox

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

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

Main/linux/USB: forgot to remove a fixed todo

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