VirtualBox

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

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

ValdiationKit/usb: Return bus and device ID for the created gadget to make it usable for device filters

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