VirtualBox

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

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

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