VirtualBox

source: vbox/trunk/src/VBox/ValidationKit/utils/TestExecServ/TestExecService.cpp@ 62673

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

ValidationKit/utils: warnings.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 120.3 KB
Line 
1/* $Id: TestExecService.cpp 62673 2016-07-29 11:04:35Z vboxsync $ */
2/** @file
3 * TestExecServ - Basic Remote Execution Service.
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/cdrom.h>
36#include <iprt/critsect.h>
37#include <iprt/crc.h>
38#include <iprt/ctype.h>
39#include <iprt/dir.h>
40#include <iprt/env.h>
41#include <iprt/err.h>
42#include <iprt/file.h>
43#include <iprt/getopt.h>
44#include <iprt/handle.h>
45#include <iprt/initterm.h>
46#include <iprt/log.h>
47#include <iprt/mem.h>
48#include <iprt/message.h>
49#include <iprt/param.h>
50#include <iprt/path.h>
51#include <iprt/pipe.h>
52#include <iprt/poll.h>
53#include <iprt/process.h>
54#include <iprt/stream.h>
55#include <iprt/string.h>
56#include <iprt/system.h>
57#include <iprt/thread.h>
58#include <iprt/time.h>
59#include <iprt/uuid.h>
60
61#ifndef RT_OS_WINDOWS
62# include <iprt/zip.h>
63#endif
64
65#include "TestExecServiceInternal.h"
66
67
68
69/*********************************************************************************************************************************
70* Structures and Typedefs *
71*********************************************************************************************************************************/
72/**
73 * Handle IDs used by txsDoExec for the poll set.
74 */
75typedef enum TXSEXECHNDID
76{
77 TXSEXECHNDID_STDIN = 0,
78 TXSEXECHNDID_STDOUT,
79 TXSEXECHNDID_STDERR,
80 TXSEXECHNDID_TESTPIPE,
81 TXSEXECHNDID_STDIN_WRITABLE,
82 TXSEXECHNDID_TRANSPORT,
83 TXSEXECHNDID_THREAD
84} TXSEXECHNDID;
85
86
87/**
88 * For buffering process input supplied by the client.
89 */
90typedef struct TXSEXECSTDINBUF
91{
92 /** The mount of buffered data. */
93 size_t cb;
94 /** The current data offset. */
95 size_t off;
96 /** The data buffer. */
97 char *pch;
98 /** The amount of allocated buffer space. */
99 size_t cbAllocated;
100 /** Send further input into the bit bucket (stdin is dead). */
101 bool fBitBucket;
102 /** The CRC-32 for standard input (received part). */
103 uint32_t uCrc32;
104} TXSEXECSTDINBUF;
105/** Pointer to a standard input buffer. */
106typedef TXSEXECSTDINBUF *PTXSEXECSTDINBUF;
107
108/**
109 * TXS child process info.
110 */
111typedef struct TXSEXEC
112{
113 PCTXSPKTHDR pPktHdr;
114 RTMSINTERVAL cMsTimeout;
115 int rcReplySend;
116
117 RTPOLLSET hPollSet;
118 RTPIPE hStdInW;
119 RTPIPE hStdOutR;
120 RTPIPE hStdErrR;
121 RTPIPE hTestPipeR;
122 RTPIPE hWakeUpPipeR;
123 RTTHREAD hThreadWaiter;
124
125 /** @name For the setup phase
126 * @{ */
127 struct StdPipe
128 {
129 RTHANDLE hChild;
130 PRTHANDLE phChild;
131 } StdIn,
132 StdOut,
133 StdErr;
134 RTPIPE hTestPipeW;
135 RTENV hEnv;
136 /** @} */
137
138 /** For serializating some access. */
139 RTCRITSECT CritSect;
140 /** @name Members protected by the critical section.
141 * @{ */
142 RTPROCESS hProcess;
143 /** The process status. Only valid when fProcessAlive is cleared. */
144 RTPROCSTATUS ProcessStatus;
145 /** Set when the process is alive, clear when dead. */
146 bool volatile fProcessAlive;
147 /** The end of the pipe that hThreadWaiter writes to. */
148 RTPIPE hWakeUpPipeW;
149 /** @} */
150} TXSEXEC;
151/** Pointer to a the TXS child process info. */
152typedef TXSEXEC *PTXSEXEC;
153
154
155/*********************************************************************************************************************************
156* Global Variables *
157*********************************************************************************************************************************/
158/**
159 * Transport layers.
160 */
161static const PCTXSTRANSPORT g_apTransports[] =
162{
163 &g_TcpTransport,
164 //&g_SerialTransport,
165 //&g_FileSysTransport,
166 //&g_GuestPropTransport,
167 //&g_TestDevTransport,
168};
169
170/** The select transport layer. */
171static PCTXSTRANSPORT g_pTransport;
172/** The scratch path. */
173static char g_szScratchPath[RTPATH_MAX];
174/** The default scratch path. */
175static char g_szDefScratchPath[RTPATH_MAX];
176/** The CD/DVD-ROM path. */
177static char g_szCdRomPath[RTPATH_MAX];
178/** The default CD/DVD-ROM path. */
179static char g_szDefCdRomPath[RTPATH_MAX];
180/** The operating system short name. */
181static char g_szOsShortName[16];
182/** The CPU architecture short name. */
183static char g_szArchShortName[16];
184/** The combined "OS.arch" name. */
185static char g_szOsDotArchShortName[32];
186/** The combined "OS/arch" name. */
187static char g_szOsSlashArchShortName[32];
188/** The executable suffix. */
189static char g_szExeSuff[8];
190/** The shell script suffix. */
191static char g_szScriptSuff[8];
192/** UUID identifying this TXS instance. This can be used to see if TXS
193 * has been restarted or not. */
194static RTUUID g_InstanceUuid;
195/** Whether to display the output of the child process or not. */
196static bool g_fDisplayOutput = true;
197/** Whether to terminate or not.
198 * @todo implement signals and stuff. */
199static bool volatile g_fTerminate = false;
200
201/**
202 * Calculates the checksum value, zero any padding space and send the packet.
203 *
204 * @returns IPRT status code.
205 * @param pPkt The packet to send. Must point to a correctly
206 * aligned buffer.
207 */
208static int txsSendPkt(PTXSPKTHDR pPkt)
209{
210 Assert(pPkt->cb >= sizeof(*pPkt));
211 pPkt->uCrc32 = RTCrc32(pPkt->achOpcode, pPkt->cb - RT_OFFSETOF(TXSPKTHDR, achOpcode));
212 if (pPkt->cb != RT_ALIGN_32(pPkt->cb, TXSPKT_ALIGNMENT))
213 memset((uint8_t *)pPkt + pPkt->cb, '\0', RT_ALIGN_32(pPkt->cb, TXSPKT_ALIGNMENT) - pPkt->cb);
214
215 Log(("txsSendPkt: cb=%#x opcode=%.8s\n", pPkt->cb, pPkt->achOpcode));
216 Log2(("%.*Rhxd\n", RT_MIN(pPkt->cb, 256), pPkt));
217 int rc = g_pTransport->pfnSendPkt(pPkt);
218 while (RT_UNLIKELY(rc == VERR_INTERRUPTED) && !g_fTerminate)
219 rc = g_pTransport->pfnSendPkt(pPkt);
220 if (RT_FAILURE(rc))
221 Log(("txsSendPkt: rc=%Rrc\n", rc));
222
223 return rc;
224}
225
226/**
227 * Sends a babble reply and disconnects the client (if applicable).
228 *
229 * @param pszOpcode The BABBLE opcode.
230 */
231static void txsReplyBabble(const char *pszOpcode)
232{
233 TXSPKTHDR Reply;
234 Reply.cb = sizeof(Reply);
235 Reply.uCrc32 = 0;
236 memcpy(Reply.achOpcode, pszOpcode, sizeof(Reply.achOpcode));
237
238 g_pTransport->pfnBabble(&Reply, 20*1000);
239}
240
241/**
242 * Receive and validate a packet.
243 *
244 * Will send bable responses to malformed packets that results in a error status
245 * code.
246 *
247 * @returns IPRT status code.
248 * @param ppPktHdr Where to return the packet on success. Free
249 * with RTMemFree.
250 * @param fAutoRetryOnFailure Whether to retry on error.
251 */
252static int txsRecvPkt(PPTXSPKTHDR ppPktHdr, bool fAutoRetryOnFailure)
253{
254 for (;;)
255 {
256 PTXSPKTHDR pPktHdr;
257 int rc = g_pTransport->pfnRecvPkt(&pPktHdr);
258 if (RT_SUCCESS(rc))
259 {
260 /* validate the packet. */
261 if ( pPktHdr->cb >= sizeof(TXSPKTHDR)
262 && pPktHdr->cb < TXSPKT_MAX_SIZE)
263 {
264 Log2(("txsRecvPkt: 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(TXSPKTHDR, achOpcode))
269 : 0;
270 if (pPktHdr->uCrc32 == uCrc32Calc)
271 {
272 AssertCompileMemberSize(TXSPKTHDR, 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(("txsRecvPkt: 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(("txsRecvPkt: 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 txsReplyBabble("BABBLE L");
304 else if (rc == VERR_IO_CRC)
305 txsReplyBabble("BABBLE C");
306 else if (rc == VERR_IO_BAD_COMMAND)
307 txsReplyBabble("BABBLE O");
308 else
309 txsReplyBabble("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(("txsRecvPkt: 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 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 txsReplyInternal(PTXSPKTHDR 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->achOpcode)))
339 memcpy(pReply->achOpcode, pszOpcode, sizeof(pReply->achOpcode));
340 else
341 {
342 Assert(cchOpcode == sizeof(pReply->achOpcode));
343 while (cchOpcode > 0 && pszOpcode[cchOpcode - 1] == ' ')
344 cchOpcode--;
345 AssertMsgReturn(cchOpcode < sizeof(pReply->achOpcode), ("%d/'%.8s'\n", cchOpcode, pszOpcode), VERR_INTERNAL_ERROR_4);
346 memcpy(pReply->achOpcode, pszOpcode, cchOpcode);
347 memset(&pReply->achOpcode[cchOpcode], ' ', sizeof(pReply->achOpcode) - cchOpcode);
348 }
349
350 pReply->cb = (uint32_t)sizeof(TXSPKTHDR) + (uint32_t)cbExtra;
351 pReply->uCrc32 = 0;
352
353 return txsSendPkt(pReply);
354}
355
356/**
357 * Make a simple reply, only status opcode.
358 *
359 * @returns IPRT status code of the send.
360 * @param pPktHdr The original packet (for future use).
361 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
362 * with space.
363 */
364static int txsReplySimple(PCTXSPKTHDR pPktHdr, const char *pszOpcode)
365{
366 TXSPKTHDR Pkt;
367 NOREF(pPktHdr);
368 return txsReplyInternal(&Pkt, pszOpcode, 0);
369}
370
371/**
372 * Acknowledges a packet with success.
373 *
374 * @returns IPRT status code of the send.
375 * @param pPktHdr The original packet (for future use).
376 */
377static int txsReplyAck(PCTXSPKTHDR pPktHdr)
378{
379 return txsReplySimple(pPktHdr, "ACK ");
380}
381
382/**
383 * Replies with a failure.
384 *
385 * @returns IPRT status code of the send.
386 * @param pPktHdr The original packet (for future use).
387 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
388 * with space.
389 * @param pszDetailsFmt Longer description of the problem (format
390 * string).
391 * @param va Format arguments.
392 */
393static int txsReplyFailureV(PCTXSPKTHDR pPktHdr, const char *pszOpcode, const char *pszDetailFmt, va_list va)
394{
395 NOREF(pPktHdr);
396 union
397 {
398 TXSPKTHDR Hdr;
399 char ach[256];
400 } uPkt;
401
402 size_t cchDetail = RTStrPrintfV(&uPkt.ach[sizeof(TXSPKTHDR)],
403 sizeof(uPkt) - sizeof(TXSPKTHDR),
404 pszDetailFmt, va);
405 return txsReplyInternal(&uPkt.Hdr, pszOpcode, cchDetail + 1);
406}
407
408/**
409 * Replies with a failure.
410 *
411 * @returns IPRT status code of the send.
412 * @param pPktHdr The original packet (for future use).
413 * @param pszOpcode The status opcode. Exactly 8 chars long, padd
414 * with space.
415 * @param pszDetails Longer description of the problem (format
416 * string).
417 * @param ... Format arguments.
418 */
419static int txsReplyFailure(PCTXSPKTHDR pPktHdr, const char *pszOpcode, const char *pszDetailFmt, ...)
420{
421 va_list va;
422 va_start(va, pszDetailFmt);
423 int rc = txsReplyFailureV(pPktHdr, pszOpcode, pszDetailFmt, va);
424 va_end(va);
425 return rc;
426}
427
428/**
429 * Replies according to the return code.
430 *
431 * @returns IPRT status code of the send.
432 * @param pPktHdr The packet to reply to.
433 * @param rcOperation The status code to report.
434 * @param pszOperationFmt The operation that failed. Typically giving the
435 * function call with important arguments.
436 * @param ... Arguments to the format string.
437 */
438static int txsReplyRC(PCTXSPKTHDR pPktHdr, int rcOperation, const char *pszOperationFmt, ...)
439{
440 if (RT_SUCCESS(rcOperation))
441 return txsReplyAck(pPktHdr);
442
443 char szOperation[128];
444 va_list va;
445 va_start(va, pszOperationFmt);
446 RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
447 va_end(va);
448
449 return txsReplyFailure(pPktHdr, "FAILED ", "%s failed with rc=%Rrc (opcode '%.8s')",
450 szOperation, rcOperation, pPktHdr->achOpcode);
451}
452
453/**
454 * Signal a bad packet minum size.
455 *
456 * @returns IPRT status code of the send.
457 * @param pPktHdr The packet to reply to.
458 * @param cbMin The minimum size.
459 */
460static int txsReplyBadMinSize(PCTXSPKTHDR pPktHdr, size_t cbMin)
461{
462 return txsReplyFailure(pPktHdr, "BAD SIZE", "Expected at least %zu bytes, got %u (opcode '%.8s')",
463 cbMin, pPktHdr->cb, pPktHdr->achOpcode);
464}
465
466/**
467 * Signal a bad packet exact size.
468 *
469 * @returns IPRT status code of the send.
470 * @param pPktHdr The packet to reply to.
471 * @param cb The wanted size.
472 */
473static int txsReplyBadSize(PCTXSPKTHDR pPktHdr, size_t cb)
474{
475 return txsReplyFailure(pPktHdr, "BAD SIZE", "Expected at %zu bytes, got %u (opcode '%.8s')",
476 cb, pPktHdr->cb, pPktHdr->achOpcode);
477}
478
479/**
480 * Deals with a command that isn't implemented yet.
481 * @returns IPRT status code of the send.
482 * @param pPktHdr The packet which opcode isn't implemented.
483 */
484static int txsReplyNotImplemented(PCTXSPKTHDR pPktHdr)
485{
486 return txsReplyFailure(pPktHdr, "NOT IMPL", "Opcode '%.8s' is not implemented", pPktHdr->achOpcode);
487}
488
489/**
490 * Deals with a unknown command.
491 * @returns IPRT status code of the send.
492 * @param pPktHdr The packet to reply to.
493 */
494static int txsReplyUnknown(PCTXSPKTHDR pPktHdr)
495{
496 return txsReplyFailure(pPktHdr, "UNKNOWN ", "Opcode '%.8s' is not known", pPktHdr->achOpcode);
497}
498
499/**
500 * Replaces a variable with its value.
501 *
502 * @returns VINF_SUCCESS or VERR_NO_STR_MEMORY.
503 * @param ppszNew In/Out.
504 * @param pcchNew In/Out. (Messed up on failure.)
505 * @param offVar Variable offset.
506 * @param cchVar Variable length.
507 * @param pszValue The value.
508 * @param cchValue Value length.
509 */
510static int txsReplaceStringVariable(char **ppszNew, size_t *pcchNew, size_t offVar, size_t cchVar,
511 const char *pszValue, size_t cchValue)
512{
513 size_t const cchAfter = *pcchNew - offVar - cchVar;
514 if (cchVar < cchValue)
515 {
516 *pcchNew += cchValue - cchVar;
517 int rc = RTStrRealloc(ppszNew, *pcchNew + 1);
518 if (RT_FAILURE(rc))
519 return rc;
520 }
521
522 char *pszNew = *ppszNew;
523 memmove(&pszNew[offVar + cchValue], &pszNew[offVar + cchVar], cchAfter + 1);
524 memcpy(&pszNew[offVar], pszValue, cchValue);
525 return VINF_SUCCESS;
526}
527
528/**
529 * Replace the variables found in the source string, returning a new string that
530 * lives on the string heap.
531 *
532 * @returns Boolean success indicator. Will reply to the client with all the
533 * gory detail on failure.
534 * @param pPktHdr The packet the string relates to. For replying
535 * on error.
536 * @param pszSrc The source string.
537 * @param ppszNew Where to return the new string.
538 * @param prcSend Where to return the status code of the send on
539 * failure.
540 */
541static int txsReplaceStringVariables(PCTXSPKTHDR pPktHdr, const char *pszSrc, char **ppszNew, int *prcSend)
542{
543 /* Lazy approach that employs memmove. */
544 size_t cchNew = strlen(pszSrc);
545 char *pszNew = RTStrDup(pszSrc);
546 char *pszDollar = pszNew;
547 while ((pszDollar = strchr(pszDollar, '$')) != NULL)
548 {
549 if (pszDollar[1] == '{')
550 {
551 const char *pszEnd = strchr(&pszDollar[2], '}');
552 if (pszEnd)
553 {
554#define IF_VARIABLE_DO(pszDollar, szVarExpr, pszValue) \
555 if ( cchVar == sizeof(szVarExpr) - 1 \
556 && !memcmp(pszDollar, szVarExpr, sizeof(szVarExpr) - 1) ) \
557 { \
558 size_t const cchValue = strlen(pszValue); \
559 rc = txsReplaceStringVariable(&pszNew, &cchNew, offDollar, \
560 sizeof(szVarExpr) - 1, pszValue, cchValue); \
561 offDollar += cchValue; \
562 }
563 int rc;
564 size_t const cchVar = pszEnd - pszDollar + 1; /* includes "${}" */
565 size_t offDollar = pszDollar - pszNew;
566 IF_VARIABLE_DO(pszDollar, "${CDROM}", g_szCdRomPath)
567 else IF_VARIABLE_DO(pszDollar, "${SCRATCH}", g_szScratchPath)
568 else IF_VARIABLE_DO(pszDollar, "${ARCH}", g_szArchShortName)
569 else IF_VARIABLE_DO(pszDollar, "${OS}", g_szOsShortName)
570 else IF_VARIABLE_DO(pszDollar, "${OS.ARCH}", g_szOsDotArchShortName)
571 else IF_VARIABLE_DO(pszDollar, "${OS/ARCH}", g_szOsSlashArchShortName)
572 else IF_VARIABLE_DO(pszDollar, "${EXESUFF}", g_szExeSuff)
573 else IF_VARIABLE_DO(pszDollar, "${SCRIPTSUFF}", g_szScriptSuff)
574 else
575 {
576 RTStrFree(pszNew);
577 *prcSend = txsReplyFailure(pPktHdr, "UNKN VAR", "Unknown variable '%.*s' encountered in '%s'",
578 cchVar, pszDollar, pszSrc);
579 *ppszNew = NULL;
580 return false;
581 }
582 pszDollar = &pszNew[offDollar];
583
584 if (RT_FAILURE(rc))
585 {
586 RTStrFree(pszNew);
587 *prcSend = txsReplyRC(pPktHdr, rc, "RTStrRealloc");
588 *ppszNew = NULL;
589 return false;
590 }
591#undef IF_VARIABLE_DO
592 }
593 }
594 }
595
596 *ppszNew = pszNew;
597 *prcSend = VINF_SUCCESS;
598 return true;
599}
600
601/**
602 * Checks if the string is valid and returns the expanded version.
603 *
604 * @returns true if valid, false if invalid.
605 * @param pPktHdr The packet being unpacked.
606 * @param pszArgName The argument name.
607 * @param psz Pointer to the string within pPktHdr.
608 * @param ppszExp Where to return the expanded string. Must be
609 * freed by calling RTStrFree().
610 * @param ppszNext Where to return the pointer to the next field.
611 * If NULL, then we assume this string is at the
612 * end of the packet and will make sure it has the
613 * advertised length.
614 * @param prcSend Where to return the status code of the send on
615 * failure.
616 */
617static bool txsIsStringValid(PCTXSPKTHDR pPktHdr, const char *pszArgName, const char *psz,
618 char **ppszExp, const char **ppszNext, int *prcSend)
619{
620 *ppszExp = NULL;
621 if (ppszNext)
622 *ppszNext = NULL;
623
624 size_t const off = psz - (const char *)pPktHdr;
625 if (pPktHdr->cb <= off)
626 {
627 *prcSend = txsReplyFailure(pPktHdr, "STR MISS", "Missing string argument '%s' in '%.8s'",
628 pszArgName, pPktHdr->achOpcode);
629 return false;
630 }
631
632 size_t const cchMax = pPktHdr->cb - off;
633 const char *pszEnd = RTStrEnd(psz, cchMax);
634 if (!pszEnd)
635 {
636 *prcSend = txsReplyFailure(pPktHdr, "STR TERM", "The string argument '%s' in '%.8s' is unterminated",
637 pszArgName, pPktHdr->achOpcode);
638 return false;
639 }
640
641 if (!ppszNext && (size_t)(pszEnd - psz) != cchMax - 1)
642 {
643 *prcSend = txsReplyFailure(pPktHdr, "STR SHRT", "The string argument '%s' in '%.8s' is shorter than advertised",
644 pszArgName, pPktHdr->achOpcode);
645 return false;
646 }
647
648 if (!txsReplaceStringVariables(pPktHdr, psz, ppszExp, prcSend))
649 return false;
650 if (ppszNext)
651 *ppszNext = pszEnd + 1;
652 return true;
653}
654
655/**
656 * Validates a packet with a single string after the header.
657 *
658 * @returns true if valid, false if invalid.
659 * @param pPktHdr The packet.
660 * @param pszArgName The argument name.
661 * @param ppszExp Where to return the string pointer. Variables
662 * will be replaced and it must therefore be freed
663 * by calling RTStrFree().
664 * @param prcSend Where to return the status code of the send on
665 * failure.
666 */
667static bool txsIsStringPktValid(PCTXSPKTHDR pPktHdr, const char *pszArgName, char **ppszExp, int *prcSend)
668{
669 if (pPktHdr->cb < sizeof(TXSPKTHDR) + 2)
670 {
671 *ppszExp = NULL;
672 *prcSend = txsReplyBadMinSize(pPktHdr, sizeof(TXSPKTHDR) + 2);
673 return false;
674 }
675
676 return txsIsStringValid(pPktHdr, pszArgName, (const char *)(pPktHdr + 1), ppszExp, NULL, prcSend);
677}
678
679/**
680 * Checks if the two opcodes match.
681 *
682 * @returns true on match, false on mismatch.
683 * @param pPktHdr The packet header.
684 * @param pszOpcode2 The opcode we're comparing with. Does not have
685 * to be the whole 8 chars long.
686 */
687DECLINLINE(bool) txsIsSameOpcode(PCTXSPKTHDR pPktHdr, const char *pszOpcode2)
688{
689 if (pPktHdr->achOpcode[0] != pszOpcode2[0])
690 return false;
691 if (pPktHdr->achOpcode[1] != pszOpcode2[1])
692 return false;
693
694 unsigned i = 2;
695 while ( i < RT_SIZEOFMEMB(TXSPKTHDR, achOpcode)
696 && pszOpcode2[i] != '\0')
697 {
698 if (pPktHdr->achOpcode[i] != pszOpcode2[i])
699 break;
700 i++;
701 }
702
703 if ( i < RT_SIZEOFMEMB(TXSPKTHDR, achOpcode)
704 && pszOpcode2[i] == '\0')
705 {
706 while ( i < RT_SIZEOFMEMB(TXSPKTHDR, achOpcode)
707 && pPktHdr->achOpcode[i] == ' ')
708 i++;
709 }
710
711 return i == RT_SIZEOFMEMB(TXSPKTHDR, achOpcode);
712}
713
714/**
715 * Used by txsDoGetFile to wait for a reply ACK from the client.
716 *
717 * @returns VINF_SUCCESS on ACK, VERR_GENERAL_FAILURE on NACK,
718 * VERR_NET_NOT_CONNECTED on unknown response (sending a bable reply),
719 * or whatever txsRecvPkt returns.
720 * @param pPktHdr The original packet (for future use).
721 */
722static int txsWaitForAck(PCTXSPKTHDR pPktHdr)
723{
724 NOREF(pPktHdr);
725 /** @todo timeout? */
726 PTXSPKTHDR pReply;
727 int rc = txsRecvPkt(&pReply, false /*fAutoRetryOnFailure*/);
728 if (RT_SUCCESS(rc))
729 {
730 if (txsIsSameOpcode(pReply, "ACK"))
731 rc = VINF_SUCCESS;
732 else if (txsIsSameOpcode(pReply, "NACK"))
733 rc = VERR_GENERAL_FAILURE;
734 else
735 {
736 txsReplyBabble("BABBLE ");
737 rc = VERR_NET_NOT_CONNECTED;
738 }
739 RTMemFree(pReply);
740 }
741 return rc;
742}
743
744#ifndef RT_OS_WINDOWS
745/**
746 * Unpacks a tar file.
747 *
748 * @returns IPRT status code from send.
749 * @param pPktHdr The unpack file packet.
750 */
751static int txsDoUnpackFile(PCTXSPKTHDR pPktHdr)
752{
753 int rc;
754 char *pszFile = NULL;
755 char *pszDirectory = NULL;
756
757 /* Packet cursor. */
758 const char *pchEnd = (const char *)pPktHdr + pPktHdr->cb;
759 const char *pch = (const char *)(pPktHdr + 1);
760
761 if (txsIsStringValid(pPktHdr, "file", pch, &pszFile, &pch, &rc))
762 {
763 if (txsIsStringValid(pPktHdr, "directory", pch, &pszDirectory, &pch, &rc))
764 {
765 char *pszSuff = RTPathSuffix(pszFile);
766
767 const char *apszArgs[7];
768 unsigned cArgs = 0;
769
770 apszArgs[cArgs++] = "RTTar";
771 apszArgs[cArgs++] = "--extract";
772
773 apszArgs[cArgs++] = "--file";
774 apszArgs[cArgs++] = pszFile;
775
776 apszArgs[cArgs++] = "--directory";
777 apszArgs[cArgs++] = pszDirectory;
778
779 if ( pszSuff
780 && ( !RTStrICmp(pszSuff, ".gz")
781 || !RTStrICmp(pszSuff, ".tgz")))
782 apszArgs[cArgs++] = "--gunzip";
783
784 RTEXITCODE rcExit = RTZipTarCmd(cArgs, (char **)apszArgs);
785 if (rcExit != RTEXITCODE_SUCCESS)
786 rc = VERR_GENERAL_FAILURE; /** @todo proper return code. */
787 else
788 rc = VINF_SUCCESS;
789
790 rc = txsReplyRC(pPktHdr, rc, "RTZipTarCmd(\"%s\",\"%s\")",
791 pszFile, pszDirectory);
792
793 RTStrFree(pszDirectory);
794 }
795 RTStrFree(pszFile);
796 }
797
798 return rc;
799}
800#endif
801
802/**
803 * Downloads a file to the client.
804 *
805 * The transfer sends a stream of DATA packets (0 or more) and ends it all with
806 * a ACK packet. If an error occurs, a FAILURE packet is sent and the transfer
807 * aborted.
808 *
809 * @returns IPRT status code from send.
810 * @param pPktHdr The get file packet.
811 */
812static int txsDoGetFile(PCTXSPKTHDR pPktHdr)
813{
814 int rc;
815 char *pszPath;
816 if (!txsIsStringPktValid(pPktHdr, "file", &pszPath, &rc))
817 return rc;
818
819 RTFILE hFile;
820 rc = RTFileOpen(&hFile, pszPath, RTFILE_O_READ | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN);
821 if (RT_SUCCESS(rc))
822 {
823 uint32_t uMyCrc32 = RTCrc32Start();
824 for (;;)
825 {
826 struct
827 {
828 TXSPKTHDR Hdr;
829 uint32_t uCrc32;
830 char ab[_64K];
831 char abPadding[TXSPKT_ALIGNMENT];
832 } Pkt;
833 size_t cbRead;
834 rc = RTFileRead(hFile, &Pkt.ab[0], _64K, &cbRead);
835 if (RT_FAILURE(rc) || cbRead == 0)
836 {
837 if (rc == VERR_EOF || (RT_SUCCESS(rc) && cbRead == 0))
838 {
839 Pkt.uCrc32 = RTCrc32Finish(uMyCrc32);
840 rc = txsReplyInternal(&Pkt.Hdr, "DATA EOF", sizeof(uint32_t));
841 if (RT_SUCCESS(rc))
842 rc = txsWaitForAck(&Pkt.Hdr);
843 }
844 else
845 rc = txsReplyRC(pPktHdr, rc, "RTFileRead");
846 break;
847 }
848
849 uMyCrc32 = RTCrc32Process(uMyCrc32, &Pkt.ab[0], cbRead);
850 Pkt.uCrc32 = RTCrc32Finish(uMyCrc32);
851 rc = txsReplyInternal(&Pkt.Hdr, "DATA ", cbRead + sizeof(uint32_t));
852 if (RT_FAILURE(rc))
853 break;
854 rc = txsWaitForAck(&Pkt.Hdr);
855 if (RT_FAILURE(rc))
856 break;
857 }
858
859 RTFileClose(hFile);
860 }
861 else
862 rc = txsReplyRC(pPktHdr, rc, "RTFileOpen(,\"%s\",)", pszPath);
863
864 RTStrFree(pszPath);
865 return rc;
866}
867
868/**
869 * Uploads a file from the client.
870 *
871 * The transfer sends a stream of DATA packets (0 or more) and ends it all with
872 * a DATA EOF packet. We ACK each of these, so that if a write error occurs we
873 * can abort the transfer straight away.
874 *
875 * @returns IPRT status code from send.
876 * @param pPktHdr The put file packet.
877 */
878static int txsDoPutFile(PCTXSPKTHDR pPktHdr)
879{
880 int rc;
881 char *pszPath;
882 if (!txsIsStringPktValid(pPktHdr, "file", &pszPath, &rc))
883 return rc;
884
885 RTFILE hFile;
886 rc = RTFileOpen(&hFile, pszPath, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE);
887 if (RT_SUCCESS(rc))
888 {
889 bool fSuccess = false;
890 rc = txsReplyAck(pPktHdr);
891 if (RT_SUCCESS(rc))
892 {
893 /*
894 * Read client command packets and process them.
895 */
896 uint32_t uMyCrc32 = RTCrc32Start();
897 for (;;)
898 {
899 PTXSPKTHDR pDataPktHdr;
900 rc = txsRecvPkt(&pDataPktHdr, false /*fAutoRetryOnFailure*/);
901 if (RT_FAILURE(rc))
902 break;
903
904 if (txsIsSameOpcode(pDataPktHdr, "DATA"))
905 {
906 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(uint32_t);
907 if (pDataPktHdr->cb >= cbMin)
908 {
909 size_t cbData = pDataPktHdr->cb - cbMin;
910 const void *pvData = (const char *)pDataPktHdr + cbMin;
911 uint32_t uCrc32 = *(uint32_t const *)(pDataPktHdr + 1);
912
913 uMyCrc32 = RTCrc32Process(uMyCrc32, pvData, cbData);
914 if (RTCrc32Finish(uMyCrc32) == uCrc32)
915 {
916 rc = RTFileWrite(hFile, pvData, cbData, NULL);
917 if (RT_SUCCESS(rc))
918 {
919 rc = txsReplyAck(pDataPktHdr);
920 RTMemFree(pDataPktHdr);
921 continue;
922 }
923
924 rc = txsReplyRC(pDataPktHdr, rc, "RTFileWrite");
925 }
926 else
927 rc = txsReplyFailure(pDataPktHdr, "BAD DCRC", "mycrc=%#x your=%#x", uMyCrc32, uCrc32);
928 }
929 else
930 rc = txsReplyBadMinSize(pPktHdr, cbMin);
931 }
932 else if (txsIsSameOpcode(pDataPktHdr, "DATA EOF"))
933 {
934 if (pDataPktHdr->cb == sizeof(TXSPKTHDR) + sizeof(uint32_t))
935 {
936 uint32_t uCrc32 = *(uint32_t const *)(pDataPktHdr + 1);
937 if (RTCrc32Finish(uMyCrc32) == uCrc32)
938 {
939 rc = txsReplyAck(pDataPktHdr);
940 fSuccess = RT_SUCCESS(rc);
941 }
942 else
943 rc = txsReplyFailure(pDataPktHdr, "BAD DCRC", "mycrc=%#x your=%#x", uMyCrc32, uCrc32);
944 }
945 else
946 rc = txsReplyAck(pDataPktHdr);
947 }
948 else if (txsIsSameOpcode(pDataPktHdr, "ABORT"))
949 rc = txsReplyAck(pDataPktHdr);
950 else
951 rc = txsReplyFailure(pDataPktHdr, "UNKNOWN ", "Opcode '%.8s' is not known or not recognized during PUT FILE", pDataPktHdr->achOpcode);
952 RTMemFree(pDataPktHdr);
953 break;
954 }
955 }
956
957 RTFileClose(hFile);
958
959 /*
960 * Delete the file on failure.
961 */
962 if (!fSuccess)
963 RTFileDelete(pszPath);
964 }
965 else
966 rc = txsReplyRC(pPktHdr, rc, "RTFileOpen(,\"%s\",)", pszPath);
967
968 RTStrFree(pszPath);
969 return rc;
970}
971
972/**
973 * List the entries in the specified directory.
974 *
975 * @returns IPRT status code from send.
976 * @param pPktHdr The list packet.
977 */
978static int txsDoList(PCTXSPKTHDR pPktHdr)
979{
980 int rc;
981 char *pszPath;
982 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
983 return rc;
984
985 rc = txsReplyNotImplemented(pPktHdr);
986
987 RTStrFree(pszPath);
988 return rc;
989}
990
991
992/**
993 * Get info about a file system object, following all but the symbolic links
994 * except in the final path component.
995 *
996 * @returns IPRT status code from send.
997 * @param pPktHdr The lstat packet.
998 */
999static int txsDoLStat(PCTXSPKTHDR pPktHdr)
1000{
1001 int rc;
1002 char *pszPath;
1003 if (!txsIsStringPktValid(pPktHdr, "path", &pszPath, &rc))
1004 return rc;
1005
1006 RTFSOBJINFO Info;
1007 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_UNIX, RTPATH_F_ON_LINK);
1008 if (RT_SUCCESS(rc))
1009 /** @todo figure out how to format the return buffer here. */
1010 rc = txsReplyNotImplemented(pPktHdr);
1011 else
1012 rc = txsReplyRC(pPktHdr, rc, "RTPathQueryInfoEx(\"%s\",,UNIX,ON_LINK)", pszPath);
1013
1014 RTStrFree(pszPath);
1015 return rc;
1016}
1017
1018/**
1019 * Get info about a file system object, following all symbolic links.
1020 *
1021 * @returns IPRT status code from send.
1022 * @param pPktHdr The stat packet.
1023 */
1024static int txsDoStat(PCTXSPKTHDR pPktHdr)
1025{
1026 int rc;
1027 char *pszPath;
1028 if (!txsIsStringPktValid(pPktHdr, "path", &pszPath, &rc))
1029 return rc;
1030
1031 RTFSOBJINFO Info;
1032 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_UNIX, RTPATH_F_FOLLOW_LINK);
1033 if (RT_SUCCESS(rc))
1034 /** @todo figure out how to format the return buffer here. */
1035 rc = txsReplyNotImplemented(pPktHdr);
1036 else
1037 rc = txsReplyRC(pPktHdr, rc, "RTPathQueryInfoEx(\"%s\",,UNIX,FOLLOW_LINK)", pszPath);
1038
1039 RTStrFree(pszPath);
1040 return rc;
1041}
1042
1043/**
1044 * Checks if the specified path is a symbolic link.
1045 *
1046 * @returns IPRT status code from send.
1047 * @param pPktHdr The issymlnk packet.
1048 */
1049static int txsDoIsSymlnk(PCTXSPKTHDR pPktHdr)
1050{
1051 int rc;
1052 char *pszPath;
1053 if (!txsIsStringPktValid(pPktHdr, "symlink", &pszPath, &rc))
1054 return rc;
1055
1056 RTFSOBJINFO Info;
1057 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1058 if (RT_SUCCESS(rc) && RTFS_IS_SYMLINK(Info.Attr.fMode))
1059 rc = txsReplySimple(pPktHdr, "TRUE ");
1060 else
1061 rc = txsReplySimple(pPktHdr, "FALSE ");
1062
1063 RTStrFree(pszPath);
1064 return rc;
1065}
1066
1067/**
1068 * Checks if the specified path is a file or not.
1069 *
1070 * If the final path element is a symbolic link to a file, we'll return
1071 * FALSE.
1072 *
1073 * @returns IPRT status code from send.
1074 * @param pPktHdr The isfile packet.
1075 */
1076static int txsDoIsFile(PCTXSPKTHDR pPktHdr)
1077{
1078 int rc;
1079 char *pszPath;
1080 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1081 return rc;
1082
1083 RTFSOBJINFO Info;
1084 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1085 if (RT_SUCCESS(rc) && RTFS_IS_FILE(Info.Attr.fMode))
1086 rc = txsReplySimple(pPktHdr, "TRUE ");
1087 else
1088 rc = txsReplySimple(pPktHdr, "FALSE ");
1089
1090 RTStrFree(pszPath);
1091 return rc;
1092}
1093
1094/**
1095 * Checks if the specified path is a directory or not.
1096 *
1097 * If the final path element is a symbolic link to a directory, we'll return
1098 * FALSE.
1099 *
1100 * @returns IPRT status code from send.
1101 * @param pPktHdr The isdir packet.
1102 */
1103static int txsDoIsDir(PCTXSPKTHDR pPktHdr)
1104{
1105 int rc;
1106 char *pszPath;
1107 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1108 return rc;
1109
1110 RTFSOBJINFO Info;
1111 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1112 if (RT_SUCCESS(rc) && RTFS_IS_DIRECTORY(Info.Attr.fMode))
1113 rc = txsReplySimple(pPktHdr, "TRUE ");
1114 else
1115 rc = txsReplySimple(pPktHdr, "FALSE ");
1116
1117 RTStrFree(pszPath);
1118 return rc;
1119}
1120
1121/**
1122 * Changes the group of a file, directory of symbolic link.
1123 *
1124 * @returns IPRT status code from send.
1125 * @param pPktHdr The chmod packet.
1126 */
1127static int txsDoChGrp(PCTXSPKTHDR pPktHdr)
1128{
1129 return txsReplyNotImplemented(pPktHdr);
1130}
1131
1132/**
1133 * Changes the owner of a file, directory of symbolic link.
1134 *
1135 * @returns IPRT status code from send.
1136 * @param pPktHdr The chmod packet.
1137 */
1138static int txsDoChOwn(PCTXSPKTHDR pPktHdr)
1139{
1140 return txsReplyNotImplemented(pPktHdr);
1141}
1142
1143/**
1144 * Changes the mode of a file or directory.
1145 *
1146 * @returns IPRT status code from send.
1147 * @param pPktHdr The chmod packet.
1148 */
1149static int txsDoChMod(PCTXSPKTHDR pPktHdr)
1150{
1151 return txsReplyNotImplemented(pPktHdr);
1152}
1153
1154/**
1155 * Removes a directory tree.
1156 *
1157 * @returns IPRT status code from send.
1158 * @param pPktHdr The rmtree packet.
1159 */
1160static int txsDoRmTree(PCTXSPKTHDR pPktHdr)
1161{
1162 int rc;
1163 char *pszPath;
1164 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1165 return rc;
1166
1167 rc = RTDirRemoveRecursive(pszPath, 0 /*fFlags*/);
1168
1169 rc = txsReplyRC(pPktHdr, rc, "RTDirRemoveRecusive(\"%s\",0)", pszPath);
1170 RTStrFree(pszPath);
1171 return rc;
1172}
1173
1174/**
1175 * Removes a symbolic link.
1176 *
1177 * @returns IPRT status code from send.
1178 * @param pPktHdr The rmsymlink packet.
1179 */
1180static int txsDoRmSymlnk(PCTXSPKTHDR pPktHdr)
1181{
1182 int rc;
1183 char *pszPath;
1184 if (!txsIsStringPktValid(pPktHdr, "symlink", &pszPath, &rc))
1185 return rc;
1186
1187 rc = VERR_NOT_IMPLEMENTED; /// @todo RTSymlinkDelete(pszPath);
1188
1189 rc = txsReplyRC(pPktHdr, rc, "RTSymlinkDelete(\"%s\")", pszPath);
1190 RTStrFree(pszPath);
1191 return rc;
1192}
1193
1194/**
1195 * Removes a file.
1196 *
1197 * @returns IPRT status code from send.
1198 * @param pPktHdr The rmfile packet.
1199 */
1200static int txsDoRmFile(PCTXSPKTHDR pPktHdr)
1201{
1202 int rc;
1203 char *pszPath;
1204 if (!txsIsStringPktValid(pPktHdr, "file", &pszPath, &rc))
1205 return rc;
1206
1207 rc = RTFileDelete(pszPath);
1208
1209 rc = txsReplyRC(pPktHdr, rc, "RTFileDelete(\"%s\")", pszPath);
1210 RTStrFree(pszPath);
1211 return rc;
1212}
1213
1214/**
1215 * Removes a directory.
1216 *
1217 * @returns IPRT status code from send.
1218 * @param pPktHdr The rmdir packet.
1219 */
1220static int txsDoRmDir(PCTXSPKTHDR pPktHdr)
1221{
1222 int rc;
1223 char *pszPath;
1224 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1225 return rc;
1226
1227 rc = RTDirRemove(pszPath);
1228
1229 rc = txsReplyRC(pPktHdr, rc, "RTDirRemove(\"%s\")", pszPath);
1230 RTStrFree(pszPath);
1231 return rc;
1232}
1233
1234/**
1235 * Creates a symbolic link.
1236 *
1237 * @returns IPRT status code from send.
1238 * @param pPktHdr The mksymlnk packet.
1239 */
1240static int txsDoMkSymlnk(PCTXSPKTHDR pPktHdr)
1241{
1242 return txsReplyNotImplemented(pPktHdr);
1243}
1244
1245/**
1246 * Creates a directory and all its parents.
1247 *
1248 * @returns IPRT status code from send.
1249 * @param pPktHdr The mkdir -p packet.
1250 */
1251static int txsDoMkDrPath(PCTXSPKTHDR pPktHdr)
1252{
1253 /* The same format as the MKDIR command. */
1254 if (pPktHdr->cb < sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2)
1255 return txsReplyBadMinSize(pPktHdr, sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2);
1256
1257 int rc;
1258 char *pszPath;
1259 if (!txsIsStringValid(pPktHdr, "dir", (const char *)(pPktHdr + 1) + sizeof(RTFMODE), &pszPath, NULL, &rc))
1260 return rc;
1261
1262 RTFMODE fMode = *(RTFMODE const *)(pPktHdr + 1);
1263 rc = RTDirCreateFullPath(pszPath, fMode);
1264
1265 rc = txsReplyRC(pPktHdr, rc, "RTDirCreateFullPath(\"%s\", %#x)", pszPath, fMode);
1266 RTStrFree(pszPath);
1267 return rc;
1268}
1269
1270/**
1271 * Creates a directory.
1272 *
1273 * @returns IPRT status code from send.
1274 * @param pPktHdr The mkdir packet.
1275 */
1276static int txsDoMkDir(PCTXSPKTHDR pPktHdr)
1277{
1278 /* After the packet header follows a mode mask and the remainder of
1279 the packet is the zero terminated directory name. */
1280 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2;
1281 if (pPktHdr->cb < cbMin)
1282 return txsReplyBadMinSize(pPktHdr, cbMin);
1283
1284 int rc;
1285 char *pszPath;
1286 if (!txsIsStringValid(pPktHdr, "dir", (const char *)(pPktHdr + 1) + sizeof(RTFMODE), &pszPath, NULL, &rc))
1287 return rc;
1288
1289 RTFMODE fMode = *(RTFMODE const *)(pPktHdr + 1);
1290 rc = RTDirCreate(pszPath, fMode, 0);
1291
1292 rc = txsReplyRC(pPktHdr, rc, "RTDirCreate(\"%s\", %#x)", pszPath, fMode);
1293 RTStrFree(pszPath);
1294 return rc;
1295}
1296
1297/**
1298 * Cleans up the scratch area.
1299 *
1300 * @returns IPRT status code from send.
1301 * @param pPktHdr The shutdown packet.
1302 */
1303static int txsDoCleanup(PCTXSPKTHDR pPktHdr)
1304{
1305 int rc = RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
1306 return txsReplyRC(pPktHdr, rc, "RTDirRemoveRecursive(\"%s\", CONTENT_ONLY)", g_szScratchPath);
1307}
1308
1309/**
1310 * Ejects the specified DVD/CD drive.
1311 *
1312 * @returns IPRT status code from send.
1313 * @param pPktHdr The eject packet.
1314 */
1315static int txsDoCdEject(PCTXSPKTHDR pPktHdr)
1316{
1317 /* After the packet header follows a uint32_t ordinal. */
1318 size_t const cbExpected = sizeof(TXSPKTHDR) + sizeof(uint32_t);
1319 if (pPktHdr->cb != cbExpected)
1320 return txsReplyBadSize(pPktHdr, cbExpected);
1321 uint32_t iOrdinal = *(uint32_t const *)(pPktHdr + 1);
1322
1323 RTCDROM hCdrom;
1324 int rc = RTCdromOpenByOrdinal(iOrdinal, RTCDROM_O_CONTROL, &hCdrom);
1325 if (RT_FAILURE(rc))
1326 return txsReplyRC(pPktHdr, rc, "RTCdromOpenByOrdinal(%u, RTCDROM_O_CONTROL, )", iOrdinal);
1327 rc = RTCdromEject(hCdrom, true /*fForce*/);
1328 RTCdromRelease(hCdrom);
1329
1330 return txsReplyRC(pPktHdr, rc, "RTCdromEject(ord=%u, fForce=true)", iOrdinal);
1331}
1332
1333/**
1334 * Common worker for txsDoShutdown and txsDoReboot.
1335 *
1336 * @returns IPRT status code from send.
1337 * @param pPktHdr The reboot packet.
1338 * @param fAction Which action to take.
1339 */
1340static int txsCommonShutdownReboot(PCTXSPKTHDR pPktHdr, uint32_t fAction)
1341{
1342 /*
1343 * We ACK the reboot & shutdown before actually performing them, then we
1344 * terminate the transport layer.
1345 *
1346 * This is to make sure the client isn't stuck with a dead connection. The
1347 * transport layer termination also make sure we won't accept new
1348 * connections in case the client is too eager to reconnect to a rebooted
1349 * test victim. On the down side, we cannot easily report RTSystemShutdown
1350 * failures failures this way. But the client can kind of figure it out by
1351 * reconnecting and seeing that our UUID was unchanged.
1352 */
1353 int rc;
1354 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1355 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1356 g_pTransport->pfnNotifyReboot();
1357 rc = txsReplyAck(pPktHdr);
1358 RTThreadSleep(2560); /* fudge factor */
1359 g_pTransport->pfnTerm();
1360
1361 /*
1362 * Do the job, if it fails we'll restart the transport layer.
1363 */
1364#if 0
1365 rc = VINF_SUCCESS;
1366#else
1367 rc = RTSystemShutdown(0 /*cMsDelay*/,
1368 fAction | RTSYSTEM_SHUTDOWN_PLANNED | RTSYSTEM_SHUTDOWN_FORCE,
1369 "Test Execution Service");
1370#endif
1371 if (RT_SUCCESS(rc))
1372 {
1373 RTMsgInfo(fAction == RTSYSTEM_SHUTDOWN_REBOOT ? "Rebooting...\n" : "Shutting down...\n");
1374 g_fTerminate = true;
1375 }
1376 else
1377 {
1378 RTMsgError("RTSystemShutdown w/ fAction=%#x failed: %Rrc", fAction, rc);
1379
1380 int rc2 = g_pTransport->pfnInit();
1381 if (RT_FAILURE(rc2))
1382 {
1383 g_fTerminate = true;
1384 rc = rc2;
1385 }
1386 }
1387 return rc;
1388}
1389
1390/**
1391 * Shuts down the machine, powering it off if possible.
1392 *
1393 * @returns IPRT status code from send.
1394 * @param pPktHdr The shutdown packet.
1395 */
1396static int txsDoShutdown(PCTXSPKTHDR pPktHdr)
1397{
1398 return txsCommonShutdownReboot(pPktHdr, RTSYSTEM_SHUTDOWN_POWER_OFF_HALT);
1399}
1400
1401/**
1402 * Reboots the machine.
1403 *
1404 * @returns IPRT status code from send.
1405 * @param pPktHdr The reboot packet.
1406 */
1407static int txsDoReboot(PCTXSPKTHDR pPktHdr)
1408{
1409 return txsCommonShutdownReboot(pPktHdr, RTSYSTEM_SHUTDOWN_REBOOT);
1410}
1411
1412/**
1413 * Verifies and acknowledges a "UUID" request.
1414 *
1415 * @returns IPRT status code.
1416 * @param pPktHdr The howdy packet.
1417 */
1418static int txsDoUuid(PCTXSPKTHDR pPktHdr)
1419{
1420 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1421 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1422
1423 struct
1424 {
1425 TXSPKTHDR Hdr;
1426 char szUuid[RTUUID_STR_LENGTH];
1427 char abPadding[TXSPKT_ALIGNMENT];
1428 } Pkt;
1429
1430 int rc = RTUuidToStr(&g_InstanceUuid, Pkt.szUuid, sizeof(Pkt.szUuid));
1431 if (RT_FAILURE(rc))
1432 return txsReplyRC(pPktHdr, rc, "RTUuidToStr");
1433 return txsReplyInternal(&Pkt.Hdr, "ACK UUID", strlen(Pkt.szUuid) + 1);
1434}
1435
1436/**
1437 * Verifies and acknowledges a "BYE" request.
1438 *
1439 * @returns IPRT status code.
1440 * @param pPktHdr The howdy packet.
1441 */
1442static int txsDoBye(PCTXSPKTHDR pPktHdr)
1443{
1444 int rc;
1445 if (pPktHdr->cb == sizeof(TXSPKTHDR))
1446 rc = txsReplyAck(pPktHdr);
1447 else
1448 rc = txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1449 g_pTransport->pfnNotifyBye();
1450 return rc;
1451}
1452
1453/**
1454 * Verifies and acknowledges a "HOWDY" request.
1455 *
1456 * @returns IPRT status code.
1457 * @param pPktHdr The howdy packet.
1458 */
1459static int txsDoHowdy(PCTXSPKTHDR pPktHdr)
1460{
1461 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1462 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1463 int rc = txsReplyAck(pPktHdr);
1464 if (RT_SUCCESS(rc))
1465 {
1466 g_pTransport->pfnNotifyHowdy();
1467 RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
1468 }
1469 return rc;
1470}
1471
1472/**
1473 * Replies according to the return code.
1474 *
1475 * @returns rcOperation and pTxsExec->rcReplySend.
1476 * @param pTxsExec The TXSEXEC instance.
1477 * @param rcOperation The status code to report.
1478 * @param pszOperationFmt The operation that failed. Typically giving the
1479 * function call with important arguments.
1480 * @param ... Arguments to the format string.
1481 */
1482static int txsExecReplyRC(PTXSEXEC pTxsExec, int rcOperation, const char *pszOperationFmt, ...)
1483{
1484 AssertStmt(RT_FAILURE_NP(rcOperation), rcOperation = VERR_IPE_UNEXPECTED_INFO_STATUS);
1485
1486 char szOperation[128];
1487 va_list va;
1488 va_start(va, pszOperationFmt);
1489 RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
1490 va_end(va);
1491
1492 pTxsExec->rcReplySend = txsReplyFailure(pTxsExec->pPktHdr, "FAILED ",
1493 "%s failed with rc=%Rrc (opcode '%.8s')",
1494 szOperation, rcOperation, pTxsExec->pPktHdr->achOpcode);
1495 return rcOperation;
1496}
1497
1498
1499/**
1500 * Sends the process exit status reply to the TXS client.
1501 *
1502 * @returns IPRT status code of the send.
1503 * @param pTxsExec The TXSEXEC instance.
1504 * @param fProcessAlive Whether the process is still alive (against our
1505 * will).
1506 * @param fProcessTimedOut Whether the process timed out.
1507 * @param MsProcessKilled When the process was killed, UINT64_MAX if not.
1508 */
1509static int txsExecSendExitStatus(PTXSEXEC pTxsExec, bool fProcessAlive, bool fProcessTimedOut, uint64_t MsProcessKilled)
1510{
1511 int rc;
1512 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
1513 {
1514 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC TOK");
1515 if (g_fDisplayOutput)
1516 RTPrintf("txs: Process timed out and was killed\n");
1517 }
1518 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
1519 {
1520 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC TOA");
1521 if (g_fDisplayOutput)
1522 RTPrintf("txs: Process timed out and was not killed successfully\n");
1523 }
1524 else if (g_fTerminate && (fProcessAlive || MsProcessKilled != UINT64_MAX))
1525 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC DWN");
1526 else if (fProcessAlive)
1527 {
1528 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "Doofus! process is alive when it should not");
1529 AssertFailed();
1530 }
1531 else if (MsProcessKilled != UINT64_MAX)
1532 {
1533 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "Doofus! process has been killed when it should not");
1534 AssertFailed();
1535 }
1536 else if ( pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL
1537 && pTxsExec->ProcessStatus.iStatus == 0)
1538 {
1539 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC OK ");
1540 if (g_fDisplayOutput)
1541 RTPrintf("txs: Process exited with status: 0\n");
1542 }
1543 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
1544 {
1545 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC NOK", "%d", pTxsExec->ProcessStatus.iStatus);
1546 if (g_fDisplayOutput)
1547 RTPrintf("txs: Process exited with status: %d\n", pTxsExec->ProcessStatus.iStatus);
1548 }
1549 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
1550 {
1551 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC SIG", "%d", pTxsExec->ProcessStatus.iStatus);
1552 if (g_fDisplayOutput)
1553 RTPrintf("txs: Process exited with status: signal %d\n", pTxsExec->ProcessStatus.iStatus);
1554 }
1555 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
1556 {
1557 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC ABD", "");
1558 if (g_fDisplayOutput)
1559 RTPrintf("txs: Process exited with status: abend\n");
1560 }
1561 else
1562 {
1563 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "enmReason=%d iStatus=%d",
1564 pTxsExec->ProcessStatus.enmReason, pTxsExec->ProcessStatus.iStatus);
1565 AssertMsgFailed(("enmReason=%d iStatus=%d", pTxsExec->ProcessStatus.enmReason, pTxsExec->ProcessStatus.iStatus));
1566 }
1567 return rc;
1568}
1569
1570/**
1571 * Handle pending output data or error on standard out, standard error or the
1572 * test pipe.
1573 *
1574 * @returns IPRT status code from client send.
1575 * @param hPollSet The polling set.
1576 * @param fPollEvt The event mask returned by RTPollNoResume.
1577 * @param phPipeR The pipe handle.
1578 * @param pu32Crc The current CRC-32 of the stream. (In/Out)
1579 * @param enmHndId The handle ID.
1580 * @param pszOpcode The opcode for the data upload.
1581 *
1582 * @todo Put the last 4 parameters into a struct!
1583 */
1584static int txsDoExecHlpHandleOutputEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phPipeR,
1585 uint32_t *puCrc32, TXSEXECHNDID enmHndId, const char *pszOpcode)
1586{
1587 Log(("txsDoExecHlpHandleOutputEvent: %s fPollEvt=%#x\n", pszOpcode, fPollEvt));
1588
1589 /*
1590 * Try drain the pipe before acting on any errors.
1591 */
1592 int rc = VINF_SUCCESS;
1593 struct
1594 {
1595 TXSPKTHDR Hdr;
1596 uint32_t uCrc32;
1597 char abBuf[_64K];
1598 char abPadding[TXSPKT_ALIGNMENT];
1599 } Pkt;
1600 size_t cbRead;
1601 int rc2 = RTPipeRead(*phPipeR, Pkt.abBuf, sizeof(Pkt.abBuf), &cbRead);
1602 if (RT_SUCCESS(rc2) && cbRead)
1603 {
1604 Log(("Crc32=%#x ", *puCrc32));
1605 *puCrc32 = RTCrc32Process(*puCrc32, Pkt.abBuf, cbRead);
1606 Log(("cbRead=%#x Crc32=%#x \n", cbRead, *puCrc32));
1607 Pkt.uCrc32 = RTCrc32Finish(*puCrc32);
1608 if (g_fDisplayOutput)
1609 {
1610 if (enmHndId == TXSEXECHNDID_STDOUT)
1611 RTStrmPrintf(g_pStdErr, "%.*s", cbRead, Pkt.abBuf);
1612 else if (enmHndId == TXSEXECHNDID_STDERR)
1613 RTStrmPrintf(g_pStdErr, "%.*s", cbRead, Pkt.abBuf);
1614 }
1615
1616 rc = txsReplyInternal(&Pkt.Hdr, pszOpcode, cbRead + sizeof(uint32_t));
1617
1618 /* Make sure we go another poll round in case there was too much data
1619 for the buffer to hold. */
1620 fPollEvt &= RTPOLL_EVT_ERROR;
1621 }
1622 else if (RT_FAILURE(rc2))
1623 {
1624 fPollEvt |= RTPOLL_EVT_ERROR;
1625 AssertMsg(rc2 == VERR_BROKEN_PIPE, ("%Rrc\n", rc));
1626 }
1627
1628 /*
1629 * If an error was raised signalled,
1630 */
1631 if (fPollEvt & RTPOLL_EVT_ERROR)
1632 {
1633 rc2 = RTPollSetRemove(hPollSet, enmHndId);
1634 AssertRC(rc2);
1635
1636 rc2 = RTPipeClose(*phPipeR);
1637 AssertRC(rc2);
1638 *phPipeR = NIL_RTPIPE;
1639 }
1640 return rc;
1641}
1642
1643/**
1644 * Try write some more data to the standard input of the child.
1645 *
1646 * @returns IPRT status code.
1647 * @param pStdInBuf The standard input buffer.
1648 * @param hStdInW The standard input pipe.
1649 */
1650static int txsDoExecHlpWriteStdIn(PTXSEXECSTDINBUF pStdInBuf, RTPIPE hStdInW)
1651{
1652 size_t cbToWrite = pStdInBuf->cb - pStdInBuf->off;
1653 size_t cbWritten;
1654 int rc = RTPipeWrite(hStdInW, &pStdInBuf->pch[pStdInBuf->off], cbToWrite, &cbWritten);
1655 if (RT_SUCCESS(rc))
1656 {
1657 Assert(cbWritten == cbToWrite);
1658 pStdInBuf->off += cbWritten;
1659 }
1660 return rc;
1661}
1662
1663/**
1664 * Handle an error event on standard input.
1665 *
1666 * @param hPollSet The polling set.
1667 * @param fPollEvt The event mask returned by RTPollNoResume.
1668 * @param phStdInW The standard input pipe handle.
1669 * @param pStdInBuf The standard input buffer.
1670 */
1671static void txsDoExecHlpHandleStdInErrorEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
1672 PTXSEXECSTDINBUF pStdInBuf)
1673{
1674 NOREF(fPollEvt);
1675 int rc2;
1676 if (pStdInBuf->off < pStdInBuf->cb)
1677 {
1678 rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1679 AssertRC(rc2);
1680 }
1681
1682 rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN);
1683 AssertRC(rc2);
1684
1685 rc2 = RTPipeClose(*phStdInW);
1686 AssertRC(rc2);
1687 *phStdInW = NIL_RTPIPE;
1688
1689 RTMemFree(pStdInBuf->pch);
1690 pStdInBuf->pch = NULL;
1691 pStdInBuf->off = 0;
1692 pStdInBuf->cb = 0;
1693 pStdInBuf->cbAllocated = 0;
1694 pStdInBuf->fBitBucket = true;
1695}
1696
1697/**
1698 * Handle an event indicating we can write to the standard input pipe of the
1699 * child process.
1700 *
1701 * @param hPollSet The polling set.
1702 * @param fPollEvt The event mask returned by RTPollNoResume.
1703 * @param phStdInW The standard input pipe.
1704 * @param pStdInBuf The standard input buffer.
1705 */
1706static void txsDoExecHlpHandleStdInWritableEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
1707 PTXSEXECSTDINBUF pStdInBuf)
1708{
1709 int rc;
1710 if (!(fPollEvt & RTPOLL_EVT_ERROR))
1711 {
1712 rc = txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
1713 if (RT_FAILURE(rc) && rc != VERR_BAD_PIPE)
1714 {
1715 /** @todo do we need to do something about this error condition? */
1716 AssertRC(rc);
1717 }
1718
1719 if (pStdInBuf->off < pStdInBuf->cb)
1720 {
1721 rc = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1722 AssertRC(rc);
1723 }
1724 }
1725 else
1726 txsDoExecHlpHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
1727}
1728
1729/**
1730 * Handle a transport event or successful pfnPollIn() call.
1731 *
1732 * @returns IPRT status code from client send.
1733 * @retval VINF_EOF indicates ABORT command.
1734 *
1735 * @param hPollSet The polling set.
1736 * @param fPollEvt The event mask returned by RTPollNoResume.
1737 * @param idPollHnd The handle ID.
1738 * @param hStdInW The standard input pipe.
1739 * @param pStdInBuf The standard input buffer.
1740 */
1741static int txsDoExecHlpHandleTransportEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, uint32_t idPollHnd,
1742 PRTPIPE phStdInW, PTXSEXECSTDINBUF pStdInBuf)
1743{
1744 /* ASSUMES the transport layer will detect or clear any error condition. */
1745 NOREF(fPollEvt); NOREF(idPollHnd);
1746 Log(("txsDoExecHlpHandleTransportEvent\n"));
1747 /** @todo Use a callback for this case? */
1748
1749 /*
1750 * Read client command packet and process it.
1751 */
1752 /** @todo Sometimes this hangs on windows because there isn't any data pending.
1753 * We probably get woken up at the wrong time or in the wrong way, i.e. RTPoll()
1754 * is busted for sockets.
1755 *
1756 * Temporary workaround: Poll for input before trying to read it. */
1757 if (!g_pTransport->pfnPollIn())
1758 {
1759 Log(("Bad transport event\n"));
1760 RTThreadYield();
1761 return VINF_SUCCESS;
1762 }
1763 PTXSPKTHDR pPktHdr;
1764 int rc = txsRecvPkt(&pPktHdr, false /*fAutoRetryOnFailure*/);
1765 if (RT_FAILURE(rc))
1766 return rc;
1767 Log(("Bad transport event\n"));
1768
1769 /*
1770 * The most common thing here would be a STDIN request with data
1771 * for the child process.
1772 */
1773 if (txsIsSameOpcode(pPktHdr, "STDIN"))
1774 {
1775 if ( !pStdInBuf->fBitBucket
1776 && pPktHdr->cb >= sizeof(TXSPKTHDR) + sizeof(uint32_t))
1777 {
1778 uint32_t uCrc32 = *(uint32_t *)(pPktHdr + 1);
1779 const char *pch = (const char *)(pPktHdr + 1) + sizeof(uint32_t);
1780 size_t cb = pPktHdr->cb - sizeof(TXSPKTHDR) - sizeof(uint32_t);
1781
1782 /* Check the CRC */
1783 pStdInBuf->uCrc32 = RTCrc32Process(pStdInBuf->uCrc32, pch, cb);
1784 if (RTCrc32Finish(pStdInBuf->uCrc32) == uCrc32)
1785 {
1786
1787 /* Rewind the buffer if it's empty. */
1788 size_t cbInBuf = pStdInBuf->cb - pStdInBuf->off;
1789 bool const fAddToSet = cbInBuf == 0;
1790 if (fAddToSet)
1791 pStdInBuf->cb = pStdInBuf->off = 0;
1792
1793 /* Try and see if we can simply append the data. */
1794 if (cb + pStdInBuf->cb <= pStdInBuf->cbAllocated)
1795 {
1796 memcpy(&pStdInBuf->pch[pStdInBuf->cb], pch, cb);
1797 pStdInBuf->cb += cb;
1798 rc = txsReplyAck(pPktHdr);
1799 }
1800 else
1801 {
1802 /* Try write a bit or two before we move+realloc the buffer. */
1803 if (cbInBuf > 0)
1804 txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
1805
1806 /* Move any buffered data to the front. */
1807 cbInBuf = pStdInBuf->cb - pStdInBuf->off;
1808 if (cbInBuf == 0)
1809 pStdInBuf->cb = pStdInBuf->off = 0;
1810 else
1811 {
1812 memmove(pStdInBuf->pch, &pStdInBuf->pch[pStdInBuf->off], cbInBuf);
1813 pStdInBuf->cb = cbInBuf;
1814 pStdInBuf->off = 0;
1815 }
1816
1817 /* Do we need to grow the buffer? */
1818 if (cb + pStdInBuf->cb > pStdInBuf->cbAllocated)
1819 {
1820 size_t cbAlloc = pStdInBuf->cb + cb;
1821 cbAlloc = RT_ALIGN_Z(cbAlloc, _64K);
1822 void *pvNew = RTMemRealloc(pStdInBuf->pch, cbAlloc);
1823 if (pvNew)
1824 {
1825 pStdInBuf->pch = (char *)pvNew;
1826 pStdInBuf->cbAllocated = cbAlloc;
1827 }
1828 }
1829
1830 /* Finally, copy the data. */
1831 if (cb + pStdInBuf->cb <= pStdInBuf->cbAllocated)
1832 {
1833 memcpy(&pStdInBuf->pch[pStdInBuf->cb], pch, cb);
1834 pStdInBuf->cb += cb;
1835 rc = txsReplyAck(pPktHdr);
1836 }
1837 else
1838 rc = txsReplySimple(pPktHdr, "STDINMEM");
1839 }
1840
1841 /*
1842 * Flush the buffered data and add/remove the standard input
1843 * handle from the set.
1844 */
1845 txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
1846 if (fAddToSet && pStdInBuf->off < pStdInBuf->cb)
1847 {
1848 int rc2 = RTPollSetAddPipe(hPollSet, *phStdInW, RTPOLL_EVT_WRITE, TXSEXECHNDID_STDIN_WRITABLE);
1849 AssertRC(rc2);
1850 }
1851 else if (!fAddToSet && pStdInBuf->off >= pStdInBuf->cb)
1852 {
1853 int rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1854 AssertRC(rc2);
1855 }
1856 }
1857 else
1858 rc = txsReplyFailure(pPktHdr, "STDINCRC", "Invalid CRC checksum expected %#x got %#x",
1859 pStdInBuf->uCrc32, uCrc32);
1860 }
1861 else if (pPktHdr->cb < sizeof(TXSPKTHDR) + sizeof(uint32_t))
1862 rc = txsReplySimple(pPktHdr, "STDINBAD");
1863 else
1864 rc = txsReplySimple(pPktHdr, "STDINIGN");
1865 }
1866 /*
1867 * Marks the end of the stream for stdin.
1868 */
1869 else if (txsIsSameOpcode(pPktHdr, "STDINEOS"))
1870 {
1871 if (RT_LIKELY(pPktHdr->cb == sizeof(TXSPKTHDR)))
1872 {
1873 /* Close the pipe. */
1874 txsDoExecHlpHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
1875 rc = txsReplyAck(pPktHdr);
1876 }
1877 else
1878 rc = txsReplySimple(pPktHdr, "STDINBAD");
1879 }
1880 /*
1881 * The only other two requests are connection oriented and we return a error
1882 * code so that we unwind the whole EXEC shebang and start afresh.
1883 */
1884 else if (txsIsSameOpcode(pPktHdr, "BYE"))
1885 {
1886 rc = txsDoBye(pPktHdr);
1887 if (RT_SUCCESS(rc))
1888 rc = VERR_NET_NOT_CONNECTED;
1889 }
1890 else if (txsIsSameOpcode(pPktHdr, "HOWDY"))
1891 {
1892 rc = txsDoHowdy(pPktHdr);
1893 if (RT_SUCCESS(rc))
1894 rc = VERR_NET_NOT_CONNECTED;
1895 }
1896 else if (txsIsSameOpcode(pPktHdr, "ABORT"))
1897 {
1898 rc = txsReplyAck(pPktHdr);
1899 if (RT_SUCCESS(rc))
1900 rc = VINF_EOF; /* this is but ugly! */
1901 }
1902 else
1903 rc = txsReplyFailure(pPktHdr, "UNKNOWN ", "Opcode '%.8s' is not known or not recognized during EXEC", pPktHdr->achOpcode);
1904
1905 RTMemFree(pPktHdr);
1906 return rc;
1907}
1908
1909/**
1910 * Handles the output and input of the process, waits for it finish up.
1911 *
1912 * @returns IPRT status code from reply send.
1913 * @param pTxsExec The TXSEXEC instance.
1914 */
1915static int txsDoExecHlp2(PTXSEXEC pTxsExec)
1916{
1917 int rc; /* client send. */
1918 int rc2;
1919 TXSEXECSTDINBUF StdInBuf = { 0, 0, NULL, 0, pTxsExec->hStdInW == NIL_RTPIPE, RTCrc32Start() };
1920 uint32_t uStdOutCrc32 = RTCrc32Start();
1921 uint32_t uStdErrCrc32 = uStdOutCrc32;
1922 uint32_t uTestPipeCrc32 = uStdOutCrc32;
1923 uint64_t const MsStart = RTTimeMilliTS();
1924 bool fProcessTimedOut = false;
1925 uint64_t MsProcessKilled = UINT64_MAX;
1926 RTMSINTERVAL const cMsPollBase = g_pTransport->pfnPollSetAdd || pTxsExec->hStdInW == NIL_RTPIPE
1927 ? 5000 : 100;
1928 RTMSINTERVAL cMsPollCur = 0;
1929
1930 /*
1931 * Before entering the loop, tell the client that we've started the guest
1932 * and that it's now OK to send input to the process. (This is not the
1933 * final ACK, so the packet header is NULL ... kind of bogus.)
1934 */
1935 rc = txsReplyAck(NULL);
1936
1937 /*
1938 * Process input, output, the test pipe and client requests.
1939 */
1940 while ( RT_SUCCESS(rc)
1941 && RT_UNLIKELY(!g_fTerminate))
1942 {
1943 /*
1944 * Wait/Process all pending events.
1945 */
1946 uint32_t idPollHnd;
1947 uint32_t fPollEvt;
1948 Log3(("Calling RTPollNoResume(,%u,)...\n", cMsPollCur));
1949 rc2 = RTPollNoResume(pTxsExec->hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
1950 Log3(("RTPollNoResume -> fPollEvt=%#x idPollHnd=%u\n", fPollEvt, idPollHnd));
1951 if (g_fTerminate)
1952 continue;
1953 cMsPollCur = 0; /* no rest until we've checked everything. */
1954
1955 if (RT_SUCCESS(rc2))
1956 {
1957 switch (idPollHnd)
1958 {
1959 case TXSEXECHNDID_STDOUT:
1960 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdOutR, &uStdOutCrc32,
1961 TXSEXECHNDID_STDOUT, "STDOUT ");
1962 break;
1963
1964 case TXSEXECHNDID_STDERR:
1965 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdErrR, &uStdErrCrc32,
1966 TXSEXECHNDID_STDERR, "STDERR ");
1967 break;
1968
1969 case TXSEXECHNDID_TESTPIPE:
1970 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hTestPipeR, &uTestPipeCrc32,
1971 TXSEXECHNDID_TESTPIPE, "TESTPIPE");
1972 break;
1973
1974 case TXSEXECHNDID_STDIN:
1975 txsDoExecHlpHandleStdInErrorEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdInW, &StdInBuf);
1976 break;
1977
1978 case TXSEXECHNDID_STDIN_WRITABLE:
1979 txsDoExecHlpHandleStdInWritableEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdInW, &StdInBuf);
1980 break;
1981
1982 case TXSEXECHNDID_THREAD:
1983 rc2 = RTPollSetRemove(pTxsExec->hPollSet, TXSEXECHNDID_THREAD); AssertRC(rc2);
1984 break;
1985
1986 default:
1987 rc = txsDoExecHlpHandleTransportEvent(pTxsExec->hPollSet, fPollEvt, idPollHnd, &pTxsExec->hStdInW,
1988 &StdInBuf);
1989 break;
1990 }
1991 if (RT_FAILURE(rc) || rc == VINF_EOF)
1992 break; /* abort command, or client dead or something */
1993 continue;
1994 }
1995
1996 /*
1997 * Check for incoming data.
1998 */
1999 if (g_pTransport->pfnPollIn())
2000 {
2001 rc = txsDoExecHlpHandleTransportEvent(pTxsExec->hPollSet, 0, UINT32_MAX, &pTxsExec->hStdInW, &StdInBuf);
2002 if (RT_FAILURE(rc) || rc == VINF_EOF)
2003 break; /* abort command, or client dead or something */
2004 continue;
2005 }
2006
2007 /*
2008 * If the process has terminated, we're should head out.
2009 */
2010 if (!ASMAtomicReadBool(&pTxsExec->fProcessAlive))
2011 break;
2012
2013 /*
2014 * Check for timed out, killing the process.
2015 */
2016 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
2017 if (pTxsExec->cMsTimeout != RT_INDEFINITE_WAIT)
2018 {
2019 uint64_t u64Now = RTTimeMilliTS();
2020 uint64_t cMsElapsed = u64Now - MsStart;
2021 if (cMsElapsed >= pTxsExec->cMsTimeout)
2022 {
2023 fProcessTimedOut = true;
2024 if ( MsProcessKilled == UINT64_MAX
2025 || u64Now - MsProcessKilled > 1000)
2026 {
2027 if (u64Now - MsProcessKilled > 20*60*1000)
2028 break; /* give up after 20 mins */
2029 RTCritSectEnter(&pTxsExec->CritSect);
2030 if (pTxsExec->fProcessAlive)
2031 RTProcTerminate(pTxsExec->hProcess);
2032 RTCritSectLeave(&pTxsExec->CritSect);
2033 MsProcessKilled = u64Now;
2034 continue;
2035 }
2036 cMilliesLeft = 10000;
2037 }
2038 else
2039 cMilliesLeft = pTxsExec->cMsTimeout - (uint32_t)cMsElapsed;
2040 }
2041
2042 /* Reset the polling interval since we've done all pending work. */
2043 cMsPollCur = cMilliesLeft >= cMsPollBase ? cMsPollBase : cMilliesLeft;
2044 }
2045
2046 /*
2047 * At this point we should hopefully only have to wait 0 ms on the thread
2048 * to release the handle... But if for instance the process refuses to die,
2049 * we'll have to try kill it again. Bothersome.
2050 */
2051 for (size_t i = 0; i < 22; i++)
2052 {
2053 rc2 = RTThreadWait(pTxsExec->hThreadWaiter, 500, NULL);
2054 if (RT_SUCCESS(rc))
2055 {
2056 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2057 Assert(!pTxsExec->fProcessAlive);
2058 break;
2059 }
2060 if (i == 0 || i == 10 || i == 15 || i == 18 || i > 20)
2061 {
2062 RTCritSectEnter(&pTxsExec->CritSect);
2063 if (pTxsExec->fProcessAlive)
2064 RTProcTerminate(pTxsExec->hProcess);
2065 RTCritSectLeave(&pTxsExec->CritSect);
2066 }
2067 }
2068
2069 /*
2070 * If we don't have a client problem (RT_FAILURE(rc) we'll reply to the
2071 * clients exec packet now.
2072 */
2073 if (RT_SUCCESS(rc))
2074 rc = txsExecSendExitStatus(pTxsExec, pTxsExec->fProcessAlive, fProcessTimedOut, MsProcessKilled);
2075
2076 RTMemFree(StdInBuf.pch);
2077 return rc;
2078}
2079
2080/**
2081 * Creates a poll set for the pipes and let the transport layer add stuff to it
2082 * as well.
2083 *
2084 * @returns IPRT status code, reply to client made on error.
2085 * @param pTxsExec The TXSEXEC instance.
2086 */
2087static int txsExecSetupPollSet(PTXSEXEC pTxsExec)
2088{
2089 int rc = RTPollSetCreate(&pTxsExec->hPollSet);
2090 if (RT_FAILURE(rc))
2091 return txsExecReplyRC(pTxsExec, rc, "RTPollSetCreate");
2092
2093 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdInW, RTPOLL_EVT_ERROR, TXSEXECHNDID_STDIN);
2094 if (RT_FAILURE(rc))
2095 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stdin");
2096
2097 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2098 TXSEXECHNDID_STDOUT);
2099 if (RT_FAILURE(rc))
2100 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stdout");
2101
2102 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2103 TXSEXECHNDID_STDERR);
2104 if (RT_FAILURE(rc))
2105 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stderr");
2106
2107 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hTestPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2108 TXSEXECHNDID_TESTPIPE);
2109 if (RT_FAILURE(rc))
2110 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/test");
2111
2112 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hWakeUpPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2113 TXSEXECHNDID_THREAD);
2114 if (RT_FAILURE(rc))
2115 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/wakeup");
2116
2117 if (g_pTransport->pfnPollSetAdd)
2118 {
2119 rc = g_pTransport->pfnPollSetAdd(pTxsExec->hPollSet, TXSEXECHNDID_TRANSPORT);
2120 if (RT_FAILURE(rc))
2121 return txsExecReplyRC(pTxsExec, rc, "%s->pfnPollSetAdd/stdin", g_pTransport->szName);
2122 }
2123
2124 return VINF_SUCCESS;
2125}
2126
2127/**
2128 * Thread that calls RTProcWait and signals the main thread when it returns.
2129 *
2130 * The thread is created before the process is started and is waiting for a user
2131 * signal from the main thread before it calls RTProcWait.
2132 *
2133 * @returns VINF_SUCCESS (ignored).
2134 * @param hThreadSelf The thread handle.
2135 * @param pvUser The TXEEXEC structure.
2136 */
2137static DECLCALLBACK(int) txsExecWaitThreadProc(RTTHREAD hThreadSelf, void *pvUser)
2138{
2139 PTXSEXEC pTxsExec = (PTXSEXEC)pvUser;
2140
2141 /* Wait for the go ahead... */
2142 int rc = RTThreadUserWait(hThreadSelf, RT_INDEFINITE_WAIT); AssertRC(rc);
2143
2144 RTCritSectEnter(&pTxsExec->CritSect);
2145 for (;;)
2146 {
2147 RTCritSectLeave(&pTxsExec->CritSect);
2148 rc = RTProcWaitNoResume(pTxsExec->hProcess, RTPROCWAIT_FLAGS_BLOCK, &pTxsExec->ProcessStatus);
2149 RTCritSectEnter(&pTxsExec->CritSect);
2150
2151 /* If the pipe is NIL, the destructor wants us to get lost ASAP. */
2152 if (pTxsExec->hWakeUpPipeW == NIL_RTPIPE)
2153 break;
2154
2155 if (RT_FAILURE(rc))
2156 {
2157 rc = RTProcWait(pTxsExec->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &pTxsExec->ProcessStatus);
2158 if (rc == VERR_PROCESS_RUNNING)
2159 continue;
2160
2161 if (RT_FAILURE(rc))
2162 {
2163 AssertRC(rc);
2164 pTxsExec->ProcessStatus.iStatus = rc;
2165 pTxsExec->ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
2166 }
2167 }
2168
2169 /* The process finished, signal the main thread over the pipe. */
2170 ASMAtomicWriteBool(&pTxsExec->fProcessAlive, false);
2171 size_t cbIgnored;
2172 RTPipeWrite(pTxsExec->hWakeUpPipeW, "done", 4, &cbIgnored);
2173 RTPipeClose(pTxsExec->hWakeUpPipeW);
2174 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2175 break;
2176 }
2177 RTCritSectLeave(&pTxsExec->CritSect);
2178
2179 return VINF_SUCCESS;
2180}
2181
2182/**
2183 * Sets up the thread that waits for the process to complete.
2184 *
2185 * @returns IPRT status code, reply to client made on error.
2186 * @param pTxsExec The TXSEXEC instance.
2187 */
2188static int txsExecSetupThread(PTXSEXEC pTxsExec)
2189{
2190 int rc = RTPipeCreate(&pTxsExec->hWakeUpPipeR, &pTxsExec->hWakeUpPipeW, 0 /*fFlags*/);
2191 if (RT_FAILURE(rc))
2192 {
2193 pTxsExec->hWakeUpPipeR = pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2194 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/wait");
2195 }
2196
2197 rc = RTThreadCreate(&pTxsExec->hThreadWaiter, txsExecWaitThreadProc,
2198 pTxsExec, 0 /*cbStack */, RTTHREADTYPE_DEFAULT,
2199 RTTHREADFLAGS_WAITABLE, "TxsProcW");
2200 if (RT_FAILURE(rc))
2201 {
2202 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2203 return txsExecReplyRC(pTxsExec, rc, "RTThreadCreate");
2204 }
2205
2206 return VINF_SUCCESS;
2207}
2208
2209/**
2210 * Sets up the test pipe.
2211 *
2212 * @returns IPRT status code, reply to client made on error.
2213 * @param pTxsExec The TXSEXEC instance.
2214 * @param pszTestPipe How to set up the test pipe.
2215 */
2216static int txsExecSetupTestPipe(PTXSEXEC pTxsExec, const char *pszTestPipe)
2217{
2218 if (strcmp(pszTestPipe, "|"))
2219 return VINF_SUCCESS;
2220
2221 int rc = RTPipeCreate(&pTxsExec->hTestPipeR, &pTxsExec->hTestPipeW, RTPIPE_C_INHERIT_WRITE);
2222 if (RT_FAILURE(rc))
2223 {
2224 pTxsExec->hTestPipeR = pTxsExec->hTestPipeW = NIL_RTPIPE;
2225 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/test/%s", pszTestPipe);
2226 }
2227
2228 char szVal[64];
2229 RTStrPrintf(szVal, sizeof(szVal), "%#llx", (uint64_t)RTPipeToNative(pTxsExec->hTestPipeW));
2230 rc = RTEnvSetEx(pTxsExec->hEnv, "IPRT_TEST_PIPE", szVal);
2231 if (RT_FAILURE(rc))
2232 return txsExecReplyRC(pTxsExec, rc, "RTEnvSetEx/test/%s", pszTestPipe);
2233
2234 return VINF_SUCCESS;
2235}
2236
2237/**
2238 * Sets up the redirection / pipe / nothing for one of the standard handles.
2239 *
2240 * @returns IPRT status code, reply to client made on error.
2241 * @param pTxsExec The TXSEXEC instance.
2242 * @param pszHowTo How to set up this standard handle.
2243 * @param fd Which standard handle it is (0 == stdin, 1 ==
2244 * stdout, 2 == stderr).
2245 * @param ph The generic handle that @a pph may be set
2246 * pointing to. Always set.
2247 * @param pph Pointer to the RTProcCreateExec argument.
2248 * Always set.
2249 * @param phPipe Where to return the end of the pipe that we
2250 * should service. Always set.
2251 */
2252static int txsExecSetupRedir(PTXSEXEC pTxsExec, const char *pszHowTo, const char *pszStdWhat, int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
2253{
2254 ph->enmType = RTHANDLETYPE_PIPE;
2255 ph->u.hPipe = NIL_RTPIPE;
2256 *pph = NULL;
2257 *phPipe = NIL_RTPIPE;
2258
2259 int rc;
2260 if (!strcmp(pszHowTo, "|"))
2261 {
2262 /*
2263 * Setup a pipe for forwarding to/from the client.
2264 */
2265 if (fd == 0)
2266 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
2267 else
2268 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
2269 if (RT_FAILURE(rc))
2270 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/%s/%s", pszStdWhat, pszHowTo);
2271 ph->enmType = RTHANDLETYPE_PIPE;
2272 *pph = ph;
2273 }
2274 else if (!strcmp(pszHowTo, "/dev/null"))
2275 {
2276 /*
2277 * Redirect to/from /dev/null.
2278 */
2279 RTFILE hFile;
2280 rc = RTFileOpenBitBucket(&hFile, fd == 0 ? RTFILE_O_READ : RTFILE_O_WRITE);
2281 if (RT_FAILURE(rc))
2282 return txsExecReplyRC(pTxsExec, rc, "RTFileOpenBitBucket/%s/%s", pszStdWhat, pszHowTo);
2283
2284 ph->enmType = RTHANDLETYPE_FILE;
2285 ph->u.hFile = hFile;
2286 *pph = ph;
2287 }
2288 else if (*pszHowTo)
2289 {
2290 /*
2291 * Redirect to/from file.
2292 */
2293 uint32_t fFlags;
2294 if (fd == 0)
2295 fFlags = RTFILE_O_READ | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN;
2296 else
2297 {
2298 if (pszHowTo[0] != '>' || pszHowTo[1] != '>')
2299 fFlags = RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE;
2300 else
2301 {
2302 /* append */
2303 pszHowTo += 2;
2304 fFlags = RTFILE_O_WRITE | RTFILE_O_DENY_NONE | RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND;
2305 }
2306 }
2307
2308 RTFILE hFile;
2309 rc = RTFileOpen(&hFile, pszHowTo, fFlags);
2310 if (RT_FAILURE(rc))
2311 return txsExecReplyRC(pTxsExec, rc, "RTFileOpen/%s/%s", pszStdWhat, pszHowTo);
2312
2313 ph->enmType = RTHANDLETYPE_FILE;
2314 ph->u.hFile = hFile;
2315 *pph = ph;
2316 }
2317 else
2318 /* same as parent (us) */
2319 rc = VINF_SUCCESS;
2320 return rc;
2321}
2322
2323/**
2324 * Create the environment.
2325 *
2326 * @returns IPRT status code, reply to client made on error.
2327 * @param pTxsExec The TXSEXEC instance.
2328 * @param cEnvVars The number of environment variables.
2329 * @param papszEnv The environment variables (var=value).
2330 */
2331static int txsExecSetupEnv(PTXSEXEC pTxsExec, uint32_t cEnvVars, const char * const *papszEnv)
2332{
2333 /*
2334 * Create the environment.
2335 */
2336 int rc = RTEnvClone(&pTxsExec->hEnv, RTENV_DEFAULT);
2337 if (RT_FAILURE(rc))
2338 return txsExecReplyRC(pTxsExec, rc, "RTEnvClone");
2339
2340 for (size_t i = 0; i < cEnvVars; i++)
2341 {
2342 rc = RTEnvPutEx(pTxsExec->hEnv, papszEnv[i]);
2343 if (RT_FAILURE(rc))
2344 return txsExecReplyRC(pTxsExec, rc, "RTEnvPutEx(,'%s')", papszEnv[i]);
2345 }
2346 return VINF_SUCCESS;
2347}
2348
2349/**
2350 * Deletes the TXSEXEC structure and frees the memory backing it.
2351 *
2352 * @param pTxsExec The structure to destroy.
2353 */
2354static void txsExecDestroy(PTXSEXEC pTxsExec)
2355{
2356 int rc2;
2357
2358 rc2 = RTEnvDestroy(pTxsExec->hEnv); AssertRC(rc2);
2359 pTxsExec->hEnv = NIL_RTENV;
2360 rc2 = RTPipeClose(pTxsExec->hTestPipeW); AssertRC(rc2);
2361 pTxsExec->hTestPipeW = NIL_RTPIPE;
2362 rc2 = RTHandleClose(pTxsExec->StdErr.phChild); AssertRC(rc2);
2363 pTxsExec->StdErr.phChild = NULL;
2364 rc2 = RTHandleClose(pTxsExec->StdOut.phChild); AssertRC(rc2);
2365 pTxsExec->StdOut.phChild = NULL;
2366 rc2 = RTHandleClose(pTxsExec->StdIn.phChild); AssertRC(rc2);
2367 pTxsExec->StdIn.phChild = NULL;
2368
2369 rc2 = RTPipeClose(pTxsExec->hTestPipeR); AssertRC(rc2);
2370 pTxsExec->hTestPipeR = NIL_RTPIPE;
2371 rc2 = RTPipeClose(pTxsExec->hStdErrR); AssertRC(rc2);
2372 pTxsExec->hStdErrR = NIL_RTPIPE;
2373 rc2 = RTPipeClose(pTxsExec->hStdOutR); AssertRC(rc2);
2374 pTxsExec->hStdOutR = NIL_RTPIPE;
2375 rc2 = RTPipeClose(pTxsExec->hStdInW); AssertRC(rc2);
2376 pTxsExec->hStdInW = NIL_RTPIPE;
2377
2378 RTPollSetDestroy(pTxsExec->hPollSet);
2379 pTxsExec->hPollSet = NIL_RTPOLLSET;
2380
2381 /*
2382 * If the process is still running we're in a bit of a fix... Try kill it,
2383 * although that's potentially racing process termination and reusage of
2384 * the pid.
2385 */
2386 RTCritSectEnter(&pTxsExec->CritSect);
2387
2388 RTPipeClose(pTxsExec->hWakeUpPipeW);
2389 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2390 RTPipeClose(pTxsExec->hWakeUpPipeR);
2391 pTxsExec->hWakeUpPipeR = NIL_RTPIPE;
2392
2393 if ( pTxsExec->hProcess != NIL_RTPROCESS
2394 && pTxsExec->fProcessAlive)
2395 RTProcTerminate(pTxsExec->hProcess);
2396
2397 RTCritSectLeave(&pTxsExec->CritSect);
2398
2399 int rcThread = VINF_SUCCESS;
2400 if (pTxsExec->hThreadWaiter != NIL_RTTHREAD)
2401 rcThread = RTThreadWait(pTxsExec->hThreadWaiter, 5000, NULL);
2402 if (RT_SUCCESS(rcThread))
2403 {
2404 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2405 RTCritSectDelete(&pTxsExec->CritSect);
2406 RTMemFree(pTxsExec);
2407 }
2408 /* else: leak it or RTThreadWait may cause heap corruption later. */
2409}
2410
2411/**
2412 * Initializes the TXSEXEC structure.
2413 *
2414 * @returns VINF_SUCCESS and non-NULL *ppTxsExec on success, reply send status
2415 * and *ppTxsExec set to NULL on failure.
2416 * @param pPktHdr The exec packet.
2417 * @param cMsTimeout The time parameter.
2418 * @param ppTxsExec Where to return the structure.
2419 */
2420static int txsExecCreate(PCTXSPKTHDR pPktHdr, RTMSINTERVAL cMsTimeout, PTXSEXEC *ppTxsExec)
2421{
2422 *ppTxsExec = NULL;
2423
2424 /*
2425 * Allocate the basic resources.
2426 */
2427 PTXSEXEC pTxsExec = (PTXSEXEC)RTMemAlloc(sizeof(*pTxsExec));
2428 if (!pTxsExec)
2429 return txsReplyRC(pPktHdr, VERR_NO_MEMORY, "RTMemAlloc(%zu)", sizeof(*pTxsExec));
2430 int rc = RTCritSectInit(&pTxsExec->CritSect);
2431 if (RT_FAILURE(rc))
2432 {
2433 RTMemFree(pTxsExec);
2434 return txsReplyRC(pPktHdr, rc, "RTCritSectInit");
2435 }
2436
2437 /*
2438 * Initialize the member to NIL values.
2439 */
2440 pTxsExec->pPktHdr = pPktHdr;
2441 pTxsExec->cMsTimeout = cMsTimeout;
2442 pTxsExec->rcReplySend = VINF_SUCCESS;
2443
2444 pTxsExec->hPollSet = NIL_RTPOLLSET;
2445 pTxsExec->hStdInW = NIL_RTPIPE;
2446 pTxsExec->hStdOutR = NIL_RTPIPE;
2447 pTxsExec->hStdErrR = NIL_RTPIPE;
2448 pTxsExec->hTestPipeR = NIL_RTPIPE;
2449 pTxsExec->hWakeUpPipeR = NIL_RTPIPE;
2450 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2451
2452 pTxsExec->StdIn.phChild = NULL;
2453 pTxsExec->StdOut.phChild = NULL;
2454 pTxsExec->StdErr.phChild = NULL;
2455 pTxsExec->hTestPipeW = NIL_RTPIPE;
2456 pTxsExec->hEnv = NIL_RTENV;
2457
2458 pTxsExec->hProcess = NIL_RTPROCESS;
2459 pTxsExec->ProcessStatus.iStatus = 254;
2460 pTxsExec->ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
2461 pTxsExec->fProcessAlive = false;
2462 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2463
2464 *ppTxsExec = pTxsExec;
2465 return VINF_SUCCESS;
2466}
2467
2468/**
2469 * txsDoExec helper that takes over when txsDoExec has expanded the packet.
2470 *
2471 * @returns IPRT status code from send.
2472 * @param pPktHdr The exec packet.
2473 * @param fFlags Flags, reserved for future use.
2474 * @param pszExecName The executable name.
2475 * @param cArgs The argument count.
2476 * @param papszArgs The arguments.
2477 * @param cEnvVars The environment variable count.
2478 * @param papszEnv The environment variables.
2479 * @param pszStdIn How to deal with standard in.
2480 * @param pszStdOut How to deal with standard out.
2481 * @param pszStdErr How to deal with standard err.
2482 * @param pszTestPipe How to deal with the test pipe.
2483 * @param pszUsername The user to run the program as.
2484 * @param cMillies The process time limit in milliseconds.
2485 */
2486static int txsDoExecHlp(PCTXSPKTHDR pPktHdr, uint32_t fFlags, const char *pszExecName,
2487 uint32_t cArgs, const char * const *papszArgs,
2488 uint32_t cEnvVars, const char * const *papszEnv,
2489 const char *pszStdIn, const char *pszStdOut, const char *pszStdErr, const char *pszTestPipe,
2490 const char *pszUsername, RTMSINTERVAL cMillies)
2491{
2492 int rc2;
2493 RT_NOREF_PV(fFlags);
2494
2495 /*
2496 * Input validation, filter out things we don't yet support..
2497 */
2498 Assert(!fFlags);
2499 if (!*pszExecName)
2500 return txsReplyFailure(pPktHdr, "STR ZERO", "Executable name is empty");
2501 if (!*pszStdIn)
2502 return txsReplyFailure(pPktHdr, "STR ZERO", "The stdin howto is empty");
2503 if (!*pszStdOut)
2504 return txsReplyFailure(pPktHdr, "STR ZERO", "The stdout howto is empty");
2505 if (!*pszStdErr)
2506 return txsReplyFailure(pPktHdr, "STR ZERO", "The stderr howto is empty");
2507 if (!*pszTestPipe)
2508 return txsReplyFailure(pPktHdr, "STR ZERO", "The testpipe howto is empty");
2509 if (strcmp(pszTestPipe, "|") && strcmp(pszTestPipe, "/dev/null"))
2510 return txsReplyFailure(pPktHdr, "BAD TSTP", "Only \"|\" and \"/dev/null\" are allowed as testpipe howtos ('%s')",
2511 pszTestPipe);
2512 if (*pszUsername)
2513 return txsReplyFailure(pPktHdr, "NOT IMPL", "Executing as a specific user is not implemented ('%s')", pszUsername);
2514
2515 /*
2516 * Prepare for process launch.
2517 */
2518 PTXSEXEC pTxsExec;
2519 int rc = txsExecCreate(pPktHdr, cMillies, &pTxsExec);
2520 if (pTxsExec == NULL)
2521 return rc;
2522 rc = txsExecSetupEnv(pTxsExec, cEnvVars, papszEnv);
2523 if (RT_SUCCESS(rc))
2524 rc = txsExecSetupRedir(pTxsExec, pszStdIn, "StdIn", 0, &pTxsExec->StdIn.hChild, &pTxsExec->StdIn.phChild, &pTxsExec->hStdInW);
2525 if (RT_SUCCESS(rc))
2526 rc = txsExecSetupRedir(pTxsExec, pszStdOut, "StdOut", 1, &pTxsExec->StdOut.hChild, &pTxsExec->StdOut.phChild, &pTxsExec->hStdOutR);
2527 if (RT_SUCCESS(rc))
2528 rc = txsExecSetupRedir(pTxsExec, pszStdErr, "StdErr", 2, &pTxsExec->StdErr.hChild, &pTxsExec->StdErr.phChild, &pTxsExec->hStdErrR);
2529 if (RT_SUCCESS(rc))
2530 rc = txsExecSetupTestPipe(pTxsExec, pszTestPipe);
2531 if (RT_SUCCESS(rc))
2532 rc = txsExecSetupThread(pTxsExec);
2533 if (RT_SUCCESS(rc))
2534 rc = txsExecSetupPollSet(pTxsExec);
2535 if (RT_SUCCESS(rc))
2536 {
2537 /*
2538 * Create the process.
2539 */
2540 if (g_fDisplayOutput)
2541 {
2542 RTPrintf("txs: Executing \"%s\": ", pszExecName);
2543 for (uint32_t i = 0; i < cArgs; i++)
2544 RTPrintf(" \"%s\"", papszArgs[i]);
2545 RTPrintf("\n");
2546 }
2547 rc = RTProcCreateEx(pszExecName, papszArgs, pTxsExec->hEnv, 0 /*fFlags*/,
2548 pTxsExec->StdIn.phChild, pTxsExec->StdOut.phChild, pTxsExec->StdErr.phChild,
2549 *pszUsername ? pszUsername : NULL, NULL,
2550 &pTxsExec->hProcess);
2551 if (RT_SUCCESS(rc))
2552 {
2553 ASMAtomicWriteBool(&pTxsExec->fProcessAlive, true);
2554 rc2 = RTThreadUserSignal(pTxsExec->hThreadWaiter); AssertRC(rc2);
2555
2556 /*
2557 * Close the child ends of any pipes and redirected files.
2558 */
2559 rc2 = RTHandleClose(pTxsExec->StdIn.phChild); AssertRC(rc2);
2560 pTxsExec->StdIn.phChild = NULL;
2561 rc2 = RTHandleClose(pTxsExec->StdOut.phChild); AssertRC(rc2);
2562 pTxsExec->StdOut.phChild = NULL;
2563 rc2 = RTHandleClose(pTxsExec->StdErr.phChild); AssertRC(rc2);
2564 pTxsExec->StdErr.phChild = NULL;
2565 rc2 = RTPipeClose(pTxsExec->hTestPipeW); AssertRC(rc2);
2566 pTxsExec->hTestPipeW = NIL_RTPIPE;
2567
2568 /*
2569 * Let another worker function funnel output and input to the
2570 * client as well as the process exit code.
2571 */
2572 rc = txsDoExecHlp2(pTxsExec);
2573 }
2574 else
2575 rc = txsReplyFailure(pPktHdr, "FAILED ", "Executing process \"%s\" failed with %Rrc",
2576 pszExecName, rc);
2577 }
2578 else
2579 rc = pTxsExec->rcReplySend;
2580 txsExecDestroy(pTxsExec);
2581 return rc;
2582}
2583
2584/**
2585 * Execute a program.
2586 *
2587 * @returns IPRT status code from send.
2588 * @param pPktHdr The exec packet.
2589 */
2590static int txsDoExec(PCTXSPKTHDR pPktHdr)
2591{
2592 /*
2593 * This packet has a lot of parameters, most of which are zero terminated
2594 * strings. The strings used in items 7 thru 10 are either file names,
2595 * "/dev/null" or a pipe char (|).
2596 *
2597 * Packet content:
2598 * 1. Flags reserved for future use (32-bit unsigned).
2599 * 2. The executable name (string).
2600 * 3. The argument count given as a 32-bit unsigned integer.
2601 * 4. The arguments strings.
2602 * 5. The number of environment strings (32-bit unsigned).
2603 * 6. The environment strings (var=val) to apply the environment.
2604 * 7. What to do about standard in (string).
2605 * 8. What to do about standard out (string).
2606 * 9. What to do about standard err (string).
2607 * 10. What to do about the test pipe (string).
2608 * 11. The name of the user to run the program as (string). Empty string
2609 * means running it as the current user.
2610 * 12. Process time limit in milliseconds (32-bit unsigned). Max == no limit.
2611 */
2612 size_t const cbMin = sizeof(TXSPKTHDR)
2613 + sizeof(uint32_t) /* flags */ + 2
2614 + sizeof(uint32_t) /* argc */ + 2 /* argv */
2615 + sizeof(uint32_t) + 0 /* environ */
2616 + 4 * 1
2617 + sizeof(uint32_t) /* timeout */;
2618 if (pPktHdr->cb < cbMin)
2619 return txsReplyBadMinSize(pPktHdr, cbMin);
2620
2621 /* unpack the packet */
2622 char const *pchEnd = (char const *)pPktHdr + pPktHdr->cb;
2623 char const *pch = (char const *)(pPktHdr + 1); /* cursor */
2624
2625 /* 1. flags */
2626 uint32_t const fFlags = *(uint32_t const *)pch;
2627 pch += sizeof(uint32_t);
2628 if (fFlags != 0)
2629 return txsReplyFailure(pPktHdr, "BAD FLAG", "Invalid EXEC flags %#x, expected 0", fFlags);
2630
2631 /* 2. exec name */
2632 int rc;
2633 char *pszExecName = NULL;
2634 if (!txsIsStringValid(pPktHdr, "execname", pch, &pszExecName, &pch, &rc))
2635 return rc;
2636
2637 /* 3. argc */
2638 uint32_t const cArgs = (size_t)(pchEnd - pch) > sizeof(uint32_t) ? *(uint32_t const *)pch : 0xff;
2639 pch += sizeof(uint32_t);
2640 if (cArgs * 1 >= (size_t)(pchEnd - pch))
2641 rc = txsReplyFailure(pPktHdr, "BAD ARGC", "Bad or missing argument count (%#x)", cArgs);
2642 else if (cArgs > 128)
2643 rc = txsReplyFailure(pPktHdr, "BAD ARGC", "Too many arguments (%#x)", cArgs);
2644 else
2645 {
2646 char **papszArgs = (char **)RTMemTmpAllocZ(sizeof(char *) * (cArgs + 1));
2647 if (papszArgs)
2648 {
2649 /* 4. argv */
2650 bool fOk = true;
2651 for (size_t i = 0; i < cArgs && fOk; i++)
2652 {
2653 fOk = txsIsStringValid(pPktHdr, "argvN", pch, &papszArgs[i], &pch, &rc);
2654 if (!fOk)
2655 break;
2656 }
2657 if (fOk)
2658 {
2659 /* 5. cEnvVars */
2660 uint32_t const cEnvVars = (size_t)(pchEnd - pch) > sizeof(uint32_t) ? *(uint32_t const *)pch : 0xfff;
2661 pch += sizeof(uint32_t);
2662 if (cEnvVars * 1 >= (size_t)(pchEnd - pch))
2663 rc = txsReplyFailure(pPktHdr, "BAD ENVC", "Bad or missing environment variable count (%#x)", cEnvVars);
2664 else if (cEnvVars > 256)
2665 rc = txsReplyFailure(pPktHdr, "BAD ENVC", "Too many environment variables (%#x)", cEnvVars);
2666 else
2667 {
2668 char **papszEnv = (char **)RTMemTmpAllocZ(sizeof(char *) * (cEnvVars + 1));
2669 if (papszEnv)
2670 {
2671 /* 6. environ */
2672 for (size_t i = 0; i < cEnvVars && fOk; i++)
2673 {
2674 fOk = txsIsStringValid(pPktHdr, "envN", pch, &papszEnv[i], &pch, &rc);
2675 if (!fOk) /* Bail out on error. */
2676 break;
2677 }
2678 if (fOk)
2679 {
2680 /* 7. stdout */
2681 char *pszStdIn;
2682 if (txsIsStringValid(pPktHdr, "stdin", pch, &pszStdIn, &pch, &rc))
2683 {
2684 /* 8. stdout */
2685 char *pszStdOut;
2686 if (txsIsStringValid(pPktHdr, "stdout", pch, &pszStdOut, &pch, &rc))
2687 {
2688 /* 9. stderr */
2689 char *pszStdErr;
2690 if (txsIsStringValid(pPktHdr, "stderr", pch, &pszStdErr, &pch, &rc))
2691 {
2692 /* 10. testpipe */
2693 char *pszTestPipe;
2694 if (txsIsStringValid(pPktHdr, "testpipe", pch, &pszTestPipe, &pch, &rc))
2695 {
2696 /* 11. username */
2697 char *pszUsername;
2698 if (txsIsStringValid(pPktHdr, "username", pch, &pszUsername, &pch, &rc))
2699 {
2700 /** @todo No password value? */
2701
2702 /* 12. time limit */
2703 uint32_t const cMillies = (size_t)(pchEnd - pch) >= sizeof(uint32_t)
2704 ? *(uint32_t const *)pch
2705 : 0;
2706 if ((size_t)(pchEnd - pch) > sizeof(uint32_t))
2707 rc = txsReplyFailure(pPktHdr, "BAD END ", "Timeout argument not at end of packet (%#x)", (size_t)(pchEnd - pch));
2708 else if ((size_t)(pchEnd - pch) < sizeof(uint32_t))
2709 rc = txsReplyFailure(pPktHdr, "BAD NOTO", "No timeout argument");
2710 else if (cMillies < 1000)
2711 rc = txsReplyFailure(pPktHdr, "BAD TO ", "Timeout is less than a second (%#x)", cMillies);
2712 else
2713 {
2714 pch += sizeof(uint32_t);
2715
2716 /*
2717 * Time to employ a helper here before we go way beyond
2718 * the right margin...
2719 */
2720 rc = txsDoExecHlp(pPktHdr, fFlags, pszExecName,
2721 cArgs, papszArgs,
2722 cEnvVars, papszEnv,
2723 pszStdIn, pszStdOut, pszStdErr, pszTestPipe,
2724 pszUsername,
2725 cMillies == UINT32_MAX ? RT_INDEFINITE_WAIT : cMillies);
2726 }
2727 RTStrFree(pszUsername);
2728 }
2729 RTStrFree(pszTestPipe);
2730 }
2731 RTStrFree(pszStdErr);
2732 }
2733 RTStrFree(pszStdOut);
2734 }
2735 RTStrFree(pszStdIn);
2736 }
2737 }
2738 for (size_t i = 0; i < cEnvVars; i++)
2739 RTStrFree(papszEnv[i]);
2740 RTMemTmpFree(papszEnv);
2741 }
2742 else
2743 rc = txsReplyFailure(pPktHdr, "NO MEM ", "Failed to allocate %zu bytes environ", sizeof(char *) * (cEnvVars + 1));
2744 }
2745 }
2746 for (size_t i = 0; i < cArgs; i++)
2747 RTStrFree(papszArgs[i]);
2748 RTMemTmpFree(papszArgs);
2749 }
2750 else
2751 rc = txsReplyFailure(pPktHdr, "NO MEM ", "Failed to allocate %zu bytes for argv", sizeof(char *) * (cArgs + 1));
2752 }
2753 RTStrFree(pszExecName);
2754
2755 return rc;
2756}
2757
2758/**
2759 * The main loop.
2760 *
2761 * @returns exit code.
2762 */
2763static RTEXITCODE txsMainLoop(void)
2764{
2765 RTEXITCODE enmExitCode = RTEXITCODE_SUCCESS;
2766 while (!g_fTerminate)
2767 {
2768 /*
2769 * Read client command packet and process it.
2770 */
2771 PTXSPKTHDR pPktHdr;
2772 int rc = txsRecvPkt(&pPktHdr, true /*fAutoRetryOnFailure*/);
2773 if (RT_FAILURE(rc))
2774 continue;
2775
2776 /*
2777 * Do a string switch on the opcode bit.
2778 */
2779 /* Connection: */
2780 if ( txsIsSameOpcode(pPktHdr, "HOWDY "))
2781 rc = txsDoHowdy(pPktHdr);
2782 else if (txsIsSameOpcode(pPktHdr, "BYE "))
2783 rc = txsDoBye(pPktHdr);
2784 else if (txsIsSameOpcode(pPktHdr, "UUID "))
2785 rc = txsDoUuid(pPktHdr);
2786 /* Process: */
2787 else if (txsIsSameOpcode(pPktHdr, "EXEC "))
2788 rc = txsDoExec(pPktHdr);
2789 /* Admin: */
2790 else if (txsIsSameOpcode(pPktHdr, "REBOOT "))
2791 rc = txsDoReboot(pPktHdr);
2792 else if (txsIsSameOpcode(pPktHdr, "SHUTDOWN"))
2793 rc = txsDoShutdown(pPktHdr);
2794 /* CD/DVD control: */
2795 else if (txsIsSameOpcode(pPktHdr, "CD EJECT"))
2796 rc = txsDoCdEject(pPktHdr);
2797 /* File system: */
2798 else if (txsIsSameOpcode(pPktHdr, "CLEANUP "))
2799 rc = txsDoCleanup(pPktHdr);
2800 else if (txsIsSameOpcode(pPktHdr, "MKDIR "))
2801 rc = txsDoMkDir(pPktHdr);
2802 else if (txsIsSameOpcode(pPktHdr, "MKDRPATH"))
2803 rc = txsDoMkDrPath(pPktHdr);
2804 else if (txsIsSameOpcode(pPktHdr, "MKSYMLNK"))
2805 rc = txsDoMkSymlnk(pPktHdr);
2806 else if (txsIsSameOpcode(pPktHdr, "RMDIR "))
2807 rc = txsDoRmDir(pPktHdr);
2808 else if (txsIsSameOpcode(pPktHdr, "RMFILE "))
2809 rc = txsDoRmFile(pPktHdr);
2810 else if (txsIsSameOpcode(pPktHdr, "RMSYMLNK"))
2811 rc = txsDoRmSymlnk(pPktHdr);
2812 else if (txsIsSameOpcode(pPktHdr, "RMTREE "))
2813 rc = txsDoRmTree(pPktHdr);
2814 else if (txsIsSameOpcode(pPktHdr, "CHMOD "))
2815 rc = txsDoChMod(pPktHdr);
2816 else if (txsIsSameOpcode(pPktHdr, "CHOWN "))
2817 rc = txsDoChOwn(pPktHdr);
2818 else if (txsIsSameOpcode(pPktHdr, "CHGRP "))
2819 rc = txsDoChGrp(pPktHdr);
2820 else if (txsIsSameOpcode(pPktHdr, "ISDIR "))
2821 rc = txsDoIsDir(pPktHdr);
2822 else if (txsIsSameOpcode(pPktHdr, "ISFILE "))
2823 rc = txsDoIsFile(pPktHdr);
2824 else if (txsIsSameOpcode(pPktHdr, "ISSYMLNK"))
2825 rc = txsDoIsSymlnk(pPktHdr);
2826 else if (txsIsSameOpcode(pPktHdr, "STAT "))
2827 rc = txsDoStat(pPktHdr);
2828 else if (txsIsSameOpcode(pPktHdr, "LSTAT "))
2829 rc = txsDoLStat(pPktHdr);
2830 else if (txsIsSameOpcode(pPktHdr, "LIST "))
2831 rc = txsDoList(pPktHdr);
2832 else if (txsIsSameOpcode(pPktHdr, "PUT FILE"))
2833 rc = txsDoPutFile(pPktHdr);
2834 else if (txsIsSameOpcode(pPktHdr, "GET FILE"))
2835 rc = txsDoGetFile(pPktHdr);
2836#ifndef RT_OS_WINDOWS
2837 else if (txsIsSameOpcode(pPktHdr, "UNPKFILE"))
2838 rc = txsDoUnpackFile(pPktHdr);
2839#endif
2840 /* Misc: */
2841 else
2842 rc = txsReplyUnknown(pPktHdr);
2843
2844 RTMemFree(pPktHdr);
2845 }
2846
2847 return enmExitCode;
2848}
2849
2850
2851/**
2852 * Finalizes the scratch directory, making sure it exists.
2853 *
2854 * @returns exit code.
2855 */
2856static RTEXITCODE txsFinalizeScratch(void)
2857{
2858 RTPathStripTrailingSlash(g_szScratchPath);
2859 char *pszFilename = RTPathFilename(g_szScratchPath);
2860 if (!pszFilename)
2861 return RTMsgErrorExit(RTEXITCODE_FAILURE, "cannot use root for scratch (%s)\n", g_szScratchPath);
2862
2863 int rc;
2864 if (strchr(pszFilename, 'X'))
2865 {
2866 char ch = *pszFilename;
2867 rc = RTDirCreateFullPath(g_szScratchPath, 0700);
2868 *pszFilename = ch;
2869 if (RT_SUCCESS(rc))
2870 rc = RTDirCreateTemp(g_szScratchPath, 0700);
2871 }
2872 else
2873 {
2874 if (RTDirExists(g_szScratchPath))
2875 rc = VINF_SUCCESS;
2876 else
2877 rc = RTDirCreateFullPath(g_szScratchPath, 0700);
2878 }
2879 if (RT_FAILURE(rc))
2880 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create scratch directory: %Rrc (%s)\n", rc, g_szScratchPath);
2881 return RTEXITCODE_SUCCESS;
2882}
2883
2884/**
2885 * Attempts to complete an upgrade by updating the original and relaunching
2886 * ourselves from there again.
2887 *
2888 * On failure, we'll continue running as the temporary copy.
2889 *
2890 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
2891 * @param argc The number of arguments.
2892 * @param argv The argument vector.
2893 * @param pfExit For indicating exit when the exit code is zero.
2894 */
2895static RTEXITCODE txsAutoUpdateStage2(int argc, char **argv, bool *pfExit, const char *pszUpgrading)
2896{
2897 /*
2898 * Copy the current executable onto the original.
2899 * Note that we're racing the original program on some platforms, thus the
2900 * 60 sec sleep mess.
2901 */
2902 char szUpgradePath[RTPATH_MAX];
2903 if (!RTProcGetExecutablePath(szUpgradePath, sizeof(szUpgradePath)))
2904 {
2905 RTMsgError("RTProcGetExecutablePath failed (step 2)\n");
2906 return RTEXITCODE_SUCCESS;
2907 }
2908 void *pvUpgrade;
2909 size_t cbUpgrade;
2910 int rc = RTFileReadAll(szUpgradePath, &pvUpgrade, &cbUpgrade);
2911 if (RT_FAILURE(rc))
2912 {
2913 RTMsgError("RTFileReadAllEx(\"%s\"): %Rrc (step 2)\n", szUpgradePath, rc);
2914 return RTEXITCODE_SUCCESS;
2915 }
2916
2917 uint64_t StartMilliTS = RTTimeMilliTS();
2918 RTFILE hFile;
2919 rc = RTFileOpen(&hFile, pszUpgrading,
2920 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE
2921 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
2922 while ( RT_FAILURE(rc)
2923 && RTTimeMilliTS() - StartMilliTS < 60000)
2924 {
2925 RTThreadSleep(1000);
2926 rc = RTFileOpen(&hFile, pszUpgrading,
2927 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE
2928 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
2929 }
2930 if (RT_SUCCESS(rc))
2931 {
2932 rc = RTFileWrite(hFile, pvUpgrade, cbUpgrade, NULL);
2933 RTFileClose(hFile);
2934 if (RT_SUCCESS(rc))
2935 {
2936 /*
2937 * Relaunch the service with the original name, foricbly barring
2938 * further upgrade cycles in case of bugs (and simplifying the code).
2939 */
2940 const char **papszArgs = (const char **)RTMemAlloc((argc + 1 + 1) * sizeof(char **));
2941 if (papszArgs)
2942 {
2943 papszArgs[0] = pszUpgrading;
2944 for (int i = 1; i < argc; i++)
2945 papszArgs[i] = argv[i];
2946 papszArgs[argc] = "--no-auto-upgrade";
2947 papszArgs[argc + 1] = NULL;
2948
2949 RTMsgInfo("Launching upgraded image: \"%s\"\n", pszUpgrading);
2950 RTPROCESS hProc;
2951 rc = RTProcCreate(pszUpgrading, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, &hProc);
2952 if (RT_SUCCESS(rc))
2953 *pfExit = true;
2954 else
2955 RTMsgError("RTProcCreate(\"%s\"): %Rrc (upgrade stage 2)\n", pszUpgrading, rc);
2956 RTMemFree(papszArgs);
2957 }
2958 else
2959 RTMsgError("RTMemAlloc failed during upgrade attempt (stage 2)\n");
2960 }
2961 else
2962 RTMsgError("RTFileWrite(%s,,%zu): %Rrc (step 2) - BAD\n", pszUpgrading, cbUpgrade, rc);
2963 }
2964 else
2965 RTMsgError("RTFileOpen(,%s,): %Rrc\n", pszUpgrading, rc);
2966 RTFileReadAllFree(pvUpgrade, cbUpgrade);
2967 return RTEXITCODE_SUCCESS;
2968}
2969
2970/**
2971 * Checks for an upgrade and respawns if there is.
2972 *
2973 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
2974 * @param argc The number of arguments.
2975 * @param argv The argument vector.
2976 * @param pfExit For indicating exit when the exit code is zero.
2977 */
2978static RTEXITCODE txsAutoUpdateStage1(int argc, char **argv, bool *pfExit)
2979{
2980 /*
2981 * Figure names of the current service image and the potential upgrade.
2982 */
2983 char szOrgPath[RTPATH_MAX];
2984 if (!RTProcGetExecutablePath(szOrgPath, sizeof(szOrgPath)))
2985 {
2986 RTMsgError("RTProcGetExecutablePath failed\n");
2987 return RTEXITCODE_SUCCESS;
2988 }
2989
2990 char szUpgradePath[RTPATH_MAX];
2991 int rc = RTPathJoin(szUpgradePath, sizeof(szUpgradePath), g_szCdRomPath, g_szOsSlashArchShortName);
2992 if (RT_SUCCESS(rc))
2993 rc = RTPathAppend(szUpgradePath, sizeof(szUpgradePath), RTPathFilename(szOrgPath));
2994 if (RT_FAILURE(rc))
2995 {
2996 RTMsgError("Failed to construct path to potential service upgrade: %Rrc\n", rc);
2997 return RTEXITCODE_SUCCESS;
2998 }
2999
3000 /*
3001 * Query information about the two images and read the entire potential source file.
3002 */
3003 RTFSOBJINFO UpgradeInfo;
3004 rc = RTPathQueryInfo(szUpgradePath, &UpgradeInfo, RTFSOBJATTRADD_NOTHING);
3005 if ( rc == VERR_FILE_NOT_FOUND
3006 || rc == VERR_PATH_NOT_FOUND
3007 || rc == VERR_MEDIA_NOT_PRESENT
3008 || rc == VERR_MEDIA_NOT_RECOGNIZED)
3009 return RTEXITCODE_SUCCESS;
3010 if (RT_FAILURE(rc))
3011 {
3012 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (upgrade)\n", szUpgradePath, rc);
3013 return RTEXITCODE_SUCCESS;
3014 }
3015
3016 RTFSOBJINFO OrgInfo;
3017 rc = RTPathQueryInfo(szOrgPath, &OrgInfo, RTFSOBJATTRADD_NOTHING);
3018 if (RT_FAILURE(rc))
3019 {
3020 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (old)\n", szOrgPath, rc);
3021 return RTEXITCODE_SUCCESS;
3022 }
3023
3024 void *pvUpgrade;
3025 size_t cbUpgrade;
3026 rc = RTFileReadAllEx(szUpgradePath, 0, UpgradeInfo.cbObject, RTFILE_RDALL_O_DENY_NONE, &pvUpgrade, &cbUpgrade);
3027 if (RT_FAILURE(rc))
3028 {
3029 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (old)\n", szOrgPath, rc);
3030 return RTEXITCODE_SUCCESS;
3031 }
3032
3033 /*
3034 * Compare and see if we've got a different service image or not.
3035 */
3036 if (OrgInfo.cbObject == UpgradeInfo.cbObject)
3037 {
3038 /* must compare bytes. */
3039 void *pvOrg;
3040 size_t cbOrg;
3041 rc = RTFileReadAllEx(szOrgPath, 0, OrgInfo.cbObject, RTFILE_RDALL_O_DENY_NONE, &pvOrg, &cbOrg);
3042 if (RT_FAILURE(rc))
3043 {
3044 RTMsgError("RTFileReadAllEx(\"%s\"): %Rrc\n", szOrgPath, rc);
3045 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3046 return RTEXITCODE_SUCCESS;
3047 }
3048 bool fSame = !memcmp(pvUpgrade, pvOrg, OrgInfo.cbObject);
3049 RTFileReadAllFree(pvOrg, cbOrg);
3050 if (fSame)
3051 {
3052 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3053 return RTEXITCODE_SUCCESS;
3054 }
3055 }
3056
3057 /*
3058 * Should upgrade. Start by creating an executable copy of the update
3059 * image in the scratch area.
3060 */
3061 RTEXITCODE rcExit = txsFinalizeScratch();
3062 if (rcExit == RTEXITCODE_SUCCESS)
3063 {
3064 char szTmpPath[RTPATH_MAX];
3065 rc = RTPathJoin(szTmpPath, sizeof(szTmpPath), g_szScratchPath, RTPathFilename(szOrgPath));
3066 if (RT_SUCCESS(rc))
3067 {
3068 RTFileDelete(szTmpPath); /* shouldn't hurt. */
3069
3070 RTFILE hFile;
3071 rc = RTFileOpen(&hFile, szTmpPath,
3072 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE
3073 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3074 if (RT_SUCCESS(rc))
3075 {
3076 rc = RTFileWrite(hFile, pvUpgrade, UpgradeInfo.cbObject, NULL);
3077 RTFileClose(hFile);
3078 if (RT_SUCCESS(rc))
3079 {
3080 /*
3081 * Try execute the new image and quit if it works.
3082 */
3083 const char **papszArgs = (const char **)RTMemAlloc((argc + 2 + 1) * sizeof(char **));
3084 if (papszArgs)
3085 {
3086 papszArgs[0] = szTmpPath;
3087 for (int i = 1; i < argc; i++)
3088 papszArgs[i] = argv[i];
3089 papszArgs[argc] = "--upgrading";
3090 papszArgs[argc + 1] = szOrgPath;
3091 papszArgs[argc + 2] = NULL;
3092
3093 RTMsgInfo("Launching intermediate automatic upgrade stage: \"%s\"\n", szTmpPath);
3094 RTPROCESS hProc;
3095 rc = RTProcCreate(szTmpPath, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, &hProc);
3096 if (RT_SUCCESS(rc))
3097 *pfExit = true;
3098 else
3099 RTMsgError("RTProcCreate(\"%s\"): %Rrc (upgrade stage 1)\n", szTmpPath, rc);
3100 RTMemFree(papszArgs);
3101 }
3102 else
3103 RTMsgError("RTMemAlloc failed during upgrade attempt (stage)\n");
3104 }
3105 else
3106 RTMsgError("RTFileWrite(%s,,%zu): %Rrc\n", szTmpPath, UpgradeInfo.cbObject, rc);
3107 }
3108 else
3109 RTMsgError("RTFileOpen(,%s,): %Rrc\n", szTmpPath, rc);
3110 }
3111 else
3112 RTMsgError("Failed to construct path to temporary upgrade image: %Rrc\n", rc);
3113 }
3114
3115 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3116 return rcExit;
3117}
3118
3119/**
3120 * Determines the default configuration.
3121 */
3122static void txsSetDefaults(void)
3123{
3124 /*
3125 * OS and ARCH.
3126 */
3127 AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
3128 strcpy(g_szOsShortName, KBUILD_TARGET);
3129
3130 AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
3131 strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);
3132
3133 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
3134 strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
3135 g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
3136 strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
3137
3138 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
3139 strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
3140 g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
3141 strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
3142
3143#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
3144 strcpy(g_szExeSuff, ".exe");
3145 strcpy(g_szScriptSuff, ".cmd");
3146#else
3147 strcpy(g_szExeSuff, "");
3148 strcpy(g_szScriptSuff, ".sh");
3149#endif
3150
3151 /*
3152 * The CD/DVD-ROM location.
3153 */
3154 /** @todo do a better job here :-) */
3155#ifdef RT_OS_WINDOWS
3156 strcpy(g_szDefCdRomPath, "D:/");
3157#elif defined(RT_OS_OS2)
3158 strcpy(g_szDefCdRomPath, "D:/");
3159#else
3160 if (RTDirExists("/media"))
3161 strcpy(g_szDefCdRomPath, "/media/cdrom");
3162 else
3163 strcpy(g_szDefCdRomPath, "/mnt/cdrom");
3164#endif
3165 strcpy(g_szCdRomPath, g_szDefCdRomPath);
3166
3167 /*
3168 * Temporary directory.
3169 */
3170 int rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
3171 if (RT_SUCCESS(rc))
3172#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
3173 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "txs-XXXX.tmp");
3174#else
3175 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "txs-XXXXXXXXX.tmp");
3176#endif
3177 if (RT_FAILURE(rc))
3178 {
3179 RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
3180 strcpy(g_szDefScratchPath, "/tmp/txs-XXXX.tmp");
3181 }
3182 strcpy(g_szScratchPath, g_szDefScratchPath);
3183
3184 /*
3185 * The default transporter is the first one.
3186 */
3187 g_pTransport = g_apTransports[0];
3188}
3189
3190/**
3191 * Prints the usage.
3192 *
3193 * @param pStrm Where to print it.
3194 * @param pszArgv0 The program name (argv[0]).
3195 */
3196static void txsUsage(PRTSTREAM pStrm, const char *argv0)
3197{
3198 RTStrmPrintf(pStrm,
3199 "Usage: %Rbn [options]\n"
3200 "\n"
3201 "Options:\n"
3202 " --cdrom <path>\n"
3203 " Where the CD/DVD-ROM will be mounted.\n"
3204 " Default: %s\n"
3205 " --scratch <path>\n"
3206 " Where to put scratch files.\n"
3207 " Default: %s \n"
3208 ,
3209 argv0,
3210 g_szDefCdRomPath,
3211 g_szDefScratchPath);
3212 RTStrmPrintf(pStrm,
3213 " --transport <name>\n"
3214 " Use the specified transport layer, one of the following:\n");
3215 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3216 RTStrmPrintf(pStrm, " %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
3217 RTStrmPrintf(pStrm, " Default: %s\n", g_pTransport->szName);
3218 RTStrmPrintf(pStrm,
3219 " --auto-upgrade, --no-auto-upgrade\n"
3220 " To enable or disable the automatic upgrade mechanism where any different\n"
3221 " version found on the CD-ROM on startup will replace the initial copy.\n"
3222 " Default: --auto-upgrade\n"
3223 " --upgrading <org-path>\n"
3224 " Internal use only.\n");
3225 RTStrmPrintf(pStrm,
3226 " --display-output, --no-display-output\n"
3227 " Display the output and the result of all child processes.\n");
3228 RTStrmPrintf(pStrm,
3229 " --foreground\n"
3230 " Don't daemonize, run in the foreground.\n");
3231 RTStrmPrintf(pStrm,
3232 " --help, -h, -?\n"
3233 " Display this message and exit.\n"
3234 " --version, -V\n"
3235 " Display the version and exit.\n");
3236
3237 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3238 if (g_apTransports[i]->cOpts)
3239 {
3240 RTStrmPrintf(pStrm,
3241 "\n"
3242 "Options for %s:\n", g_apTransports[i]->szName);
3243 g_apTransports[i]->pfnUsage(g_pStdOut);
3244 }
3245}
3246
3247/**
3248 * Parses the arguments.
3249 *
3250 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3251 * @param argc The number of arguments.
3252 * @param argv The argument vector.
3253 * @param pfExit For indicating exit when the exit code is zero.
3254 */
3255static RTEXITCODE txsParseArgv(int argc, char **argv, bool *pfExit)
3256{
3257 *pfExit = false;
3258
3259 /*
3260 * Storage for locally handled options.
3261 */
3262 bool fAutoUpgrade = true;
3263 bool fDaemonize = true;
3264 bool fDaemonized = false;
3265 const char *pszUpgrading = NULL;
3266
3267 /*
3268 * Combine the base and transport layer option arrays.
3269 */
3270 static const RTGETOPTDEF s_aBaseOptions[] =
3271 {
3272 { "--transport", 't', RTGETOPT_REQ_STRING },
3273 { "--cdrom", 'c', RTGETOPT_REQ_STRING },
3274 { "--scratch", 's', RTGETOPT_REQ_STRING },
3275 { "--auto-upgrade", 'a', RTGETOPT_REQ_NOTHING },
3276 { "--no-auto-upgrade", 'A', RTGETOPT_REQ_NOTHING },
3277 { "--upgrading", 'U', RTGETOPT_REQ_STRING },
3278 { "--display-output", 'd', RTGETOPT_REQ_NOTHING },
3279 { "--no-display-output",'D', RTGETOPT_REQ_NOTHING },
3280 { "--foreground", 'f', RTGETOPT_REQ_NOTHING },
3281 { "--daemonized", 'Z', RTGETOPT_REQ_NOTHING },
3282 };
3283
3284 size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
3285 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3286 cOptions += g_apTransports[i]->cOpts;
3287
3288 PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
3289 if (!paOptions)
3290 return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");
3291
3292 memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
3293 cOptions = RT_ELEMENTS(s_aBaseOptions);
3294 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3295 {
3296 memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
3297 cOptions += g_apTransports[i]->cOpts;
3298 }
3299
3300 /*
3301 * Parse the arguments.
3302 */
3303 RTGETOPTSTATE GetState;
3304 int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
3305 AssertRC(rc);
3306
3307 int ch;
3308 RTGETOPTUNION Val;
3309 while ((ch = RTGetOpt(&GetState, &Val)))
3310 {
3311 switch (ch)
3312 {
3313 case 'a':
3314 fAutoUpgrade = true;
3315 break;
3316
3317 case 'A':
3318 fAutoUpgrade = false;
3319 break;
3320
3321 case 'c':
3322 rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
3323 if (RT_FAILURE(rc))
3324 return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
3325 break;
3326
3327 case 'd':
3328 g_fDisplayOutput = true;
3329 break;
3330
3331 case 'D':
3332 g_fDisplayOutput = false;
3333 break;
3334
3335 case 'f':
3336 fDaemonize = false;
3337 break;
3338
3339 case 'h':
3340 txsUsage(g_pStdOut, argv[0]);
3341 *pfExit = true;
3342 return RTEXITCODE_SUCCESS;
3343
3344 case 's':
3345 rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
3346 if (RT_FAILURE(rc))
3347 return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
3348 break;
3349
3350 case 't':
3351 {
3352 PCTXSTRANSPORT pTransport = NULL;
3353 for (size_t i = 0; RT_ELEMENTS(g_apTransports); i++)
3354 if (!strcmp(g_apTransports[i]->szName, Val.psz))
3355 {
3356 pTransport = g_apTransports[i];
3357 break;
3358 }
3359 if (!pTransport)
3360 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
3361 g_pTransport = pTransport;
3362 break;
3363 }
3364
3365 case 'U':
3366 pszUpgrading = Val.psz;
3367 break;
3368
3369 case 'V':
3370 RTPrintf("$Revision: 62673 $\n");
3371 *pfExit = true;
3372 return RTEXITCODE_SUCCESS;
3373
3374 case 'Z':
3375 fDaemonized = true;
3376 fDaemonize = false;
3377 break;
3378
3379 default:
3380 {
3381 rc = VERR_TRY_AGAIN;
3382 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3383 if (g_apTransports[i]->cOpts)
3384 {
3385 rc = g_apTransports[i]->pfnOption(ch, &Val);
3386 if (RT_SUCCESS(rc))
3387 break;
3388 if (rc != VERR_TRY_AGAIN)
3389 {
3390 *pfExit = true;
3391 return RTEXITCODE_SYNTAX;
3392 }
3393 }
3394 if (rc == VERR_TRY_AGAIN)
3395 {
3396 *pfExit = true;
3397 return RTGetOptPrintError(ch, &Val);
3398 }
3399 break;
3400 }
3401 }
3402 }
3403
3404 /*
3405 * Handle automatic upgrading of the service.
3406 */
3407 if (fAutoUpgrade && !*pfExit)
3408 {
3409 RTEXITCODE rcExit;
3410 if (pszUpgrading)
3411 rcExit = txsAutoUpdateStage2(argc, argv, pfExit, pszUpgrading);
3412 else
3413 rcExit = txsAutoUpdateStage1(argc, argv, pfExit);
3414 if ( *pfExit
3415 || rcExit != RTEXITCODE_SUCCESS)
3416 return rcExit;
3417 }
3418
3419 /*
3420 * Daemonize ourselves if asked to.
3421 */
3422 if (fDaemonize && !*pfExit)
3423 {
3424 rc = RTProcDaemonize(argv, "--daemonized");
3425 if (RT_FAILURE(rc))
3426 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
3427 *pfExit = true;
3428 }
3429
3430 return RTEXITCODE_SUCCESS;
3431}
3432
3433
3434int main(int argc, char **argv)
3435{
3436 /*
3437 * Initialize the runtime.
3438 */
3439 int rc = RTR3InitExe(argc, &argv, 0);
3440 if (RT_FAILURE(rc))
3441 return RTMsgInitFailure(rc);
3442
3443 /*
3444 * Determine defaults and parse the arguments.
3445 */
3446 txsSetDefaults();
3447 bool fExit;
3448 RTEXITCODE rcExit = txsParseArgv(argc, argv, &fExit);
3449 if (rcExit != RTEXITCODE_SUCCESS || fExit)
3450 return rcExit;
3451
3452 /*
3453 * Generate a UUID for this TXS instance.
3454 */
3455 rc = RTUuidCreate(&g_InstanceUuid);
3456 if (RT_FAILURE(rc))
3457 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTUuidCreate failed: %Rrc", rc);
3458
3459 /*
3460 * Finalize the scratch directory and initialize the transport layer.
3461 */
3462 rcExit = txsFinalizeScratch();
3463 if (rcExit != RTEXITCODE_SUCCESS)
3464 return rcExit;
3465
3466 rc = g_pTransport->pfnInit();
3467 if (RT_FAILURE(rc))
3468 return RTEXITCODE_FAILURE;
3469
3470 /*
3471 * Ok, start working
3472 */
3473 rcExit = txsMainLoop();
3474
3475 /*
3476 * Cleanup.
3477 */
3478 g_pTransport->pfnTerm();
3479
3480 return rcExit;
3481}
3482
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