VirtualBox

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

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

ValidationKit/usb: Fixes, basic compliance testing works finally

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.1 KB
Line 
1/* $Id: UsbTestService.cpp 60522 2016-04-15 14:34:35Z 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/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 rc = utsReplyInternal(pClient, &Rep.Sts, "ACK ", sizeof(Rep) - sizeof(UTSPKTSTS));
706 }
707 else
708 rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to create gadget with %Rrc\n", rc);
709
710 return rc;
711}
712
713/**
714 * Verifies and processes a "GADGET DESTROY" request.
715 *
716 * @returns IPRT status code.
717 * @param pClient The UTS client structure.
718 * @param pPktHdr The gadget destroy packet.
719 */
720static int utsDoGadgetDestroy(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
721{
722 if (pPktHdr->cb != sizeof(UTSPKTREQGDGTDTOR))
723 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTDTOR));
724
725 if ( pClient->enmState != UTSCLIENTSTATE_READY
726 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
727 return utsReplyInvalidState(pClient, pPktHdr);
728
729 PUTSPKTREQGDGTDTOR pReq = (PUTSPKTREQGDGTDTOR)pPktHdr;
730
731 if (pReq->idGadget != 0)
732 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
733 if (pClient->hGadget == NIL_UTSGADGET)
734 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");
735
736 utsGadgetRelease(pClient->hGadget);
737 pClient->hGadget = NIL_UTSGADGET;
738
739 return utsReplyAck(pClient, pPktHdr);
740}
741
742/**
743 * Verifies and processes a "GADGET CONNECT" request.
744 *
745 * @returns IPRT status code.
746 * @param pClient The UTS client structure.
747 * @param pPktHdr The gadget connect packet.
748 */
749static int utsDoGadgetConnect(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
750{
751 if (pPktHdr->cb != sizeof(UTSPKTREQGDGTCNCT))
752 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTCNCT));
753
754 if ( pClient->enmState != UTSCLIENTSTATE_READY
755 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
756 return utsReplyInvalidState(pClient, pPktHdr);
757
758 PUTSPKTREQGDGTCNCT pReq = (PUTSPKTREQGDGTCNCT)pPktHdr;
759
760 if (pReq->idGadget != 0)
761 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
762 if (pClient->hGadget == NIL_UTSGADGET)
763 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");
764
765 int rc = utsGadgetConnect(pClient->hGadget);
766 if (RT_SUCCESS(rc))
767 rc = utsReplyAck(pClient, pPktHdr);
768 else
769 rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to connect the gadget");
770
771 return rc;
772}
773
774/**
775 * Verifies and processes a "GADGET DISCONNECT" request.
776 *
777 * @returns IPRT status code.
778 * @param pClient The UTS client structure.
779 * @param pPktHdr The gadget disconnect packet.
780 */
781static int utsDoGadgetDisconnect(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
782{
783 if (pPktHdr->cb != sizeof(UTSPKTREQGDGTDCNT))
784 return utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTREQGDGTDCNT));
785
786 if ( pClient->enmState != UTSCLIENTSTATE_READY
787 || pClient->hGadgetHost == NIL_UTSGADGETHOST)
788 return utsReplyInvalidState(pClient, pPktHdr);
789
790 PUTSPKTREQGDGTDCNT pReq = (PUTSPKTREQGDGTDCNT)pPktHdr;
791
792 if (pReq->idGadget != 0)
793 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_HANDLE, "The given gadget handle is invalid");
794 if (pClient->hGadget == NIL_UTSGADGET)
795 return utsReplyRC(pClient, pPktHdr, VERR_INVALID_STATE, "The gadget is not set up");
796
797 int rc = utsGadgetDisconnect(pClient->hGadget);
798 if (RT_SUCCESS(rc))
799 rc = utsReplyAck(pClient, pPktHdr);
800 else
801 rc = utsReplyRC(pClient, pPktHdr, rc, "Failed to disconnect the gadget");
802
803 return rc;
804}
805
806/**
807 * Main request processing routine for each client.
808 *
809 * @returns IPRT status code.
810 * @param pClient The UTS client structure sending the request.
811 */
812static int utsClientReqProcess(PUTSCLIENT pClient)
813{
814 /*
815 * Read client command packet and process it.
816 */
817 PUTSPKTHDR pPktHdr = NULL;
818 int rc = utsRecvPkt(pClient, &pPktHdr, true /*fAutoRetryOnFailure*/);
819 if (RT_FAILURE(rc))
820 return rc;
821
822 /*
823 * Do a string switch on the opcode bit.
824 */
825 /* Connection: */
826 if ( utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_HOWDY))
827 rc = utsDoHowdy(pClient, pPktHdr);
828 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_BYE))
829 rc = utsDoBye(pClient, pPktHdr);
830 /* Gadget API. */
831 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_CREATE))
832 rc = utsDoGadgetCreate(pClient, pPktHdr);
833 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_DESTROY))
834 rc = utsDoGadgetDestroy(pClient, pPktHdr);
835 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_CONNECT))
836 rc = utsDoGadgetConnect(pClient, pPktHdr);
837 else if (utsIsSameOpcode(pPktHdr, UTSPKT_OPCODE_GADGET_DISCONNECT))
838 rc = utsDoGadgetDisconnect(pClient, pPktHdr);
839 /* Misc: */
840 else
841 rc = utsReplyUnknown(pClient, pPktHdr);
842
843 RTMemFree(pPktHdr);
844
845 return rc;
846}
847
848/**
849 * Destroys a client instance.
850 *
851 * @returns nothing.
852 * @param pClient The UTS client structure.
853 */
854static void utsClientDestroy(PUTSCLIENT pClient)
855{
856 if (pClient->pszHostname)
857 RTStrFree(pClient->pszHostname);
858 if (pClient->hGadget != NIL_UTSGADGET)
859 utsGadgetRelease(pClient->hGadget);
860 if (pClient->hGadgetHost != NIL_UTSGADGETHOST)
861 utsGadgetHostRelease(pClient->hGadgetHost);
862 RTMemFree(pClient);
863}
864
865/**
866 * The main thread worker serving the clients.
867 */
868static DECLCALLBACK(int) utsClientWorker(RTTHREAD hThread, void *pvUser)
869{
870 unsigned cClientsMax = 0;
871 unsigned cClientsCur = 0;
872 PUTSCLIENT *papClients = NULL;
873 RTPOLLSET hPollSet;
874
875 int rc = RTPollSetCreate(&hPollSet);
876 if (RT_FAILURE(rc))
877 return rc;
878
879 /* Add the pipe to the poll set. */
880 rc = RTPollSetAddPipe(hPollSet, g_hPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 0);
881 if (RT_SUCCESS(rc))
882 {
883 while (!g_fTerminate)
884 {
885 uint32_t fEvts;
886 uint32_t uId;
887 rc = RTPoll(hPollSet, RT_INDEFINITE_WAIT, &fEvts, &uId);
888 if (RT_SUCCESS(rc))
889 {
890 if (uId == 0)
891 {
892 if (fEvts & RTPOLL_EVT_ERROR)
893 break;
894
895 /* We got woken up because of a new client. */
896 Assert(fEvts & RTPOLL_EVT_READ);
897
898 uint8_t bRead;
899 size_t cbRead = 0;
900 rc = RTPipeRead(g_hPipeR, &bRead, 1, &cbRead);
901 AssertRC(rc);
902
903 RTCritSectEnter(&g_CritSectClients);
904 /* Walk the list and add all new clients. */
905 PUTSCLIENT pIt, pItNext;
906 RTListForEachSafe(&g_LstClientsNew, pIt, pItNext, UTSCLIENT, NdLst)
907 {
908 RTListNodeRemove(&pIt->NdLst);
909 Assert(cClientsCur <= cClientsMax);
910 if (cClientsCur == cClientsMax)
911 {
912 /* Realloc to accommodate for the new clients. */
913 PUTSCLIENT *papClientsNew = (PUTSCLIENT *)RTMemRealloc(papClients, (cClientsMax + 10) * sizeof(PUTSCLIENT));
914 if (RT_LIKELY(papClientsNew))
915 {
916 cClientsMax += 10;
917 papClients = papClientsNew;
918 }
919 }
920
921 if (cClientsCur < cClientsMax)
922 {
923 /* Find a free slot in the client array. */
924 unsigned idxSlt = 0;
925 while ( idxSlt < cClientsMax
926 && papClients[idxSlt] != NULL)
927 idxSlt++;
928
929 rc = g_pTransport->pfnPollSetAdd(hPollSet, pIt->pTransportClient, idxSlt + 1);
930 if (RT_SUCCESS(rc))
931 {
932 cClientsCur++;
933 papClients[idxSlt] = pIt;
934 }
935 else
936 {
937 g_pTransport->pfnNotifyBye(pIt->pTransportClient);
938 utsClientDestroy(pIt);
939 }
940 }
941 else
942 {
943 g_pTransport->pfnNotifyBye(pIt->pTransportClient);
944 utsClientDestroy(pIt);
945 }
946 }
947 RTCritSectLeave(&g_CritSectClients);
948 }
949 else
950 {
951 /* Client sends a request, pick the right client and process it. */
952 PUTSCLIENT pClient = papClients[uId - 1];
953 AssertPtr(pClient);
954 if (fEvts & RTPOLL_EVT_READ)
955 rc = utsClientReqProcess(pClient);
956
957 if ( (fEvts & RTPOLL_EVT_ERROR)
958 || RT_FAILURE(rc))
959 {
960 /* Close connection and remove client from array. */
961 rc = g_pTransport->pfnPollSetRemove(hPollSet, pClient->pTransportClient, uId);
962 AssertRC(rc);
963
964 g_pTransport->pfnNotifyBye(pClient->pTransportClient);
965 papClients[uId - 1] = NULL;
966 cClientsCur--;
967 utsClientDestroy(pClient);
968 }
969 }
970 }
971 }
972 }
973
974 RTPollSetDestroy(hPollSet);
975
976 return rc;
977}
978
979/**
980 * The main loop.
981 *
982 * @returns exit code.
983 */
984static RTEXITCODE utsMainLoop(void)
985{
986 RTEXITCODE enmExitCode = RTEXITCODE_SUCCESS;
987 while (!g_fTerminate)
988 {
989 /*
990 * Wait for new connection and spin off a new thread
991 * for every new client.
992 */
993 PUTSTRANSPORTCLIENT pTransportClient;
994 int rc = g_pTransport->pfnWaitForConnect(&pTransportClient);
995 if (RT_FAILURE(rc))
996 continue;
997
998 /*
999 * New connection, create new client structure and spin of
1000 * the request handling thread.
1001 */
1002 PUTSCLIENT pClient = (PUTSCLIENT)RTMemAllocZ(sizeof(UTSCLIENT));
1003 if (RT_LIKELY(pClient))
1004 {
1005 pClient->enmState = UTSCLIENTSTATE_INITIALISING;
1006 pClient->pTransportClient = pTransportClient;
1007 pClient->pszHostname = NULL;
1008 pClient->hGadgetHost = NIL_UTSGADGETHOST;
1009 pClient->hGadget = NIL_UTSGADGET;
1010
1011 /* Add client to the new list and inform the worker thread. */
1012 RTCritSectEnter(&g_CritSectClients);
1013 RTListAppend(&g_LstClientsNew, &pClient->NdLst);
1014 RTCritSectLeave(&g_CritSectClients);
1015
1016 size_t cbWritten = 0;
1017 rc = RTPipeWrite(g_hPipeW, "", 1, &cbWritten);
1018 if (RT_FAILURE(rc))
1019 RTMsgError("Failed to inform worker thread of a new client");
1020 }
1021 else
1022 {
1023 RTMsgError("Creating new client structure failed with out of memory error\n");
1024 g_pTransport->pfnNotifyBye(pTransportClient);
1025 }
1026
1027
1028 }
1029
1030 return enmExitCode;
1031}
1032
1033/**
1034 * Initializes the global UTS state.
1035 *
1036 * @returns IPRT status code.
1037 */
1038static int utsInit(void)
1039{
1040 int rc = VINF_SUCCESS;
1041 PRTERRINFO pErrInfo = NULL;
1042
1043 RTListInit(&g_LstClientsNew);
1044
1045 rc = utsParseConfig(g_szCfgPath, &g_pCfgAst, &pErrInfo);
1046 if (RT_SUCCESS(rc))
1047 {
1048 rc = utsPlatformInit();
1049 if (RT_SUCCESS(rc))
1050 {
1051 rc = RTCritSectInit(&g_CritSectClients);
1052 if (RT_SUCCESS(rc))
1053 {
1054 rc = RTPipeCreate(&g_hPipeR, &g_hPipeW, 0);
1055 if (RT_SUCCESS(rc))
1056 {
1057 /* Spin off the thread serving connections. */
1058 rc = RTThreadCreate(&g_hThreadServing, utsClientWorker, NULL, 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE,
1059 "USBTSTSRV");
1060 if (RT_SUCCESS(rc))
1061 return VINF_SUCCESS;
1062 else
1063 RTMsgError("Creating the client worker thread failed with %Rrc\n", rc);
1064
1065 RTPipeClose(g_hPipeR);
1066 RTPipeClose(g_hPipeW);
1067 }
1068 else
1069 RTMsgError("Creating communications pipe failed with %Rrc\n", rc);
1070
1071 RTCritSectDelete(&g_CritSectClients);
1072 }
1073 else
1074 RTMsgError("Creating global critical section failed with %Rrc\n", rc);
1075
1076 utsConfigAstDestroy(g_pCfgAst);
1077 }
1078 else
1079 {
1080 if (RTErrInfoIsSet(pErrInfo))
1081 {
1082 RTMsgError("Failed to parse config with detailed error: %s (%Rrc)\n",
1083 pErrInfo->pszMsg, pErrInfo->rc);
1084 RTErrInfoFree(pErrInfo);
1085 }
1086 else
1087 RTMsgError("Faield to parse config with unknown error (%Rrc)\n", rc);
1088 return rc;
1089 }
1090 }
1091
1092 return rc;
1093}
1094
1095/**
1096 * Determines the default configuration.
1097 */
1098static void utsSetDefaults(void)
1099{
1100 /*
1101 * OS and ARCH.
1102 */
1103 AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
1104 strcpy(g_szOsShortName, KBUILD_TARGET);
1105
1106 AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
1107 strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);
1108
1109 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
1110 strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
1111 g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
1112 strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
1113
1114 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
1115 strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
1116 g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
1117 strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
1118
1119#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1120 strcpy(g_szExeSuff, ".exe");
1121 strcpy(g_szScriptSuff, ".cmd");
1122#else
1123 strcpy(g_szExeSuff, "");
1124 strcpy(g_szScriptSuff, ".sh");
1125#endif
1126
1127 /*
1128 * The CD/DVD-ROM location.
1129 */
1130 /** @todo do a better job here :-) */
1131#ifdef RT_OS_WINDOWS
1132 strcpy(g_szDefCdRomPath, "D:/");
1133#elif defined(RT_OS_OS2)
1134 strcpy(g_szDefCdRomPath, "D:/");
1135#else
1136 if (RTDirExists("/media"))
1137 strcpy(g_szDefCdRomPath, "/media/cdrom");
1138 else
1139 strcpy(g_szDefCdRomPath, "/mnt/cdrom");
1140#endif
1141 strcpy(g_szCdRomPath, g_szDefCdRomPath);
1142
1143 /*
1144 * Temporary directory.
1145 */
1146 int rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
1147 if (RT_SUCCESS(rc))
1148#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
1149 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXX.tmp");
1150#else
1151 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXXXXXXX.tmp");
1152#endif
1153 if (RT_FAILURE(rc))
1154 {
1155 RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
1156 strcpy(g_szDefScratchPath, "/tmp/uts-XXXX.tmp");
1157 }
1158 strcpy(g_szScratchPath, g_szDefScratchPath);
1159
1160 /*
1161 * Config file location.
1162 */
1163 /** @todo: Improve */
1164#if !defined(RT_OS_WINDOWS)
1165 strcpy(g_szCfgPath, "/etc/uts.conf");
1166#else
1167 strcpy(g_szCfgPath, "");
1168#endif
1169
1170 /*
1171 * The default transporter is the first one.
1172 */
1173 g_pTransport = g_apTransports[0];
1174}
1175
1176/**
1177 * Prints the usage.
1178 *
1179 * @param pStrm Where to print it.
1180 * @param pszArgv0 The program name (argv[0]).
1181 */
1182static void utsUsage(PRTSTREAM pStrm, const char *argv0)
1183{
1184 RTStrmPrintf(pStrm,
1185 "Usage: %Rbn [options]\n"
1186 "\n"
1187 "Options:\n"
1188 " --config <path>\n"
1189 " Where to load the config from\n"
1190 " --cdrom <path>\n"
1191 " Where the CD/DVD-ROM will be mounted.\n"
1192 " Default: %s\n"
1193 " --scratch <path>\n"
1194 " Where to put scratch files.\n"
1195 " Default: %s \n"
1196 ,
1197 argv0,
1198 g_szDefCdRomPath,
1199 g_szDefScratchPath);
1200 RTStrmPrintf(pStrm,
1201 " --transport <name>\n"
1202 " Use the specified transport layer, one of the following:\n");
1203 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1204 RTStrmPrintf(pStrm, " %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
1205 RTStrmPrintf(pStrm, " Default: %s\n", g_pTransport->szName);
1206 RTStrmPrintf(pStrm,
1207 " --display-output, --no-display-output\n"
1208 " Display the output and the result of all child processes.\n");
1209 RTStrmPrintf(pStrm,
1210 " --foreground\n"
1211 " Don't daemonize, run in the foreground.\n");
1212 RTStrmPrintf(pStrm,
1213 " --help, -h, -?\n"
1214 " Display this message and exit.\n"
1215 " --version, -V\n"
1216 " Display the version and exit.\n");
1217
1218 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1219 if (g_apTransports[i]->cOpts)
1220 {
1221 RTStrmPrintf(pStrm,
1222 "\n"
1223 "Options for %s:\n", g_apTransports[i]->szName);
1224 g_apTransports[i]->pfnUsage(g_pStdOut);
1225 }
1226}
1227
1228/**
1229 * Parses the arguments.
1230 *
1231 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
1232 * @param argc The number of arguments.
1233 * @param argv The argument vector.
1234 * @param pfExit For indicating exit when the exit code is zero.
1235 */
1236static RTEXITCODE utsParseArgv(int argc, char **argv, bool *pfExit)
1237{
1238 *pfExit = false;
1239
1240 /*
1241 * Storage for locally handled options.
1242 */
1243 bool fDaemonize = true;
1244 bool fDaemonized = false;
1245
1246 /*
1247 * Combine the base and transport layer option arrays.
1248 */
1249 static const RTGETOPTDEF s_aBaseOptions[] =
1250 {
1251 { "--config", 'C', RTGETOPT_REQ_STRING },
1252 { "--transport", 't', RTGETOPT_REQ_STRING },
1253 { "--cdrom", 'c', RTGETOPT_REQ_STRING },
1254 { "--scratch", 's', RTGETOPT_REQ_STRING },
1255 { "--display-output", 'd', RTGETOPT_REQ_NOTHING },
1256 { "--no-display-output",'D', RTGETOPT_REQ_NOTHING },
1257 { "--foreground", 'f', RTGETOPT_REQ_NOTHING },
1258 { "--daemonized", 'Z', RTGETOPT_REQ_NOTHING },
1259 };
1260
1261 size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
1262 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1263 cOptions += g_apTransports[i]->cOpts;
1264
1265 PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
1266 if (!paOptions)
1267 return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");
1268
1269 memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
1270 cOptions = RT_ELEMENTS(s_aBaseOptions);
1271 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1272 {
1273 memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
1274 cOptions += g_apTransports[i]->cOpts;
1275 }
1276
1277 /*
1278 * Parse the arguments.
1279 */
1280 RTGETOPTSTATE GetState;
1281 int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
1282 AssertRC(rc);
1283
1284 int ch;
1285 RTGETOPTUNION Val;
1286 while ((ch = RTGetOpt(&GetState, &Val)))
1287 {
1288 switch (ch)
1289 {
1290 case 'C':
1291 rc = RTStrCopy(g_szCfgPath, sizeof(g_szCfgPath), Val.psz);
1292 if (RT_FAILURE(rc))
1293 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Config file path is path too long (%Rrc)\n", rc);
1294 break;
1295
1296 case 'c':
1297 rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
1298 if (RT_FAILURE(rc))
1299 return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
1300 break;
1301
1302 case 'd':
1303 g_fDisplayOutput = true;
1304 break;
1305
1306 case 'D':
1307 g_fDisplayOutput = false;
1308 break;
1309
1310 case 'f':
1311 fDaemonize = false;
1312 break;
1313
1314 case 'h':
1315 utsUsage(g_pStdOut, argv[0]);
1316 *pfExit = true;
1317 return RTEXITCODE_SUCCESS;
1318
1319 case 's':
1320 rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
1321 if (RT_FAILURE(rc))
1322 return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
1323 break;
1324
1325 case 't':
1326 {
1327 PCUTSTRANSPORT pTransport = NULL;
1328 for (size_t i = 0; RT_ELEMENTS(g_apTransports); i++)
1329 if (!strcmp(g_apTransports[i]->szName, Val.psz))
1330 {
1331 pTransport = g_apTransports[i];
1332 break;
1333 }
1334 if (!pTransport)
1335 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
1336 g_pTransport = pTransport;
1337 break;
1338 }
1339
1340 case 'V':
1341 RTPrintf("$Revision: 60522 $\n");
1342 *pfExit = true;
1343 return RTEXITCODE_SUCCESS;
1344
1345 case 'Z':
1346 fDaemonized = true;
1347 fDaemonize = false;
1348 break;
1349
1350 default:
1351 {
1352 rc = VERR_TRY_AGAIN;
1353 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1354 if (g_apTransports[i]->cOpts)
1355 {
1356 rc = g_apTransports[i]->pfnOption(ch, &Val);
1357 if (RT_SUCCESS(rc))
1358 break;
1359 if (rc != VERR_TRY_AGAIN)
1360 {
1361 *pfExit = true;
1362 return RTEXITCODE_SYNTAX;
1363 }
1364 }
1365 if (rc == VERR_TRY_AGAIN)
1366 {
1367 *pfExit = true;
1368 return RTGetOptPrintError(ch, &Val);
1369 }
1370 break;
1371 }
1372 }
1373 }
1374
1375 /*
1376 * Daemonize ourselves if asked to.
1377 */
1378 if (fDaemonize && !*pfExit)
1379 {
1380 rc = RTProcDaemonize(argv, "--daemonized");
1381 if (RT_FAILURE(rc))
1382 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
1383 *pfExit = true;
1384 }
1385
1386 return RTEXITCODE_SUCCESS;
1387}
1388
1389
1390int main(int argc, char **argv)
1391{
1392 /*
1393 * Initialize the runtime.
1394 */
1395 int rc = RTR3InitExe(argc, &argv, 0);
1396 if (RT_FAILURE(rc))
1397 return RTMsgInitFailure(rc);
1398
1399 /*
1400 * Determine defaults and parse the arguments.
1401 */
1402 utsSetDefaults();
1403 bool fExit;
1404 RTEXITCODE rcExit = utsParseArgv(argc, argv, &fExit);
1405 if (rcExit != RTEXITCODE_SUCCESS || fExit)
1406 return rcExit;
1407
1408 /*
1409 * Initialize global state.
1410 */
1411 rc = utsInit();
1412 if (RT_FAILURE(rc))
1413 return RTEXITCODE_FAILURE;
1414
1415 /*
1416 * Initialize the transport layer.
1417 */
1418 rc = g_pTransport->pfnInit();
1419 if (RT_FAILURE(rc))
1420 return RTEXITCODE_FAILURE;
1421
1422 /*
1423 * Ok, start working
1424 */
1425 rcExit = utsMainLoop();
1426
1427 /*
1428 * Cleanup.
1429 */
1430 g_pTransport->pfnTerm();
1431
1432 utsPlatformTerm();
1433
1434 return rcExit;
1435}
1436
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