VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/utils/usb/UsbTestService.cpp@ 62598

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

Misc: scm

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 56.0 KB
Line 
1/* $Id: UsbTestService.cpp 62471 2016-07-22 18:04:30Z vboxsync $ */
2/** @file
3 * UsbTestService - Remote USB test configuration and execution server.
4 */
5
6/*
7 * Copyright (C) 2010-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 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP RTLOGGROUP_DEFAULT
32#include <iprt/alloca.h>
33#include <iprt/asm.h>
34#include <iprt/assert.h>
35#include <iprt/critsect.h>
36#include <iprt/crc.h>
37#include <iprt/ctype.h>
38#include <iprt/dir.h>
39#include <iprt/env.h>
40#include <iprt/err.h>
41#include <iprt/getopt.h>
42#include <iprt/handle.h>
43#include <iprt/initterm.h>
44#include <iprt/json.h>
45#include <iprt/list.h>
46#include <iprt/log.h>
47#include <iprt/mem.h>
48#include <iprt/message.h>
49#include <iprt/param.h>
50#include <iprt/path.h>
51#include <iprt/pipe.h>
52#include <iprt/poll.h>
53#include <iprt/process.h>
54#include <iprt/stream.h>
55#include <iprt/string.h>
56#include <iprt/thread.h>
57
58#include "UsbTestServiceInternal.h"
59#include "UsbTestServiceGadget.h"
60#include "UsbTestServicePlatform.h"
61
62
63
64/*********************************************************************************************************************************
65* Structures and Typedefs *
66*********************************************************************************************************************************/
67
68#define UTS_USBIP_PORT_FIRST 3240
69#define UTS_USBIP_PORT_LAST 3340
70
71/**
72 * UTS client state.
73 */
74typedef enum UTSCLIENTSTATE
75{
76 /** Invalid client state. */
77 UTSCLIENTSTATE_INVALID = 0,
78 /** Client is initialising, only the HOWDY and BYE packets are allowed. */
79 UTSCLIENTSTATE_INITIALISING,
80 /** Client is in fully cuntional state and ready to process all requests. */
81 UTSCLIENTSTATE_READY,
82 /** Client is destroying. */
83 UTSCLIENTSTATE_DESTROYING,
84 /** 32bit hack. */
85 UTSCLIENTSTATE_32BIT_HACK = 0x7fffffff
86} UTSCLIENTSTATE;
87
88/**
89 * UTS client instance.
90 */
91typedef struct UTSCLIENT
92{
93 /** List node for new clients. */
94 RTLISTNODE NdLst;
95 /** The current client state. */
96 UTSCLIENTSTATE enmState;
97 /** Transport backend specific data. */
98 PUTSTRANSPORTCLIENT pTransportClient;
99 /** Client hostname. */
100 char *pszHostname;
101 /** Gadget host handle. */
102 UTSGADGETHOST hGadgetHost;
103 /** Handle fo the current configured gadget. */
104 UTSGADGET hGadget;
105} UTSCLIENT;
106/** Pointer to a UTS client instance. */
107typedef UTSCLIENT *PUTSCLIENT;
108
109
110/*********************************************************************************************************************************
111* Global Variables *
112*********************************************************************************************************************************/
113/**
114 * Transport layers.
115 */
116static const PCUTSTRANSPORT g_apTransports[] =
117{
118 &g_TcpTransport,
119 //&g_SerialTransport,
120 //&g_FileSysTransport,
121 //&g_GuestPropTransport,
122 //&g_TestDevTransport,
123};
124
125/** The select transport layer. */
126static PCUTSTRANSPORT g_pTransport;
127/** The config path. */
128static char g_szCfgPath[RTPATH_MAX];
129/** The scratch path. */
130static char g_szScratchPath[RTPATH_MAX];
131/** The default scratch path. */
132static char g_szDefScratchPath[RTPATH_MAX];
133/** The CD/DVD-ROM path. */
134static char g_szCdRomPath[RTPATH_MAX];
135/** The default CD/DVD-ROM path. */
136static char g_szDefCdRomPath[RTPATH_MAX];
137/** The operating system short name. */
138static char g_szOsShortName[16];
139/** The CPU architecture short name. */
140static char g_szArchShortName[16];
141/** The combined "OS.arch" name. */
142static char g_szOsDotArchShortName[32];
143/** The combined "OS/arch" name. */
144static char g_szOsSlashArchShortName[32];
145/** The executable suffix. */
146static char g_szExeSuff[8];
147/** The shell script suffix. */
148static char g_szScriptSuff[8];
149/** Whether to display the output of the child process or not. */
150static bool g_fDisplayOutput = true;
151/** Whether to terminate or not.
152 * @todo implement signals and stuff. */
153static bool volatile g_fTerminate = false;
154/** Configuration AST. */
155static RTJSONVAL g_hCfgJson = NIL_RTJSONVAL;
156/** Pipe for communicating with the serving thread about new clients. - read end */
157static RTPIPE g_hPipeR;
158/** Pipe for communicating with the serving thread about new clients. - write end */
159static RTPIPE g_hPipeW;
160/** Thread serving connected clients. */
161static RTTHREAD g_hThreadServing;
162/** Critical section protecting the list of new clients. */
163static RTCRITSECT g_CritSectClients;
164/** List of new clients waiting to be picked up by the client worker thread. */
165static RTLISTANCHOR g_LstClientsNew;
166/** First USB/IP port we can use. */
167static uint16_t g_uUsbIpPortFirst = UTS_USBIP_PORT_FIRST;
168/** Last USB/IP port we can use. */
169static uint16_t g_uUsbIpPortLast = UTS_USBIP_PORT_LAST;
170/** Next free port. */
171static uint16_t g_uUsbIpPortNext = UTS_USBIP_PORT_FIRST;
172
173
174
175/**
176 * Returns the string represenation of the given state.
177 */
178static const char *utsClientStateStringify(UTSCLIENTSTATE enmState)
179{
180 switch (enmState)
181 {
182 case UTSCLIENTSTATE_INVALID:
183 return "INVALID";
184 case UTSCLIENTSTATE_INITIALISING:
185 return "INITIALISING";
186 case UTSCLIENTSTATE_READY:
187 return "READY";
188 case UTSCLIENTSTATE_DESTROYING:
189 return "DESTROYING";
190 case UTSCLIENTSTATE_32BIT_HACK:
191 default:
192 break;
193 }
194
195 AssertMsgFailed(("Unknown state %#x\n", enmState));
196 return "UNKNOWN";
197}
198
199/**
200 * Calculates the checksum value, zero any padding space and send the packet.
201 *
202 * @returns IPRT status code.
203 * @param pClient The UTS client structure.
204 * @param pPkt The packet to send. Must point to a correctly
205 * aligned buffer.
206 */
207static int utsSendPkt(PUTSCLIENT pClient, PUTSPKTHDR pPkt)
208{
209 Assert(pPkt->cb >= sizeof(*pPkt));
210 pPkt->uCrc32 = RTCrc32(pPkt->achOpcode, pPkt->cb - RT_OFFSETOF(UTSPKTHDR, achOpcode));
211 if (pPkt->cb != RT_ALIGN_32(pPkt->cb, UTSPKT_ALIGNMENT))
212 memset((uint8_t *)pPkt + pPkt->cb, '\0', RT_ALIGN_32(pPkt->cb, UTSPKT_ALIGNMENT) - pPkt->cb);
213
214 Log(("utsSendPkt: cb=%#x opcode=%.8s\n", pPkt->cb, pPkt->achOpcode));
215 Log2(("%.*Rhxd\n", RT_MIN(pPkt->cb, 256), pPkt));
216 int rc = g_pTransport->pfnSendPkt(pClient->pTransportClient, pPkt);
217 while (RT_UNLIKELY(rc == VERR_INTERRUPTED) && !g_fTerminate)
218 rc = g_pTransport->pfnSendPkt(pClient->pTransportClient, pPkt);
219 if (RT_FAILURE(rc))
220 Log(("utsSendPkt: rc=%Rrc\n", rc));
221
222 return rc;
223}
224
225/**
226 * Sends a babble reply and disconnects the client (if applicable).
227 *
228 * @param pClient The UTS client structure.
229 * @param pszOpcode The BABBLE opcode.
230 */
231static void utsReplyBabble(PUTSCLIENT pClient, const char *pszOpcode)
232{
233 UTSPKTHDR Reply;
234 Reply.cb = sizeof(Reply);
235 Reply.uCrc32 = 0;
236 memcpy(Reply.achOpcode, pszOpcode, sizeof(Reply.achOpcode));
237
238 g_pTransport->pfnBabble(pClient->pTransportClient, &Reply, 20*1000);
239}
240
241/**
242 * Receive and validate a packet.
243 *
244 * Will send bable responses to malformed packets that results in a error status
245 * code.
246 *
247 * @returns IPRT status code.
248 * @param pClient The UTS client structure.
249 * @param ppPktHdr Where to return the packet on success. Free
250 * with RTMemFree.
251 * @param fAutoRetryOnFailure Whether to retry on error.
252 */
253static int utsRecvPkt(PUTSCLIENT pClient, PPUTSPKTHDR ppPktHdr, bool fAutoRetryOnFailure)
254{
255 for (;;)
256 {
257 PUTSPKTHDR pPktHdr;
258 int rc = g_pTransport->pfnRecvPkt(pClient->pTransportClient, &pPktHdr);
259 if (RT_SUCCESS(rc))
260 {
261 /* validate the packet. */
262 if ( pPktHdr->cb >= sizeof(UTSPKTHDR)
263 && pPktHdr->cb < UTSPKT_MAX_SIZE)
264 {
265 Log2(("utsRecvPkt: pPktHdr=%p cb=%#x crc32=%#x opcode=%.8s\n"
266 "%.*Rhxd\n",
267 pPktHdr, pPktHdr->cb, pPktHdr->uCrc32, pPktHdr->achOpcode, RT_MIN(pPktHdr->cb, 256), pPktHdr));
268 uint32_t uCrc32Calc = pPktHdr->uCrc32 != 0
269 ? RTCrc32(&pPktHdr->achOpcode[0], pPktHdr->cb - RT_OFFSETOF(UTSPKTHDR, achOpcode))
270 : 0;
271 if (pPktHdr->uCrc32 == uCrc32Calc)
272 {
273 AssertCompileMemberSize(UTSPKTHDR, achOpcode, 8);
274 if ( RT_C_IS_UPPER(pPktHdr->achOpcode[0])
275 && RT_C_IS_UPPER(pPktHdr->achOpcode[1])
276 && (RT_C_IS_UPPER(pPktHdr->achOpcode[2]) || pPktHdr->achOpcode[2] == ' ')
277 && (RT_C_IS_PRINT(pPktHdr->achOpcode[3]) || pPktHdr->achOpcode[3] == ' ')
278 && (RT_C_IS_PRINT(pPktHdr->achOpcode[4]) || pPktHdr->achOpcode[4] == ' ')
279 && (RT_C_IS_PRINT(pPktHdr->achOpcode[5]) || pPktHdr->achOpcode[5] == ' ')
280 && (RT_C_IS_PRINT(pPktHdr->achOpcode[6]) || pPktHdr->achOpcode[6] == ' ')
281 && (RT_C_IS_PRINT(pPktHdr->achOpcode[7]) || pPktHdr->achOpcode[7] == ' ')
282 )
283 {
284 Log(("utsRecvPkt: cb=%#x opcode=%.8s\n", pPktHdr->cb, pPktHdr->achOpcode));
285 *ppPktHdr = pPktHdr;
286 return rc;
287 }
288
289 rc = VERR_IO_BAD_COMMAND;
290 }
291 else
292 {
293 Log(("utsRecvPkt: cb=%#x opcode=%.8s crc32=%#x actual=%#x\n",
294 pPktHdr->cb, pPktHdr->achOpcode, pPktHdr->uCrc32, uCrc32Calc));
295 rc = VERR_IO_CRC;
296 }
297 }
298 else
299 rc = VERR_IO_BAD_LENGTH;
300
301 /* Send babble reply and disconnect the client if the transport is
302 connection oriented. */
303 if (rc == VERR_IO_BAD_LENGTH)
304 utsReplyBabble(pClient, "BABBLE L");
305 else if (rc == VERR_IO_CRC)
306 utsReplyBabble(pClient, "BABBLE C");
307 else if (rc == VERR_IO_BAD_COMMAND)
308 utsReplyBabble(pClient, "BABBLE O");
309 else
310 utsReplyBabble(pClient, "BABBLE ");
311 RTMemFree(pPktHdr);
312 }
313
314 /* Try again or return failure? */
315 if ( g_fTerminate
316 || rc != VERR_INTERRUPTED
317 || !fAutoRetryOnFailure
318 )
319 {
320 Log(("utsRecvPkt: rc=%Rrc\n", rc));
321 return rc;
322 }
323 }
324}
325
326/**
327 * Make a simple reply, only status opcode.
328 *
329 * @returns IPRT status code of the send.
330 * @param pClient The UTS client structure.
331 * @param pReply The reply packet.
332 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
333 * with space.
334 * @param cbExtra Bytes in addition to the header.
335 */
336static int utsReplyInternal(PUTSCLIENT pClient, PUTSPKTSTS pReply, const char *pszOpcode, size_t cbExtra)
337{
338 /* copy the opcode, don't be too strict in case of a padding screw up. */
339 size_t cchOpcode = strlen(pszOpcode);
340 if (RT_LIKELY(cchOpcode == sizeof(pReply->Hdr.achOpcode)))
341 memcpy(pReply->Hdr.achOpcode, pszOpcode, sizeof(pReply->Hdr.achOpcode));
342 else
343 {
344 Assert(cchOpcode == sizeof(pReply->Hdr.achOpcode));
345 while (cchOpcode > 0 && pszOpcode[cchOpcode - 1] == ' ')
346 cchOpcode--;
347 AssertMsgReturn(cchOpcode < sizeof(pReply->Hdr.achOpcode), ("%d/'%.8s'\n", cchOpcode, pszOpcode), VERR_INTERNAL_ERROR_4);
348 memcpy(pReply->Hdr.achOpcode, pszOpcode, cchOpcode);
349 memset(&pReply->Hdr.achOpcode[cchOpcode], ' ', sizeof(pReply->Hdr.achOpcode) - cchOpcode);
350 }
351
352 pReply->Hdr.cb = (uint32_t)sizeof(UTSPKTSTS) + (uint32_t)cbExtra;
353 pReply->Hdr.uCrc32 = 0;
354
355 return utsSendPkt(pClient, &pReply->Hdr);
356}
357
358/**
359 * Make a simple reply, only status opcode.
360 *
361 * @returns IPRT status code of the send.
362 * @param pClient The UTS client structure.
363 * @param pPktHdr The original packet (for future use).
364 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
365 * with space.
366 */
367static int utsReplySimple(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode)
368{
369 UTSPKTSTS Pkt;
370
371 RT_ZERO(Pkt);
372 Pkt.rcReq = VINF_SUCCESS;
373 Pkt.cchStsMsg = 0;
374 NOREF(pPktHdr);
375 return utsReplyInternal(pClient, &Pkt, pszOpcode, 0);
376}
377
378/**
379 * Acknowledges a packet with success.
380 *
381 * @returns IPRT status code of the send.
382 * @param pClient The UTS client structure.
383 * @param pPktHdr The original packet (for future use).
384 */
385static int utsReplyAck(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
386{
387 return utsReplySimple(pClient, pPktHdr, "ACK ");
388}
389
390/**
391 * Replies with a failure.
392 *
393 * @returns IPRT status code of the send.
394 * @param pClient The UTS client structure.
395 * @param pPktHdr The original packet (for future use).
396 * @param rcReq Status code.
397 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
398 * with space.
399 * @param pszDetailsFmt Longer description of the problem (format
400 * string).
401 * @param va Format arguments.
402 */
403static int utsReplyFailureV(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode, int rcReq, const char *pszDetailFmt, va_list va)
404{
405 NOREF(pPktHdr);
406 union
407 {
408 UTSPKTSTS Hdr;
409 char ach[256];
410 } uPkt;
411
412 RT_ZERO(uPkt);
413 size_t cchDetail = RTStrPrintfV(&uPkt.ach[sizeof(UTSPKTSTS)],
414 sizeof(uPkt) - sizeof(UTSPKTSTS),
415 pszDetailFmt, va);
416 uPkt.Hdr.rcReq = rcReq;
417 uPkt.Hdr.cchStsMsg = cchDetail;
418 return utsReplyInternal(pClient, &uPkt.Hdr, pszOpcode, cchDetail + 1);
419}
420
421/**
422 * Replies with a failure.
423 *
424 * @returns IPRT status code of the send.
425 * @param pClient The UTS client structure.
426 * @param pPktHdr The original packet (for future use).
427 * @param rcReq Status code.
428 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
429 * with space.
430 * @param pszDetails Longer description of the problem (format
431 * string).
432 * @param ... Format arguments.
433 */
434static int utsReplyFailure(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode, int rcReq, const char *pszDetailFmt, ...)
435{
436 va_list va;
437 va_start(va, pszDetailFmt);
438 int rc = utsReplyFailureV(pClient, pPktHdr, pszOpcode, rcReq, pszDetailFmt, va);
439 va_end(va);
440 return rc;
441}
442
443/**
444 * Replies according to the return code.
445 *
446 * @returns IPRT status code of the send.
447 * @param pClient The UTS client structure.
448 * @param pPktHdr The packet to reply to.
449 * @param rcOperation The status code to report.
450 * @param pszOperationFmt The operation that failed. Typically giving the
451 * function call with important arguments.
452 * @param ... Arguments to the format string.
453 */
454static int utsReplyRC(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, int rcOperation, const char *pszOperationFmt, ...)
455{
456 if (RT_SUCCESS(rcOperation))
457 return utsReplyAck(pClient, pPktHdr);
458
459 char szOperation[128];
460 va_list va;
461 va_start(va, pszOperationFmt);
462 RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
463 va_end(va);
464
465 return utsReplyFailure(pClient, pPktHdr, "FAILED ", rcOperation, "%s failed with rc=%Rrc (opcode '%.8s')",
466 szOperation, rcOperation, pPktHdr->achOpcode);
467}
468
469/**
470 * Signal a bad packet minum size.
471 *
472 * @returns IPRT status code of the send.
473 * @param pClient The UTS client structure.
474 * @param pPktHdr The packet to reply to.
475 * @param cbMin The minimum size.
476 */
477static int utsReplyBadMinSize(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, size_t cbMin)
478{
479 return utsReplyFailure(pClient, pPktHdr, "BAD SIZE", VERR_INVALID_PARAMETER, "Expected at least %zu bytes, got %u (opcode '%.8s')",
480 cbMin, pPktHdr->cb, pPktHdr->achOpcode);
481}
482
483/**
484 * Signal a bad packet exact size.
485 *
486 * @returns IPRT status code of the send.
487 * @param pClient The UTS client structure.
488 * @param pPktHdr The packet to reply to.
489 * @param cb The wanted size.
490 */
491static int utsReplyBadSize(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, size_t cb)
492{
493 return utsReplyFailure(pClient, pPktHdr, "BAD SIZE", VERR_INVALID_PARAMETER, "Expected at %zu bytes, got %u (opcode '%.8s')",
494 cb, pPktHdr->cb, pPktHdr->achOpcode);
495}
496
497/**
498 * Deals with a command that isn't implemented yet.
499 * @returns IPRT status code of the send.
500 * @param pClient The UTS client structure.
501 * @param pPktHdr The packet which opcode isn't implemented.
502 */
503static int utsReplyNotImplemented(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
504{
505 return utsReplyFailure(pClient, pPktHdr, "NOT IMPL", VERR_NOT_IMPLEMENTED, "Opcode '%.8s' is not implemented", pPktHdr->achOpcode);
506}
507
508/**
509 * Deals with a unknown command.
510 * @returns IPRT status code of the send.
511 * @param pClient The UTS client structure.
512 * @param pPktHdr The packet to reply to.
513 */
514static int utsReplyUnknown(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
515{
516 return utsReplyFailure(pClient, pPktHdr, "UNKNOWN ", VERR_NOT_FOUND, "Opcode '%.8s' is not known", pPktHdr->achOpcode);
517}
518
519/**
520 * Deals with a command which contains an unterminated string.
521 *
522 * @returns IPRT status code of the send.
523 * @param pClient The UTS client structure.
524 * @param pPktHdr The packet containing the unterminated string.
525 */
526static int utsReplyBadStrTermination(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
527{
528 return utsReplyFailure(pClient, pPktHdr, "BAD TERM", VERR_INVALID_PARAMETER, "Opcode '%.8s' contains an unterminated string", pPktHdr->achOpcode);
529}
530
531/**
532 * Deals with a command sent in an invalid client state.
533 *
534 * @returns IPRT status code of the send.
535 * @param pClient The UTS client structure.
536 * @param pPktHdr The packet containing the unterminated string.
537 */
538static int utsReplyInvalidState(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
539{
540 return utsReplyFailure(pClient, pPktHdr, "INVSTATE", VERR_INVALID_STATE, "Opcode '%.8s' is not supported at client state '%s",
541 pPktHdr->achOpcode, utsClientStateStringify(pClient->enmState));
542}
543
544/**
545 * Parses an unsigned integer from the given value string.
546 *
547 * @returns IPRT status code.
548 * @retval VERR_OUT_OF_RANGE if the parsed value exceeds the given maximum.
549 * @param uMax The maximum value.
550 * @param pu64 Where to store the parsed number on success.
551 */
552static int utsDoGadgetCreateCfgParseUInt(const char *pszVal, uint64_t uMax, uint64_t *pu64)
553{
554 int rc = RTStrToUInt64Ex(pszVal, NULL, 0, pu64);
555 if (RT_SUCCESS(rc))
556 {
557 if (*pu64 > uMax)
558 rc = VERR_OUT_OF_RANGE;
559 }
560
561 return rc;
562}
563
564/**
565 * Parses a signed integer from the given value string.
566 *
567 * @returns IPRT status code.
568 * @retval VERR_OUT_OF_RANGE if the parsed value exceeds the given range.
569 * @param iMin The minimum value.
570 * @param iMax The maximum value.
571 * @param pi64 Where to store the parsed number on success.
572 */
573static int utsDoGadgetCreateCfgParseInt(const char *pszVal, int64_t iMin, int64_t iMax, int64_t *pi64)
574{
575 int rc = RTStrToInt64Ex(pszVal, NULL, 0, pi64);
576 if (RT_SUCCESS(rc))
577 {
578 if ( *pi64 < iMin
579 || *pi64 > iMax)
580 rc = VERR_OUT_OF_RANGE;
581 }
582
583 return rc;
584}
585
586/**
587 * Parses the given config item and fills in the value according to the given type.
588 *
589 * @returns IPRT status code.
590 * @param pCfgItem The config item to parse.
591 * @param u32Type The config type.
592 * @param pszVal The value encoded as a string.
593 */
594static int utsDoGadgetCreateCfgParseItem(PUTSGADGETCFGITEM pCfgItem, uint32_t u32Type,
595 const char *pszVal)
596{
597 int rc = VINF_SUCCESS;
598
599 switch (u32Type)
600 {
601 case UTSPKT_GDGT_CFG_ITEM_TYPE_BOOLEAN:
602 {
603 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_BOOLEAN;
604 if ( RTStrICmp(pszVal, "enabled")
605 || RTStrICmp(pszVal, "1")
606 || RTStrICmp(pszVal, "true"))
607 pCfgItem->Val.u.f = true;
608 else if ( RTStrICmp(pszVal, "disabled")
609 || RTStrICmp(pszVal, "0")
610 || RTStrICmp(pszVal, "false"))
611 pCfgItem->Val.u.f = false;
612 else
613 rc = VERR_INVALID_PARAMETER;
614 break;
615 }
616 case UTSPKT_GDGT_CFG_ITEM_TYPE_STRING:
617 {
618 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_STRING;
619 pCfgItem->Val.u.psz = RTStrDup(pszVal);
620 if (!pCfgItem->Val.u.psz)
621 rc = VERR_NO_STR_MEMORY;
622 break;
623 }
624 case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT8:
625 {
626 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT8;
627
628 uint64_t u64;
629 rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT8_MAX, &u64);
630 if (RT_SUCCESS(rc))
631 pCfgItem->Val.u.u8 = (uint8_t)u64;
632 break;
633 }
634 case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT16:
635 {
636 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT16;
637
638 uint64_t u64;
639 rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT16_MAX, &u64);
640 if (RT_SUCCESS(rc))
641 pCfgItem->Val.u.u16 = (uint16_t)u64;
642 break;
643 }
644 case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT32:
645 {
646 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT32;
647
648 uint64_t u64;
649 rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT32_MAX, &u64);
650 if (RT_SUCCESS(rc))
651 pCfgItem->Val.u.u32 = (uint32_t)u64;
652 break;
653 }
654 case UTSPKT_GDGT_CFG_ITEM_TYPE_UINT64:
655 {
656 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_UINT64;
657 rc = utsDoGadgetCreateCfgParseUInt(pszVal, UINT64_MAX, &pCfgItem->Val.u.u64);
658 break;
659 }
660 case UTSPKT_GDGT_CFG_ITEM_TYPE_INT8:
661 {
662 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT8;
663
664 int64_t i64;
665 rc = utsDoGadgetCreateCfgParseInt(pszVal, INT8_MIN, INT8_MAX, &i64);
666 if (RT_SUCCESS(rc))
667 pCfgItem->Val.u.i8 = (int8_t)i64;
668 break;
669 }
670 case UTSPKT_GDGT_CFG_ITEM_TYPE_INT16:
671 {
672 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT16;
673
674 int64_t i64;
675 rc = utsDoGadgetCreateCfgParseInt(pszVal, INT16_MIN, INT16_MAX, &i64);
676 if (RT_SUCCESS(rc))
677 pCfgItem->Val.u.i16 = (int16_t)i64;
678 break;
679 }
680 case UTSPKT_GDGT_CFG_ITEM_TYPE_INT32:
681 {
682 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT32;
683
684 int64_t i64;
685 rc = utsDoGadgetCreateCfgParseInt(pszVal, INT32_MIN, INT32_MAX, &i64);
686 if (RT_SUCCESS(rc))
687 pCfgItem->Val.u.i32 = (int32_t)i64;
688 break;
689 }
690 case UTSPKT_GDGT_CFG_ITEM_TYPE_INT64:
691 {
692 pCfgItem->Val.enmType = UTSGADGETCFGTYPE_INT64;
693 rc = utsDoGadgetCreateCfgParseInt(pszVal, INT64_MIN, INT64_MAX, &pCfgItem->Val.u.i64);
694 break;
695 }
696 default:
697 rc = VERR_INVALID_PARAMETER;
698 }
699
700 return rc;
701}
702
703/**
704 * Creates the configuration from the given GADGET CREATE packet.
705 *
706 * @returns IPRT status code.
707 * @param pCfgItem The first config item header in the request packet.
708 * @param cCfgItems Number of config items in the packet to parse.
709 * @param cbPkt Number of bytes left in the packet for the config data.
710 * @param paCfg The array of configuration items to fill.
711 */
712static int utsDoGadgetCreateFillCfg(PUTSPKTREQGDGTCTORCFGITEM pCfgItem, unsigned cCfgItems,
713 size_t cbPkt, PUTSGADGETCFGITEM paCfg)
714{
715 int rc = VINF_SUCCESS;
716 unsigned idxCfg = 0;
717
718 while ( RT_SUCCESS(rc)
719 && cCfgItems
720 && cbPkt)
721 {
722 if (cbPkt >= sizeof(UTSPKTREQGDGTCTORCFGITEM))
723 {
724 cbPkt -= sizeof(UTSPKTREQGDGTCTORCFGITEM);
725 if (pCfgItem->u32KeySize + pCfgItem->u32ValSize >= cbPkt)
726 {
727 const char *pszKey = (const char *)(pCfgItem + 1);
728 const char *pszVal = pszKey + pCfgItem->u32KeySize;
729
730 /* Validate termination. */
731 if ( *(pszKey + pCfgItem->u32KeySize - 1) != '\0'
732 || *(pszVal + pCfgItem->u32ValSize - 1) != '\0')
733 rc = VERR_INVALID_PARAMETER;
734 else
735 {
736 paCfg[idxCfg].pszKey = RTStrDup(pszKey);
737
738 rc = utsDoGadgetCreateCfgParseItem(&paCfg[idxCfg], pCfgItem->u32Type, pszVal);
739 if (RT_SUCCESS(rc))
740 {
741 cbPkt -= pCfgItem->u32KeySize + pCfgItem->u32ValSize;
742 cCfgItems--;
743 idxCfg++;
744 pCfgItem = (PUTSPKTREQGDGTCTORCFGITEM)(pszVal + pCfgItem->u32ValSize);
745 }
746 }
747 }
748 else
749 rc = VERR_INVALID_PARAMETER;
750 }
751 else
752 rc = VERR_INVALID_PARAMETER;
753 }
754
755 return rc;
756}
757
758/**
759 * Verifies and acknowledges a "BYE" request.
760 *
761 * @returns IPRT status code.
762 * @param pClient The UTS client structure.
763 * @param pPktHdr The howdy packet.
764 */
765static int utsDoBye(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
766{
767 int rc;
768 if (pPktHdr->cb == sizeof(UTSPKTHDR))
769 rc = utsReplyAck(pClient, pPktHdr);
770 else
771 rc = utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTHDR));
772 return rc;
773}
774
775/**
776 * Verifies and acknowledges a "HOWDY" request.
777 *
778 * @returns IPRT status code.
779 * @param pClient The UTS client structure.
780 * @param pPktHdr The howdy packet.
781 */
782static int utsDoHowdy(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
783{
784 int rc = VINF_SUCCESS;
785
786 if (pPktHdr->cb != sizeof(UTSPKTREQHOWDY))
787 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQHOWDY));
788
789 if (pClient->enmState != UTSCLIENTSTATE_INITIALISING)
790 return utsReplyInvalidState(pClient, pPktHdr);
791
792 PUTSPKTREQHOWDY pReq = (PUTSPKTREQHOWDY)pPktHdr;
793
794 if (pReq->uVersion != UTS_PROTOCOL_VS)
795 return utsReplyRC(pClient, pPktHdr, VERR_VERSION_MISMATCH, "The given version %#x is not supported", pReq->uVersion);
796
797 /* Verify hostname string. */
798 if (pReq->cchHostname >= sizeof(pReq->achHostname))
799 return utsReplyBadSize(pClient, pPktHdr, sizeof(pReq->achHostname) - 1);
800
801 if (pReq->achHostname[pReq->cchHostname] != '\0')
802 return utsReplyBadStrTermination(pClient, pPktHdr);
803
804 /* Extract string. */
805 pClient->pszHostname = RTStrDup(&pReq->achHostname[0]);
806 if (!pClient->pszHostname)
807 return utsReplyRC(pClient, pPktHdr, VERR_NO_MEMORY, "Failed to allocate memory for the hostname string");
808
809 if (pReq->fUsbConn & UTSPKT_HOWDY_CONN_F_PHYSICAL)
810 return utsReplyRC(pClient, pPktHdr, VERR_NOT_SUPPORTED, "Physical connections are not yet supported");
811
812 if (pReq->fUsbConn & UTSPKT_HOWDY_CONN_F_USBIP)
813 {
814 /* Set up the USB/IP server, find an unused port we can start the server on. */
815 UTSGADGETCFGITEM aCfg[2];
816
817 uint16_t uPort = g_uUsbIpPortNext;
818
819 if (g_uUsbIpPortNext == g_uUsbIpPortLast)
820 g_uUsbIpPortNext = g_uUsbIpPortFirst;
821 else
822 g_uUsbIpPortNext++;
823
824 aCfg[0].pszKey = "UsbIp/Port";
825 aCfg[0].Val.enmType = UTSGADGETCFGTYPE_UINT16;
826 aCfg[0].Val.u.u16 = uPort;
827 aCfg[1].pszKey = NULL;
828
829 rc = utsGadgetHostCreate(UTSGADGETHOSTTYPE_USBIP, &aCfg[0], &pClient->hGadgetHost);
830 if (RT_SUCCESS(rc))
831 {
832 /* Send the reply with the configured USB/IP port. */
833 UTSPKTREPHOWDY Rep;
834
835 RT_ZERO(Rep);
836
837 Rep.uVersion = UTS_PROTOCOL_VS;
838 Rep.fUsbConn = UTSPKT_HOWDY_CONN_F_USBIP;
839 Rep.uUsbIpPort = uPort;
840 Rep.cUsbIpDevices = 1;
841 Rep.cPhysicalDevices = 0;
842
843 rc = utsReplyInternal(pClient, &Rep.Sts, "ACK ", sizeof(Rep) - sizeof(UTSPKTSTS));
844 if (RT_SUCCESS(rc))
845 {
846 g_pTransport->pfnNotifyHowdy(pClient->pTransportClient);
847 pClient->enmState = UTSCLIENTSTATE_READY;
848 RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
849 }
850 }
851 else
852 return utsReplyRC(pClient, pPktHdr, rc, "Creating the USB/IP gadget host failed");
853 }
854 else
855 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_PARAMETER, "No access method requested");
856
857 return rc;
858}
859
860/**
861 * Verifies and processes a "GADGET CREATE" request.
862 *
863 * @returns IPRT status code.
864 * @param pClient The UTS client structure.
865 * @param pPktHdr The gadget create packet.
866 */
867static int utsDoGadgetCreate(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
868{
869 int rc = VINF_SUCCESS;
870
871 if (pPktHdr->cb < sizeof(UTSPKTREQGDGTCTOR))
872 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTCTOR));
873
874 if ( pClient->enmState != UTSCLIENTSTATE_READY
875 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
876 return utsReplyInvalidState(pClient, pPktHdr);
877
878 PUTSPKTREQGDGTCTOR pReq = (PUTSPKTREQGDGTCTOR)pPktHdr;
879
880 if (pReq->u32GdgtType != UTSPKT_GDGT_CREATE_TYPE_TEST)
881 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_PARAMETER, "The given gadget type is not supported");
882
883 if (pReq->u32GdgtAccess != UTSPKT_GDGT_CREATE_ACCESS_USBIP)
884 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_PARAMETER, "The given gadget access method is not supported");
885
886 PUTSGADGETCFGITEM paCfg = NULL;
887 if (pReq->u32CfgItems > 0)
888 {
889 paCfg = (PUTSGADGETCFGITEM)RTMemAllocZ((pReq->u32CfgItems + 1) * sizeof(UTSGADGETCFGITEM));
890 if (RT_UNLIKELY(!paCfg))
891 return utsReplyRC(pClient, pPktHdr, VERR_NO_MEMORY, "Failed to allocate memory for configration items");
892
893 rc = utsDoGadgetCreateFillCfg((PUTSPKTREQGDGTCTORCFGITEM)(pReq + 1), pReq->u32CfgItems,
894 pPktHdr->cb - sizeof(UTSPKTREQGDGTCTOR), paCfg);
895 if (RT_FAILURE(rc))
896 {
897 RTMemFree(paCfg);
898 return utsReplyRC(pClient, pPktHdr, rc, "Failed to parse configuration");
899 }
900 }
901
902 rc = utsGadgetCreate(pClient->hGadgetHost, UTSGADGETCLASS_TEST, paCfg, &pClient->hGadget);
903 if (RT_SUCCESS(rc))
904 {
905 UTSPKTREPGDGTCTOR Rep;
906 RT_ZERO(Rep);
907
908 Rep.idGadget = 0;
909 Rep.u32BusId = utsGadgetGetBusId(pClient->hGadget);
910 Rep.u32DevId = utsGadgetGetDevId(pClient->hGadget);
911 rc = utsReplyInternal(pClient, &Rep.Sts, "ACK ", sizeof(Rep) - sizeof(UTSPKTSTS));
912 }
913 else
914 rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to create gadget with %Rrc\n", rc);
915
916 return rc;
917}
918
919/**
920 * Verifies and processes a "GADGET DESTROY" request.
921 *
922 * @returns IPRT status code.
923 * @param pClient The UTS client structure.
924 * @param pPktHdr The gadget destroy packet.
925 */
926static int utsDoGadgetDestroy(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
927{
928 if (pPktHdr->cb != sizeof(UTSPKTREQGDGTDTOR))
929 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTDTOR));
930
931 if ( pClient->enmState != UTSCLIENTSTATE_READY
932 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
933 return utsReplyInvalidState(pClient, pPktHdr);
934
935 PUTSPKTREQGDGTDTOR pReq = (PUTSPKTREQGDGTDTOR)pPktHdr;
936
937 if (pReq->idGadget != 0)
938 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
939 if (pClient->hGadget == NIL_UTSGADGET)
940 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");
941
942 utsGadgetRelease(pClient->hGadget);
943 pClient->hGadget = NIL_UTSGADGET;
944
945 return utsReplyAck(pClient, pPktHdr);
946}
947
948/**
949 * Verifies and processes a "GADGET CONNECT" request.
950 *
951 * @returns IPRT status code.
952 * @param pClient The UTS client structure.
953 * @param pPktHdr The gadget connect packet.
954 */
955static int utsDoGadgetConnect(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
956{
957 if (pPktHdr->cb != sizeof(UTSPKTREQGDGTCNCT))
958 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTCNCT));
959
960 if ( pClient->enmState != UTSCLIENTSTATE_READY
961 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
962 return utsReplyInvalidState(pClient, pPktHdr);
963
964 PUTSPKTREQGDGTCNCT pReq = (PUTSPKTREQGDGTCNCT)pPktHdr;
965
966 if (pReq->idGadget != 0)
967 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
968 if (pClient->hGadget == NIL_UTSGADGET)
969 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");
970
971 int rc = utsGadgetConnect(pClient->hGadget);
972 if (RT_SUCCESS(rc))
973 rc = utsReplyAck(pClient, pPktHdr);
974 else
975 rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to connect the gadget");
976
977 return rc;
978}
979
980/**
981 * Verifies and processes a "GADGET DISCONNECT" request.
982 *
983 * @returns IPRT status code.
984 * @param pClient The UTS client structure.
985 * @param pPktHdr The gadget disconnect packet.
986 */
987static int utsDoGadgetDisconnect(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
988{
989 if (pPktHdr->cb != sizeof(UTSPKTREQGDGTDCNT))
990 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTDCNT));
991
992 if ( pClient->enmState != UTSCLIENTSTATE_READY
993 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
994 return utsReplyInvalidState(pClient, pPktHdr);
995
996 PUTSPKTREQGDGTDCNT pReq = (PUTSPKTREQGDGTDCNT)pPktHdr;
997
998 if (pReq->idGadget != 0)
999 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
1000 if (pClient->hGadget == NIL_UTSGADGET)
1001 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");
1002
1003 int rc = utsGadgetDisconnect(pClient->hGadget);
1004 if (RT_SUCCESS(rc))
1005 rc = utsReplyAck(pClient, pPktHdr);
1006 else
1007 rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to disconnect the gadget");
1008
1009 return rc;
1010}
1011
1012/**
1013 * Main request processing routine for each client.
1014 *
1015 * @returns IPRT status code.
1016 * @param pClient The UTS client structure sending the request.
1017 */
1018static int utsClientReqProcess(PUTSCLIENT pClient)
1019{
1020 /*
1021 * Read client command packet and process it.
1022 */
1023 PUTSPKTHDR pPktHdr = NULL;
1024 int rc = utsRecvPkt(pClient, &pPktHdr, true /*fAutoRetryOnFailure*/);
1025 if (RT_FAILURE(rc))
1026 return rc;
1027
1028 /*
1029 * Do a string switch on the opcode bit.
1030 */
1031 /* Connection: */
1032 if ( utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_HOWDY))
1033 rc = utsDoHowdy(pClient, pPktHdr);
1034 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_BYE))
1035 rc = utsDoBye(pClient, pPktHdr);
1036 /* Gadget API. */
1037 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_CREATE))
1038 rc = utsDoGadgetCreate(pClient, pPktHdr);
1039 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_DESTROY))
1040 rc = utsDoGadgetDestroy(pClient, pPktHdr);
1041 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_CONNECT))
1042 rc = utsDoGadgetConnect(pClient, pPktHdr);
1043 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_DISCONNECT))
1044 rc = utsDoGadgetDisconnect(pClient, pPktHdr);
1045 /* Misc: */
1046 else
1047 rc = utsReplyUnknown(pClient, pPktHdr);
1048
1049 RTMemFree(pPktHdr);
1050
1051 return rc;
1052}
1053
1054/**
1055 * Destroys a client instance.
1056 *
1057 * @returns nothing.
1058 * @param pClient The UTS client structure.
1059 */
1060static void utsClientDestroy(PUTSCLIENT pClient)
1061{
1062 if (pClient->pszHostname)
1063 RTStrFree(pClient->pszHostname);
1064 if (pClient->hGadget != NIL_UTSGADGET)
1065 utsGadgetRelease(pClient->hGadget);
1066 if (pClient->hGadgetHost != NIL_UTSGADGETHOST)
1067 utsGadgetHostRelease(pClient->hGadgetHost);
1068 RTMemFree(pClient);
1069}
1070
1071/**
1072 * The main thread worker serving the clients.
1073 */
1074static DECLCALLBACK(int) utsClientWorker(RTTHREAD hThread, void *pvUser)
1075{
1076 unsigned cClientsMax = 0;
1077 unsigned cClientsCur = 0;
1078 PUTSCLIENT *papClients = NULL;
1079 RTPOLLSET hPollSet;
1080
1081 int rc = RTPollSetCreate(&hPollSet);
1082 if (RT_FAILURE(rc))
1083 return rc;
1084
1085 /* Add the pipe to the poll set. */
1086 rc = RTPollSetAddPipe(hPollSet, g_hPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 0);
1087 if (RT_SUCCESS(rc))
1088 {
1089 while (!g_fTerminate)
1090 {
1091 uint32_t fEvts;
1092 uint32_t uId;
1093 rc = RTPoll(hPollSet, RT_INDEFINITE_WAIT, &fEvts, &uId);
1094 if (RT_SUCCESS(rc))
1095 {
1096 if (uId == 0)
1097 {
1098 if (fEvts & RTPOLL_EVT_ERROR)
1099 break;
1100
1101 /* We got woken up because of a new client. */
1102 Assert(fEvts & RTPOLL_EVT_READ);
1103
1104 uint8_t bRead;
1105 size_t cbRead = 0;
1106 rc = RTPipeRead(g_hPipeR, &bRead, 1, &cbRead);
1107 AssertRC(rc);
1108
1109 RTCritSectEnter(&g_CritSectClients);
1110 /* Walk the list and add all new clients. */
1111 PUTSCLIENT pIt, pItNext;
1112 RTListForEachSafe(&g_LstClientsNew, pIt, pItNext, UTSCLIENT, NdLst)
1113 {
1114 RTListNodeRemove(&pIt->NdLst);
1115 Assert(cClientsCur <= cClientsMax);
1116 if (cClientsCur == cClientsMax)
1117 {
1118 /* Realloc to accommodate for the new clients. */
1119 PUTSCLIENT *papClientsNew = (PUTSCLIENT *)RTMemRealloc(papClients, (cClientsMax + 10) * sizeof(PUTSCLIENT));
1120 if (RT_LIKELY(papClientsNew))
1121 {
1122 cClientsMax += 10;
1123 papClients = papClientsNew;
1124 }
1125 }
1126
1127 if (cClientsCur < cClientsMax)
1128 {
1129 /* Find a free slot in the client array. */
1130 unsigned idxSlt = 0;
1131 while ( idxSlt < cClientsMax
1132 && papClients[idxSlt] != NULL)
1133 idxSlt++;
1134
1135 rc = g_pTransport->pfnPollSetAdd(hPollSet, pIt->pTransportClient, idxSlt + 1);
1136 if (RT_SUCCESS(rc))
1137 {
1138 cClientsCur++;
1139 papClients[idxSlt] = pIt;
1140 }
1141 else
1142 {
1143 g_pTransport->pfnNotifyBye(pIt->pTransportClient);
1144 utsClientDestroy(pIt);
1145 }
1146 }
1147 else
1148 {
1149 g_pTransport->pfnNotifyBye(pIt->pTransportClient);
1150 utsClientDestroy(pIt);
1151 }
1152 }
1153 RTCritSectLeave(&g_CritSectClients);
1154 }
1155 else
1156 {
1157 /* Client sends a request, pick the right client and process it. */
1158 PUTSCLIENT pClient = papClients[uId - 1];
1159 AssertPtr(pClient);
1160 if (fEvts & RTPOLL_EVT_READ)
1161 rc = utsClientReqProcess(pClient);
1162
1163 if ( (fEvts & RTPOLL_EVT_ERROR)
1164 || RT_FAILURE(rc))
1165 {
1166 /* Close connection and remove client from array. */
1167 rc = g_pTransport->pfnPollSetRemove(hPollSet, pClient->pTransportClient, uId);
1168 AssertRC(rc);
1169
1170 g_pTransport->pfnNotifyBye(pClient->pTransportClient);
1171 papClients[uId - 1] = NULL;
1172 cClientsCur--;
1173 utsClientDestroy(pClient);
1174 }
1175 }
1176 }
1177 }
1178 }
1179
1180 RTPollSetDestroy(hPollSet);
1181
1182 return rc;
1183}
1184
1185/**
1186 * The main loop.
1187 *
1188 * @returns exit code.
1189 */
1190static RTEXITCODE utsMainLoop(void)
1191{
1192 RTEXITCODE enmExitCode = RTEXITCODE_SUCCESS;
1193 while (!g_fTerminate)
1194 {
1195 /*
1196 * Wait for new connection and spin off a new thread
1197 * for every new client.
1198 */
1199 PUTSTRANSPORTCLIENT pTransportClient;
1200 int rc = g_pTransport->pfnWaitForConnect(&pTransportClient);
1201 if (RT_FAILURE(rc))
1202 continue;
1203
1204 /*
1205 * New connection, create new client structure and spin of
1206 * the request handling thread.
1207 */
1208 PUTSCLIENT pClient = (PUTSCLIENT)RTMemAllocZ(sizeof(UTSCLIENT));
1209 if (RT_LIKELY(pClient))
1210 {
1211 pClient->enmState = UTSCLIENTSTATE_INITIALISING;
1212 pClient->pTransportClient = pTransportClient;
1213 pClient->pszHostname = NULL;
1214 pClient->hGadgetHost = NIL_UTSGADGETHOST;
1215 pClient->hGadget = NIL_UTSGADGET;
1216
1217 /* Add client to the new list and inform the worker thread. */
1218 RTCritSectEnter(&g_CritSectClients);
1219 RTListAppend(&g_LstClientsNew, &pClient->NdLst);
1220 RTCritSectLeave(&g_CritSectClients);
1221
1222 size_t cbWritten = 0;
1223 rc = RTPipeWrite(g_hPipeW, "", 1, &cbWritten);
1224 if (RT_FAILURE(rc))
1225 RTMsgError("Failed to inform worker thread of a new client");
1226 }
1227 else
1228 {
1229 RTMsgError("Creating new client structure failed with out of memory error\n");
1230 g_pTransport->pfnNotifyBye(pTransportClient);
1231 }
1232
1233
1234 }
1235
1236 return enmExitCode;
1237}
1238
1239/**
1240 * Initializes the global UTS state.
1241 *
1242 * @returns IPRT status code.
1243 */
1244static int utsInit(void)
1245{
1246 int rc = VINF_SUCCESS;
1247 PRTERRINFO pErrInfo = NULL;
1248
1249 RTListInit(&g_LstClientsNew);
1250
1251 rc = RTJsonParseFromFile(&g_hCfgJson, g_szCfgPath, pErrInfo);
1252 if (RT_SUCCESS(rc))
1253 {
1254 rc = utsPlatformInit();
1255 if (RT_SUCCESS(rc))
1256 {
1257 rc = RTCritSectInit(&g_CritSectClients);
1258 if (RT_SUCCESS(rc))
1259 {
1260 rc = RTPipeCreate(&g_hPipeR, &g_hPipeW, 0);
1261 if (RT_SUCCESS(rc))
1262 {
1263 /* Spin off the thread serving connections. */
1264 rc = RTThreadCreate(&g_hThreadServing, utsClientWorker, NULL, 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE,
1265 "USBTSTSRV");
1266 if (RT_SUCCESS(rc))
1267 return VINF_SUCCESS;
1268 else
1269 RTMsgError("Creating the client worker thread failed with %Rrc\n", rc);
1270
1271 RTPipeClose(g_hPipeR);
1272 RTPipeClose(g_hPipeW);
1273 }
1274 else
1275 RTMsgError("Creating communications pipe failed with %Rrc\n", rc);
1276
1277 RTCritSectDelete(&g_CritSectClients);
1278 }
1279 else
1280 RTMsgError("Creating global critical section failed with %Rrc\n", rc);
1281
1282 RTJsonValueRelease(g_hCfgJson);
1283 }
1284 else
1285 RTMsgError("Initializing the platform failed with %Rrc\n", rc);
1286 }
1287 else
1288 {
1289 if (RTErrInfoIsSet(pErrInfo))
1290 {
1291 RTMsgError("Failed to parse config with detailed error: %s (%Rrc)\n",
1292 pErrInfo->pszMsg, pErrInfo->rc);
1293 RTErrInfoFree(pErrInfo);
1294 }
1295 else
1296 RTMsgError("Failed to parse config with unknown error (%Rrc)\n", rc);
1297 }
1298
1299 return rc;
1300}
1301
1302/**
1303 * Determines the default configuration.
1304 */
1305static void utsSetDefaults(void)
1306{
1307 /*
1308 * OS and ARCH.
1309 */
1310 AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
1311 strcpy(g_szOsShortName, KBUILD_TARGET);
1312
1313 AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
1314 strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);
1315
1316 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
1317 strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
1318 g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
1319 strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
1320
1321 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
1322 strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
1323 g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
1324 strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
1325
1326#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1327 strcpy(g_szExeSuff, ".exe");
1328 strcpy(g_szScriptSuff, ".cmd");
1329#else
1330 strcpy(g_szExeSuff, "");
1331 strcpy(g_szScriptSuff, ".sh");
1332#endif
1333
1334 /*
1335 * The CD/DVD-ROM location.
1336 */
1337 /** @todo do a better job here :-) */
1338#ifdef RT_OS_WINDOWS
1339 strcpy(g_szDefCdRomPath, "D:/");
1340#elif defined(RT_OS_OS2)
1341 strcpy(g_szDefCdRomPath, "D:/");
1342#else
1343 if (RTDirExists("/media"))
1344 strcpy(g_szDefCdRomPath, "/media/cdrom");
1345 else
1346 strcpy(g_szDefCdRomPath, "/mnt/cdrom");
1347#endif
1348 strcpy(g_szCdRomPath, g_szDefCdRomPath);
1349
1350 /*
1351 * Temporary directory.
1352 */
1353 int rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
1354 if (RT_SUCCESS(rc))
1355#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
1356 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXX.tmp");
1357#else
1358 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXXXXXXX.tmp");
1359#endif
1360 if (RT_FAILURE(rc))
1361 {
1362 RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
1363 strcpy(g_szDefScratchPath, "/tmp/uts-XXXX.tmp");
1364 }
1365 strcpy(g_szScratchPath, g_szDefScratchPath);
1366
1367 /*
1368 * Config file location.
1369 */
1370 /** @todo: Improve */
1371#if !defined(RT_OS_WINDOWS)
1372 strcpy(g_szCfgPath, "/etc/uts.conf");
1373#else
1374 strcpy(g_szCfgPath, "");
1375#endif
1376
1377 /*
1378 * The default transporter is the first one.
1379 */
1380 g_pTransport = g_apTransports[0];
1381}
1382
1383/**
1384 * Prints the usage.
1385 *
1386 * @param pStrm Where to print it.
1387 * @param pszArgv0 The program name (argv[0]).
1388 */
1389static void utsUsage(PRTSTREAM pStrm, const char *argv0)
1390{
1391 RTStrmPrintf(pStrm,
1392 "Usage: %Rbn [options]\n"
1393 "\n"
1394 "Options:\n"
1395 " --config <path>\n"
1396 " Where to load the config from\n"
1397 " --cdrom <path>\n"
1398 " Where the CD/DVD-ROM will be mounted.\n"
1399 " Default: %s\n"
1400 " --scratch <path>\n"
1401 " Where to put scratch files.\n"
1402 " Default: %s \n"
1403 ,
1404 argv0,
1405 g_szDefCdRomPath,
1406 g_szDefScratchPath);
1407 RTStrmPrintf(pStrm,
1408 " --transport <name>\n"
1409 " Use the specified transport layer, one of the following:\n");
1410 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1411 RTStrmPrintf(pStrm, " %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
1412 RTStrmPrintf(pStrm, " Default: %s\n", g_pTransport->szName);
1413 RTStrmPrintf(pStrm,
1414 " --display-output, --no-display-output\n"
1415 " Display the output and the result of all child processes.\n");
1416 RTStrmPrintf(pStrm,
1417 " --foreground\n"
1418 " Don't daemonize, run in the foreground.\n");
1419 RTStrmPrintf(pStrm,
1420 " --help, -h, -?\n"
1421 " Display this message and exit.\n"
1422 " --version, -V\n"
1423 " Display the version and exit.\n");
1424
1425 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1426 if (g_apTransports[i]->cOpts)
1427 {
1428 RTStrmPrintf(pStrm,
1429 "\n"
1430 "Options for %s:\n", g_apTransports[i]->szName);
1431 g_apTransports[i]->pfnUsage(g_pStdOut);
1432 }
1433}
1434
1435/**
1436 * Parses the arguments.
1437 *
1438 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
1439 * @param argc The number of arguments.
1440 * @param argv The argument vector.
1441 * @param pfExit For indicating exit when the exit code is zero.
1442 */
1443static RTEXITCODE utsParseArgv(int argc, char **argv, bool *pfExit)
1444{
1445 *pfExit = false;
1446
1447 /*
1448 * Storage for locally handled options.
1449 */
1450 bool fDaemonize = true;
1451 bool fDaemonized = false;
1452
1453 /*
1454 * Combine the base and transport layer option arrays.
1455 */
1456 static const RTGETOPTDEF s_aBaseOptions[] =
1457 {
1458 { "--config", 'C', RTGETOPT_REQ_STRING },
1459 { "--transport", 't', RTGETOPT_REQ_STRING },
1460 { "--cdrom", 'c', RTGETOPT_REQ_STRING },
1461 { "--scratch", 's', RTGETOPT_REQ_STRING },
1462 { "--display-output", 'd', RTGETOPT_REQ_NOTHING },
1463 { "--no-display-output",'D', RTGETOPT_REQ_NOTHING },
1464 { "--foreground", 'f', RTGETOPT_REQ_NOTHING },
1465 { "--daemonized", 'Z', RTGETOPT_REQ_NOTHING },
1466 };
1467
1468 size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
1469 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1470 cOptions += g_apTransports[i]->cOpts;
1471
1472 PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
1473 if (!paOptions)
1474 return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");
1475
1476 memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
1477 cOptions = RT_ELEMENTS(s_aBaseOptions);
1478 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1479 {
1480 memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
1481 cOptions += g_apTransports[i]->cOpts;
1482 }
1483
1484 /*
1485 * Parse the arguments.
1486 */
1487 RTGETOPTSTATE GetState;
1488 int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
1489 AssertRC(rc);
1490
1491 int ch;
1492 RTGETOPTUNION Val;
1493 while ((ch = RTGetOpt(&GetState, &Val)))
1494 {
1495 switch (ch)
1496 {
1497 case 'C':
1498 rc = RTStrCopy(g_szCfgPath, sizeof(g_szCfgPath), Val.psz);
1499 if (RT_FAILURE(rc))
1500 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Config file path is path too long (%Rrc)\n", rc);
1501 break;
1502
1503 case 'c':
1504 rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
1505 if (RT_FAILURE(rc))
1506 return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
1507 break;
1508
1509 case 'd':
1510 g_fDisplayOutput = true;
1511 break;
1512
1513 case 'D':
1514 g_fDisplayOutput = false;
1515 break;
1516
1517 case 'f':
1518 fDaemonize = false;
1519 break;
1520
1521 case 'h':
1522 utsUsage(g_pStdOut, argv[0]);
1523 *pfExit = true;
1524 return RTEXITCODE_SUCCESS;
1525
1526 case 's':
1527 rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
1528 if (RT_FAILURE(rc))
1529 return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
1530 break;
1531
1532 case 't':
1533 {
1534 PCUTSTRANSPORT pTransport = NULL;
1535 for (size_t i = 0; RT_ELEMENTS(g_apTransports); i++)
1536 if (!strcmp(g_apTransports[i]->szName, Val.psz))
1537 {
1538 pTransport = g_apTransports[i];
1539 break;
1540 }
1541 if (!pTransport)
1542 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
1543 g_pTransport = pTransport;
1544 break;
1545 }
1546
1547 case 'V':
1548 RTPrintf("$Revision: 62471 $\n");
1549 *pfExit = true;
1550 return RTEXITCODE_SUCCESS;
1551
1552 case 'Z':
1553 fDaemonized = true;
1554 fDaemonize = false;
1555 break;
1556
1557 default:
1558 {
1559 rc = VERR_TRY_AGAIN;
1560 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1561 if (g_apTransports[i]->cOpts)
1562 {
1563 rc = g_apTransports[i]->pfnOption(ch, &Val);
1564 if (RT_SUCCESS(rc))
1565 break;
1566 if (rc != VERR_TRY_AGAIN)
1567 {
1568 *pfExit = true;
1569 return RTEXITCODE_SYNTAX;
1570 }
1571 }
1572 if (rc == VERR_TRY_AGAIN)
1573 {
1574 *pfExit = true;
1575 return RTGetOptPrintError(ch, &Val);
1576 }
1577 break;
1578 }
1579 }
1580 }
1581
1582 /*
1583 * Daemonize ourselves if asked to.
1584 */
1585 if (fDaemonize && !*pfExit)
1586 {
1587 rc = RTProcDaemonize(argv, "--daemonized");
1588 if (RT_FAILURE(rc))
1589 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
1590 *pfExit = true;
1591 }
1592
1593 return RTEXITCODE_SUCCESS;
1594}
1595
1596
1597int main(int argc, char **argv)
1598{
1599 /*
1600 * Initialize the runtime.
1601 */
1602 int rc = RTR3InitExe(argc, &argv, 0);
1603 if (RT_FAILURE(rc))
1604 return RTMsgInitFailure(rc);
1605
1606 /*
1607 * Determine defaults and parse the arguments.
1608 */
1609 utsSetDefaults();
1610 bool fExit;
1611 RTEXITCODE rcExit = utsParseArgv(argc, argv, &fExit);
1612 if (rcExit != RTEXITCODE_SUCCESS || fExit)
1613 return rcExit;
1614
1615 /*
1616 * Initialize global state.
1617 */
1618 rc = utsInit();
1619 if (RT_FAILURE(rc))
1620 return RTEXITCODE_FAILURE;
1621
1622 /*
1623 * Initialize the transport layer.
1624 */
1625 rc = g_pTransport->pfnInit();
1626 if (RT_FAILURE(rc))
1627 return RTEXITCODE_FAILURE;
1628
1629 /*
1630 * Ok, start working
1631 */
1632 rcExit = utsMainLoop();
1633
1634 /*
1635 * Cleanup.
1636 */
1637 g_pTransport->pfnTerm();
1638
1639 utsPlatformTerm();
1640
1641 return rcExit;
1642}
1643
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