VirtualBox

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

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

Main,VBoxManage: Add API to IHost for adding and removing USB device sources in addition to the default host one (only USB/IP backend supported so far which will be used in the future for automatic USB testing). Add support for it in VBoxManage

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.2 KB
Line 
1/* $Id: USBProxyBackendUsbIp.cpp 60089 2016-03-18 10:51:02Z 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.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/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 m = new Data;
289
290 /* Split address into hostname and port. */
291 RTCList<RTCString> lstAddress = strAddress.split(":");
292 if (lstAddress.size() < 1)
293 return VERR_INVALID_PARAMETER;
294 m->pszHost = RTStrDup(lstAddress[0].c_str());
295 if (!m->pszHost)
296 return VERR_NO_STR_MEMORY;
297 if (lstAddress.size() == 2)
298 {
299 m->uPort = lstAddress[1].toUInt32();
300 if (!m->uPort)
301 return VERR_INVALID_PARAMETER;
302 }
303
304 /* Setup wakeup pipe and poll set first. */
305 rc = RTSemFastMutexCreate(&m->hMtxDevices);
306 if (RT_SUCCESS(rc))
307 {
308 rc = RTPipeCreate(&m->hWakeupPipeR, &m->hWakeupPipeW, 0);
309 if (RT_SUCCESS(rc))
310 {
311 rc = RTPollSetCreate(&m->hPollSet);
312 if (RT_SUCCESS(rc))
313 {
314 rc = RTPollSetAddPipe(m->hPollSet, m->hWakeupPipeR,
315 RTPOLL_EVT_READ, USBIP_POLL_ID_PIPE);
316 if (RT_SUCCESS(rc))
317 {
318 /* Connect to the USB/IP host. */
319 rc = reconnect();
320 if (RT_SUCCESS(rc))
321 rc = start(); /* Start service thread. */
322 }
323
324 if (RT_FAILURE(rc))
325 {
326 RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_PIPE);
327 int rc2 = RTPollSetDestroy(m->hPollSet);
328 AssertRC(rc2);
329 }
330 }
331
332 if (RT_FAILURE(rc))
333 {
334 int rc2 = RTPipeClose(m->hWakeupPipeR);
335 AssertRC(rc2);
336 rc2 = RTPipeClose(m->hWakeupPipeW);
337 AssertRC(rc2);
338 }
339 }
340 if (RT_FAILURE(rc))
341 RTSemFastMutexDestroy(m->hMtxDevices);
342 }
343
344 return rc;
345}
346
347/**
348 * Stop all service threads and free the device chain.
349 */
350void USBProxyBackendUsbIp::uninit()
351{
352 LogFlowThisFunc(("\n"));
353
354 /*
355 * Stop the service.
356 */
357 if (isActive())
358 stop();
359
360 /*
361 * Free resources.
362 */
363 if (m->hPollSet != NIL_RTPOLLSET)
364 {
365 disconnect();
366
367 int rc = RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_PIPE);
368 AssertRC(rc);
369 rc = RTPollSetDestroy(m->hPollSet);
370 AssertRC(rc);
371 rc = RTPipeClose(m->hWakeupPipeR);
372 AssertRC(rc);
373 rc = RTPipeClose(m->hWakeupPipeW);
374 AssertRC(rc);
375 }
376
377 if (m->pszHost)
378 RTStrFree(m->pszHost);
379 if (m->hMtxDevices != NIL_RTSEMFASTMUTEX)
380 RTSemFastMutexDestroy(m->hMtxDevices);
381
382 delete m;
383 USBProxyBackend::uninit();
384}
385
386
387int USBProxyBackendUsbIp::captureDevice(HostUSBDevice *aDevice)
388{
389 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
390 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
391
392 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
393 LogFlowThisFunc(("aDevice=%s\n", aDevice->i_getName().c_str()));
394
395 /*
396 * We don't need to do anything when the device is held... fake it.
397 */
398 Assert(aDevice->i_getUnistate() == kHostUSBDeviceState_Capturing);
399 devLock.release();
400 interruptWait();
401
402 return VINF_SUCCESS;
403}
404
405
406int USBProxyBackendUsbIp::releaseDevice(HostUSBDevice *aDevice)
407{
408 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
409 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
410
411 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
412 LogFlowThisFunc(("aDevice=%s\n", aDevice->i_getName().c_str()));
413
414 /*
415 * We're not really holding it atm., just fake it.
416 */
417 Assert(aDevice->i_getUnistate() == kHostUSBDeviceState_ReleasingToHost);
418 devLock.release();
419 interruptWait();
420
421 return VINF_SUCCESS;
422}
423
424
425bool USBProxyBackendUsbIp::updateDeviceState(HostUSBDevice *aDevice, PUSBDEVICE aUSBDevice, bool *aRunFilters,
426 SessionMachine **aIgnoreMachine)
427{
428 AssertReturn(aDevice, false);
429 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), false);
430 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
431 if ( aUSBDevice->enmState == USBDEVICESTATE_USED_BY_HOST_CAPTURABLE
432 && aDevice->i_getUsbData()->enmState == USBDEVICESTATE_USED_BY_HOST)
433 LogRel(("USBProxy: Device %04x:%04x (%s) has become accessible.\n",
434 aUSBDevice->idVendor, aUSBDevice->idProduct, aUSBDevice->pszAddress));
435 devLock.release();
436 return updateDeviceStateFake(aDevice, aUSBDevice, aRunFilters, aIgnoreMachine);
437}
438
439
440int USBProxyBackendUsbIp::wait(RTMSINTERVAL aMillies)
441{
442 int rc = VINF_SUCCESS;
443 bool fDeviceListChangedOrWokenUp = false;
444
445 /* Try to reconnect once when we enter if we lost the connection earlier. */
446 if (m->hSocket == NIL_RTSOCKET)
447 rc = reconnect();
448
449 /* Query a new device list upon entering. */
450 if (m->enmRecvState == kUsbIpRecvState_None)
451 {
452 rc = startListExportedDevicesReq();
453 if (RT_FAILURE(rc))
454 disconnect();
455 }
456
457 /*
458 * Because the USB/IP protocol doesn't specify a way to get notified about
459 * new or removed exported devices we have to poll the host periodically for
460 * a new device list and compare it with the previous one notifying the proxy
461 * service about changes.
462 */
463 while ( !fDeviceListChangedOrWokenUp
464 && (aMillies == RT_INDEFINITE_WAIT || aMillies > 0)
465 && RT_SUCCESS(rc))
466 {
467 RTMSINTERVAL msWait = aMillies;
468 uint64_t msPollStart = RTTimeMilliTS();
469 uint32_t uIdReady = 0;
470 uint32_t fEventsRecv = 0;
471
472 /* Limit the waiting time to 1sec so we can either reconnect or get a new device list. */
473 if (m->hSocket == NIL_RTSOCKET || m->enmRecvState == kUsbIpRecvState_None)
474 msWait = RT_MIN(1000, aMillies);
475
476 rc = RTPoll(m->hPollSet, msWait, &fEventsRecv, &uIdReady);
477 if (RT_SUCCESS(rc))
478 {
479 if (uIdReady == USBIP_POLL_ID_PIPE)
480 {
481 /* Drain the wakeup pipe. */
482 char bRead = 0;
483 size_t cbRead = 0;
484
485 rc = RTPipeRead(m->hWakeupPipeR, &bRead, 1, &cbRead);
486 Assert(RT_SUCCESS(rc) && cbRead == 1);
487 fDeviceListChangedOrWokenUp = true;
488 }
489 else if (uIdReady == USBIP_POLL_ID_SOCKET)
490 {
491 if (fEventsRecv & RTPOLL_EVT_ERROR)
492 rc = VERR_NET_SHUTDOWN;
493 else
494 rc = receiveData();
495 if (RT_SUCCESS(rc))
496 {
497 /*
498 * If we are in the none state again we received the previous request
499 * and have a new device list to compare the old against.
500 */
501 if (m->enmRecvState == kUsbIpRecvState_None)
502 {
503 if (hasDevListChanged(m->pHead))
504 fDeviceListChangedOrWokenUp = true;
505
506 /* Update to the new list in any case now that we have it anyway. */
507 RTSemFastMutexRequest(m->hMtxDevices);
508 freeDeviceList(m->pUsbDevicesCur);
509 m->cUsbDevicesCur = m->cDevicesCur;
510 m->pUsbDevicesCur = m->pHead;
511 RTSemFastMutexRelease(m->hMtxDevices);
512
513 m->pHead = NULL;
514 resetRecvState();
515 }
516 }
517 else if (rc == VERR_NET_SHUTDOWN || rc == VERR_BROKEN_PIPE)
518 {
519 LogRelMax(10, ("USB/IP: Lost connection to host \"%s\", trying to reconnect...\n", m->pszHost));
520 disconnect();
521 rc = VINF_SUCCESS;
522 }
523 }
524 else
525 {
526 AssertMsgFailed(("Invalid poll ID returned\n"));
527 rc = VERR_INVALID_STATE;
528 }
529 aMillies -= (RTTimeMilliTS() - msPollStart);
530 }
531 else if (rc == VERR_TIMEOUT)
532 {
533 aMillies -= msWait;
534 if (aMillies)
535 {
536 /* Try to reconnect and start a new request if we lost the connection before. */
537 if (m->hSocket == NIL_RTSOCKET)
538 rc = reconnect();
539
540 if (RT_SUCCESS(rc))
541 rc = startListExportedDevicesReq();
542 }
543 }
544 }
545
546 return rc;
547}
548
549
550int USBProxyBackendUsbIp::interruptWait(void)
551{
552 AssertReturn(!isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
553
554 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
555
556 int rc = RTPipeWriteBlocking(m->hWakeupPipeW, "", 1, NULL);
557 if (RT_SUCCESS(rc))
558 RTPipeFlush(m->hWakeupPipeW);
559 LogFlowFunc(("returning %Rrc\n", rc));
560 return rc;
561}
562
563
564PUSBDEVICE USBProxyBackendUsbIp::getDevices(void)
565{
566 PUSBDEVICE pFirst = NULL;
567 PUSBDEVICE *ppNext = &pFirst;
568
569 /* Create a deep copy of the device list. */
570 RTSemFastMutexRequest(m->hMtxDevices);
571 PUSBDEVICE pCur = m->pUsbDevicesCur;
572 while (pCur)
573 {
574 PUSBDEVICE pNew = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
575 if (pNew)
576 {
577 pNew->pszManufacturer = RTStrDup(pCur->pszManufacturer);
578 pNew->pszProduct = RTStrDup(pCur->pszProduct);
579 if (pCur->pszSerialNumber)
580 pNew->pszSerialNumber = RTStrDup(pCur->pszSerialNumber);
581 pNew->pszBackend = RTStrDup(pCur->pszBackend);
582 pNew->pszAddress = RTStrDup(pCur->pszAddress);
583
584 pNew->idVendor = pCur->idVendor;
585 pNew->idProduct = pCur->idProduct;
586 pNew->bcdDevice = pCur->bcdDevice;
587 pNew->bcdUSB = pCur->bcdUSB;
588 pNew->bDeviceClass = pCur->bDeviceClass;
589 pNew->bDeviceSubClass = pCur->bDeviceSubClass;
590 pNew->bDeviceProtocol = pCur->bDeviceProtocol;
591 pNew->bNumConfigurations = pCur->bNumConfigurations;
592 pNew->enmState = pCur->enmState;
593 pNew->u64SerialHash = pCur->u64SerialHash;
594 pNew->bBus = pCur->bBus;
595 pNew->bPort = pCur->bPort;
596 pNew->enmSpeed = pCur->enmSpeed;
597
598 /* link it */
599 pNew->pNext = NULL;
600 pNew->pPrev = *ppNext;
601 *ppNext = pNew;
602 ppNext = &pNew->pNext;
603 }
604
605 pCur = pCur->pNext;
606 }
607 RTSemFastMutexRelease(m->hMtxDevices);
608
609 return pFirst;
610}
611
612/**
613 * Frees a given device list.
614 *
615 * @returns nothing.
616 * @param pHead The head of the device list to free.
617 */
618void USBProxyBackendUsbIp::freeDeviceList(PUSBDEVICE pHead)
619{
620 PUSBDEVICE pNext = pHead;
621 while (pNext)
622 {
623 PUSBDEVICE pFree = pNext;
624 pNext = pNext->pNext;
625 freeDevice(pFree);
626 }
627}
628
629/**
630 * Resets the receive state to the idle state.
631 *
632 * @returns nothing.
633 */
634void USBProxyBackendUsbIp::resetRecvState()
635{
636 freeDeviceList(m->pHead);
637 m->pHead = NULL;
638 m->ppNext = &m->pHead;
639 m->cDevicesCur = 0;
640 m->enmRecvState = kUsbIpRecvState_None;
641 m->cbResidualRecv = 0;
642 m->pbRecvBuf = &m->Scratch.abRecv[0];
643 m->cDevicesLeft = 0;
644}
645
646/**
647 * Disconnects from the host and resets the receive state.
648 *
649 * @returns nothing.
650 */
651void USBProxyBackendUsbIp::disconnect()
652{
653 if (m->hSocket != NIL_RTSOCKET)
654 {
655 int rc = RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_SOCKET);
656 Assert(RT_SUCCESS(rc) || rc == VERR_POLL_HANDLE_ID_NOT_FOUND);
657
658 RTTcpClientCloseEx(m->hSocket, false /*fGracefulShutdown*/);
659 m->hSocket = NIL_RTSOCKET;
660 }
661
662 resetRecvState();
663}
664
665/**
666 * Tries to reconnect to the USB/IP host.
667 *
668 * @returns VBox status code.
669 */
670int USBProxyBackendUsbIp::reconnect()
671{
672 /* Make sure we are disconnected. */
673 disconnect();
674
675 /* Connect to the USB/IP host. */
676 int rc = RTTcpClientConnect(m->pszHost, m->uPort, &m->hSocket);
677 if (RT_SUCCESS(rc))
678 {
679 rc = RTTcpSetSendCoalescing(m->hSocket, false);
680 if (RT_FAILURE(rc))
681 LogRel(("USB/IP: Disabling send coalescing failed (rc=%Rrc), continuing nevertheless but expect increased latency\n", rc));
682
683 rc = RTPollSetAddSocket(m->hPollSet, m->hSocket, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
684 USBIP_POLL_ID_SOCKET);
685 if (RT_FAILURE(rc))
686 {
687 RTTcpClientCloseEx(m->hSocket, false /*fGracefulShutdown*/);
688 m->hSocket = NIL_RTSOCKET;
689 }
690 }
691
692 return rc;
693}
694
695/**
696 * Initiates a new List Exported Devices request.
697 *
698 * @returns VBox status code.
699 */
700int USBProxyBackendUsbIp::startListExportedDevicesReq()
701{
702 int rc = VINF_SUCCESS;
703
704 /*
705 * Reset the current state and reconnect in case we were called in the middle
706 * of another transfer (which should not happen).
707 */
708 Assert(m->enmRecvState == kUsbIpRecvState_None);
709 if (m->enmRecvState != kUsbIpRecvState_None)
710 rc = reconnect();
711
712 if (RT_SUCCESS(rc))
713 {
714 /* Send of the request. */
715 UsbIpReqDevList ReqDevList;
716 ReqDevList.u16Version = RT_H2N_U16(USBIP_VERSION);
717 ReqDevList.u16Cmd = RT_H2N_U16(USBIP_INDICATOR_REQ | USBIP_REQ_RET_DEVLIST);
718 ReqDevList.u32Status = RT_H2N_U32(0);
719 rc = RTTcpWrite(m->hSocket, &ReqDevList, sizeof(ReqDevList));
720 if (RT_SUCCESS(rc))
721 advanceState(kUsbIpRecvState_Hdr);
722 }
723
724 return rc;
725}
726
727/**
728 * Advances the state machine to the given state.
729 *
730 * @returns nothing.
731 * @param enmRecvState The new receive state.
732 */
733void USBProxyBackendUsbIp::advanceState(USBIPRECVSTATE enmRecvState)
734{
735 switch (enmRecvState)
736 {
737 case kUsbIpRecvState_None:
738 break;
739 case kUsbIpRecvState_Hdr:
740 {
741 m->cbResidualRecv = sizeof(UsbIpRetDevList);
742 m->pbRecvBuf = (uint8_t *)&m->Scratch.RetDevList;
743 break;
744 }
745 case kUsbIpRecvState_ExportedDevice:
746 {
747 m->cbResidualRecv = sizeof(UsbIpExportedDevice);
748 m->pbRecvBuf = (uint8_t *)&m->Scratch.ExportedDevice;
749 break;
750 }
751 case kUsbIpRecvState_DeviceInterface:
752 {
753 m->cbResidualRecv = sizeof(UsbIpDeviceInterface);
754 m->pbRecvBuf = (uint8_t *)&m->Scratch.DeviceInterface;
755 break;
756 }
757 default:
758 AssertMsgFailed(("Invalid USB/IP receive state %d\n", enmRecvState));
759 return;
760 }
761
762 m->enmRecvState = enmRecvState;
763}
764
765/**
766 * Receives data from the USB/IP host and processes it when everything for the current
767 * state was received.
768 *
769 * @returns VBox status code.
770 */
771int USBProxyBackendUsbIp::receiveData()
772{
773 size_t cbRecvd = 0;
774 int rc = RTTcpReadNB(m->hSocket, m->pbRecvBuf, m->cbResidualRecv, &cbRecvd);
775 if (RT_SUCCESS(rc))
776 {
777 m->cbResidualRecv -= cbRecvd;
778 m->pbRecvBuf += cbRecvd;
779 /* In case we received everything for the current state process the data. */
780 if (!m->cbResidualRecv)
781 rc = processData();
782 }
783
784 return rc;
785}
786
787/**
788 * Processes the data in the scratch buffer based on the current state.
789 *
790 * @returns VBox status code.
791 */
792int USBProxyBackendUsbIp::processData()
793{
794 int rc = VINF_SUCCESS;
795
796 switch (m->enmRecvState)
797 {
798 case kUsbIpRecvState_Hdr:
799 {
800 /* Check that the reply matches our expectations. */
801 if ( RT_N2H_U16(m->Scratch.RetDevList.u16Version) == USBIP_VERSION
802 && RT_N2H_U16(m->Scratch.RetDevList.u16Cmd) == USBIP_REQ_RET_DEVLIST
803 && RT_N2H_U32(m->Scratch.RetDevList.u32Status) == USBIP_STATUS_SUCCESS)
804 {
805 /* Populate the number of exported devices in the list and go to the next state. */
806 m->cDevicesLeft = RT_N2H_U32(m->Scratch.RetDevList.u32DevicesExported);
807 if (m->cDevicesLeft)
808 advanceState(kUsbIpRecvState_ExportedDevice);
809 else
810 advanceState(kUsbIpRecvState_None);
811 }
812 else
813 {
814 LogRelMax(10, ("USB/IP: Host sent an invalid reply to the list exported device request (Version: %#x Cmd: %#x Status: %#x)\n",
815 RT_N2H_U16(m->Scratch.RetDevList.u16Version), RT_N2H_U16(m->Scratch.RetDevList.u16Cmd),
816 RT_N2H_U32(m->Scratch.RetDevList.u32Status)));
817 rc = VERR_INVALID_STATE;
818 }
819 break;
820 }
821 case kUsbIpRecvState_ExportedDevice:
822 {
823 /* Create a new device and add it to the list. */
824 usbProxyBackendUsbIpExportedDeviceN2H(&m->Scratch.ExportedDevice);
825 rc = addDeviceToList(&m->Scratch.ExportedDevice);
826 if (RT_SUCCESS(rc))
827 {
828 m->cInterfacesLeft = m->Scratch.ExportedDevice.bNumInterfaces;
829 if (m->cInterfacesLeft)
830 advanceState(kUsbIpRecvState_DeviceInterface);
831 else
832 {
833 m->cDevicesLeft--;
834 if (m->cDevicesLeft)
835 advanceState(kUsbIpRecvState_ExportedDevice);
836 else
837 advanceState(kUsbIpRecvState_None);
838 }
839 }
840 break;
841 }
842 case kUsbIpRecvState_DeviceInterface:
843 {
844 /*
845 * If all interfaces for the current device were received receive the next device
846 * if there is another one left, if not we are done with the current request.
847 */
848 m->cInterfacesLeft--;
849 if (m->cInterfacesLeft)
850 advanceState(kUsbIpRecvState_DeviceInterface);
851 else
852 {
853 m->cDevicesLeft--;
854 if (m->cDevicesLeft)
855 advanceState(kUsbIpRecvState_ExportedDevice);
856 else
857 advanceState(kUsbIpRecvState_None);
858 }
859 break;
860 }
861 case kUsbIpRecvState_None:
862 default:
863 AssertMsgFailed(("Invalid USB/IP receive state %d\n", m->enmRecvState));
864 return VERR_INVALID_STATE;
865 }
866
867 return rc;
868}
869
870/**
871 * Creates a new USB device and adds it to the list.
872 *
873 * @returns VBox status code.
874 * @param pDev Pointer to the USB/IP exported device structure to take
875 * the information for the new device from.
876 */
877int USBProxyBackendUsbIp::addDeviceToList(PUsbIpExportedDevice pDev)
878{
879 PUSBDEVICE pNew = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
880 if (!pNew)
881 return VERR_NO_MEMORY;
882
883 pNew->pszManufacturer = RTStrDup("");
884 pNew->pszProduct = RTStrDup("");
885 pNew->pszSerialNumber = NULL;
886 pNew->pszBackend = RTStrDup("usbip");
887
888 /* Make sure the Bus id is 0 terminated. */
889 pDev->szBusId[31] = '\0';
890 RTStrAPrintf((char **)&pNew->pszAddress, "usbip://%s:%u:%s", m->pszHost, m->uPort, &pDev->szBusId[0]);
891
892 pNew->idVendor = pDev->u16VendorId;
893 pNew->idProduct = pDev->u16ProductId;
894 pNew->bcdDevice = pDev->u16BcdDevice;
895 pNew->bDeviceClass = pDev->bDeviceClass;
896 pNew->bDeviceSubClass = pDev->bDeviceSubClass;
897 pNew->bDeviceProtocol = pDev->bDeviceProtocol;
898 pNew->bNumConfigurations = pDev->bNumConfigurations;
899 pNew->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
900 pNew->u64SerialHash = 0;
901 pNew->bBus = (uint8_t)pDev->u32BusNum;
902 pNew->bPort = (uint8_t)pDev->u32DevNum;
903
904 switch (pDev->u32Speed)
905 {
906 case USBIP_SPEED_LOW:
907 pNew->enmSpeed = USBDEVICESPEED_LOW;
908 pNew->bcdUSB = 1 << 8;
909 break;
910 case USBIP_SPEED_FULL:
911 pNew->enmSpeed = USBDEVICESPEED_FULL;
912 pNew->bcdUSB = 1 << 8;
913 break;
914 case USBIP_SPEED_HIGH:
915 pNew->enmSpeed = USBDEVICESPEED_HIGH;
916 pNew->bcdUSB = 2 << 8;
917 break;
918 case USBIP_SPEED_WIRELESS:
919 pNew->enmSpeed = USBDEVICESPEED_VARIABLE;
920 pNew->bcdUSB = 1 << 8;
921 break;
922 case USBIP_SPEED_SUPER:
923 pNew->enmSpeed = USBDEVICESPEED_SUPER;
924 pNew->bcdUSB = 3 << 8;
925 break;
926 case USBIP_SPEED_UNKNOWN:
927 default:
928 pNew->bcdUSB = 1 << 8;
929 pNew->enmSpeed = USBDEVICESPEED_UNKNOWN;
930 }
931
932 /* link it */
933 pNew->pNext = NULL;
934 pNew->pPrev = *m->ppNext;
935 *m->ppNext = pNew;
936 m->ppNext = &pNew->pNext;
937 m->cDevicesCur++;
938
939 return VINF_SUCCESS;
940}
941
942/**
943 * Compares the given device list with the current one and returns whether it has
944 * changed.
945 *
946 * @returns flag whether the device list has changed compared to the current one.
947 * @param pDevices The device list to compare the current one against.
948 */
949bool USBProxyBackendUsbIp::hasDevListChanged(PUSBDEVICE pDevices)
950{
951 /** @todo */
952 return true;
953}
954
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