VirtualBox

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

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

ValidationKit/usb: Fixes

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.9 KB
Line 
1/* $Id: UsbTestService.cpp 60488 2016-04-14 10:33:11Z 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
61
62
63/*********************************************************************************************************************************
64* Structures and Typedefs *
65*********************************************************************************************************************************/
66
67#define UTS_USBIP_PORT_FIRST 3240
68#define UTS_USBIP_PORT_LAST 3340
69
70/**
71 * UTS client state.
72 */
73typedef enum UTSCLIENTSTATE
74{
75 /** Invalid client state. */
76 UTSCLIENTSTATE_INVALID = 0,
77 /** Client is initialising, only the HOWDY and BYE packets are allowed. */
78 UTSCLIENTSTATE_INITIALISING,
79 /** Client is in fully cuntional state and ready to process all requests. */
80 UTSCLIENTSTATE_READY,
81 /** Client is destroying. */
82 UTSCLIENTSTATE_DESTROYING,
83 /** 32bit hack. */
84 UTSCLIENTSTATE_32BIT_HACK = 0x7fffffff
85} UTSCLIENTSTATE;
86
87/**
88 * UTS client instance.
89 */
90typedef struct UTSCLIENT
91{
92 /** List node for new clients. */
93 RTLISTNODE NdLst;
94 /** The current client state. */
95 UTSCLIENTSTATE enmState;
96 /** Transport backend specific data. */
97 PUTSTRANSPORTCLIENT pTransportClient;
98 /** Client hostname. */
99 char *pszHostname;
100 /** Gadget host handle. */
101 UTSGADGETHOST hGadgetHost;
102 /** Handle fo the current configured gadget. */
103 UTSGADGET hGadget;
104} UTSCLIENT;
105/** Pointer to a UTS client instance. */
106typedef UTSCLIENT *PUTSCLIENT;
107
108/*********************************************************************************************************************************
109* Global Variables *
110*********************************************************************************************************************************/
111/**
112 * Transport layers.
113 */
114static const PCUTSTRANSPORT g_apTransports[] =
115{
116 &g_TcpTransport,
117 //&g_SerialTransport,
118 //&g_FileSysTransport,
119 //&g_GuestPropTransport,
120 //&g_TestDevTransport,
121};
122
123/** The select transport layer. */
124static PCUTSTRANSPORT g_pTransport;
125/** The config path. */
126static char g_szCfgPath[RTPATH_MAX];
127/** The scratch path. */
128static char g_szScratchPath[RTPATH_MAX];
129/** The default scratch path. */
130static char g_szDefScratchPath[RTPATH_MAX];
131/** The CD/DVD-ROM path. */
132static char g_szCdRomPath[RTPATH_MAX];
133/** The default CD/DVD-ROM path. */
134static char g_szDefCdRomPath[RTPATH_MAX];
135/** The operating system short name. */
136static char g_szOsShortName[16];
137/** The CPU architecture short name. */
138static char g_szArchShortName[16];
139/** The combined "OS.arch" name. */
140static char g_szOsDotArchShortName[32];
141/** The combined "OS/arch" name. */
142static char g_szOsSlashArchShortName[32];
143/** The executable suffix. */
144static char g_szExeSuff[8];
145/** The shell script suffix. */
146static char g_szScriptSuff[8];
147/** Whether to display the output of the child process or not. */
148static bool g_fDisplayOutput = true;
149/** Whether to terminate or not.
150 * @todo implement signals and stuff. */
151static bool volatile g_fTerminate = false;
152/** Configuration AST. */
153static PCFGAST g_pCfgAst = NULL;
154/** Pipe for communicating with the serving thread about new clients. - read end */
155static RTPIPE g_hPipeR;
156/** Pipe for communicating with the serving thread about new clients. - write end */
157static RTPIPE g_hPipeW;
158/** Thread serving connected clients. */
159static RTTHREAD g_hThreadServing;
160/** Critical section protecting the list of new clients. */
161static RTCRITSECT g_CritSectClients;
162/** List of new clients waiting to be picked up by the client worker thread. */
163static RTLISTANCHOR g_LstClientsNew;
164/** First USB/IP port we can use. */
165static uint16_t g_uUsbIpPortFirst = UTS_USBIP_PORT_FIRST;
166/** Last USB/IP port we can use. */
167static uint16_t g_uUsbIpPortLast = UTS_USBIP_PORT_LAST;
168/** Next free port. */
169static uint16_t g_uUsbIpPortNext = UTS_USBIP_PORT_FIRST;
170
171
172
173/**
174 * Returns the string represenation of the given state.
175 */
176static const char *utsClientStateStringify(UTSCLIENTSTATE enmState)
177{
178 switch (enmState)
179 {
180 case UTSCLIENTSTATE_INVALID:
181 return "INVALID";
182 case UTSCLIENTSTATE_INITIALISING:
183 return "INITIALISING";
184 case UTSCLIENTSTATE_READY:
185 return "READY";
186 case UTSCLIENTSTATE_DESTROYING:
187 return "DESTROYING";
188 case UTSCLIENTSTATE_32BIT_HACK:
189 default:
190 break;
191 }
192
193 AssertMsgFailed(("Unknown state %#x\n", enmState));
194 return "UNKNOWN";
195}
196
197/**
198 * Calculates the checksum value, zero any padding space and send the packet.
199 *
200 * @returns IPRT status code.
201 * @param pClient The UTS client structure.
202 * @param pPkt The packet to send. Must point to a correctly
203 * aligned buffer.
204 */
205static int utsSendPkt(PUTSCLIENT pClient, PUTSPKTHDR pPkt)
206{
207 Assert(pPkt->cb >= sizeof(*pPkt));
208 pPkt->uCrc32 = RTCrc32(pPkt->achOpcode, pPkt->cb - RT_OFFSETOF(UTSPKTHDR, achOpcode));
209 if (pPkt->cb != RT_ALIGN_32(pPkt->cb, UTSPKT_ALIGNMENT))
210 memset((uint8_t *)pPkt + pPkt->cb, '\0', RT_ALIGN_32(pPkt->cb, UTSPKT_ALIGNMENT) - pPkt->cb);
211
212 Log(("utsSendPkt: cb=%#x opcode=%.8s\n", pPkt->cb, pPkt->achOpcode));
213 Log2(("%.*Rhxd\n", RT_MIN(pPkt->cb, 256), pPkt));
214 int rc = g_pTransport->pfnSendPkt(pClient->pTransportClient, pPkt);
215 while (RT_UNLIKELY(rc == VERR_INTERRUPTED) && !g_fTerminate)
216 rc = g_pTransport->pfnSendPkt(pClient->pTransportClient, pPkt);
217 if (RT_FAILURE(rc))
218 Log(("utsSendPkt: rc=%Rrc\n", rc));
219
220 return rc;
221}
222
223/**
224 * Sends a babble reply and disconnects the client (if applicable).
225 *
226 * @param pClient The UTS client structure.
227 * @param pszOpcode The BABBLE opcode.
228 */
229static void utsReplyBabble(PUTSCLIENT pClient, const char *pszOpcode)
230{
231 UTSPKTHDR Reply;
232 Reply.cb = sizeof(Reply);
233 Reply.uCrc32 = 0;
234 memcpy(Reply.achOpcode, pszOpcode, sizeof(Reply.achOpcode));
235
236 g_pTransport->pfnBabble(pClient->pTransportClient, &Reply, 20*1000);
237}
238
239/**
240 * Receive and validate a packet.
241 *
242 * Will send bable responses to malformed packets that results in a error status
243 * code.
244 *
245 * @returns IPRT status code.
246 * @param pClient The UTS client structure.
247 * @param ppPktHdr Where to return the packet on success. Free
248 * with RTMemFree.
249 * @param fAutoRetryOnFailure Whether to retry on error.
250 */
251static int utsRecvPkt(PUTSCLIENT pClient, PPUTSPKTHDR ppPktHdr, bool fAutoRetryOnFailure)
252{
253 for (;;)
254 {
255 PUTSPKTHDR pPktHdr;
256 int rc = g_pTransport->pfnRecvPkt(pClient->pTransportClient, &pPktHdr);
257 if (RT_SUCCESS(rc))
258 {
259 /* validate the packet. */
260 if ( pPktHdr->cb >= sizeof(UTSPKTHDR)
261 && pPktHdr->cb < UTSPKT_MAX_SIZE)
262 {
263 Log2(("utsRecvPkt: pPktHdr=%p cb=%#x crc32=%#x opcode=%.8s\n"
264 "%.*Rhxd\n",
265 pPktHdr, pPktHdr->cb, pPktHdr->uCrc32, pPktHdr->achOpcode, RT_MIN(pPktHdr->cb, 256), pPktHdr));
266 uint32_t uCrc32Calc = pPktHdr->uCrc32 != 0
267 ? RTCrc32(&pPktHdr->achOpcode[0], pPktHdr->cb - RT_OFFSETOF(UTSPKTHDR, achOpcode))
268 : 0;
269 if (pPktHdr->uCrc32 == uCrc32Calc)
270 {
271 AssertCompileMemberSize(UTSPKTHDR, achOpcode, 8);
272 if ( RT_C_IS_UPPER(pPktHdr->achOpcode[0])
273 && RT_C_IS_UPPER(pPktHdr->achOpcode[1])
274 && (RT_C_IS_UPPER(pPktHdr->achOpcode[2]) || pPktHdr->achOpcode[2] == ' ')
275 && (RT_C_IS_PRINT(pPktHdr->achOpcode[3]) || pPktHdr->achOpcode[3] == ' ')
276 && (RT_C_IS_PRINT(pPktHdr->achOpcode[4]) || pPktHdr->achOpcode[4] == ' ')
277 && (RT_C_IS_PRINT(pPktHdr->achOpcode[5]) || pPktHdr->achOpcode[5] == ' ')
278 && (RT_C_IS_PRINT(pPktHdr->achOpcode[6]) || pPktHdr->achOpcode[6] == ' ')
279 && (RT_C_IS_PRINT(pPktHdr->achOpcode[7]) || pPktHdr->achOpcode[7] == ' ')
280 )
281 {
282 Log(("utsRecvPkt: cb=%#x opcode=%.8s\n", pPktHdr->cb, pPktHdr->achOpcode));
283 *ppPktHdr = pPktHdr;
284 return rc;
285 }
286
287 rc = VERR_IO_BAD_COMMAND;
288 }
289 else
290 {
291 Log(("utsRecvPkt: cb=%#x opcode=%.8s crc32=%#x actual=%#x\n",
292 pPktHdr->cb, pPktHdr->achOpcode, pPktHdr->uCrc32, uCrc32Calc));
293 rc = VERR_IO_CRC;
294 }
295 }
296 else
297 rc = VERR_IO_BAD_LENGTH;
298
299 /* Send babble reply and disconnect the client if the transport is
300 connection oriented. */
301 if (rc == VERR_IO_BAD_LENGTH)
302 utsReplyBabble(pClient, "BABBLE L");
303 else if (rc == VERR_IO_CRC)
304 utsReplyBabble(pClient, "BABBLE C");
305 else if (rc == VERR_IO_BAD_COMMAND)
306 utsReplyBabble(pClient, "BABBLE O");
307 else
308 utsReplyBabble(pClient, "BABBLE ");
309 RTMemFree(pPktHdr);
310 }
311
312 /* Try again or return failure? */
313 if ( g_fTerminate
314 || rc != VERR_INTERRUPTED
315 || !fAutoRetryOnFailure
316 )
317 {
318 Log(("utsRecvPkt: rc=%Rrc\n", rc));
319 return rc;
320 }
321 }
322}
323
324/**
325 * Make a simple reply, only status opcode.
326 *
327 * @returns IPRT status code of the send.
328 * @param pClient The UTS client structure.
329 * @param pReply The reply packet.
330 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
331 * with space.
332 * @param cbExtra Bytes in addition to the header.
333 */
334static int utsReplyInternal(PUTSCLIENT pClient, PUTSPKTSTS pReply, const char *pszOpcode, size_t cbExtra)
335{
336 /* copy the opcode, don't be too strict in case of a padding screw up. */
337 size_t cchOpcode = strlen(pszOpcode);
338 if (RT_LIKELY(cchOpcode == sizeof(pReply->Hdr.achOpcode)))
339 memcpy(pReply->Hdr.achOpcode, pszOpcode, sizeof(pReply->Hdr.achOpcode));
340 else
341 {
342 Assert(cchOpcode == sizeof(pReply->Hdr.achOpcode));
343 while (cchOpcode > 0 && pszOpcode[cchOpcode - 1] == ' ')
344 cchOpcode--;
345 AssertMsgReturn(cchOpcode < sizeof(pReply->Hdr.achOpcode), ("%d/'%.8s'\n", cchOpcode, pszOpcode), VERR_INTERNAL_ERROR_4);
346 memcpy(pReply->Hdr.achOpcode, pszOpcode, cchOpcode);
347 memset(&pReply->Hdr.achOpcode[cchOpcode], ' ', sizeof(pReply->Hdr.achOpcode) - cchOpcode);
348 }
349
350 pReply->Hdr.cb = (uint32_t)sizeof(UTSPKTSTS) + (uint32_t)cbExtra;
351 pReply->Hdr.uCrc32 = 0;
352
353 return utsSendPkt(pClient, &pReply->Hdr);
354}
355
356/**
357 * Make a simple reply, only status opcode.
358 *
359 * @returns IPRT status code of the send.
360 * @param pClient The UTS client structure.
361 * @param pPktHdr The original packet (for future use).
362 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
363 * with space.
364 */
365static int utsReplySimple(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode)
366{
367 UTSPKTSTS Pkt;
368
369 RT_ZERO(Pkt);
370 Pkt.rcReq = VINF_SUCCESS;
371 Pkt.cchStsMsg = 0;
372 NOREF(pPktHdr);
373 return utsReplyInternal(pClient, &Pkt, pszOpcode, 0);
374}
375
376/**
377 * Acknowledges a packet with success.
378 *
379 * @returns IPRT status code of the send.
380 * @param pClient The UTS client structure.
381 * @param pPktHdr The original packet (for future use).
382 */
383static int utsReplyAck(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
384{
385 return utsReplySimple(pClient, pPktHdr, "ACK ");
386}
387
388/**
389 * Replies with a failure.
390 *
391 * @returns IPRT status code of the send.
392 * @param pClient The UTS client structure.
393 * @param pPktHdr The original packet (for future use).
394 * @param rcReq Status code.
395 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
396 * with space.
397 * @param pszDetailsFmt Longer description of the problem (format
398 * string).
399 * @param va Format arguments.
400 */
401static int utsReplyFailureV(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode, int rcReq, const char *pszDetailFmt, va_list va)
402{
403 NOREF(pPktHdr);
404 union
405 {
406 UTSPKTSTS Hdr;
407 char ach[256];
408 } uPkt;
409
410 RT_ZERO(uPkt);
411 size_t cchDetail = RTStrPrintfV(&uPkt.ach[sizeof(UTSPKTSTS)],
412 sizeof(uPkt) - sizeof(UTSPKTSTS),
413 pszDetailFmt, va);
414 uPkt.Hdr.rcReq = rcReq;
415 uPkt.Hdr.cchStsMsg = cchDetail;
416 return utsReplyInternal(pClient, &uPkt.Hdr, pszOpcode, cchDetail + 1);
417}
418
419/**
420 * Replies with a failure.
421 *
422 * @returns IPRT status code of the send.
423 * @param pClient The UTS client structure.
424 * @param pPktHdr The original packet (for future use).
425 * @param rcReq Status code.
426 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
427 * with space.
428 * @param pszDetails Longer description of the problem (format
429 * string).
430 * @param ... Format arguments.
431 */
432static int utsReplyFailure(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, const char *pszOpcode, int rcReq, const char *pszDetailFmt, ...)
433{
434 va_list va;
435 va_start(va, pszDetailFmt);
436 int rc = utsReplyFailureV(pClient, pPktHdr, pszOpcode, rcReq, pszDetailFmt, va);
437 va_end(va);
438 return rc;
439}
440
441/**
442 * Replies according to the return code.
443 *
444 * @returns IPRT status code of the send.
445 * @param pClient The UTS client structure.
446 * @param pPktHdr The packet to reply to.
447 * @param rcOperation The status code to report.
448 * @param pszOperationFmt The operation that failed. Typically giving the
449 * function call with important arguments.
450 * @param ... Arguments to the format string.
451 */
452static int utsReplyRC(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, int rcOperation, const char *pszOperationFmt, ...)
453{
454 if (RT_SUCCESS(rcOperation))
455 return utsReplyAck(pClient, pPktHdr);
456
457 char szOperation[128];
458 va_list va;
459 va_start(va, pszOperationFmt);
460 RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
461 va_end(va);
462
463 return utsReplyFailure(pClient, pPktHdr, "FAILED ", rcOperation, "%s failed with rc=%Rrc (opcode '%.8s')",
464 szOperation, rcOperation, pPktHdr->achOpcode);
465}
466
467/**
468 * Signal a bad packet minum size.
469 *
470 * @returns IPRT status code of the send.
471 * @param pClient The UTS client structure.
472 * @param pPktHdr The packet to reply to.
473 * @param cbMin The minimum size.
474 */
475static int utsReplyBadMinSize(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, size_t cbMin)
476{
477 return utsReplyFailure(pClient, pPktHdr, "BAD SIZE", VERR_INVALID_PARAMETER, "Expected at least %zu bytes, got %u (opcode '%.8s')",
478 cbMin, pPktHdr->cb, pPktHdr->achOpcode);
479}
480
481/**
482 * Signal a bad packet exact size.
483 *
484 * @returns IPRT status code of the send.
485 * @param pClient The UTS client structure.
486 * @param pPktHdr The packet to reply to.
487 * @param cb The wanted size.
488 */
489static int utsReplyBadSize(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr, size_t cb)
490{
491 return utsReplyFailure(pClient, pPktHdr, "BAD SIZE", VERR_INVALID_PARAMETER, "Expected at %zu bytes, got %u (opcode '%.8s')",
492 cb, pPktHdr->cb, pPktHdr->achOpcode);
493}
494
495/**
496 * Deals with a command that isn't implemented yet.
497 * @returns IPRT status code of the send.
498 * @param pClient The UTS client structure.
499 * @param pPktHdr The packet which opcode isn't implemented.
500 */
501static int utsReplyNotImplemented(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
502{
503 return utsReplyFailure(pClient, pPktHdr, "NOT IMPL", VERR_NOT_IMPLEMENTED, "Opcode '%.8s' is not implemented", pPktHdr->achOpcode);
504}
505
506/**
507 * Deals with a unknown command.
508 * @returns IPRT status code of the send.
509 * @param pClient The UTS client structure.
510 * @param pPktHdr The packet to reply to.
511 */
512static int utsReplyUnknown(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
513{
514 return utsReplyFailure(pClient, pPktHdr, "UNKNOWN ", VERR_NOT_FOUND, "Opcode '%.8s' is not known", pPktHdr->achOpcode);
515}
516
517/**
518 * Deals with a command which contains an unterminated string.
519 *
520 * @returns IPRT status code of the send.
521 * @param pClient The UTS client structure.
522 * @param pPktHdr The packet containing the unterminated string.
523 */
524static int utsReplyBadStrTermination(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
525{
526 return utsReplyFailure(pClient, pPktHdr, "BAD TERM", VERR_INVALID_PARAMETER, "Opcode '%.8s' contains an unterminated string", pPktHdr->achOpcode);
527}
528
529/**
530 * Deals with a command sent in an invalid client state.
531 *
532 * @returns IPRT status code of the send.
533 * @param pClient The UTS client structure.
534 * @param pPktHdr The packet containing the unterminated string.
535 */
536static int utsReplyInvalidState(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
537{
538 return utsReplyFailure(pClient, pPktHdr, "INVSTATE", VERR_INVALID_STATE, "Opcode '%.8s' is not supported at client state '%s",
539 pPktHdr->achOpcode, utsClientStateStringify(pClient->enmState));
540}
541
542/**
543 * Creates the configuration from the given GADGET CREATE packet.
544 *
545 * @returns IPRT status code.
546 * @param pReq The gadget create request.
547 * @param paCfg The array of configuration items.
548 */
549static int utsDoGadgetCreateFillCfg(PUTSPKTREQGDGTCTOR pReq, PUTSGADGETCFGITEM paCfg)
550{
551 return VERR_NOT_IMPLEMENTED;
552}
553
554/**
555 * Verifies and acknowledges a "BYE" request.
556 *
557 * @returns IPRT status code.
558 * @param pClient The UTS client structure.
559 * @param pPktHdr The howdy packet.
560 */
561static int utsDoBye(PUTSCLIENT pClient, PCUTSPKTHDR pPktHdr)
562{
563 int rc;
564 if (pPktHdr->cb == sizeof(UTSPKTHDR))
565 rc = utsReplyAck(pClient, pPktHdr);
566 else
567 rc = utsReplyBadSize(pClient, pPktHdr, sizeof(UTSPKTHDR));
568 g_pTransport->pfnNotifyBye(pClient->pTransportClient);
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 = utsDoGadgetCreate(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 = RTCritSectInit(&g_CritSectClients);
1049 if (RT_SUCCESS(rc))
1050 {
1051 rc = RTPipeCreate(&g_hPipeR, &g_hPipeW, 0);
1052 if (RT_SUCCESS(rc))
1053 {
1054 /* Spin off the thread serving connections. */
1055 rc = RTThreadCreate(&g_hThreadServing, utsClientWorker, NULL, 0, RTTHREADTYPE_IO, RTTHREADFLAGS_WAITABLE,
1056 "USBTSTSRV");
1057 if (RT_SUCCESS(rc))
1058 return VINF_SUCCESS;
1059 else
1060 RTMsgError("Creating the client worker thread failed with %Rrc\n", rc);
1061
1062 RTPipeClose(g_hPipeR);
1063 RTPipeClose(g_hPipeW);
1064 }
1065 else
1066 RTMsgError("Creating communications pipe failed with %Rrc\n", rc);
1067
1068 RTCritSectDelete(&g_CritSectClients);
1069 }
1070 else
1071 RTMsgError("Creating global critical section failed with %Rrc\n", rc);
1072
1073 utsConfigAstDestroy(g_pCfgAst);
1074 }
1075 else
1076 {
1077 if (RTErrInfoIsSet(pErrInfo))
1078 {
1079 RTMsgError("Failed to parse config with detailed error: %s (%Rrc)\n",
1080 pErrInfo->pszMsg, pErrInfo->rc);
1081 RTErrInfoFree(pErrInfo);
1082 }
1083 else
1084 RTMsgError("Faield to parse config with unknown error (%Rrc)\n", rc);
1085 return rc;
1086 }
1087
1088 return rc;
1089}
1090
1091/**
1092 * Determines the default configuration.
1093 */
1094static void utsSetDefaults(void)
1095{
1096 /*
1097 * OS and ARCH.
1098 */
1099 AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
1100 strcpy(g_szOsShortName, KBUILD_TARGET);
1101
1102 AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
1103 strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);
1104
1105 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
1106 strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
1107 g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
1108 strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
1109
1110 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
1111 strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
1112 g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
1113 strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
1114
1115#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
1116 strcpy(g_szExeSuff, ".exe");
1117 strcpy(g_szScriptSuff, ".cmd");
1118#else
1119 strcpy(g_szExeSuff, "");
1120 strcpy(g_szScriptSuff, ".sh");
1121#endif
1122
1123 /*
1124 * The CD/DVD-ROM location.
1125 */
1126 /** @todo do a better job here :-) */
1127#ifdef RT_OS_WINDOWS
1128 strcpy(g_szDefCdRomPath, "D:/");
1129#elif defined(RT_OS_OS2)
1130 strcpy(g_szDefCdRomPath, "D:/");
1131#else
1132 if (RTDirExists("/media"))
1133 strcpy(g_szDefCdRomPath, "/media/cdrom");
1134 else
1135 strcpy(g_szDefCdRomPath, "/mnt/cdrom");
1136#endif
1137 strcpy(g_szCdRomPath, g_szDefCdRomPath);
1138
1139 /*
1140 * Temporary directory.
1141 */
1142 int rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
1143 if (RT_SUCCESS(rc))
1144#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
1145 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXX.tmp");
1146#else
1147 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "uts-XXXXXXXXX.tmp");
1148#endif
1149 if (RT_FAILURE(rc))
1150 {
1151 RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
1152 strcpy(g_szDefScratchPath, "/tmp/uts-XXXX.tmp");
1153 }
1154 strcpy(g_szScratchPath, g_szDefScratchPath);
1155
1156 /*
1157 * Config file location.
1158 */
1159 /** @todo: Improve */
1160#if !defined(RT_OS_WINDOWS)
1161 strcpy(g_szCfgPath, "/etc/uts.conf");
1162#else
1163 strcpy(g_szCfgPath, "");
1164#endif
1165
1166 /*
1167 * The default transporter is the first one.
1168 */
1169 g_pTransport = g_apTransports[0];
1170}
1171
1172/**
1173 * Prints the usage.
1174 *
1175 * @param pStrm Where to print it.
1176 * @param pszArgv0 The program name (argv[0]).
1177 */
1178static void utsUsage(PRTSTREAM pStrm, const char *argv0)
1179{
1180 RTStrmPrintf(pStrm,
1181 "Usage: %Rbn [options]\n"
1182 "\n"
1183 "Options:\n"
1184 " --config <path>\n"
1185 " Where to load the config from\n"
1186 " --cdrom <path>\n"
1187 " Where the CD/DVD-ROM will be mounted.\n"
1188 " Default: %s\n"
1189 " --scratch <path>\n"
1190 " Where to put scratch files.\n"
1191 " Default: %s \n"
1192 ,
1193 argv0,
1194 g_szDefCdRomPath,
1195 g_szDefScratchPath);
1196 RTStrmPrintf(pStrm,
1197 " --transport <name>\n"
1198 " Use the specified transport layer, one of the following:\n");
1199 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1200 RTStrmPrintf(pStrm, " %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
1201 RTStrmPrintf(pStrm, " Default: %s\n", g_pTransport->szName);
1202 RTStrmPrintf(pStrm,
1203 " --display-output, --no-display-output\n"
1204 " Display the output and the result of all child processes.\n");
1205 RTStrmPrintf(pStrm,
1206 " --foreground\n"
1207 " Don't daemonize, run in the foreground.\n");
1208 RTStrmPrintf(pStrm,
1209 " --help, -h, -?\n"
1210 " Display this message and exit.\n"
1211 " --version, -V\n"
1212 " Display the version and exit.\n");
1213
1214 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1215 if (g_apTransports[i]->cOpts)
1216 {
1217 RTStrmPrintf(pStrm,
1218 "\n"
1219 "Options for %s:\n", g_apTransports[i]->szName);
1220 g_apTransports[i]->pfnUsage(g_pStdOut);
1221 }
1222}
1223
1224/**
1225 * Parses the arguments.
1226 *
1227 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
1228 * @param argc The number of arguments.
1229 * @param argv The argument vector.
1230 * @param pfExit For indicating exit when the exit code is zero.
1231 */
1232static RTEXITCODE utsParseArgv(int argc, char **argv, bool *pfExit)
1233{
1234 *pfExit = false;
1235
1236 /*
1237 * Storage for locally handled options.
1238 */
1239 bool fDaemonize = true;
1240 bool fDaemonized = false;
1241
1242 /*
1243 * Combine the base and transport layer option arrays.
1244 */
1245 static const RTGETOPTDEF s_aBaseOptions[] =
1246 {
1247 { "--config", 'C', RTGETOPT_REQ_STRING },
1248 { "--transport", 't', RTGETOPT_REQ_STRING },
1249 { "--cdrom", 'c', RTGETOPT_REQ_STRING },
1250 { "--scratch", 's', RTGETOPT_REQ_STRING },
1251 { "--display-output", 'd', RTGETOPT_REQ_NOTHING },
1252 { "--no-display-output",'D', RTGETOPT_REQ_NOTHING },
1253 { "--foreground", 'f', RTGETOPT_REQ_NOTHING },
1254 { "--daemonized", 'Z', RTGETOPT_REQ_NOTHING },
1255 };
1256
1257 size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
1258 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1259 cOptions += g_apTransports[i]->cOpts;
1260
1261 PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
1262 if (!paOptions)
1263 return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");
1264
1265 memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
1266 cOptions = RT_ELEMENTS(s_aBaseOptions);
1267 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1268 {
1269 memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
1270 cOptions += g_apTransports[i]->cOpts;
1271 }
1272
1273 /*
1274 * Parse the arguments.
1275 */
1276 RTGETOPTSTATE GetState;
1277 int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
1278 AssertRC(rc);
1279
1280 int ch;
1281 RTGETOPTUNION Val;
1282 while ((ch = RTGetOpt(&GetState, &Val)))
1283 {
1284 switch (ch)
1285 {
1286 case 'C':
1287 rc = RTStrCopy(g_szCfgPath, sizeof(g_szCfgPath), Val.psz);
1288 if (RT_FAILURE(rc))
1289 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Config file path is path too long (%Rrc)\n", rc);
1290 break;
1291
1292 case 'c':
1293 rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
1294 if (RT_FAILURE(rc))
1295 return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
1296 break;
1297
1298 case 'd':
1299 g_fDisplayOutput = true;
1300 break;
1301
1302 case 'D':
1303 g_fDisplayOutput = false;
1304 break;
1305
1306 case 'f':
1307 fDaemonize = false;
1308 break;
1309
1310 case 'h':
1311 utsUsage(g_pStdOut, argv[0]);
1312 *pfExit = true;
1313 return RTEXITCODE_SUCCESS;
1314
1315 case 's':
1316 rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
1317 if (RT_FAILURE(rc))
1318 return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
1319 break;
1320
1321 case 't':
1322 {
1323 PCUTSTRANSPORT pTransport = NULL;
1324 for (size_t i = 0; RT_ELEMENTS(g_apTransports); i++)
1325 if (!strcmp(g_apTransports[i]->szName, Val.psz))
1326 {
1327 pTransport = g_apTransports[i];
1328 break;
1329 }
1330 if (!pTransport)
1331 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
1332 g_pTransport = pTransport;
1333 break;
1334 }
1335
1336 case 'V':
1337 RTPrintf("$Revision: 60488 $\n");
1338 *pfExit = true;
1339 return RTEXITCODE_SUCCESS;
1340
1341 case 'Z':
1342 fDaemonized = true;
1343 fDaemonize = false;
1344 break;
1345
1346 default:
1347 {
1348 rc = VERR_TRY_AGAIN;
1349 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
1350 if (g_apTransports[i]->cOpts)
1351 {
1352 rc = g_apTransports[i]->pfnOption(ch, &Val);
1353 if (RT_SUCCESS(rc))
1354 break;
1355 if (rc != VERR_TRY_AGAIN)
1356 {
1357 *pfExit = true;
1358 return RTEXITCODE_SYNTAX;
1359 }
1360 }
1361 if (rc == VERR_TRY_AGAIN)
1362 {
1363 *pfExit = true;
1364 return RTGetOptPrintError(ch, &Val);
1365 }
1366 break;
1367 }
1368 }
1369 }
1370
1371 /*
1372 * Daemonize ourselves if asked to.
1373 */
1374 if (fDaemonize && !*pfExit)
1375 {
1376 rc = RTProcDaemonize(argv, "--daemonized");
1377 if (RT_FAILURE(rc))
1378 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
1379 *pfExit = true;
1380 }
1381
1382 return RTEXITCODE_SUCCESS;
1383}
1384
1385
1386int main(int argc, char **argv)
1387{
1388 /*
1389 * Initialize the runtime.
1390 */
1391 int rc = RTR3InitExe(argc, &argv, 0);
1392 if (RT_FAILURE(rc))
1393 return RTMsgInitFailure(rc);
1394
1395 /*
1396 * Determine defaults and parse the arguments.
1397 */
1398 utsSetDefaults();
1399 bool fExit;
1400 RTEXITCODE rcExit = utsParseArgv(argc, argv, &fExit);
1401 if (rcExit != RTEXITCODE_SUCCESS || fExit)
1402 return rcExit;
1403
1404 /*
1405 * Initialize global state.
1406 */
1407 rc = utsInit();
1408 if (RT_FAILURE(rc))
1409 return RTEXITCODE_FAILURE;
1410
1411 /*
1412 * Initialize the transport layer.
1413 */
1414 rc = g_pTransport->pfnInit();
1415 if (RT_FAILURE(rc))
1416 return RTEXITCODE_FAILURE;
1417
1418 /*
1419 * Ok, start working
1420 */
1421 rcExit = utsMainLoop();
1422
1423 /*
1424 * Cleanup.
1425 */
1426 g_pTransport->pfnTerm();
1427
1428 return rcExit;
1429}
1430
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