VirtualBox

source: vbox/trunk/src/VBox/Main/src-server/generic/USBProxyBackendUsbIp.cpp@ 60713

Last change on this file since 60713 was 60713, checked in by vboxsync, 9 years ago

Main/USBProxyBackendUsbIp.cpp: Fixes for Windows, RTPoll returns with both the read and error events set so we have to check for available data first before handling the error

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 30.9 KB
Line 
1/* $Id: USBProxyBackendUsbIp.cpp 60713 2016-04-27 08:02:31Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Backend, USB/IP.
4 */
5
6/*
7 * Copyright (C) 2015 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
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/tcp.h>
35#include <iprt/env.h>
36#include <iprt/err.h>
37#include <iprt/mem.h>
38#include <iprt/pipe.h>
39#include <iprt/asm.h>
40#include <iprt/cdefs.h>
41
42/** The USB/IP default port to connect to. */
43#define USBIP_PORT_DEFAULT 3240
44/** The USB version number used for the protocol. */
45#define USBIP_VERSION UINT16_C(0x0111)
46/** Request indicator in the command code. */
47#define USBIP_INDICATOR_REQ RT_BIT(15)
48
49/** Command/Reply code for OP_REQ/RET_DEVLIST. */
50#define USBIP_REQ_RET_DEVLIST UINT16_C(5)
51
52/** @todo: Duplicate code in USBProxyDevice-usbip.cpp */
53/**
54 * Exported device entry in the OP_RET_DEVLIST reply.
55 */
56#pragma pack(1)
57typedef struct UsbIpExportedDevice
58{
59 /** Path of the device, zero terminated string. */
60 char szPath[256];
61 /** Bus ID of the exported device, zero terminated string. */
62 char szBusId[32];
63 /** Bus number. */
64 uint32_t u32BusNum;
65 /** Device number. */
66 uint32_t u32DevNum;
67 /** Speed indicator of the device. */
68 uint32_t u32Speed;
69 /** Vendor ID of the device. */
70 uint16_t u16VendorId;
71 /** Product ID of the device. */
72 uint16_t u16ProductId;
73 /** Device release number. */
74 uint16_t u16BcdDevice;
75 /** Device class. */
76 uint8_t bDeviceClass;
77 /** Device Subclass. */
78 uint8_t bDeviceSubClass;
79 /** Device protocol. */
80 uint8_t bDeviceProtocol;
81 /** Configuration value. */
82 uint8_t bConfigurationValue;
83 /** Current configuration value of the device. */
84 uint8_t bNumConfigurations;
85 /** Number of interfaces for the device. */
86 uint8_t bNumInterfaces;
87} UsbIpExportedDevice;
88/** Pointer to a exported device entry. */
89typedef UsbIpExportedDevice *PUsbIpExportedDevice;
90#pragma pack()
91AssertCompileSize(UsbIpExportedDevice, 312);
92
93/**
94 * Interface descriptor entry for an exported device.
95 */
96#pragma pack(1)
97typedef struct UsbIpDeviceInterface
98{
99 /** Intefrace class. */
100 uint8_t bInterfaceClass;
101 /** Interface sub class. */
102 uint8_t bInterfaceSubClass;
103 /** Interface protocol identifier. */
104 uint8_t bInterfaceProtocol;
105 /** Padding byte for alignment. */
106 uint8_t bPadding;
107} UsbIpDeviceInterface;
108/** Pointer to an interface descriptor entry. */
109typedef UsbIpDeviceInterface *PUsbIpDeviceInterface;
110#pragma pack()
111
112/**
113 * USB/IP device list request.
114 */
115#pragma pack(1)
116typedef struct UsbIpReqDevList
117{
118 /** Protocol version number. */
119 uint16_t u16Version;
120 /** Command code. */
121 uint16_t u16Cmd;
122 /** Status field, unused. */
123 int32_t u32Status;
124} UsbIpReqDevList;
125/** Pointer to a device list request. */
126typedef UsbIpReqDevList *PUsbIpReqDevList;
127#pragma pack()
128
129/**
130 * USB/IP Import reply.
131 *
132 * This is only the header, for successful
133 * requests the device details are sent to as
134 * defined in UsbIpExportedDevice.
135 */
136#pragma pack(1)
137typedef struct UsbIpRetDevList
138{
139 /** Protocol version number. */
140 uint16_t u16Version;
141 /** Command code. */
142 uint16_t u16Cmd;
143 /** Status field, unused. */
144 int32_t u32Status;
145 /** Number of exported devices. */
146 uint32_t u32DevicesExported;
147} UsbIpRetDevList;
148/** Pointer to a import reply. */
149typedef UsbIpRetDevList *PUsbIpRetDevList;
150#pragma pack()
151
152/** Pollset id of the socket. */
153#define USBIP_POLL_ID_SOCKET 0
154/** Pollset id of the pipe. */
155#define USBIP_POLL_ID_PIPE 1
156
157/** @name USB/IP error codes.
158 * @{ */
159/** Success indicator. */
160#define USBIP_STATUS_SUCCESS INT32_C(0)
161/** @} */
162
163/** @name USB/IP device speeds.
164 * @{ */
165/** Unknown speed. */
166#define USBIP_SPEED_UNKNOWN 0
167/** Low (1.0) speed. */
168#define USBIP_SPEED_LOW 1
169/** Full (1.1) speed. */
170#define USBIP_SPEED_FULL 2
171/** High (2.0) speed. */
172#define USBIP_SPEED_HIGH 3
173/** Variable (CWUSB) speed. */
174#define USBIP_SPEED_WIRELESS 4
175/** Super (3.0) speed. */
176#define USBIP_SPEED_SUPER 5
177/** @} */
178
179/**
180 * Private USB/IP proxy backend data.
181 */
182struct USBProxyBackendUsbIp::Data
183{
184 Data()
185 : hSocket(NIL_RTSOCKET),
186 hWakeupPipeR(NIL_RTPIPE),
187 hWakeupPipeW(NIL_RTPIPE),
188 hPollSet(NIL_RTPOLLSET),
189 uPort(USBIP_PORT_DEFAULT),
190 pszHost(NULL),
191 hMtxDevices(NIL_RTSEMFASTMUTEX),
192 cUsbDevicesCur(0),
193 pUsbDevicesCur(NULL),
194 enmRecvState(kUsbIpRecvState_Invalid),
195 cbResidualRecv(0),
196 pbRecvBuf(NULL),
197 cDevicesLeft(0),
198 pHead(NULL),
199 ppNext(&pHead)
200 { }
201
202 /** Socket handle to the server. */
203 RTSOCKET hSocket;
204 /** Pipe used to interrupt wait(), the read end. */
205 RTPIPE hWakeupPipeR;
206 /** Pipe used to interrupt wait(), the write end. */
207 RTPIPE hWakeupPipeW;
208 /** Pollset for the socket and wakeup pipe. */
209 RTPOLLSET hPollSet;
210 /** Port of the USB/IP host to connect to. */
211 uint32_t uPort;
212 /** USB/IP host address. */
213 char *pszHost;
214 /** Mutex protecting the device list against concurrent access. */
215 RTSEMFASTMUTEX hMtxDevices;
216 /** Number of devices in the list. */
217 uint32_t cUsbDevicesCur;
218 /** The current list of devices to compare with. */
219 PUSBDEVICE pUsbDevicesCur;
220 /** Current receive state. */
221 USBIPRECVSTATE enmRecvState;
222 /** Scratch space for holding the data until it was completely received.
223 * Which one to access is based on the current receive state. */
224 union
225 {
226 UsbIpRetDevList RetDevList;
227 UsbIpExportedDevice ExportedDevice;
228 UsbIpDeviceInterface DeviceInterface;
229 /** Byte view. */
230 uint8_t abRecv[1];
231 } Scratch;
232 /** Residual number of bytes to receive before we can work with the data. */
233 size_t cbResidualRecv;
234 /** Current pointer into the scratch buffer. */
235 uint8_t *pbRecvBuf;
236 /** Number of devices left to receive for the current request. */
237 uint32_t cDevicesLeft;
238 /** Number of interfaces to skip during receive. */
239 uint32_t cInterfacesLeft;
240 /** The current head pointer for the new device list. */
241 PUSBDEVICE pHead;
242 /** The next pointer to add a device to. */
243 PUSBDEVICE *ppNext;
244 /** Current amount of devices in the list. */
245 uint32_t cDevicesCur;
246};
247
248/**
249 * Convert the given exported device structure from host to network byte order.
250 *
251 * @returns nothing.
252 * @param pDevice The device structure to convert.
253 */
254DECLINLINE(void) usbProxyBackendUsbIpExportedDeviceN2H(PUsbIpExportedDevice pDevice)
255{
256 pDevice->u32BusNum = RT_N2H_U32(pDevice->u32BusNum);
257 pDevice->u32DevNum = RT_N2H_U32(pDevice->u32DevNum);
258 pDevice->u32Speed = RT_N2H_U16(pDevice->u32Speed);
259 pDevice->u16VendorId = RT_N2H_U16(pDevice->u16VendorId);
260 pDevice->u16ProductId = RT_N2H_U16(pDevice->u16ProductId);
261 pDevice->u16BcdDevice = RT_N2H_U16(pDevice->u16BcdDevice);
262}
263
264/**
265 * Initialize data members.
266 */
267USBProxyBackendUsbIp::USBProxyBackendUsbIp()
268 : USBProxyBackend()
269{
270}
271
272USBProxyBackendUsbIp::~USBProxyBackendUsbIp()
273{
274
275}
276
277/**
278 * Initializes the object (called right after construction).
279 *
280 * @returns S_OK on success and non-fatal failures, some COM error otherwise.
281 */
282int USBProxyBackendUsbIp::init(USBProxyService *aUsbProxyService, const com::Utf8Str &strId, const com::Utf8Str &strAddress)
283{
284 int rc = VINF_SUCCESS;
285
286 USBProxyBackend::init(aUsbProxyService, strId, strAddress);
287
288 unconst(m_strBackend) = Utf8Str("USBIP");
289
290 m = new Data;
291
292 /* Split address into hostname and port. */
293 RTCList<RTCString> lstAddress = strAddress.split(":");
294 if (lstAddress.size() < 1)
295 return VERR_INVALID_PARAMETER;
296 m->pszHost = RTStrDup(lstAddress[0].c_str());
297 if (!m->pszHost)
298 return VERR_NO_STR_MEMORY;
299 if (lstAddress.size() == 2)
300 {
301 m->uPort = lstAddress[1].toUInt32();
302 if (!m->uPort)
303 return VERR_INVALID_PARAMETER;
304 }
305
306 /* Setup wakeup pipe and poll set first. */
307 rc = RTSemFastMutexCreate(&m->hMtxDevices);
308 if (RT_SUCCESS(rc))
309 {
310 rc = RTPipeCreate(&m->hWakeupPipeR, &m->hWakeupPipeW, 0);
311 if (RT_SUCCESS(rc))
312 {
313 rc = RTPollSetCreate(&m->hPollSet);
314 if (RT_SUCCESS(rc))
315 {
316 rc = RTPollSetAddPipe(m->hPollSet, m->hWakeupPipeR,
317 RTPOLL_EVT_READ, USBIP_POLL_ID_PIPE);
318 if (RT_SUCCESS(rc))
319 {
320 /* Connect to the USB/IP host. */
321 rc = reconnect();
322 if (RT_SUCCESS(rc))
323 rc = start(); /* Start service thread. */
324 }
325
326 if (RT_FAILURE(rc))
327 {
328 RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_PIPE);
329 int rc2 = RTPollSetDestroy(m->hPollSet);
330 AssertRC(rc2);
331 m->hPollSet = NIL_RTPOLLSET;
332 }
333 }
334
335 if (RT_FAILURE(rc))
336 {
337 int rc2 = RTPipeClose(m->hWakeupPipeR);
338 AssertRC(rc2);
339 rc2 = RTPipeClose(m->hWakeupPipeW);
340 AssertRC(rc2);
341 m->hWakeupPipeR = m->hWakeupPipeW = NIL_RTPIPE;
342 }
343 }
344 if (RT_FAILURE(rc))
345 {
346 RTSemFastMutexDestroy(m->hMtxDevices);
347 m->hMtxDevices = NIL_RTSEMFASTMUTEX;
348 }
349 }
350
351 return rc;
352}
353
354/**
355 * Stop all service threads and free the device chain.
356 */
357void USBProxyBackendUsbIp::uninit()
358{
359 LogFlowThisFunc(("\n"));
360
361 /*
362 * Stop the service.
363 */
364 if (isActive())
365 stop();
366
367 /*
368 * Free resources.
369 */
370 if (m->hPollSet != NIL_RTPOLLSET)
371 {
372 disconnect();
373
374 int rc = RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_PIPE);
375 AssertRC(rc);
376 rc = RTPollSetDestroy(m->hPollSet);
377 AssertRC(rc);
378 rc = RTPipeClose(m->hWakeupPipeR);
379 AssertRC(rc);
380 rc = RTPipeClose(m->hWakeupPipeW);
381 AssertRC(rc);
382
383 m->hPollSet = NIL_RTPOLLSET;
384 m->hWakeupPipeR = NIL_RTPIPE;
385 m->hWakeupPipeW = NIL_RTPIPE;
386 }
387
388 if (m->pszHost)
389 RTStrFree(m->pszHost);
390 if (m->hMtxDevices != NIL_RTSEMFASTMUTEX)
391 {
392 RTSemFastMutexDestroy(m->hMtxDevices);
393 m->hMtxDevices = NIL_RTSEMFASTMUTEX;
394 }
395
396 delete m;
397 USBProxyBackend::uninit();
398}
399
400
401int USBProxyBackendUsbIp::captureDevice(HostUSBDevice *aDevice)
402{
403 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
404 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
405
406 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
407 LogFlowThisFunc(("aDevice=%s\n", aDevice->i_getName().c_str()));
408
409 /*
410 * We don't need to do anything when the device is held... fake it.
411 */
412 Assert(aDevice->i_getUnistate() == kHostUSBDeviceState_Capturing);
413 devLock.release();
414
415 return VINF_SUCCESS;
416}
417
418
419int USBProxyBackendUsbIp::releaseDevice(HostUSBDevice *aDevice)
420{
421 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
422 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
423
424 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
425 LogFlowThisFunc(("aDevice=%s\n", aDevice->i_getName().c_str()));
426
427 /*
428 * We're not really holding it atm., just fake it.
429 */
430 Assert(aDevice->i_getUnistate() == kHostUSBDeviceState_ReleasingToHost);
431 devLock.release();
432
433 return VINF_SUCCESS;
434}
435
436
437bool USBProxyBackendUsbIp::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters,
438 SessionMachine **aIgnoreMachine)
439{
440 AssertReturn(aDevice, false);
441 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
442 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
443 if ( aUSBDevice->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
444 && aDevice->i_getUsbData()->enmState == USBDEVICESTATE_USED_BY_HOST)
445 LogRel(("USBProxy: Device %04x:%04x (%s) has become accessible.\n",
446 aUSBDevice->idVendor, aUSBDevice->idProduct, aUSBDevice->pszAddress));
447 devLock.release();
448 return updateDeviceStateFake(aDevice, aUSBDevice, aRunFilters, aIgnoreMachine);
449}
450
451
452int USBProxyBackendUsbIp::wait(RTMSINTERVAL aMillies)
453{
454 int rc = VINF_SUCCESS;
455 bool fDeviceListChangedOrWokenUp = false;
456
457 /* Try to reconnect once when we enter if we lost the connection earlier. */
458 if (m->hSocket == NIL_RTSOCKET)
459 rc = reconnect();
460
461 /* Query a new device list upon entering. */
462 if ( RT_SUCCESS(rc)
463 && m->enmRecvState == kUsbIpRecvState_None)
464 {
465 rc = startListExportedDevicesReq();
466 if (RT_FAILURE(rc))
467 disconnect();
468 }
469
470 /*
471 * Because the USB/IP protocol doesn't specify a way to get notified about
472 * new or removed exported devices we have to poll the host periodically for
473 * a new device list and compare it with the previous one notifying the proxy
474 * service about changes.
475 */
476 while ( !fDeviceListChangedOrWokenUp
477 && (aMillies == RT_INDEFINITE_WAIT || aMillies > 0)
478 && RT_SUCCESS(rc))
479 {
480 RTMSINTERVAL msWait = aMillies;
481 uint64_t msPollStart = RTTimeMilliTS();
482 uint32_t uIdReady = 0;
483 uint32_t fEventsRecv = 0;
484
485 /* Limit the waiting time to 1sec so we can either reconnect or get a new device list. */
486 if (m->hSocket == NIL_RTSOCKET || m->enmRecvState == kUsbIpRecvState_None)
487 msWait = RT_MIN(1000, aMillies);
488
489 rc = RTPoll(m->hPollSet, msWait, &fEventsRecv, &uIdReady);
490 if (RT_SUCCESS(rc))
491 {
492 if (uIdReady == USBIP_POLL_ID_PIPE)
493 {
494 /* Drain the wakeup pipe. */
495 char bRead = 0;
496 size_t cbRead = 0;
497
498 rc = RTPipeRead(m->hWakeupPipeR, &bRead, 1, &cbRead);
499 Assert(RT_SUCCESS(rc) && cbRead == 1);
500 fDeviceListChangedOrWokenUp = true;
501 }
502 else if (uIdReady == USBIP_POLL_ID_SOCKET)
503 {
504 if (fEventsRecv & RTPOLL_EVT_READ)
505 rc = receiveData();
506 else if (fEventsRecv & RTPOLL_EVT_ERROR)
507 rc = VERR_NET_SHUTDOWN;
508
509 if (RT_SUCCESS(rc))
510 {
511 /*
512 * If we are in the none state again we received the previous request
513 * and have a new device list to compare the old against.
514 */
515 if (m->enmRecvState == kUsbIpRecvState_None)
516 {
517 if (hasDevListChanged(m->pHead))
518 fDeviceListChangedOrWokenUp = true;
519
520 /* Update to the new list in any case now that we have it anyway. */
521 RTSemFastMutexRequest(m->hMtxDevices);
522 freeDeviceList(m->pUsbDevicesCur);
523 m->cUsbDevicesCur = m->cDevicesCur;
524 m->pUsbDevicesCur = m->pHead;
525 RTSemFastMutexRelease(m->hMtxDevices);
526
527 m->pHead = NULL;
528 resetRecvState();
529 }
530 }
531 else if (rc == VERR_NET_SHUTDOWN || rc == VERR_BROKEN_PIPE)
532 {
533 LogRelMax(10, ("USB/IP: Lost connection to host \"%s\", trying to reconnect...\n", m->pszHost));
534 disconnect();
535 rc = VINF_SUCCESS;
536 }
537 }
538 else
539 {
540 AssertMsgFailed(("Invalid poll ID returned\n"));
541 rc = VERR_INVALID_STATE;
542 }
543 aMillies -= (RTTimeMilliTS() - msPollStart);
544 }
545 else if (rc == VERR_TIMEOUT)
546 {
547 aMillies -= msWait;
548 if (aMillies)
549 {
550 /* Try to reconnect and start a new request if we lost the connection before. */
551 if (m->hSocket == NIL_RTSOCKET)
552 rc = reconnect();
553
554 if (RT_SUCCESS(rc))
555 rc = startListExportedDevicesReq();
556 }
557 }
558 }
559
560 return rc;
561}
562
563
564int USBProxyBackendUsbIp::interruptWait(void)
565{
566 AssertReturn(!isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
567
568 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
569
570 int rc = RTPipeWriteBlocking(m->hWakeupPipeW, "", 1, NULL);
571 if (RT_SUCCESS(rc))
572 RTPipeFlush(m->hWakeupPipeW);
573 LogFlowFunc(("returning %Rrc\n", rc));
574 return rc;
575}
576
577
578PUSBDEVICE USBProxyBackendUsbIp::getDevices(void)
579{
580 PUSBDEVICE pFirst = NULL;
581 PUSBDEVICE *ppNext = &pFirst;
582
583 /* Create a deep copy of the device list. */
584 RTSemFastMutexRequest(m->hMtxDevices);
585 PUSBDEVICE pCur = m->pUsbDevicesCur;
586 while (pCur)
587 {
588 PUSBDEVICE pNew = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
589 if (pNew)
590 {
591 pNew->pszManufacturer = RTStrDup(pCur->pszManufacturer);
592 pNew->pszProduct = RTStrDup(pCur->pszProduct);
593 if (pCur->pszSerialNumber)
594 pNew->pszSerialNumber = RTStrDup(pCur->pszSerialNumber);
595 pNew->pszBackend = RTStrDup(pCur->pszBackend);
596 pNew->pszAddress = RTStrDup(pCur->pszAddress);
597
598 pNew->idVendor = pCur->idVendor;
599 pNew->idProduct = pCur->idProduct;
600 pNew->bcdDevice = pCur->bcdDevice;
601 pNew->bcdUSB = pCur->bcdUSB;
602 pNew->bDeviceClass = pCur->bDeviceClass;
603 pNew->bDeviceSubClass = pCur->bDeviceSubClass;
604 pNew->bDeviceProtocol = pCur->bDeviceProtocol;
605 pNew->bNumConfigurations = pCur->bNumConfigurations;
606 pNew->enmState = pCur->enmState;
607 pNew->u64SerialHash = pCur->u64SerialHash;
608 pNew->bBus = pCur->bBus;
609 pNew->bPort = pCur->bPort;
610 pNew->enmSpeed = pCur->enmSpeed;
611
612 /* link it */
613 pNew->pNext = NULL;
614 pNew->pPrev = *ppNext;
615 *ppNext = pNew;
616 ppNext = &pNew->pNext;
617 }
618
619 pCur = pCur->pNext;
620 }
621 RTSemFastMutexRelease(m->hMtxDevices);
622
623 return pFirst;
624}
625
626/**
627 * Frees a given device list.
628 *
629 * @returns nothing.
630 * @param pHead The head of the device list to free.
631 */
632void USBProxyBackendUsbIp::freeDeviceList(PUSBDEVICE pHead)
633{
634 PUSBDEVICE pNext = pHead;
635 while (pNext)
636 {
637 PUSBDEVICE pFree = pNext;
638 pNext = pNext->pNext;
639 freeDevice(pFree);
640 }
641}
642
643/**
644 * Resets the receive state to the idle state.
645 *
646 * @returns nothing.
647 */
648void USBProxyBackendUsbIp::resetRecvState()
649{
650 freeDeviceList(m->pHead);
651 m->pHead = NULL;
652 m->ppNext = &m->pHead;
653 m->cDevicesCur = 0;
654 m->enmRecvState = kUsbIpRecvState_None;
655 m->cbResidualRecv = 0;
656 m->pbRecvBuf = &m->Scratch.abRecv[0];
657 m->cDevicesLeft = 0;
658}
659
660/**
661 * Disconnects from the host and resets the receive state.
662 *
663 * @returns nothing.
664 */
665void USBProxyBackendUsbIp::disconnect()
666{
667 if (m->hSocket != NIL_RTSOCKET)
668 {
669 int rc = RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_SOCKET);
670 Assert(RT_SUCCESS(rc) || rc == VERR_POLL_HANDLE_ID_NOT_FOUND);
671
672 RTTcpClientCloseEx(m->hSocket, false /*fGracefulShutdown*/);
673 m->hSocket = NIL_RTSOCKET;
674 }
675
676 resetRecvState();
677}
678
679/**
680 * Tries to reconnect to the USB/IP host.
681 *
682 * @returns VBox status code.
683 */
684int USBProxyBackendUsbIp::reconnect()
685{
686 /* Make sure we are disconnected. */
687 disconnect();
688
689 /* Connect to the USB/IP host. */
690 int rc = RTTcpClientConnect(m->pszHost, m->uPort, &m->hSocket);
691 if (RT_SUCCESS(rc))
692 {
693 rc = RTTcpSetSendCoalescing(m->hSocket, false);
694 if (RT_FAILURE(rc))
695 LogRel(("USB/IP: Disabling send coalescing failed (rc=%Rrc), continuing nevertheless but expect increased latency\n", rc));
696
697 rc = RTPollSetAddSocket(m->hPollSet, m->hSocket, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
698 USBIP_POLL_ID_SOCKET);
699 if (RT_FAILURE(rc))
700 {
701 RTTcpClientCloseEx(m->hSocket, false /*fGracefulShutdown*/);
702 m->hSocket = NIL_RTSOCKET;
703 }
704 else
705 LogRel(("USB/IP: Connected to host \"%s\"\n", m->pszHost));
706 }
707
708 return rc;
709}
710
711/**
712 * Initiates a new List Exported Devices request.
713 *
714 * @returns VBox status code.
715 */
716int USBProxyBackendUsbIp::startListExportedDevicesReq()
717{
718 int rc = VINF_SUCCESS;
719
720 /*
721 * Reset the current state and reconnect in case we were called in the middle
722 * of another transfer (which should not happen).
723 */
724 Assert(m->enmRecvState == kUsbIpRecvState_None);
725 if (m->enmRecvState != kUsbIpRecvState_None)
726 rc = reconnect();
727
728 if (RT_SUCCESS(rc))
729 {
730 /* Send of the request. */
731 UsbIpReqDevList ReqDevList;
732 ReqDevList.u16Version = RT_H2N_U16(USBIP_VERSION);
733 ReqDevList.u16Cmd = RT_H2N_U16(USBIP_INDICATOR_REQ | USBIP_REQ_RET_DEVLIST);
734 ReqDevList.u32Status = RT_H2N_U32(0);
735 rc = RTTcpWrite(m->hSocket, &ReqDevList, sizeof(ReqDevList));
736 if (RT_SUCCESS(rc))
737 advanceState(kUsbIpRecvState_Hdr);
738 }
739
740 return rc;
741}
742
743/**
744 * Advances the state machine to the given state.
745 *
746 * @returns nothing.
747 * @param enmRecvState The new receive state.
748 */
749void USBProxyBackendUsbIp::advanceState(USBIPRECVSTATE enmRecvState)
750{
751 switch (enmRecvState)
752 {
753 case kUsbIpRecvState_None:
754 break;
755 case kUsbIpRecvState_Hdr:
756 {
757 m->cbResidualRecv = sizeof(UsbIpRetDevList);
758 m->pbRecvBuf = (uint8_t *)&m->Scratch.RetDevList;
759 break;
760 }
761 case kUsbIpRecvState_ExportedDevice:
762 {
763 m->cbResidualRecv = sizeof(UsbIpExportedDevice);
764 m->pbRecvBuf = (uint8_t *)&m->Scratch.ExportedDevice;
765 break;
766 }
767 case kUsbIpRecvState_DeviceInterface:
768 {
769 m->cbResidualRecv = sizeof(UsbIpDeviceInterface);
770 m->pbRecvBuf = (uint8_t *)&m->Scratch.DeviceInterface;
771 break;
772 }
773 default:
774 AssertMsgFailed(("Invalid USB/IP receive state %d\n", enmRecvState));
775 return;
776 }
777
778 m->enmRecvState = enmRecvState;
779}
780
781/**
782 * Receives data from the USB/IP host and processes it when everything for the current
783 * state was received.
784 *
785 * @returns VBox status code.
786 */
787int USBProxyBackendUsbIp::receiveData()
788{
789 int rc = VINF_SUCCESS;
790 size_t cbRecvd = 0;
791
792 do
793 {
794 rc = RTTcpReadNB(m->hSocket, m->pbRecvBuf, m->cbResidualRecv, &cbRecvd);
795 if (RT_SUCCESS(rc))
796 {
797 m->cbResidualRecv -= cbRecvd;
798 m->pbRecvBuf += cbRecvd;
799 /* In case we received everything for the current state process the data. */
800 if (!m->cbResidualRecv)
801 {
802 rc = processData();
803 if ( RT_SUCCESS(rc)
804 && m->enmRecvState == kUsbIpRecvState_None)
805 break;
806 }
807 }
808 } while (RT_SUCCESS(rc) && cbRecvd > 0);
809
810 return rc;
811}
812
813/**
814 * Processes the data in the scratch buffer based on the current state.
815 *
816 * @returns VBox status code.
817 */
818int USBProxyBackendUsbIp::processData()
819{
820 int rc = VINF_SUCCESS;
821
822 switch (m->enmRecvState)
823 {
824 case kUsbIpRecvState_Hdr:
825 {
826 /* Check that the reply matches our expectations. */
827 if ( RT_N2H_U16(m->Scratch.RetDevList.u16Version) == USBIP_VERSION
828 && RT_N2H_U16(m->Scratch.RetDevList.u16Cmd) == USBIP_REQ_RET_DEVLIST
829 && RT_N2H_U32(m->Scratch.RetDevList.u32Status) == USBIP_STATUS_SUCCESS)
830 {
831 /* Populate the number of exported devices in the list and go to the next state. */
832 m->cDevicesLeft = RT_N2H_U32(m->Scratch.RetDevList.u32DevicesExported);
833 if (m->cDevicesLeft)
834 advanceState(kUsbIpRecvState_ExportedDevice);
835 else
836 advanceState(kUsbIpRecvState_None);
837 }
838 else
839 {
840 LogRelMax(10, ("USB/IP: Host sent an invalid reply to the list exported device request (Version: %#x Cmd: %#x Status: %#x)\n",
841 RT_N2H_U16(m->Scratch.RetDevList.u16Version), RT_N2H_U16(m->Scratch.RetDevList.u16Cmd),
842 RT_N2H_U32(m->Scratch.RetDevList.u32Status)));
843 rc = VERR_INVALID_STATE;
844 }
845 break;
846 }
847 case kUsbIpRecvState_ExportedDevice:
848 {
849 /* Create a new device and add it to the list. */
850 usbProxyBackendUsbIpExportedDeviceN2H(&m->Scratch.ExportedDevice);
851 rc = addDeviceToList(&m->Scratch.ExportedDevice);
852 if (RT_SUCCESS(rc))
853 {
854 m->cInterfacesLeft = m->Scratch.ExportedDevice.bNumInterfaces;
855 if (m->cInterfacesLeft)
856 advanceState(kUsbIpRecvState_DeviceInterface);
857 else
858 {
859 m->cDevicesLeft--;
860 if (m->cDevicesLeft)
861 advanceState(kUsbIpRecvState_ExportedDevice);
862 else
863 advanceState(kUsbIpRecvState_None);
864 }
865 }
866 break;
867 }
868 case kUsbIpRecvState_DeviceInterface:
869 {
870 /*
871 * If all interfaces for the current device were received receive the next device
872 * if there is another one left, if not we are done with the current request.
873 */
874 m->cInterfacesLeft--;
875 if (m->cInterfacesLeft)
876 advanceState(kUsbIpRecvState_DeviceInterface);
877 else
878 {
879 m->cDevicesLeft--;
880 if (m->cDevicesLeft)
881 advanceState(kUsbIpRecvState_ExportedDevice);
882 else
883 advanceState(kUsbIpRecvState_None);
884 }
885 break;
886 }
887 case kUsbIpRecvState_None:
888 default:
889 AssertMsgFailed(("Invalid USB/IP receive state %d\n", m->enmRecvState));
890 return VERR_INVALID_STATE;
891 }
892
893 return rc;
894}
895
896/**
897 * Creates a new USB device and adds it to the list.
898 *
899 * @returns VBox status code.
900 * @param pDev Pointer to the USB/IP exported device structure to take
901 * the information for the new device from.
902 */
903int USBProxyBackendUsbIp::addDeviceToList(PUsbIpExportedDevice pDev)
904{
905 PUSBDEVICE pNew = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
906 if (!pNew)
907 return VERR_NO_MEMORY;
908
909 pNew->pszManufacturer = RTStrDup("");
910 pNew->pszProduct = RTStrDup("");
911 pNew->pszSerialNumber = NULL;
912 pNew->pszBackend = RTStrDup("usbip");
913
914 /* Make sure the Bus id is 0 terminated. */
915 pDev->szBusId[31] = '\0';
916 int rc = RTStrAPrintf((char **)&pNew->pszAddress, "usbip://%s:%u:%s", m->pszHost, m->uPort, &pDev->szBusId[0]);
917 if (RT_SUCCESS(rc))
918 {
919 pNew->idVendor = pDev->u16VendorId;
920 pNew->idProduct = pDev->u16ProductId;
921 pNew->bcdDevice = pDev->u16BcdDevice;
922 pNew->bDeviceClass = pDev->bDeviceClass;
923 pNew->bDeviceSubClass = pDev->bDeviceSubClass;
924 pNew->bDeviceProtocol = pDev->bDeviceProtocol;
925 pNew->bNumConfigurations = pDev->bNumConfigurations;
926 pNew->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
927 pNew->u64SerialHash = 0;
928 /** @todo: The following is not correct but is required to to get USB testing working
929 * because only the port can be part of a filter (adding the required attributes for the bus
930 * breaks API and ABI compatibility).
931 * Filtering by port number is required for USB testing to connect to the correct device
932 * in case there are multiple ones.
933 */
934 pNew->bBus = (uint8_t)pDev->u32DevNum;
935 pNew->bPort = (uint8_t)pDev->u32BusNum;
936
937 switch (pDev->u32Speed)
938 {
939 case USBIP_SPEED_LOW:
940 pNew->enmSpeed = USBDEVICESPEED_LOW;
941 pNew->bcdUSB = 1 << 8;
942 break;
943 case USBIP_SPEED_FULL:
944 pNew->enmSpeed = USBDEVICESPEED_FULL;
945 pNew->bcdUSB = 1 << 8;
946 break;
947 case USBIP_SPEED_HIGH:
948 pNew->enmSpeed = USBDEVICESPEED_HIGH;
949 pNew->bcdUSB = 2 << 8;
950 break;
951 case USBIP_SPEED_WIRELESS:
952 pNew->enmSpeed = USBDEVICESPEED_VARIABLE;
953 pNew->bcdUSB = 1 << 8;
954 break;
955 case USBIP_SPEED_SUPER:
956 pNew->enmSpeed = USBDEVICESPEED_SUPER;
957 pNew->bcdUSB = 3 << 8;
958 break;
959 case USBIP_SPEED_UNKNOWN:
960 default:
961 pNew->bcdUSB = 1 << 8;
962 pNew->enmSpeed = USBDEVICESPEED_UNKNOWN;
963 }
964
965 /* link it */
966 pNew->pNext = NULL;
967 pNew->pPrev = *m->ppNext;
968 *m->ppNext = pNew;
969 m->ppNext = &pNew->pNext;
970 m->cDevicesCur++;
971 }
972
973 if (RT_FAILURE(rc))
974 {
975 if (pNew->pszManufacturer)
976 RTStrFree((char *)pNew->pszManufacturer);
977 if (pNew->pszProduct)
978 RTStrFree((char *)pNew->pszProduct);
979 if (pNew->pszBackend)
980 RTStrFree((char *)pNew->pszBackend);
981 if (pNew->pszAddress)
982 RTStrFree((char *)pNew->pszAddress);
983 RTMemFree(pNew);
984 }
985
986 return rc;
987}
988
989/**
990 * Compares the given device list with the current one and returns whether it has
991 * changed.
992 *
993 * @returns flag whether the device list has changed compared to the current one.
994 * @param pDevices The device list to compare the current one against.
995 */
996bool USBProxyBackendUsbIp::hasDevListChanged(PUSBDEVICE pDevices)
997{
998 /** @todo */
999 return true;
1000}
1001
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