VirtualBox

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

Last change on this file since 65854 was 65854, checked in by vboxsync, 8 years ago

Main/USBProxyBackendUsbIp: Don't prevent VBoxSVC from starting when the server is not reachable, just try to reconnect every 3 seconds. Smaller other fixes for stale USB device lists when the server is not reachable and a fix for saving the same USB source multiple times

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 32.8 KB
Line 
1/* $Id: USBProxyBackendUsbIp.cpp 65854 2017-02-23 11:48:49Z vboxsync $ */
2/** @file
3 * VirtualBox USB Proxy Backend, USB/IP.
4 */
5
6/*
7 * Copyright (C) 2015-2016 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_U32(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 *pUsbProxyService, const com::Utf8Str &strId,
283 const com::Utf8Str &strAddress, bool fLoadingSettings)
284{
285 int rc = VINF_SUCCESS;
286
287 USBProxyBackend::init(pUsbProxyService, strId, strAddress, fLoadingSettings);
288
289 unconst(m_strBackend) = Utf8Str("USBIP");
290
291 m = new Data;
292
293 /* Split address into hostname and port. */
294 RTCList<RTCString> lstAddress = strAddress.split(":");
295 if (lstAddress.size() < 1)
296 return VERR_INVALID_PARAMETER;
297 m->pszHost = RTStrDup(lstAddress[0].c_str());
298 if (!m->pszHost)
299 return VERR_NO_STR_MEMORY;
300 if (lstAddress.size() == 2)
301 {
302 m->uPort = lstAddress[1].toUInt32();
303 if (!m->uPort)
304 return VERR_INVALID_PARAMETER;
305 }
306
307 /* Setup wakeup pipe and poll set first. */
308 rc = RTSemFastMutexCreate(&m->hMtxDevices);
309 if (RT_SUCCESS(rc))
310 {
311 rc = RTPipeCreate(&m->hWakeupPipeR, &m->hWakeupPipeW, 0);
312 if (RT_SUCCESS(rc))
313 {
314 rc = RTPollSetCreate(&m->hPollSet);
315 if (RT_SUCCESS(rc))
316 {
317 rc = RTPollSetAddPipe(m->hPollSet, m->hWakeupPipeR,
318 RTPOLL_EVT_READ, USBIP_POLL_ID_PIPE);
319 if (RT_SUCCESS(rc))
320 {
321 /*
322 * Connect to the USB/IP host. Be more graceful to connection errors
323 * if we are instantiated while the settings are loaded to let
324 * VBoxSVC start.
325 *
326 * The worker thread keeps trying to connect every few seconds until
327 * either the USB source is removed by the user or the USB server is
328 * reachable.
329 */
330 rc = reconnect();
331 if (RT_SUCCESS(rc) || fLoadingSettings)
332 rc = start(); /* Start service thread. */
333 }
334
335 if (RT_FAILURE(rc))
336 {
337 RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_PIPE);
338 int rc2 = RTPollSetDestroy(m->hPollSet);
339 AssertRC(rc2);
340 m->hPollSet = NIL_RTPOLLSET;
341 }
342 }
343
344 if (RT_FAILURE(rc))
345 {
346 int rc2 = RTPipeClose(m->hWakeupPipeR);
347 AssertRC(rc2);
348 rc2 = RTPipeClose(m->hWakeupPipeW);
349 AssertRC(rc2);
350 m->hWakeupPipeR = m->hWakeupPipeW = NIL_RTPIPE;
351 }
352 }
353 if (RT_FAILURE(rc))
354 {
355 RTSemFastMutexDestroy(m->hMtxDevices);
356 m->hMtxDevices = NIL_RTSEMFASTMUTEX;
357 }
358 }
359
360 return rc;
361}
362
363/**
364 * Stop all service threads and free the device chain.
365 */
366void USBProxyBackendUsbIp::uninit()
367{
368 LogFlowThisFunc(("\n"));
369
370 /*
371 * Stop the service.
372 */
373 if (isActive())
374 stop();
375
376 /*
377 * Free resources.
378 */
379 if (m->hPollSet != NIL_RTPOLLSET)
380 {
381 disconnect();
382
383 int rc = RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_PIPE);
384 AssertRC(rc);
385 rc = RTPollSetDestroy(m->hPollSet);
386 AssertRC(rc);
387 rc = RTPipeClose(m->hWakeupPipeR);
388 AssertRC(rc);
389 rc = RTPipeClose(m->hWakeupPipeW);
390 AssertRC(rc);
391
392 m->hPollSet = NIL_RTPOLLSET;
393 m->hWakeupPipeR = NIL_RTPIPE;
394 m->hWakeupPipeW = NIL_RTPIPE;
395 }
396
397 if (m->pszHost)
398 RTStrFree(m->pszHost);
399 if (m->hMtxDevices != NIL_RTSEMFASTMUTEX)
400 {
401 RTSemFastMutexDestroy(m->hMtxDevices);
402 m->hMtxDevices = NIL_RTSEMFASTMUTEX;
403 }
404
405 delete m;
406 USBProxyBackend::uninit();
407}
408
409
410int USBProxyBackendUsbIp::captureDevice(HostUSBDevice *aDevice)
411{
412 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
413 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
414
415 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
416 LogFlowThisFunc(("aDevice=%s\n", aDevice->i_getName().c_str()));
417
418 /*
419 * We don't need to do anything when the device is held... fake it.
420 */
421 Assert(aDevice->i_getUnistate() == kHostUSBDeviceState_Capturing);
422 devLock.release();
423
424 return VINF_SUCCESS;
425}
426
427
428int USBProxyBackendUsbIp::releaseDevice(HostUSBDevice *aDevice)
429{
430 AssertReturn(aDevice, VERR_GENERAL_FAILURE);
431 AssertReturn(!aDevice->isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
432
433 AutoReadLock devLock(aDevice COMMA_LOCKVAL_SRC_POS);
434 LogFlowThisFunc(("aDevice=%s\n", aDevice->i_getName().c_str()));
435
436 /*
437 * We're not really holding it atm., just fake it.
438 */
439 Assert(aDevice->i_getUnistate() == kHostUSBDeviceState_ReleasingToHost);
440 devLock.release();
441
442 return VINF_SUCCESS;
443}
444
445
446bool USBProxyBackendUsbIp::isFakeUpdateRequired()
447{
448 return true;
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 reconnect();
460
461 /* Query a new device list upon entering. */
462 if ( m->hSocket != NIL_RTSOCKET
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 3sec 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(3000, 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 if ( RT_SUCCESS(rc)
507 && (fEventsRecv & RTPOLL_EVT_ERROR))
508 rc = VERR_NET_SHUTDOWN;
509
510 /*
511 * If we are in the none state again we received the previous request
512 * and have a new device list to compare the old against.
513 */
514 if (m->enmRecvState == kUsbIpRecvState_None)
515 {
516 if (hasDevListChanged(m->pHead))
517 fDeviceListChangedOrWokenUp = true;
518
519 /* Update to the new list in any case now that we have it anyway. */
520 RTSemFastMutexRequest(m->hMtxDevices);
521 freeDeviceList(m->pUsbDevicesCur);
522 m->cUsbDevicesCur = m->cDevicesCur;
523 m->pUsbDevicesCur = m->pHead;
524 RTSemFastMutexRelease(m->hMtxDevices);
525
526 m->pHead = NULL;
527 resetRecvState();
528 }
529
530 /* Current USB/IP server closes the connection after each request, don't abort but try again. */
531 if (rc == VERR_NET_SHUTDOWN || rc == VERR_BROKEN_PIPE || rc == VERR_NET_CONNECTION_RESET_BY_PEER)
532 {
533 Log(("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 -= (RTMSINTERVAL)(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 {
553 rc = reconnect();
554 if (RT_SUCCESS(rc))
555 rc = startListExportedDevicesReq();
556 else if ( rc == VERR_NET_SHUTDOWN
557 || rc == VERR_BROKEN_PIPE
558 || rc == VERR_NET_CONNECTION_RESET_BY_PEER
559 || rc == VERR_NET_CONNECTION_REFUSED)
560 {
561 /* Make sure the device list is clear. */
562 RTSemFastMutexRequest(m->hMtxDevices);
563 if (m->pUsbDevicesCur)
564 {
565 freeDeviceList(m->pUsbDevicesCur);
566 fDeviceListChangedOrWokenUp = true;
567 m->cUsbDevicesCur = 0;
568 m->pUsbDevicesCur = NULL;
569 }
570 RTSemFastMutexRelease(m->hMtxDevices);
571 rc = VINF_SUCCESS;
572 }
573 }
574 }
575 }
576 }
577
578 LogFlowFunc(("return rc=%Rrc\n", rc));
579 return rc;
580}
581
582
583int USBProxyBackendUsbIp::interruptWait(void)
584{
585 AssertReturn(!isWriteLockOnCurrentThread(), VERR_GENERAL_FAILURE);
586
587 AutoReadLock alock(this COMMA_LOCKVAL_SRC_POS);
588
589 int rc = RTPipeWriteBlocking(m->hWakeupPipeW, "", 1, NULL);
590 if (RT_SUCCESS(rc))
591 RTPipeFlush(m->hWakeupPipeW);
592 LogFlowFunc(("returning %Rrc\n", rc));
593 return rc;
594}
595
596
597PUSBDEVICE USBProxyBackendUsbIp::getDevices(void)
598{
599 PUSBDEVICE pFirst = NULL;
600 PUSBDEVICE *ppNext = &pFirst;
601
602 LogFlowThisFunc(("\n"));
603
604 /* Create a deep copy of the device list. */
605 RTSemFastMutexRequest(m->hMtxDevices);
606 PUSBDEVICE pCur = m->pUsbDevicesCur;
607 while (pCur)
608 {
609 PUSBDEVICE pNew = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
610 if (pNew)
611 {
612 pNew->pszManufacturer = RTStrDup(pCur->pszManufacturer);
613 pNew->pszProduct = RTStrDup(pCur->pszProduct);
614 if (pCur->pszSerialNumber)
615 pNew->pszSerialNumber = RTStrDup(pCur->pszSerialNumber);
616 pNew->pszBackend = RTStrDup(pCur->pszBackend);
617 pNew->pszAddress = RTStrDup(pCur->pszAddress);
618
619 pNew->idVendor = pCur->idVendor;
620 pNew->idProduct = pCur->idProduct;
621 pNew->bcdDevice = pCur->bcdDevice;
622 pNew->bcdUSB = pCur->bcdUSB;
623 pNew->bDeviceClass = pCur->bDeviceClass;
624 pNew->bDeviceSubClass = pCur->bDeviceSubClass;
625 pNew->bDeviceProtocol = pCur->bDeviceProtocol;
626 pNew->bNumConfigurations = pCur->bNumConfigurations;
627 pNew->enmState = pCur->enmState;
628 pNew->u64SerialHash = pCur->u64SerialHash;
629 pNew->bBus = pCur->bBus;
630 pNew->bPort = pCur->bPort;
631 pNew->enmSpeed = pCur->enmSpeed;
632
633 /* link it */
634 pNew->pNext = NULL;
635 pNew->pPrev = *ppNext;
636 *ppNext = pNew;
637 ppNext = &pNew->pNext;
638 }
639
640 pCur = pCur->pNext;
641 }
642 RTSemFastMutexRelease(m->hMtxDevices);
643
644 LogFlowThisFunc(("returning %#p\n", pFirst));
645 return pFirst;
646}
647
648/**
649 * Frees a given device list.
650 *
651 * @returns nothing.
652 * @param pHead The head of the device list to free.
653 */
654void USBProxyBackendUsbIp::freeDeviceList(PUSBDEVICE pHead)
655{
656 PUSBDEVICE pNext = pHead;
657 while (pNext)
658 {
659 PUSBDEVICE pFree = pNext;
660 pNext = pNext->pNext;
661 freeDevice(pFree);
662 }
663}
664
665/**
666 * Resets the receive state to the idle state.
667 *
668 * @returns nothing.
669 */
670void USBProxyBackendUsbIp::resetRecvState()
671{
672 LogFlowFunc(("\n"));
673 freeDeviceList(m->pHead);
674 m->pHead = NULL;
675 m->ppNext = &m->pHead;
676 m->cDevicesCur = 0;
677 m->enmRecvState = kUsbIpRecvState_None;
678 m->cbResidualRecv = 0;
679 m->pbRecvBuf = &m->Scratch.abRecv[0];
680 m->cDevicesLeft = 0;
681 LogFlowFunc(("\n"));
682}
683
684/**
685 * Disconnects from the host and resets the receive state.
686 *
687 * @returns nothing.
688 */
689void USBProxyBackendUsbIp::disconnect()
690{
691 LogFlowFunc(("\n"));
692
693 if (m->hSocket != NIL_RTSOCKET)
694 {
695 int rc = RTPollSetRemove(m->hPollSet, USBIP_POLL_ID_SOCKET);
696 NOREF(rc);
697 Assert(RT_SUCCESS(rc) || rc == VERR_POLL_HANDLE_ID_NOT_FOUND);
698
699 RTTcpClientCloseEx(m->hSocket, false /*fGracefulShutdown*/);
700 m->hSocket = NIL_RTSOCKET;
701 }
702
703 resetRecvState();
704 LogFlowFunc(("returns\n"));
705}
706
707/**
708 * Tries to reconnect to the USB/IP host.
709 *
710 * @returns VBox status code.
711 */
712int USBProxyBackendUsbIp::reconnect()
713{
714 LogFlowFunc(("\n"));
715
716 /* Make sure we are disconnected. */
717 disconnect();
718
719 /* Connect to the USB/IP host. */
720 int rc = RTTcpClientConnect(m->pszHost, m->uPort, &m->hSocket);
721 if (RT_SUCCESS(rc))
722 {
723 rc = RTTcpSetSendCoalescing(m->hSocket, false);
724 if (RT_FAILURE(rc))
725 LogRelMax(5, ("USB/IP: Disabling send coalescing failed (rc=%Rrc), continuing nevertheless but expect increased latency\n", rc));
726
727 rc = RTPollSetAddSocket(m->hPollSet, m->hSocket, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
728 USBIP_POLL_ID_SOCKET);
729 if (RT_FAILURE(rc))
730 {
731 RTTcpClientCloseEx(m->hSocket, false /*fGracefulShutdown*/);
732 m->hSocket = NIL_RTSOCKET;
733 }
734 else
735 LogFlowFunc(("Connected to host \"%s\"\n", m->pszHost));
736 }
737
738 LogFlowFunc(("returns rc=%Rrc\n", rc));
739 return rc;
740}
741
742/**
743 * Initiates a new List Exported Devices request.
744 *
745 * @returns VBox status code.
746 */
747int USBProxyBackendUsbIp::startListExportedDevicesReq()
748{
749 int rc = VINF_SUCCESS;
750
751 LogFlowFunc(("\n"));
752
753 /*
754 * Reset the current state and reconnect in case we were called in the middle
755 * of another transfer (which should not happen).
756 */
757 Assert(m->enmRecvState == kUsbIpRecvState_None);
758 if (m->enmRecvState != kUsbIpRecvState_None)
759 rc = reconnect();
760
761 if (RT_SUCCESS(rc))
762 {
763 /* Send of the request. */
764 UsbIpReqDevList ReqDevList;
765 ReqDevList.u16Version = RT_H2N_U16(USBIP_VERSION);
766 ReqDevList.u16Cmd = RT_H2N_U16(USBIP_INDICATOR_REQ | USBIP_REQ_RET_DEVLIST);
767 ReqDevList.u32Status = RT_H2N_U32(0);
768 rc = RTTcpWrite(m->hSocket, &ReqDevList, sizeof(ReqDevList));
769 if (RT_SUCCESS(rc))
770 advanceState(kUsbIpRecvState_Hdr);
771 }
772
773 LogFlowFunc(("returns rc=%Rrc\n", rc));
774 return rc;
775}
776
777/**
778 * Advances the state machine to the given state.
779 *
780 * @returns nothing.
781 * @param enmRecvState The new receive state.
782 */
783void USBProxyBackendUsbIp::advanceState(USBIPRECVSTATE enmRecvState)
784{
785 LogFlowFunc(("enmRecvState=%u\n", enmRecvState));
786
787 switch (enmRecvState)
788 {
789 case kUsbIpRecvState_None:
790 break;
791 case kUsbIpRecvState_Hdr:
792 {
793 m->cbResidualRecv = sizeof(UsbIpRetDevList);
794 m->pbRecvBuf = (uint8_t *)&m->Scratch.RetDevList;
795 break;
796 }
797 case kUsbIpRecvState_ExportedDevice:
798 {
799 m->cbResidualRecv = sizeof(UsbIpExportedDevice);
800 m->pbRecvBuf = (uint8_t *)&m->Scratch.ExportedDevice;
801 break;
802 }
803 case kUsbIpRecvState_DeviceInterface:
804 {
805 m->cbResidualRecv = sizeof(UsbIpDeviceInterface);
806 m->pbRecvBuf = (uint8_t *)&m->Scratch.DeviceInterface;
807 break;
808 }
809 default:
810 AssertMsgFailed(("Invalid USB/IP receive state %d\n", enmRecvState));
811 return;
812 }
813
814 m->enmRecvState = enmRecvState;
815 LogFlowFunc(("returns\n"));
816}
817
818/**
819 * Receives data from the USB/IP host and processes it when everything for the current
820 * state was received.
821 *
822 * @returns VBox status code.
823 */
824int USBProxyBackendUsbIp::receiveData()
825{
826 int rc = VINF_SUCCESS;
827 size_t cbRecvd = 0;
828
829 LogFlowFunc(("\n"));
830
831 do
832 {
833 rc = RTTcpReadNB(m->hSocket, m->pbRecvBuf, m->cbResidualRecv, &cbRecvd);
834
835 LogFlowFunc(("RTTcpReadNB(%#p, %#p, %zu, %zu) -> %Rrc\n",
836 m->hSocket, m->pbRecvBuf, m->cbResidualRecv, cbRecvd, rc));
837
838 if ( rc == VINF_SUCCESS
839 && cbRecvd > 0)
840 {
841 m->cbResidualRecv -= cbRecvd;
842 m->pbRecvBuf += cbRecvd;
843 /* In case we received everything for the current state process the data. */
844 if (!m->cbResidualRecv)
845 {
846 rc = processData();
847 if ( RT_SUCCESS(rc)
848 && m->enmRecvState == kUsbIpRecvState_None)
849 break;
850 }
851 }
852 else if (rc == VINF_TRY_AGAIN)
853 Assert(!cbRecvd);
854
855 } while (rc == VINF_SUCCESS && cbRecvd > 0);
856
857 if (rc == VINF_TRY_AGAIN)
858 rc = VINF_SUCCESS;
859
860 LogFlowFunc(("returns rc=%Rrc\n", rc));
861 return rc;
862}
863
864/**
865 * Processes the data in the scratch buffer based on the current state.
866 *
867 * @returns VBox status code.
868 */
869int USBProxyBackendUsbIp::processData()
870{
871 int rc = VINF_SUCCESS;
872
873 switch (m->enmRecvState)
874 {
875 case kUsbIpRecvState_Hdr:
876 {
877 /* Check that the reply matches our expectations. */
878 if ( RT_N2H_U16(m->Scratch.RetDevList.u16Version) == USBIP_VERSION
879 && RT_N2H_U16(m->Scratch.RetDevList.u16Cmd) == USBIP_REQ_RET_DEVLIST
880 && RT_N2H_U32(m->Scratch.RetDevList.u32Status) == USBIP_STATUS_SUCCESS)
881 {
882 /* Populate the number of exported devices in the list and go to the next state. */
883 m->cDevicesLeft = RT_N2H_U32(m->Scratch.RetDevList.u32DevicesExported);
884 if (m->cDevicesLeft)
885 advanceState(kUsbIpRecvState_ExportedDevice);
886 else
887 advanceState(kUsbIpRecvState_None);
888 }
889 else
890 {
891 LogRelMax(10, ("USB/IP: Host sent an invalid reply to the list exported device request (Version: %#x Cmd: %#x Status: %#x)\n",
892 RT_N2H_U16(m->Scratch.RetDevList.u16Version), RT_N2H_U16(m->Scratch.RetDevList.u16Cmd),
893 RT_N2H_U32(m->Scratch.RetDevList.u32Status)));
894 /* Disconnect and start over. */
895 advanceState(kUsbIpRecvState_None);
896 disconnect();
897 rc = VERR_NET_SHUTDOWN;
898 }
899 break;
900 }
901 case kUsbIpRecvState_ExportedDevice:
902 {
903 /* Create a new device and add it to the list. */
904 usbProxyBackendUsbIpExportedDeviceN2H(&m->Scratch.ExportedDevice);
905 rc = addDeviceToList(&m->Scratch.ExportedDevice);
906 if (RT_SUCCESS(rc))
907 {
908 m->cInterfacesLeft = m->Scratch.ExportedDevice.bNumInterfaces;
909 if (m->cInterfacesLeft)
910 advanceState(kUsbIpRecvState_DeviceInterface);
911 else
912 {
913 m->cDevicesLeft--;
914 if (m->cDevicesLeft)
915 advanceState(kUsbIpRecvState_ExportedDevice);
916 else
917 advanceState(kUsbIpRecvState_None);
918 }
919 }
920 break;
921 }
922 case kUsbIpRecvState_DeviceInterface:
923 {
924 /*
925 * If all interfaces for the current device were received receive the next device
926 * if there is another one left, if not we are done with the current request.
927 */
928 m->cInterfacesLeft--;
929 if (m->cInterfacesLeft)
930 advanceState(kUsbIpRecvState_DeviceInterface);
931 else
932 {
933 m->cDevicesLeft--;
934 if (m->cDevicesLeft)
935 advanceState(kUsbIpRecvState_ExportedDevice);
936 else
937 advanceState(kUsbIpRecvState_None);
938 }
939 break;
940 }
941 case kUsbIpRecvState_None:
942 default:
943 AssertMsgFailed(("Invalid USB/IP receive state %d\n", m->enmRecvState));
944 return VERR_INVALID_STATE;
945 }
946
947 return rc;
948}
949
950/**
951 * Creates a new USB device and adds it to the list.
952 *
953 * @returns VBox status code.
954 * @param pDev Pointer to the USB/IP exported device structure to take
955 * the information for the new device from.
956 */
957int USBProxyBackendUsbIp::addDeviceToList(PUsbIpExportedDevice pDev)
958{
959 int rc = VINF_SUCCESS;
960 PUSBDEVICE pNew = (PUSBDEVICE)RTMemAllocZ(sizeof(USBDEVICE));
961 if (!pNew)
962 return VERR_NO_MEMORY;
963
964 pNew->pszManufacturer = RTStrDup("");
965 pNew->pszProduct = RTStrDup("");
966 pNew->pszSerialNumber = NULL;
967 pNew->pszBackend = RTStrDup("usbip");
968
969 /* Make sure the Bus id is 0 terminated. */
970 pDev->szBusId[31] = '\0';
971 pNew->pszAddress = RTStrAPrintf2("usbip://%s:%u:%s", m->pszHost, m->uPort, &pDev->szBusId[0]);
972 if (RT_LIKELY(pNew->pszAddress))
973 {
974 pNew->idVendor = pDev->u16VendorId;
975 pNew->idProduct = pDev->u16ProductId;
976 pNew->bcdDevice = pDev->u16BcdDevice;
977 pNew->bDeviceClass = pDev->bDeviceClass;
978 pNew->bDeviceSubClass = pDev->bDeviceSubClass;
979 pNew->bDeviceProtocol = pDev->bDeviceProtocol;
980 pNew->bNumConfigurations = pDev->bNumConfigurations;
981 pNew->enmState = USBDEVICESTATE_USED_BY_HOST_CAPTURABLE;
982 pNew->u64SerialHash = 0;
983 /** @todo The following is not correct but is required to to get USB testing working
984 * because only the port can be part of a filter (adding the required attributes for the bus
985 * breaks API and ABI compatibility).
986 * Filtering by port number is required for USB testing to connect to the correct device
987 * in case there are multiple ones.
988 */
989 pNew->bBus = (uint8_t)pDev->u32DevNum;
990 pNew->bPort = (uint8_t)pDev->u32BusNum;
991
992 switch (pDev->u32Speed)
993 {
994 case USBIP_SPEED_LOW:
995 pNew->enmSpeed = USBDEVICESPEED_LOW;
996 pNew->bcdUSB = 1 << 8;
997 break;
998 case USBIP_SPEED_FULL:
999 pNew->enmSpeed = USBDEVICESPEED_FULL;
1000 pNew->bcdUSB = 1 << 8;
1001 break;
1002 case USBIP_SPEED_HIGH:
1003 pNew->enmSpeed = USBDEVICESPEED_HIGH;
1004 pNew->bcdUSB = 2 << 8;
1005 break;
1006 case USBIP_SPEED_WIRELESS:
1007 pNew->enmSpeed = USBDEVICESPEED_VARIABLE;
1008 pNew->bcdUSB = 1 << 8;
1009 break;
1010 case USBIP_SPEED_SUPER:
1011 pNew->enmSpeed = USBDEVICESPEED_SUPER;
1012 pNew->bcdUSB = 3 << 8;
1013 break;
1014 case USBIP_SPEED_UNKNOWN:
1015 default:
1016 pNew->bcdUSB = 1 << 8;
1017 pNew->enmSpeed = USBDEVICESPEED_UNKNOWN;
1018 }
1019
1020 /* link it */
1021 pNew->pNext = NULL;
1022 pNew->pPrev = *m->ppNext;
1023 *m->ppNext = pNew;
1024 m->ppNext = &pNew->pNext;
1025 m->cDevicesCur++;
1026 }
1027 else
1028 rc = VERR_NO_STR_MEMORY;
1029
1030 if (RT_FAILURE(rc))
1031 {
1032 if (pNew->pszManufacturer)
1033 RTStrFree((char *)pNew->pszManufacturer);
1034 if (pNew->pszProduct)
1035 RTStrFree((char *)pNew->pszProduct);
1036 if (pNew->pszBackend)
1037 RTStrFree((char *)pNew->pszBackend);
1038 if (pNew->pszAddress)
1039 RTStrFree((char *)pNew->pszAddress);
1040 RTMemFree(pNew);
1041 }
1042
1043 return rc;
1044}
1045
1046/**
1047 * Compares the given device list with the current one and returns whether it has
1048 * changed.
1049 *
1050 * @returns flag whether the device list has changed compared to the current one.
1051 * @param pDevices The device list to compare the current one against.
1052 */
1053bool USBProxyBackendUsbIp::hasDevListChanged(PUSBDEVICE pDevices)
1054{
1055 /** @todo */
1056 NOREF(pDevices);
1057 return true;
1058}
1059
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