VirtualBox

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

Last change on this file since 93895 was 93895, checked in by vboxsync, 3 years ago

Validation Kit/TxS: Implemented (local) copy file support for TxS. Useful for copying stuff around on guests. bugref:10195

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