VirtualBox

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

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

Validation Kit/TxS: Added release logging (via VBOX_TXS_RELEASE_LOG) to %TEMP%, to instrument testing issues on guests where TxS is being involved.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 135.8 KB
Line 
1/* $Id: TestExecService.cpp 93732 2022-02-14 15:44:35Z 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.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#define LOG_GROUP RTLOGGROUP_DEFAULT
32#include <iprt/alloca.h>
33#include <iprt/asm.h>
34#include <iprt/assert.h>
35#include <iprt/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 * Uploads a file from the client.
1014 *
1015 * The transfer sends a stream of DATA packets (0 or more) and ends it all with
1016 * a DATA EOF packet. We ACK each of these, so that if a write error occurs we
1017 * can abort the transfer straight away.
1018 *
1019 * @returns IPRT status code from send.
1020 * @param pPktHdr The put file packet.
1021 * @param fHasMode Set if the packet starts with a mode field.
1022 */
1023static int txsDoPutFile(PCTXSPKTHDR pPktHdr, bool fHasMode)
1024{
1025 int rc;
1026 RTFMODE fMode = 0;
1027 char *pszPath;
1028 if (!fHasMode)
1029 {
1030 if (!txsIsStringPktValid(pPktHdr, "file", &pszPath, &rc))
1031 return rc;
1032 }
1033 else
1034 {
1035 /* After the packet header follows a mode mask and the remainder of
1036 the packet is the zero terminated file name. */
1037 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2;
1038 if (pPktHdr->cb < cbMin)
1039 return txsReplyBadMinSize(pPktHdr, cbMin);
1040 if (!txsIsStringValid(pPktHdr, "file", (const char *)(pPktHdr + 1) + sizeof(RTFMODE), &pszPath, NULL, &rc))
1041 return rc;
1042 fMode = *(RTFMODE const *)(pPktHdr + 1);
1043 fMode <<= RTFILE_O_CREATE_MODE_SHIFT;
1044 fMode &= RTFILE_O_CREATE_MODE_MASK;
1045 }
1046
1047 RTFILE hFile;
1048 rc = RTFileOpen(&hFile, pszPath, RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE | fMode);
1049 if (RT_SUCCESS(rc))
1050 {
1051 bool fSuccess = false;
1052 rc = txsReplyAck(pPktHdr);
1053 if (RT_SUCCESS(rc))
1054 {
1055 if (fMode)
1056 RTFileSetMode(hFile, fMode);
1057
1058 /*
1059 * Read client command packets and process them.
1060 */
1061 uint32_t uMyCrc32 = RTCrc32Start();
1062 for (;;)
1063 {
1064 PTXSPKTHDR pDataPktHdr;
1065 rc = txsRecvPkt(&pDataPktHdr, false /*fAutoRetryOnFailure*/);
1066 if (RT_FAILURE(rc))
1067 break;
1068
1069 if (txsIsSameOpcode(pDataPktHdr, "DATA"))
1070 {
1071 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(uint32_t);
1072 if (pDataPktHdr->cb >= cbMin)
1073 {
1074 size_t cbData = pDataPktHdr->cb - cbMin;
1075 const void *pvData = (const char *)pDataPktHdr + cbMin;
1076 uint32_t uCrc32 = *(uint32_t const *)(pDataPktHdr + 1);
1077
1078 uMyCrc32 = RTCrc32Process(uMyCrc32, pvData, cbData);
1079 if (RTCrc32Finish(uMyCrc32) == uCrc32)
1080 {
1081 rc = RTFileWrite(hFile, pvData, cbData, NULL);
1082 if (RT_SUCCESS(rc))
1083 {
1084 rc = txsReplyAck(pDataPktHdr);
1085 RTMemFree(pDataPktHdr);
1086 continue;
1087 }
1088
1089 rc = txsReplyRC(pDataPktHdr, rc, "RTFileWrite");
1090 }
1091 else
1092 rc = txsReplyFailure(pDataPktHdr, "BAD DCRC", "mycrc=%#x your=%#x", uMyCrc32, uCrc32);
1093 }
1094 else
1095 rc = txsReplyBadMinSize(pPktHdr, cbMin);
1096 }
1097 else if (txsIsSameOpcode(pDataPktHdr, "DATA EOF"))
1098 {
1099 if (pDataPktHdr->cb == sizeof(TXSPKTHDR) + sizeof(uint32_t))
1100 {
1101 uint32_t uCrc32 = *(uint32_t const *)(pDataPktHdr + 1);
1102 if (RTCrc32Finish(uMyCrc32) == uCrc32)
1103 {
1104 rc = txsReplyAck(pDataPktHdr);
1105 fSuccess = RT_SUCCESS(rc);
1106 }
1107 else
1108 rc = txsReplyFailure(pDataPktHdr, "BAD DCRC", "mycrc=%#x your=%#x", uMyCrc32, uCrc32);
1109 }
1110 else
1111 rc = txsReplyAck(pDataPktHdr);
1112 }
1113 else if (txsIsSameOpcode(pDataPktHdr, "ABORT"))
1114 rc = txsReplyAck(pDataPktHdr);
1115 else
1116 rc = txsReplyFailure(pDataPktHdr, "UNKNOWN ", "Opcode '%.8s' is not known or not recognized during PUT FILE", pDataPktHdr->achOpcode);
1117 RTMemFree(pDataPktHdr);
1118 break;
1119 }
1120 }
1121
1122 RTFileClose(hFile);
1123
1124 /*
1125 * Delete the file on failure.
1126 */
1127 if (!fSuccess)
1128 RTFileDelete(pszPath);
1129 }
1130 else
1131 rc = txsReplyRC(pPktHdr, rc, "RTFileOpen(,\"%s\",)", pszPath);
1132
1133 RTStrFree(pszPath);
1134 return rc;
1135}
1136
1137/**
1138 * List the entries in the specified directory.
1139 *
1140 * @returns IPRT status code from send.
1141 * @param pPktHdr The list packet.
1142 */
1143static int txsDoList(PCTXSPKTHDR pPktHdr)
1144{
1145 int rc;
1146 char *pszPath;
1147 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1148 return rc;
1149
1150 rc = txsReplyNotImplemented(pPktHdr);
1151
1152 RTStrFree(pszPath);
1153 return rc;
1154}
1155
1156/**
1157 * Worker for STAT and LSTAT for packing down the file info reply.
1158 *
1159 * @returns IPRT status code from send.
1160 * @param pInfo The info to pack down.
1161 */
1162static int txsReplyObjInfo(PCRTFSOBJINFO pInfo)
1163{
1164 struct
1165 {
1166 TXSPKTHDR Hdr;
1167 int64_t cbObject;
1168 int64_t cbAllocated;
1169 int64_t nsAccessTime;
1170 int64_t nsModificationTime;
1171 int64_t nsChangeTime;
1172 int64_t nsBirthTime;
1173 uint32_t fMode;
1174 uint32_t uid;
1175 uint32_t gid;
1176 uint32_t cHardLinks;
1177 uint64_t INodeIdDevice;
1178 uint64_t INodeId;
1179 uint64_t Device;
1180 char abPadding[TXSPKT_ALIGNMENT];
1181 } Pkt;
1182
1183 Pkt.cbObject = pInfo->cbObject;
1184 Pkt.cbAllocated = pInfo->cbAllocated;
1185 Pkt.nsAccessTime = RTTimeSpecGetNano(&pInfo->AccessTime);
1186 Pkt.nsModificationTime = RTTimeSpecGetNano(&pInfo->ModificationTime);
1187 Pkt.nsChangeTime = RTTimeSpecGetNano(&pInfo->ChangeTime);
1188 Pkt.nsBirthTime = RTTimeSpecGetNano(&pInfo->BirthTime);
1189 Pkt.fMode = pInfo->Attr.fMode;
1190 Pkt.uid = pInfo->Attr.u.Unix.uid;
1191 Pkt.gid = pInfo->Attr.u.Unix.gid;
1192 Pkt.cHardLinks = pInfo->Attr.u.Unix.cHardlinks;
1193 Pkt.INodeIdDevice = pInfo->Attr.u.Unix.INodeIdDevice;
1194 Pkt.INodeId = pInfo->Attr.u.Unix.INodeId;
1195 Pkt.Device = pInfo->Attr.u.Unix.Device;
1196
1197 return txsReplyInternal(&Pkt.Hdr, "FILEINFO", sizeof(Pkt) - TXSPKT_ALIGNMENT - sizeof(TXSPKTHDR));
1198}
1199
1200/**
1201 * Get info about a file system object, following all but the symbolic links
1202 * except in the final path component.
1203 *
1204 * @returns IPRT status code from send.
1205 * @param pPktHdr The lstat packet.
1206 */
1207static int txsDoLStat(PCTXSPKTHDR pPktHdr)
1208{
1209 int rc;
1210 char *pszPath;
1211 if (!txsIsStringPktValid(pPktHdr, "path", &pszPath, &rc))
1212 return rc;
1213
1214 RTFSOBJINFO Info;
1215 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_UNIX, RTPATH_F_ON_LINK);
1216 if (RT_SUCCESS(rc))
1217 rc = txsReplyObjInfo(&Info);
1218 else
1219 rc = txsReplyRC(pPktHdr, rc, "RTPathQueryInfoEx(\"%s\",,UNIX,ON_LINK)", pszPath);
1220
1221 RTStrFree(pszPath);
1222 return rc;
1223}
1224
1225/**
1226 * Get info about a file system object, following all symbolic links.
1227 *
1228 * @returns IPRT status code from send.
1229 * @param pPktHdr The stat packet.
1230 */
1231static int txsDoStat(PCTXSPKTHDR pPktHdr)
1232{
1233 int rc;
1234 char *pszPath;
1235 if (!txsIsStringPktValid(pPktHdr, "path", &pszPath, &rc))
1236 return rc;
1237
1238 RTFSOBJINFO Info;
1239 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_UNIX, RTPATH_F_FOLLOW_LINK);
1240 if (RT_SUCCESS(rc))
1241 rc = txsReplyObjInfo(&Info);
1242 else
1243 rc = txsReplyRC(pPktHdr, rc, "RTPathQueryInfoEx(\"%s\",,UNIX,FOLLOW_LINK)", pszPath);
1244
1245 RTStrFree(pszPath);
1246 return rc;
1247}
1248
1249/**
1250 * Checks if the specified path is a symbolic link.
1251 *
1252 * @returns IPRT status code from send.
1253 * @param pPktHdr The issymlnk packet.
1254 */
1255static int txsDoIsSymlnk(PCTXSPKTHDR pPktHdr)
1256{
1257 int rc;
1258 char *pszPath;
1259 if (!txsIsStringPktValid(pPktHdr, "symlink", &pszPath, &rc))
1260 return rc;
1261
1262 RTFSOBJINFO Info;
1263 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1264 if (RT_SUCCESS(rc) && RTFS_IS_SYMLINK(Info.Attr.fMode))
1265 rc = txsReplySimple(pPktHdr, "TRUE ");
1266 else
1267 rc = txsReplySimple(pPktHdr, "FALSE ");
1268
1269 RTStrFree(pszPath);
1270 return rc;
1271}
1272
1273/**
1274 * Checks if the specified path is a file or not.
1275 *
1276 * If the final path element is a symbolic link to a file, we'll return
1277 * FALSE.
1278 *
1279 * @returns IPRT status code from send.
1280 * @param pPktHdr The isfile packet.
1281 */
1282static int txsDoIsFile(PCTXSPKTHDR pPktHdr)
1283{
1284 int rc;
1285 char *pszPath;
1286 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1287 return rc;
1288
1289 RTFSOBJINFO Info;
1290 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1291 if (RT_SUCCESS(rc) && RTFS_IS_FILE(Info.Attr.fMode))
1292 rc = txsReplySimple(pPktHdr, "TRUE ");
1293 else
1294 rc = txsReplySimple(pPktHdr, "FALSE ");
1295
1296 RTStrFree(pszPath);
1297 return rc;
1298}
1299
1300/**
1301 * Checks if the specified path is a directory or not.
1302 *
1303 * If the final path element is a symbolic link to a directory, we'll return
1304 * FALSE.
1305 *
1306 * @returns IPRT status code from send.
1307 * @param pPktHdr The isdir packet.
1308 */
1309static int txsDoIsDir(PCTXSPKTHDR pPktHdr)
1310{
1311 int rc;
1312 char *pszPath;
1313 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1314 return rc;
1315
1316 RTFSOBJINFO Info;
1317 rc = RTPathQueryInfoEx(pszPath, &Info, RTFSOBJATTRADD_NOTHING, RTPATH_F_ON_LINK);
1318 if (RT_SUCCESS(rc) && RTFS_IS_DIRECTORY(Info.Attr.fMode))
1319 rc = txsReplySimple(pPktHdr, "TRUE ");
1320 else
1321 rc = txsReplySimple(pPktHdr, "FALSE ");
1322
1323 RTStrFree(pszPath);
1324 return rc;
1325}
1326
1327/**
1328 * Changes the owner of a file, directory or symbolic link.
1329 *
1330 * @returns IPRT status code from send.
1331 * @param pPktHdr The chmod packet.
1332 */
1333static int txsDoChOwn(PCTXSPKTHDR pPktHdr)
1334{
1335#ifdef RT_OS_WINDOWS
1336 return txsReplyNotImplemented(pPktHdr);
1337#else
1338 /* After the packet header follows a 32-bit UID and 32-bit GID, while the
1339 remainder of the packet is the zero terminated path. */
1340 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2;
1341 if (pPktHdr->cb < cbMin)
1342 return txsReplyBadMinSize(pPktHdr, cbMin);
1343
1344 int rc;
1345 char *pszPath;
1346 if (!txsIsStringValid(pPktHdr, "path", (const char *)(pPktHdr + 1) + sizeof(uint32_t) * 2, &pszPath, NULL, &rc))
1347 return rc;
1348
1349 uint32_t uid = ((uint32_t const *)(pPktHdr + 1))[0];
1350 uint32_t gid = ((uint32_t const *)(pPktHdr + 1))[1];
1351
1352 rc = RTPathSetOwnerEx(pszPath, uid, gid, RTPATH_F_ON_LINK);
1353
1354 rc = txsReplyRC(pPktHdr, rc, "RTPathSetOwnerEx(\"%s\", %u, %u)", pszPath, uid, gid);
1355 RTStrFree(pszPath);
1356 return rc;
1357#endif
1358}
1359
1360/**
1361 * Changes the mode of a file or directory.
1362 *
1363 * @returns IPRT status code from send.
1364 * @param pPktHdr The chmod packet.
1365 */
1366static int txsDoChMod(PCTXSPKTHDR pPktHdr)
1367{
1368 /* After the packet header follows a mode mask and the remainder of
1369 the packet is the zero terminated file name. */
1370 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2;
1371 if (pPktHdr->cb < cbMin)
1372 return txsReplyBadMinSize(pPktHdr, cbMin);
1373
1374 int rc;
1375 char *pszPath;
1376 if (!txsIsStringValid(pPktHdr, "path", (const char *)(pPktHdr + 1) + sizeof(RTFMODE), &pszPath, NULL, &rc))
1377 return rc;
1378
1379 RTFMODE fMode = *(RTFMODE const *)(pPktHdr + 1);
1380
1381 rc = RTPathSetMode(pszPath, fMode);
1382
1383 rc = txsReplyRC(pPktHdr, rc, "RTPathSetMode(\"%s\", %o)", pszPath, fMode);
1384 RTStrFree(pszPath);
1385 return rc;
1386}
1387
1388/**
1389 * Removes a directory tree.
1390 *
1391 * @returns IPRT status code from send.
1392 * @param pPktHdr The rmtree packet.
1393 */
1394static int txsDoRmTree(PCTXSPKTHDR pPktHdr)
1395{
1396 int rc;
1397 char *pszPath;
1398 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1399 return rc;
1400
1401 rc = RTDirRemoveRecursive(pszPath, 0 /*fFlags*/);
1402
1403 rc = txsReplyRC(pPktHdr, rc, "RTDirRemoveRecusive(\"%s\",0)", pszPath);
1404 RTStrFree(pszPath);
1405 return rc;
1406}
1407
1408/**
1409 * Removes a symbolic link.
1410 *
1411 * @returns IPRT status code from send.
1412 * @param pPktHdr The rmsymlink packet.
1413 */
1414static int txsDoRmSymlnk(PCTXSPKTHDR pPktHdr)
1415{
1416 int rc;
1417 char *pszPath;
1418 if (!txsIsStringPktValid(pPktHdr, "symlink", &pszPath, &rc))
1419 return rc;
1420
1421 rc = RTSymlinkDelete(pszPath, 0);
1422
1423 rc = txsReplyRC(pPktHdr, rc, "RTSymlinkDelete(\"%s\")", pszPath);
1424 RTStrFree(pszPath);
1425 return rc;
1426}
1427
1428/**
1429 * Removes a file.
1430 *
1431 * @returns IPRT status code from send.
1432 * @param pPktHdr The rmfile packet.
1433 */
1434static int txsDoRmFile(PCTXSPKTHDR pPktHdr)
1435{
1436 int rc;
1437 char *pszPath;
1438 if (!txsIsStringPktValid(pPktHdr, "file", &pszPath, &rc))
1439 return rc;
1440
1441 rc = RTFileDelete(pszPath);
1442
1443 rc = txsReplyRC(pPktHdr, rc, "RTFileDelete(\"%s\")", pszPath);
1444 RTStrFree(pszPath);
1445 return rc;
1446}
1447
1448/**
1449 * Removes a directory.
1450 *
1451 * @returns IPRT status code from send.
1452 * @param pPktHdr The rmdir packet.
1453 */
1454static int txsDoRmDir(PCTXSPKTHDR pPktHdr)
1455{
1456 int rc;
1457 char *pszPath;
1458 if (!txsIsStringPktValid(pPktHdr, "dir", &pszPath, &rc))
1459 return rc;
1460
1461 rc = RTDirRemove(pszPath);
1462
1463 rc = txsReplyRC(pPktHdr, rc, "RTDirRemove(\"%s\")", pszPath);
1464 RTStrFree(pszPath);
1465 return rc;
1466}
1467
1468/**
1469 * Creates a symbolic link.
1470 *
1471 * @returns IPRT status code from send.
1472 * @param pPktHdr The mksymlnk packet.
1473 */
1474static int txsDoMkSymlnk(PCTXSPKTHDR pPktHdr)
1475{
1476 return txsReplyNotImplemented(pPktHdr);
1477}
1478
1479/**
1480 * Creates a directory and all its parents.
1481 *
1482 * @returns IPRT status code from send.
1483 * @param pPktHdr The mkdir -p packet.
1484 */
1485static int txsDoMkDrPath(PCTXSPKTHDR pPktHdr)
1486{
1487 /* The same format as the MKDIR command. */
1488 if (pPktHdr->cb < sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2)
1489 return txsReplyBadMinSize(pPktHdr, sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2);
1490
1491 int rc;
1492 char *pszPath;
1493 if (!txsIsStringValid(pPktHdr, "dir", (const char *)(pPktHdr + 1) + sizeof(RTFMODE), &pszPath, NULL, &rc))
1494 return rc;
1495
1496 RTFMODE fMode = *(RTFMODE const *)(pPktHdr + 1);
1497
1498 rc = RTDirCreateFullPathEx(pszPath, fMode, RTDIRCREATE_FLAGS_IGNORE_UMASK);
1499
1500 rc = txsReplyRC(pPktHdr, rc, "RTDirCreateFullPath(\"%s\", %#x)", pszPath, fMode);
1501 RTStrFree(pszPath);
1502 return rc;
1503}
1504
1505/**
1506 * Creates a directory.
1507 *
1508 * @returns IPRT status code from send.
1509 * @param pPktHdr The mkdir packet.
1510 */
1511static int txsDoMkDir(PCTXSPKTHDR pPktHdr)
1512{
1513 /* After the packet header follows a mode mask and the remainder of
1514 the packet is the zero terminated directory name. */
1515 size_t const cbMin = sizeof(TXSPKTHDR) + sizeof(RTFMODE) + 2;
1516 if (pPktHdr->cb < cbMin)
1517 return txsReplyBadMinSize(pPktHdr, cbMin);
1518
1519 int rc;
1520 char *pszPath;
1521 if (!txsIsStringValid(pPktHdr, "dir", (const char *)(pPktHdr + 1) + sizeof(RTFMODE), &pszPath, NULL, &rc))
1522 return rc;
1523
1524 RTFMODE fMode = *(RTFMODE const *)(pPktHdr + 1);
1525 rc = RTDirCreate(pszPath, fMode, RTDIRCREATE_FLAGS_IGNORE_UMASK);
1526
1527 rc = txsReplyRC(pPktHdr, rc, "RTDirCreate(\"%s\", %#x)", pszPath, fMode);
1528 RTStrFree(pszPath);
1529 return rc;
1530}
1531
1532/**
1533 * Cleans up the scratch area.
1534 *
1535 * @returns IPRT status code from send.
1536 * @param pPktHdr The shutdown packet.
1537 */
1538static int txsDoCleanup(PCTXSPKTHDR pPktHdr)
1539{
1540 int rc = RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
1541 return txsReplyRC(pPktHdr, rc, "RTDirRemoveRecursive(\"%s\", CONTENT_ONLY)", g_szScratchPath);
1542}
1543
1544/**
1545 * Ejects the specified DVD/CD drive.
1546 *
1547 * @returns IPRT status code from send.
1548 * @param pPktHdr The eject packet.
1549 */
1550static int txsDoCdEject(PCTXSPKTHDR pPktHdr)
1551{
1552 /* After the packet header follows a uint32_t ordinal. */
1553 size_t const cbExpected = sizeof(TXSPKTHDR) + sizeof(uint32_t);
1554 if (pPktHdr->cb != cbExpected)
1555 return txsReplyBadSize(pPktHdr, cbExpected);
1556 uint32_t iOrdinal = *(uint32_t const *)(pPktHdr + 1);
1557
1558 RTCDROM hCdrom;
1559 int rc = RTCdromOpenByOrdinal(iOrdinal, RTCDROM_O_CONTROL, &hCdrom);
1560 if (RT_FAILURE(rc))
1561 return txsReplyRC(pPktHdr, rc, "RTCdromOpenByOrdinal(%u, RTCDROM_O_CONTROL, )", iOrdinal);
1562 rc = RTCdromEject(hCdrom, true /*fForce*/);
1563 RTCdromRelease(hCdrom);
1564
1565 return txsReplyRC(pPktHdr, rc, "RTCdromEject(ord=%u, fForce=true)", iOrdinal);
1566}
1567
1568/**
1569 * Common worker for txsDoShutdown and txsDoReboot.
1570 *
1571 * @returns IPRT status code from send.
1572 * @param pPktHdr The reboot packet.
1573 * @param fAction Which action to take.
1574 */
1575static int txsCommonShutdownReboot(PCTXSPKTHDR pPktHdr, uint32_t fAction)
1576{
1577 /*
1578 * We ACK the reboot & shutdown before actually performing them, then we
1579 * terminate the transport layer.
1580 *
1581 * This is to make sure the client isn't stuck with a dead connection. The
1582 * transport layer termination also make sure we won't accept new
1583 * connections in case the client is too eager to reconnect to a rebooted
1584 * test victim. On the down side, we cannot easily report RTSystemShutdown
1585 * failures failures this way. But the client can kind of figure it out by
1586 * reconnecting and seeing that our UUID was unchanged.
1587 */
1588 int rc;
1589 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1590 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1591 g_pTransport->pfnNotifyReboot();
1592 rc = txsReplyAck(pPktHdr);
1593 RTThreadSleep(2560); /* fudge factor */
1594 g_pTransport->pfnTerm();
1595
1596 /*
1597 * Do the job, if it fails we'll restart the transport layer.
1598 */
1599#if 0
1600 rc = VINF_SUCCESS;
1601#else
1602 rc = RTSystemShutdown(0 /*cMsDelay*/,
1603 fAction | RTSYSTEM_SHUTDOWN_PLANNED | RTSYSTEM_SHUTDOWN_FORCE,
1604 "Test Execution Service");
1605#endif
1606 if (RT_SUCCESS(rc))
1607 {
1608 RTMsgInfo(fAction == RTSYSTEM_SHUTDOWN_REBOOT ? "Rebooting...\n" : "Shutting down...\n");
1609 g_fTerminate = true;
1610 }
1611 else
1612 {
1613 RTMsgError("RTSystemShutdown w/ fAction=%#x failed: %Rrc", fAction, rc);
1614
1615 int rc2 = g_pTransport->pfnInit();
1616 if (RT_FAILURE(rc2))
1617 {
1618 g_fTerminate = true;
1619 rc = rc2;
1620 }
1621 }
1622 return rc;
1623}
1624
1625/**
1626 * Shuts down the machine, powering it off if possible.
1627 *
1628 * @returns IPRT status code from send.
1629 * @param pPktHdr The shutdown packet.
1630 */
1631static int txsDoShutdown(PCTXSPKTHDR pPktHdr)
1632{
1633 return txsCommonShutdownReboot(pPktHdr, RTSYSTEM_SHUTDOWN_POWER_OFF_HALT);
1634}
1635
1636/**
1637 * Reboots the machine.
1638 *
1639 * @returns IPRT status code from send.
1640 * @param pPktHdr The reboot packet.
1641 */
1642static int txsDoReboot(PCTXSPKTHDR pPktHdr)
1643{
1644 return txsCommonShutdownReboot(pPktHdr, RTSYSTEM_SHUTDOWN_REBOOT);
1645}
1646
1647/**
1648 * Verifies and acknowledges a "UUID" request.
1649 *
1650 * @returns IPRT status code.
1651 * @param pPktHdr The UUID packet.
1652 */
1653static int txsDoUuid(PCTXSPKTHDR pPktHdr)
1654{
1655 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1656 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1657
1658 struct
1659 {
1660 TXSPKTHDR Hdr;
1661 char szUuid[RTUUID_STR_LENGTH];
1662 char abPadding[TXSPKT_ALIGNMENT];
1663 } Pkt;
1664
1665 int rc = RTUuidToStr(&g_InstanceUuid, Pkt.szUuid, sizeof(Pkt.szUuid));
1666 if (RT_FAILURE(rc))
1667 return txsReplyRC(pPktHdr, rc, "RTUuidToStr");
1668 return txsReplyInternal(&Pkt.Hdr, "ACK UUID", strlen(Pkt.szUuid) + 1);
1669}
1670
1671/**
1672 * Verifies and acknowledges a "BYE" request.
1673 *
1674 * @returns IPRT status code.
1675 * @param pPktHdr The bye packet.
1676 */
1677static int txsDoBye(PCTXSPKTHDR pPktHdr)
1678{
1679 int rc;
1680 if (pPktHdr->cb == sizeof(TXSPKTHDR))
1681 rc = txsReplyAck(pPktHdr);
1682 else
1683 rc = txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1684 g_pTransport->pfnNotifyBye();
1685 return rc;
1686}
1687
1688/**
1689 * Verifies and acknowledges a "VER" request.
1690 *
1691 * @returns IPRT status code.
1692 * @param pPktHdr The version packet.
1693 */
1694static int txsDoVer(PCTXSPKTHDR pPktHdr)
1695{
1696 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1697 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1698
1699 struct
1700 {
1701 TXSPKTHDR Hdr;
1702 char szVer[96];
1703 char abPadding[TXSPKT_ALIGNMENT];
1704 } Pkt;
1705
1706 if (RTStrPrintf2(Pkt.szVer, sizeof(Pkt.szVer), "%s r%s %s.%s (%s %s)",
1707 RTBldCfgVersion(), RTBldCfgRevisionStr(), KBUILD_TARGET, KBUILD_TARGET_ARCH, __DATE__, __TIME__) > 0)
1708 {
1709 return txsReplyInternal(&Pkt.Hdr, "ACK VER ", strlen(Pkt.szVer) + 1);
1710 }
1711
1712 return txsReplyRC(pPktHdr, VERR_BUFFER_OVERFLOW, "RTStrPrintf2");
1713}
1714
1715/**
1716 * Verifies and acknowledges a "HOWDY" request.
1717 *
1718 * @returns IPRT status code.
1719 * @param pPktHdr The howdy packet.
1720 */
1721static int txsDoHowdy(PCTXSPKTHDR pPktHdr)
1722{
1723 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1724 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1725 int rc = txsReplyAck(pPktHdr);
1726 if (RT_SUCCESS(rc))
1727 {
1728 g_pTransport->pfnNotifyHowdy();
1729 RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
1730 }
1731 return rc;
1732}
1733
1734/**
1735 * Replies according to the return code.
1736 *
1737 * @returns rcOperation and pTxsExec->rcReplySend.
1738 * @param pTxsExec The TXSEXEC instance.
1739 * @param rcOperation The status code to report.
1740 * @param pszOperationFmt The operation that failed. Typically giving the
1741 * function call with important arguments.
1742 * @param ... Arguments to the format string.
1743 */
1744static int txsExecReplyRC(PTXSEXEC pTxsExec, int rcOperation, const char *pszOperationFmt, ...)
1745{
1746 AssertStmt(RT_FAILURE_NP(rcOperation), rcOperation = VERR_IPE_UNEXPECTED_INFO_STATUS);
1747
1748 char szOperation[128];
1749 va_list va;
1750 va_start(va, pszOperationFmt);
1751 RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
1752 va_end(va);
1753
1754 pTxsExec->rcReplySend = txsReplyFailure(pTxsExec->pPktHdr, "FAILED ",
1755 "%s failed with rc=%Rrc (opcode '%.8s')",
1756 szOperation, rcOperation, pTxsExec->pPktHdr->achOpcode);
1757 return rcOperation;
1758}
1759
1760
1761/**
1762 * Sends the process exit status reply to the TXS client.
1763 *
1764 * @returns IPRT status code of the send.
1765 * @param pTxsExec The TXSEXEC instance.
1766 * @param fProcessAlive Whether the process is still alive (against our
1767 * will).
1768 * @param fProcessTimedOut Whether the process timed out.
1769 * @param MsProcessKilled When the process was killed, UINT64_MAX if not.
1770 */
1771static int txsExecSendExitStatus(PTXSEXEC pTxsExec, bool fProcessAlive, bool fProcessTimedOut, uint64_t MsProcessKilled)
1772{
1773 int rc;
1774 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
1775 {
1776 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC TOK");
1777 if (g_fDisplayOutput)
1778 RTPrintf("txs: Process timed out and was killed\n");
1779 }
1780 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
1781 {
1782 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC TOA");
1783 if (g_fDisplayOutput)
1784 RTPrintf("txs: Process timed out and was not killed successfully\n");
1785 }
1786 else if (g_fTerminate && (fProcessAlive || MsProcessKilled != UINT64_MAX))
1787 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC DWN");
1788 else if (fProcessAlive)
1789 {
1790 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "Doofus! process is alive when it should not");
1791 AssertFailed();
1792 }
1793 else if (MsProcessKilled != UINT64_MAX)
1794 {
1795 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "Doofus! process has been killed when it should not");
1796 AssertFailed();
1797 }
1798 else if ( pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL
1799 && pTxsExec->ProcessStatus.iStatus == 0)
1800 {
1801 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC OK ");
1802 if (g_fDisplayOutput)
1803 RTPrintf("txs: Process exited with status: 0\n");
1804 }
1805 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
1806 {
1807 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC NOK", "%d", pTxsExec->ProcessStatus.iStatus);
1808 if (g_fDisplayOutput)
1809 RTPrintf("txs: Process exited with status: %d\n", pTxsExec->ProcessStatus.iStatus);
1810 }
1811 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
1812 {
1813 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC SIG", "%d", pTxsExec->ProcessStatus.iStatus);
1814 if (g_fDisplayOutput)
1815 RTPrintf("txs: Process exited with status: signal %d\n", pTxsExec->ProcessStatus.iStatus);
1816 }
1817 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
1818 {
1819 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC ABD", "");
1820 if (g_fDisplayOutput)
1821 RTPrintf("txs: Process exited with status: abend\n");
1822 }
1823 else
1824 {
1825 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "enmReason=%d iStatus=%d",
1826 pTxsExec->ProcessStatus.enmReason, pTxsExec->ProcessStatus.iStatus);
1827 AssertMsgFailed(("enmReason=%d iStatus=%d", pTxsExec->ProcessStatus.enmReason, pTxsExec->ProcessStatus.iStatus));
1828 }
1829 return rc;
1830}
1831
1832/**
1833 * Handle pending output data or error on standard out, standard error or the
1834 * test pipe.
1835 *
1836 * @returns IPRT status code from client send.
1837 * @param hPollSet The polling set.
1838 * @param fPollEvt The event mask returned by RTPollNoResume.
1839 * @param phPipeR The pipe handle.
1840 * @param puCrc32 The current CRC-32 of the stream. (In/Out)
1841 * @param enmHndId The handle ID.
1842 * @param pszOpcode The opcode for the data upload.
1843 *
1844 * @todo Put the last 4 parameters into a struct!
1845 */
1846static int txsDoExecHlpHandleOutputEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phPipeR,
1847 uint32_t *puCrc32, TXSEXECHNDID enmHndId, const char *pszOpcode)
1848{
1849 Log(("txsDoExecHlpHandleOutputEvent: %s fPollEvt=%#x\n", pszOpcode, fPollEvt));
1850
1851 /*
1852 * Try drain the pipe before acting on any errors.
1853 */
1854 int rc = VINF_SUCCESS;
1855 struct
1856 {
1857 TXSPKTHDR Hdr;
1858 uint32_t uCrc32;
1859 char abBuf[_64K];
1860 char abPadding[TXSPKT_ALIGNMENT];
1861 } Pkt;
1862 size_t cbRead;
1863 int rc2 = RTPipeRead(*phPipeR, Pkt.abBuf, sizeof(Pkt.abBuf), &cbRead);
1864 if (RT_SUCCESS(rc2) && cbRead)
1865 {
1866 Log(("Crc32=%#x ", *puCrc32));
1867 *puCrc32 = RTCrc32Process(*puCrc32, Pkt.abBuf, cbRead);
1868 Log(("cbRead=%#x Crc32=%#x \n", cbRead, *puCrc32));
1869 Pkt.uCrc32 = RTCrc32Finish(*puCrc32);
1870 if (g_fDisplayOutput)
1871 {
1872 if (enmHndId == TXSEXECHNDID_STDOUT)
1873 RTStrmPrintf(g_pStdErr, "%.*s", cbRead, Pkt.abBuf);
1874 else if (enmHndId == TXSEXECHNDID_STDERR)
1875 RTStrmPrintf(g_pStdErr, "%.*s", cbRead, Pkt.abBuf);
1876 }
1877
1878 rc = txsReplyInternal(&Pkt.Hdr, pszOpcode, cbRead + sizeof(uint32_t));
1879
1880 /* Make sure we go another poll round in case there was too much data
1881 for the buffer to hold. */
1882 fPollEvt &= RTPOLL_EVT_ERROR;
1883 }
1884 else if (RT_FAILURE(rc2))
1885 {
1886 fPollEvt |= RTPOLL_EVT_ERROR;
1887 AssertMsg(rc2 == VERR_BROKEN_PIPE, ("%Rrc\n", rc));
1888 }
1889
1890 /*
1891 * If an error was raised signalled,
1892 */
1893 if (fPollEvt & RTPOLL_EVT_ERROR)
1894 {
1895 rc2 = RTPollSetRemove(hPollSet, enmHndId);
1896 AssertRC(rc2);
1897
1898 rc2 = RTPipeClose(*phPipeR);
1899 AssertRC(rc2);
1900 *phPipeR = NIL_RTPIPE;
1901 }
1902 return rc;
1903}
1904
1905/**
1906 * Try write some more data to the standard input of the child.
1907 *
1908 * @returns IPRT status code.
1909 * @param pStdInBuf The standard input buffer.
1910 * @param hStdInW The standard input pipe.
1911 */
1912static int txsDoExecHlpWriteStdIn(PTXSEXECSTDINBUF pStdInBuf, RTPIPE hStdInW)
1913{
1914 size_t cbToWrite = pStdInBuf->cb - pStdInBuf->off;
1915 size_t cbWritten;
1916 int rc = RTPipeWrite(hStdInW, &pStdInBuf->pch[pStdInBuf->off], cbToWrite, &cbWritten);
1917 if (RT_SUCCESS(rc))
1918 {
1919 Assert(cbWritten == cbToWrite);
1920 pStdInBuf->off += cbWritten;
1921 }
1922 return rc;
1923}
1924
1925/**
1926 * Handle an error event on standard input.
1927 *
1928 * @param hPollSet The polling set.
1929 * @param fPollEvt The event mask returned by RTPollNoResume.
1930 * @param phStdInW The standard input pipe handle.
1931 * @param pStdInBuf The standard input buffer.
1932 */
1933static void txsDoExecHlpHandleStdInErrorEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
1934 PTXSEXECSTDINBUF pStdInBuf)
1935{
1936 NOREF(fPollEvt);
1937 int rc2;
1938 if (pStdInBuf->off < pStdInBuf->cb)
1939 {
1940 rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1941 AssertRC(rc2);
1942 }
1943
1944 rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN);
1945 AssertRC(rc2);
1946
1947 rc2 = RTPipeClose(*phStdInW);
1948 AssertRC(rc2);
1949 *phStdInW = NIL_RTPIPE;
1950
1951 RTMemFree(pStdInBuf->pch);
1952 pStdInBuf->pch = NULL;
1953 pStdInBuf->off = 0;
1954 pStdInBuf->cb = 0;
1955 pStdInBuf->cbAllocated = 0;
1956 pStdInBuf->fBitBucket = true;
1957}
1958
1959/**
1960 * Handle an event indicating we can write to the standard input pipe of the
1961 * child process.
1962 *
1963 * @param hPollSet The polling set.
1964 * @param fPollEvt The event mask returned by RTPollNoResume.
1965 * @param phStdInW The standard input pipe.
1966 * @param pStdInBuf The standard input buffer.
1967 */
1968static void txsDoExecHlpHandleStdInWritableEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
1969 PTXSEXECSTDINBUF pStdInBuf)
1970{
1971 int rc;
1972 if (!(fPollEvt & RTPOLL_EVT_ERROR))
1973 {
1974 rc = txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
1975 if (RT_FAILURE(rc) && rc != VERR_BAD_PIPE)
1976 {
1977 /** @todo do we need to do something about this error condition? */
1978 AssertRC(rc);
1979 }
1980
1981 if (pStdInBuf->off < pStdInBuf->cb)
1982 {
1983 rc = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1984 AssertRC(rc);
1985 }
1986 }
1987 else
1988 txsDoExecHlpHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
1989}
1990
1991/**
1992 * Handle a transport event or successful pfnPollIn() call.
1993 *
1994 * @returns IPRT status code from client send.
1995 * @retval VINF_EOF indicates ABORT command.
1996 *
1997 * @param hPollSet The polling set.
1998 * @param fPollEvt The event mask returned by RTPollNoResume.
1999 * @param idPollHnd The handle ID.
2000 * @param phStdInW The standard input pipe.
2001 * @param pStdInBuf The standard input buffer.
2002 */
2003static int txsDoExecHlpHandleTransportEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, uint32_t idPollHnd,
2004 PRTPIPE phStdInW, PTXSEXECSTDINBUF pStdInBuf)
2005{
2006 /* ASSUMES the transport layer will detect or clear any error condition. */
2007 NOREF(fPollEvt); NOREF(idPollHnd);
2008 Log(("txsDoExecHlpHandleTransportEvent\n"));
2009 /** @todo Use a callback for this case? */
2010
2011 /*
2012 * Read client command packet and process it.
2013 */
2014 /** @todo Sometimes this hangs on windows because there isn't any data pending.
2015 * We probably get woken up at the wrong time or in the wrong way, i.e. RTPoll()
2016 * is busted for sockets.
2017 *
2018 * Temporary workaround: Poll for input before trying to read it. */
2019 if (!g_pTransport->pfnPollIn())
2020 {
2021 Log(("Bad transport event\n"));
2022 RTThreadYield();
2023 return VINF_SUCCESS;
2024 }
2025 PTXSPKTHDR pPktHdr;
2026 int rc = txsRecvPkt(&pPktHdr, false /*fAutoRetryOnFailure*/);
2027 if (RT_FAILURE(rc))
2028 return rc;
2029 Log(("Bad transport event\n"));
2030
2031 /*
2032 * The most common thing here would be a STDIN request with data
2033 * for the child process.
2034 */
2035 if (txsIsSameOpcode(pPktHdr, "STDIN"))
2036 {
2037 if ( !pStdInBuf->fBitBucket
2038 && pPktHdr->cb >= sizeof(TXSPKTHDR) + sizeof(uint32_t))
2039 {
2040 uint32_t uCrc32 = *(uint32_t *)(pPktHdr + 1);
2041 const char *pch = (const char *)(pPktHdr + 1) + sizeof(uint32_t);
2042 size_t cb = pPktHdr->cb - sizeof(TXSPKTHDR) - sizeof(uint32_t);
2043
2044 /* Check the CRC */
2045 pStdInBuf->uCrc32 = RTCrc32Process(pStdInBuf->uCrc32, pch, cb);
2046 if (RTCrc32Finish(pStdInBuf->uCrc32) == uCrc32)
2047 {
2048
2049 /* Rewind the buffer if it's empty. */
2050 size_t cbInBuf = pStdInBuf->cb - pStdInBuf->off;
2051 bool const fAddToSet = cbInBuf == 0;
2052 if (fAddToSet)
2053 pStdInBuf->cb = pStdInBuf->off = 0;
2054
2055 /* Try and see if we can simply append the data. */
2056 if (cb + pStdInBuf->cb <= pStdInBuf->cbAllocated)
2057 {
2058 memcpy(&pStdInBuf->pch[pStdInBuf->cb], pch, cb);
2059 pStdInBuf->cb += cb;
2060 rc = txsReplyAck(pPktHdr);
2061 }
2062 else
2063 {
2064 /* Try write a bit or two before we move+realloc the buffer. */
2065 if (cbInBuf > 0)
2066 txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
2067
2068 /* Move any buffered data to the front. */
2069 cbInBuf = pStdInBuf->cb - pStdInBuf->off;
2070 if (cbInBuf == 0)
2071 pStdInBuf->cb = pStdInBuf->off = 0;
2072 else
2073 {
2074 memmove(pStdInBuf->pch, &pStdInBuf->pch[pStdInBuf->off], cbInBuf);
2075 pStdInBuf->cb = cbInBuf;
2076 pStdInBuf->off = 0;
2077 }
2078
2079 /* Do we need to grow the buffer? */
2080 if (cb + pStdInBuf->cb > pStdInBuf->cbAllocated)
2081 {
2082 size_t cbAlloc = pStdInBuf->cb + cb;
2083 cbAlloc = RT_ALIGN_Z(cbAlloc, _64K);
2084 void *pvNew = RTMemRealloc(pStdInBuf->pch, cbAlloc);
2085 if (pvNew)
2086 {
2087 pStdInBuf->pch = (char *)pvNew;
2088 pStdInBuf->cbAllocated = cbAlloc;
2089 }
2090 }
2091
2092 /* Finally, copy the data. */
2093 if (cb + pStdInBuf->cb <= pStdInBuf->cbAllocated)
2094 {
2095 memcpy(&pStdInBuf->pch[pStdInBuf->cb], pch, cb);
2096 pStdInBuf->cb += cb;
2097 rc = txsReplyAck(pPktHdr);
2098 }
2099 else
2100 rc = txsReplySimple(pPktHdr, "STDINMEM");
2101 }
2102
2103 /*
2104 * Flush the buffered data and add/remove the standard input
2105 * handle from the set.
2106 */
2107 txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
2108 if (fAddToSet && pStdInBuf->off < pStdInBuf->cb)
2109 {
2110 int rc2 = RTPollSetAddPipe(hPollSet, *phStdInW, RTPOLL_EVT_WRITE, TXSEXECHNDID_STDIN_WRITABLE);
2111 AssertRC(rc2);
2112 }
2113 else if (!fAddToSet && pStdInBuf->off >= pStdInBuf->cb)
2114 {
2115 int rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
2116 AssertRC(rc2);
2117 }
2118 }
2119 else
2120 rc = txsReplyFailure(pPktHdr, "STDINCRC", "Invalid CRC checksum expected %#x got %#x",
2121 pStdInBuf->uCrc32, uCrc32);
2122 }
2123 else if (pPktHdr->cb < sizeof(TXSPKTHDR) + sizeof(uint32_t))
2124 rc = txsReplySimple(pPktHdr, "STDINBAD");
2125 else
2126 rc = txsReplySimple(pPktHdr, "STDINIGN");
2127 }
2128 /*
2129 * Marks the end of the stream for stdin.
2130 */
2131 else if (txsIsSameOpcode(pPktHdr, "STDINEOS"))
2132 {
2133 if (RT_LIKELY(pPktHdr->cb == sizeof(TXSPKTHDR)))
2134 {
2135 /* Close the pipe. */
2136 txsDoExecHlpHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
2137 rc = txsReplyAck(pPktHdr);
2138 }
2139 else
2140 rc = txsReplySimple(pPktHdr, "STDINBAD");
2141 }
2142 /*
2143 * The only other two requests are connection oriented and we return a error
2144 * code so that we unwind the whole EXEC shebang and start afresh.
2145 */
2146 else if (txsIsSameOpcode(pPktHdr, "BYE"))
2147 {
2148 rc = txsDoBye(pPktHdr);
2149 if (RT_SUCCESS(rc))
2150 rc = VERR_NET_NOT_CONNECTED;
2151 }
2152 else if (txsIsSameOpcode(pPktHdr, "HOWDY"))
2153 {
2154 rc = txsDoHowdy(pPktHdr);
2155 if (RT_SUCCESS(rc))
2156 rc = VERR_NET_NOT_CONNECTED;
2157 }
2158 else if (txsIsSameOpcode(pPktHdr, "ABORT"))
2159 {
2160 rc = txsReplyAck(pPktHdr);
2161 if (RT_SUCCESS(rc))
2162 rc = VINF_EOF; /* this is but ugly! */
2163 }
2164 else
2165 rc = txsReplyFailure(pPktHdr, "UNKNOWN ", "Opcode '%.8s' is not known or not recognized during EXEC", pPktHdr->achOpcode);
2166
2167 RTMemFree(pPktHdr);
2168 return rc;
2169}
2170
2171/**
2172 * Handles the output and input of the process, waits for it finish up.
2173 *
2174 * @returns IPRT status code from reply send.
2175 * @param pTxsExec The TXSEXEC instance.
2176 */
2177static int txsDoExecHlp2(PTXSEXEC pTxsExec)
2178{
2179 int rc; /* client send. */
2180 int rc2;
2181 TXSEXECSTDINBUF StdInBuf = { 0, 0, NULL, 0, pTxsExec->hStdInW == NIL_RTPIPE, RTCrc32Start() };
2182 uint32_t uStdOutCrc32 = RTCrc32Start();
2183 uint32_t uStdErrCrc32 = uStdOutCrc32;
2184 uint32_t uTestPipeCrc32 = uStdOutCrc32;
2185 uint64_t const MsStart = RTTimeMilliTS();
2186 bool fProcessTimedOut = false;
2187 uint64_t MsProcessKilled = UINT64_MAX;
2188 RTMSINTERVAL const cMsPollBase = g_pTransport->pfnPollSetAdd || pTxsExec->hStdInW == NIL_RTPIPE
2189 ? RT_MS_5SEC : 100;
2190 RTMSINTERVAL cMsPollCur = 0;
2191
2192 /*
2193 * Before entering the loop, tell the client that we've started the guest
2194 * and that it's now OK to send input to the process. (This is not the
2195 * final ACK, so the packet header is NULL ... kind of bogus.)
2196 */
2197 rc = txsReplyAck(NULL);
2198
2199 /*
2200 * Process input, output, the test pipe and client requests.
2201 */
2202 while ( RT_SUCCESS(rc)
2203 && RT_UNLIKELY(!g_fTerminate))
2204 {
2205 /*
2206 * Wait/Process all pending events.
2207 */
2208 uint32_t idPollHnd;
2209 uint32_t fPollEvt;
2210 Log3(("Calling RTPollNoResume(,%u,)...\n", cMsPollCur));
2211 rc2 = RTPollNoResume(pTxsExec->hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
2212 Log3(("RTPollNoResume -> fPollEvt=%#x idPollHnd=%u\n", fPollEvt, idPollHnd));
2213 if (g_fTerminate)
2214 continue;
2215 cMsPollCur = 0; /* no rest until we've checked everything. */
2216
2217 if (RT_SUCCESS(rc2))
2218 {
2219 switch (idPollHnd)
2220 {
2221 case TXSEXECHNDID_STDOUT:
2222 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdOutR, &uStdOutCrc32,
2223 TXSEXECHNDID_STDOUT, "STDOUT ");
2224 break;
2225
2226 case TXSEXECHNDID_STDERR:
2227 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdErrR, &uStdErrCrc32,
2228 TXSEXECHNDID_STDERR, "STDERR ");
2229 break;
2230
2231 case TXSEXECHNDID_TESTPIPE:
2232 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hTestPipeR, &uTestPipeCrc32,
2233 TXSEXECHNDID_TESTPIPE, "TESTPIPE");
2234 break;
2235
2236 case TXSEXECHNDID_STDIN:
2237 txsDoExecHlpHandleStdInErrorEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdInW, &StdInBuf);
2238 break;
2239
2240 case TXSEXECHNDID_STDIN_WRITABLE:
2241 txsDoExecHlpHandleStdInWritableEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdInW, &StdInBuf);
2242 break;
2243
2244 case TXSEXECHNDID_THREAD:
2245 rc2 = RTPollSetRemove(pTxsExec->hPollSet, TXSEXECHNDID_THREAD); AssertRC(rc2);
2246 break;
2247
2248 default:
2249 rc = txsDoExecHlpHandleTransportEvent(pTxsExec->hPollSet, fPollEvt, idPollHnd, &pTxsExec->hStdInW,
2250 &StdInBuf);
2251 break;
2252 }
2253 if (RT_FAILURE(rc) || rc == VINF_EOF)
2254 break; /* abort command, or client dead or something */
2255 continue;
2256 }
2257
2258 /*
2259 * Check for incoming data.
2260 */
2261 if (g_pTransport->pfnPollIn())
2262 {
2263 rc = txsDoExecHlpHandleTransportEvent(pTxsExec->hPollSet, 0, UINT32_MAX, &pTxsExec->hStdInW, &StdInBuf);
2264 if (RT_FAILURE(rc) || rc == VINF_EOF)
2265 break; /* abort command, or client dead or something */
2266 continue;
2267 }
2268
2269 /*
2270 * If the process has terminated, we're should head out.
2271 */
2272 if (!ASMAtomicReadBool(&pTxsExec->fProcessAlive))
2273 break;
2274
2275 /*
2276 * Check for timed out, killing the process.
2277 */
2278 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
2279 if (pTxsExec->cMsTimeout != RT_INDEFINITE_WAIT)
2280 {
2281 uint64_t u64Now = RTTimeMilliTS();
2282 uint64_t cMsElapsed = u64Now - MsStart;
2283 if (cMsElapsed >= pTxsExec->cMsTimeout)
2284 {
2285 fProcessTimedOut = true;
2286 if ( MsProcessKilled == UINT64_MAX
2287 || u64Now - MsProcessKilled > RT_MS_1SEC)
2288 {
2289 if ( MsProcessKilled != UINT64_MAX
2290 && u64Now - MsProcessKilled > 20*RT_MS_1MIN)
2291 break; /* give up after 20 mins */
2292 RTCritSectEnter(&pTxsExec->CritSect);
2293 if (pTxsExec->fProcessAlive)
2294 RTProcTerminate(pTxsExec->hProcess);
2295 RTCritSectLeave(&pTxsExec->CritSect);
2296 MsProcessKilled = u64Now;
2297 continue;
2298 }
2299 cMilliesLeft = RT_MS_10SEC;
2300 }
2301 else
2302 cMilliesLeft = pTxsExec->cMsTimeout - (uint32_t)cMsElapsed;
2303 }
2304
2305 /* Reset the polling interval since we've done all pending work. */
2306 cMsPollCur = cMilliesLeft >= cMsPollBase ? cMsPollBase : cMilliesLeft;
2307 }
2308
2309 /*
2310 * At this point we should hopefully only have to wait 0 ms on the thread
2311 * to release the handle... But if for instance the process refuses to die,
2312 * we'll have to try kill it again. Bothersome.
2313 */
2314 for (size_t i = 0; i < 22; i++)
2315 {
2316 rc2 = RTThreadWait(pTxsExec->hThreadWaiter, RT_MS_1SEC / 2, NULL);
2317 if (RT_SUCCESS(rc))
2318 {
2319 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2320 Assert(!pTxsExec->fProcessAlive);
2321 break;
2322 }
2323 if (i == 0 || i == 10 || i == 15 || i == 18 || i > 20)
2324 {
2325 RTCritSectEnter(&pTxsExec->CritSect);
2326 if (pTxsExec->fProcessAlive)
2327 RTProcTerminate(pTxsExec->hProcess);
2328 RTCritSectLeave(&pTxsExec->CritSect);
2329 }
2330 }
2331
2332 /*
2333 * If we don't have a client problem (RT_FAILURE(rc) we'll reply to the
2334 * clients exec packet now.
2335 */
2336 if (RT_SUCCESS(rc))
2337 rc = txsExecSendExitStatus(pTxsExec, pTxsExec->fProcessAlive, fProcessTimedOut, MsProcessKilled);
2338
2339 RTMemFree(StdInBuf.pch);
2340 return rc;
2341}
2342
2343/**
2344 * Creates a poll set for the pipes and let the transport layer add stuff to it
2345 * as well.
2346 *
2347 * @returns IPRT status code, reply to client made on error.
2348 * @param pTxsExec The TXSEXEC instance.
2349 */
2350static int txsExecSetupPollSet(PTXSEXEC pTxsExec)
2351{
2352 int rc = RTPollSetCreate(&pTxsExec->hPollSet);
2353 if (RT_FAILURE(rc))
2354 return txsExecReplyRC(pTxsExec, rc, "RTPollSetCreate");
2355
2356 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdInW, RTPOLL_EVT_ERROR, TXSEXECHNDID_STDIN);
2357 if (RT_FAILURE(rc))
2358 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stdin");
2359
2360 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2361 TXSEXECHNDID_STDOUT);
2362 if (RT_FAILURE(rc))
2363 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stdout");
2364
2365 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2366 TXSEXECHNDID_STDERR);
2367 if (RT_FAILURE(rc))
2368 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stderr");
2369
2370 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hTestPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2371 TXSEXECHNDID_TESTPIPE);
2372 if (RT_FAILURE(rc))
2373 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/test");
2374
2375 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hWakeUpPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2376 TXSEXECHNDID_THREAD);
2377 if (RT_FAILURE(rc))
2378 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/wakeup");
2379
2380 if (g_pTransport->pfnPollSetAdd)
2381 {
2382 rc = g_pTransport->pfnPollSetAdd(pTxsExec->hPollSet, TXSEXECHNDID_TRANSPORT);
2383 if (RT_FAILURE(rc))
2384 return txsExecReplyRC(pTxsExec, rc, "%s->pfnPollSetAdd/stdin", g_pTransport->szName);
2385 }
2386
2387 return VINF_SUCCESS;
2388}
2389
2390/**
2391 * Thread that calls RTProcWait and signals the main thread when it returns.
2392 *
2393 * The thread is created before the process is started and is waiting for a user
2394 * signal from the main thread before it calls RTProcWait.
2395 *
2396 * @returns VINF_SUCCESS (ignored).
2397 * @param hThreadSelf The thread handle.
2398 * @param pvUser The TXEEXEC structure.
2399 */
2400static DECLCALLBACK(int) txsExecWaitThreadProc(RTTHREAD hThreadSelf, void *pvUser)
2401{
2402 PTXSEXEC pTxsExec = (PTXSEXEC)pvUser;
2403
2404 /* Wait for the go ahead... */
2405 int rc = RTThreadUserWait(hThreadSelf, RT_INDEFINITE_WAIT); AssertRC(rc);
2406
2407 RTCritSectEnter(&pTxsExec->CritSect);
2408 for (;;)
2409 {
2410 RTCritSectLeave(&pTxsExec->CritSect);
2411 rc = RTProcWaitNoResume(pTxsExec->hProcess, RTPROCWAIT_FLAGS_BLOCK, &pTxsExec->ProcessStatus);
2412 RTCritSectEnter(&pTxsExec->CritSect);
2413
2414 /* If the pipe is NIL, the destructor wants us to get lost ASAP. */
2415 if (pTxsExec->hWakeUpPipeW == NIL_RTPIPE)
2416 break;
2417
2418 if (RT_FAILURE(rc))
2419 {
2420 rc = RTProcWait(pTxsExec->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &pTxsExec->ProcessStatus);
2421 if (rc == VERR_PROCESS_RUNNING)
2422 continue;
2423
2424 if (RT_FAILURE(rc))
2425 {
2426 AssertRC(rc);
2427 pTxsExec->ProcessStatus.iStatus = rc;
2428 pTxsExec->ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
2429 }
2430 }
2431
2432 /* The process finished, signal the main thread over the pipe. */
2433 ASMAtomicWriteBool(&pTxsExec->fProcessAlive, false);
2434 size_t cbIgnored;
2435 RTPipeWrite(pTxsExec->hWakeUpPipeW, "done", 4, &cbIgnored);
2436 RTPipeClose(pTxsExec->hWakeUpPipeW);
2437 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2438 break;
2439 }
2440 RTCritSectLeave(&pTxsExec->CritSect);
2441
2442 return VINF_SUCCESS;
2443}
2444
2445/**
2446 * Sets up the thread that waits for the process to complete.
2447 *
2448 * @returns IPRT status code, reply to client made on error.
2449 * @param pTxsExec The TXSEXEC instance.
2450 */
2451static int txsExecSetupThread(PTXSEXEC pTxsExec)
2452{
2453 int rc = RTPipeCreate(&pTxsExec->hWakeUpPipeR, &pTxsExec->hWakeUpPipeW, 0 /*fFlags*/);
2454 if (RT_FAILURE(rc))
2455 {
2456 pTxsExec->hWakeUpPipeR = pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2457 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/wait");
2458 }
2459
2460 rc = RTThreadCreate(&pTxsExec->hThreadWaiter, txsExecWaitThreadProc,
2461 pTxsExec, 0 /*cbStack */, RTTHREADTYPE_DEFAULT,
2462 RTTHREADFLAGS_WAITABLE, "TxsProcW");
2463 if (RT_FAILURE(rc))
2464 {
2465 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2466 return txsExecReplyRC(pTxsExec, rc, "RTThreadCreate");
2467 }
2468
2469 return VINF_SUCCESS;
2470}
2471
2472/**
2473 * Sets up the test pipe.
2474 *
2475 * @returns IPRT status code, reply to client made on error.
2476 * @param pTxsExec The TXSEXEC instance.
2477 * @param pszTestPipe How to set up the test pipe.
2478 */
2479static int txsExecSetupTestPipe(PTXSEXEC pTxsExec, const char *pszTestPipe)
2480{
2481 if (strcmp(pszTestPipe, "|"))
2482 return VINF_SUCCESS;
2483
2484 int rc = RTPipeCreate(&pTxsExec->hTestPipeR, &pTxsExec->hTestPipeW, RTPIPE_C_INHERIT_WRITE);
2485 if (RT_FAILURE(rc))
2486 {
2487 pTxsExec->hTestPipeR = pTxsExec->hTestPipeW = NIL_RTPIPE;
2488 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/test/%s", pszTestPipe);
2489 }
2490
2491 char szVal[64];
2492 RTStrPrintf(szVal, sizeof(szVal), "%#llx", (uint64_t)RTPipeToNative(pTxsExec->hTestPipeW));
2493 rc = RTEnvSetEx(pTxsExec->hEnv, "IPRT_TEST_PIPE", szVal);
2494 if (RT_FAILURE(rc))
2495 return txsExecReplyRC(pTxsExec, rc, "RTEnvSetEx/test/%s", pszTestPipe);
2496
2497 return VINF_SUCCESS;
2498}
2499
2500/**
2501 * Sets up the redirection / pipe / nothing for one of the standard handles.
2502 *
2503 * @returns IPRT status code, reply to client made on error.
2504 * @param pTxsExec The TXSEXEC instance.
2505 * @param pszHowTo How to set up this standard handle.
2506 * @param pszStdWhat For what to setup redirection (stdin/stdout/stderr).
2507 * @param fd Which standard handle it is (0 == stdin, 1 ==
2508 * stdout, 2 == stderr).
2509 * @param ph The generic handle that @a pph may be set
2510 * pointing to. Always set.
2511 * @param pph Pointer to the RTProcCreateExec argument.
2512 * Always set.
2513 * @param phPipe Where to return the end of the pipe that we
2514 * should service. Always set.
2515 */
2516static int txsExecSetupRedir(PTXSEXEC pTxsExec, const char *pszHowTo, const char *pszStdWhat, int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
2517{
2518 ph->enmType = RTHANDLETYPE_PIPE;
2519 ph->u.hPipe = NIL_RTPIPE;
2520 *pph = NULL;
2521 *phPipe = NIL_RTPIPE;
2522
2523 int rc;
2524 if (!strcmp(pszHowTo, "|"))
2525 {
2526 /*
2527 * Setup a pipe for forwarding to/from the client.
2528 */
2529 if (fd == 0)
2530 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
2531 else
2532 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
2533 if (RT_FAILURE(rc))
2534 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/%s/%s", pszStdWhat, pszHowTo);
2535 ph->enmType = RTHANDLETYPE_PIPE;
2536 *pph = ph;
2537 }
2538 else if (!strcmp(pszHowTo, "/dev/null"))
2539 {
2540 /*
2541 * Redirect to/from /dev/null.
2542 */
2543 RTFILE hFile;
2544 rc = RTFileOpenBitBucket(&hFile, fd == 0 ? RTFILE_O_READ : RTFILE_O_WRITE);
2545 if (RT_FAILURE(rc))
2546 return txsExecReplyRC(pTxsExec, rc, "RTFileOpenBitBucket/%s/%s", pszStdWhat, pszHowTo);
2547
2548 ph->enmType = RTHANDLETYPE_FILE;
2549 ph->u.hFile = hFile;
2550 *pph = ph;
2551 }
2552 else if (*pszHowTo)
2553 {
2554 /*
2555 * Redirect to/from file.
2556 */
2557 uint32_t fFlags;
2558 if (fd == 0)
2559 fFlags = RTFILE_O_READ | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN;
2560 else
2561 {
2562 if (pszHowTo[0] != '>' || pszHowTo[1] != '>')
2563 fFlags = RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE;
2564 else
2565 {
2566 /* append */
2567 pszHowTo += 2;
2568 fFlags = RTFILE_O_WRITE | RTFILE_O_DENY_NONE | RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND;
2569 }
2570 }
2571
2572 RTFILE hFile;
2573 rc = RTFileOpen(&hFile, pszHowTo, fFlags);
2574 if (RT_FAILURE(rc))
2575 return txsExecReplyRC(pTxsExec, rc, "RTFileOpen/%s/%s", pszStdWhat, pszHowTo);
2576
2577 ph->enmType = RTHANDLETYPE_FILE;
2578 ph->u.hFile = hFile;
2579 *pph = ph;
2580 }
2581 else
2582 /* same as parent (us) */
2583 rc = VINF_SUCCESS;
2584 return rc;
2585}
2586
2587/**
2588 * Create the environment.
2589 *
2590 * @returns IPRT status code, reply to client made on error.
2591 * @param pTxsExec The TXSEXEC instance.
2592 * @param cEnvVars The number of environment variables.
2593 * @param papszEnv The environment variables (var=value).
2594 */
2595static int txsExecSetupEnv(PTXSEXEC pTxsExec, uint32_t cEnvVars, const char * const *papszEnv)
2596{
2597 /*
2598 * Create the environment.
2599 */
2600 int rc = RTEnvClone(&pTxsExec->hEnv, RTENV_DEFAULT);
2601 if (RT_FAILURE(rc))
2602 return txsExecReplyRC(pTxsExec, rc, "RTEnvClone");
2603
2604 for (size_t i = 0; i < cEnvVars; i++)
2605 {
2606 rc = RTEnvPutEx(pTxsExec->hEnv, papszEnv[i]);
2607 if (RT_FAILURE(rc))
2608 return txsExecReplyRC(pTxsExec, rc, "RTEnvPutEx(,'%s')", papszEnv[i]);
2609 }
2610 return VINF_SUCCESS;
2611}
2612
2613/**
2614 * Deletes the TXSEXEC structure and frees the memory backing it.
2615 *
2616 * @param pTxsExec The structure to destroy.
2617 */
2618static void txsExecDestroy(PTXSEXEC pTxsExec)
2619{
2620 int rc2;
2621
2622 rc2 = RTEnvDestroy(pTxsExec->hEnv); AssertRC(rc2);
2623 pTxsExec->hEnv = NIL_RTENV;
2624 rc2 = RTPipeClose(pTxsExec->hTestPipeW); AssertRC(rc2);
2625 pTxsExec->hTestPipeW = NIL_RTPIPE;
2626 rc2 = RTHandleClose(pTxsExec->StdErr.phChild); AssertRC(rc2);
2627 pTxsExec->StdErr.phChild = NULL;
2628 rc2 = RTHandleClose(pTxsExec->StdOut.phChild); AssertRC(rc2);
2629 pTxsExec->StdOut.phChild = NULL;
2630 rc2 = RTHandleClose(pTxsExec->StdIn.phChild); AssertRC(rc2);
2631 pTxsExec->StdIn.phChild = NULL;
2632
2633 rc2 = RTPipeClose(pTxsExec->hTestPipeR); AssertRC(rc2);
2634 pTxsExec->hTestPipeR = NIL_RTPIPE;
2635 rc2 = RTPipeClose(pTxsExec->hStdErrR); AssertRC(rc2);
2636 pTxsExec->hStdErrR = NIL_RTPIPE;
2637 rc2 = RTPipeClose(pTxsExec->hStdOutR); AssertRC(rc2);
2638 pTxsExec->hStdOutR = NIL_RTPIPE;
2639 rc2 = RTPipeClose(pTxsExec->hStdInW); AssertRC(rc2);
2640 pTxsExec->hStdInW = NIL_RTPIPE;
2641
2642 RTPollSetDestroy(pTxsExec->hPollSet);
2643 pTxsExec->hPollSet = NIL_RTPOLLSET;
2644
2645 /*
2646 * If the process is still running we're in a bit of a fix... Try kill it,
2647 * although that's potentially racing process termination and reusage of
2648 * the pid.
2649 */
2650 RTCritSectEnter(&pTxsExec->CritSect);
2651
2652 RTPipeClose(pTxsExec->hWakeUpPipeW);
2653 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2654 RTPipeClose(pTxsExec->hWakeUpPipeR);
2655 pTxsExec->hWakeUpPipeR = NIL_RTPIPE;
2656
2657 if ( pTxsExec->hProcess != NIL_RTPROCESS
2658 && pTxsExec->fProcessAlive)
2659 RTProcTerminate(pTxsExec->hProcess);
2660
2661 RTCritSectLeave(&pTxsExec->CritSect);
2662
2663 int rcThread = VINF_SUCCESS;
2664 if (pTxsExec->hThreadWaiter != NIL_RTTHREAD)
2665 rcThread = RTThreadWait(pTxsExec->hThreadWaiter, 5000, NULL);
2666 if (RT_SUCCESS(rcThread))
2667 {
2668 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2669 RTCritSectDelete(&pTxsExec->CritSect);
2670 RTMemFree(pTxsExec);
2671 }
2672 /* else: leak it or RTThreadWait may cause heap corruption later. */
2673}
2674
2675/**
2676 * Initializes the TXSEXEC structure.
2677 *
2678 * @returns VINF_SUCCESS and non-NULL *ppTxsExec on success, reply send status
2679 * and *ppTxsExec set to NULL on failure.
2680 * @param pPktHdr The exec packet.
2681 * @param cMsTimeout The time parameter.
2682 * @param ppTxsExec Where to return the structure.
2683 */
2684static int txsExecCreate(PCTXSPKTHDR pPktHdr, RTMSINTERVAL cMsTimeout, PTXSEXEC *ppTxsExec)
2685{
2686 *ppTxsExec = NULL;
2687
2688 /*
2689 * Allocate the basic resources.
2690 */
2691 PTXSEXEC pTxsExec = (PTXSEXEC)RTMemAlloc(sizeof(*pTxsExec));
2692 if (!pTxsExec)
2693 return txsReplyRC(pPktHdr, VERR_NO_MEMORY, "RTMemAlloc(%zu)", sizeof(*pTxsExec));
2694 int rc = RTCritSectInit(&pTxsExec->CritSect);
2695 if (RT_FAILURE(rc))
2696 {
2697 RTMemFree(pTxsExec);
2698 return txsReplyRC(pPktHdr, rc, "RTCritSectInit");
2699 }
2700
2701 /*
2702 * Initialize the member to NIL values.
2703 */
2704 pTxsExec->pPktHdr = pPktHdr;
2705 pTxsExec->cMsTimeout = cMsTimeout;
2706 pTxsExec->rcReplySend = VINF_SUCCESS;
2707
2708 pTxsExec->hPollSet = NIL_RTPOLLSET;
2709 pTxsExec->hStdInW = NIL_RTPIPE;
2710 pTxsExec->hStdOutR = NIL_RTPIPE;
2711 pTxsExec->hStdErrR = NIL_RTPIPE;
2712 pTxsExec->hTestPipeR = NIL_RTPIPE;
2713 pTxsExec->hWakeUpPipeR = NIL_RTPIPE;
2714 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2715
2716 pTxsExec->StdIn.phChild = NULL;
2717 pTxsExec->StdOut.phChild = NULL;
2718 pTxsExec->StdErr.phChild = NULL;
2719 pTxsExec->hTestPipeW = NIL_RTPIPE;
2720 pTxsExec->hEnv = NIL_RTENV;
2721
2722 pTxsExec->hProcess = NIL_RTPROCESS;
2723 pTxsExec->ProcessStatus.iStatus = 254;
2724 pTxsExec->ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
2725 pTxsExec->fProcessAlive = false;
2726 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2727
2728 *ppTxsExec = pTxsExec;
2729 return VINF_SUCCESS;
2730}
2731
2732/**
2733 * txsDoExec helper that takes over when txsDoExec has expanded the packet.
2734 *
2735 * @returns IPRT status code from send.
2736 * @param pPktHdr The exec packet.
2737 * @param fFlags Flags, reserved for future use.
2738 * @param pszExecName The executable name.
2739 * @param cArgs The argument count.
2740 * @param papszArgs The arguments.
2741 * @param cEnvVars The environment variable count.
2742 * @param papszEnv The environment variables.
2743 * @param pszStdIn How to deal with standard in.
2744 * @param pszStdOut How to deal with standard out.
2745 * @param pszStdErr How to deal with standard err.
2746 * @param pszTestPipe How to deal with the test pipe.
2747 * @param pszUsername The user to run the program as.
2748 * @param cMillies The process time limit in milliseconds.
2749 */
2750static int txsDoExecHlp(PCTXSPKTHDR pPktHdr, uint32_t fFlags, const char *pszExecName,
2751 uint32_t cArgs, const char * const *papszArgs,
2752 uint32_t cEnvVars, const char * const *papszEnv,
2753 const char *pszStdIn, const char *pszStdOut, const char *pszStdErr, const char *pszTestPipe,
2754 const char *pszUsername, RTMSINTERVAL cMillies)
2755{
2756 int rc2;
2757 RT_NOREF_PV(fFlags);
2758
2759 /*
2760 * Input validation, filter out things we don't yet support..
2761 */
2762 Assert(!fFlags);
2763 if (!*pszExecName)
2764 return txsReplyFailure(pPktHdr, "STR ZERO", "Executable name is empty");
2765 if (!*pszStdIn)
2766 return txsReplyFailure(pPktHdr, "STR ZERO", "The stdin howto is empty");
2767 if (!*pszStdOut)
2768 return txsReplyFailure(pPktHdr, "STR ZERO", "The stdout howto is empty");
2769 if (!*pszStdErr)
2770 return txsReplyFailure(pPktHdr, "STR ZERO", "The stderr howto is empty");
2771 if (!*pszTestPipe)
2772 return txsReplyFailure(pPktHdr, "STR ZERO", "The testpipe howto is empty");
2773 if (strcmp(pszTestPipe, "|") && strcmp(pszTestPipe, "/dev/null"))
2774 return txsReplyFailure(pPktHdr, "BAD TSTP", "Only \"|\" and \"/dev/null\" are allowed as testpipe howtos ('%s')",
2775 pszTestPipe);
2776 if (*pszUsername)
2777 return txsReplyFailure(pPktHdr, "NOT IMPL", "Executing as a specific user is not implemented ('%s')", pszUsername);
2778
2779 /*
2780 * Prepare for process launch.
2781 */
2782 PTXSEXEC pTxsExec;
2783 int rc = txsExecCreate(pPktHdr, cMillies, &pTxsExec);
2784 if (pTxsExec == NULL)
2785 return rc;
2786 rc = txsExecSetupEnv(pTxsExec, cEnvVars, papszEnv);
2787 if (RT_SUCCESS(rc))
2788 rc = txsExecSetupRedir(pTxsExec, pszStdIn, "StdIn", 0, &pTxsExec->StdIn.hChild, &pTxsExec->StdIn.phChild, &pTxsExec->hStdInW);
2789 if (RT_SUCCESS(rc))
2790 rc = txsExecSetupRedir(pTxsExec, pszStdOut, "StdOut", 1, &pTxsExec->StdOut.hChild, &pTxsExec->StdOut.phChild, &pTxsExec->hStdOutR);
2791 if (RT_SUCCESS(rc))
2792 rc = txsExecSetupRedir(pTxsExec, pszStdErr, "StdErr", 2, &pTxsExec->StdErr.hChild, &pTxsExec->StdErr.phChild, &pTxsExec->hStdErrR);
2793 if (RT_SUCCESS(rc))
2794 rc = txsExecSetupTestPipe(pTxsExec, pszTestPipe);
2795 if (RT_SUCCESS(rc))
2796 rc = txsExecSetupThread(pTxsExec);
2797 if (RT_SUCCESS(rc))
2798 rc = txsExecSetupPollSet(pTxsExec);
2799 if (RT_SUCCESS(rc))
2800 {
2801 char szPathResolved[RTPATH_MAX + 1];
2802 rc = RTPathReal(pszExecName, szPathResolved, sizeof(szPathResolved));
2803 if (RT_SUCCESS(rc))
2804 {
2805 /*
2806 * Create the process.
2807 */
2808 if (g_fDisplayOutput)
2809 {
2810 RTPrintf("txs: Executing \"%s\" -> \"%s\": ", pszExecName, szPathResolved);
2811 for (uint32_t i = 0; i < cArgs; i++)
2812 RTPrintf(" \"%s\"", papszArgs[i]);
2813 RTPrintf("\n");
2814 }
2815
2816 rc = RTProcCreateEx(szPathResolved, papszArgs, pTxsExec->hEnv, 0 /*fFlags*/,
2817 pTxsExec->StdIn.phChild, pTxsExec->StdOut.phChild, pTxsExec->StdErr.phChild,
2818 *pszUsername ? pszUsername : NULL, NULL, NULL,
2819 &pTxsExec->hProcess);
2820 if (RT_SUCCESS(rc))
2821 {
2822 ASMAtomicWriteBool(&pTxsExec->fProcessAlive, true);
2823 rc2 = RTThreadUserSignal(pTxsExec->hThreadWaiter); AssertRC(rc2);
2824
2825 /*
2826 * Close the child ends of any pipes and redirected files.
2827 */
2828 rc2 = RTHandleClose(pTxsExec->StdIn.phChild); AssertRC(rc2);
2829 pTxsExec->StdIn.phChild = NULL;
2830 rc2 = RTHandleClose(pTxsExec->StdOut.phChild); AssertRC(rc2);
2831 pTxsExec->StdOut.phChild = NULL;
2832 rc2 = RTHandleClose(pTxsExec->StdErr.phChild); AssertRC(rc2);
2833 pTxsExec->StdErr.phChild = NULL;
2834 rc2 = RTPipeClose(pTxsExec->hTestPipeW); AssertRC(rc2);
2835 pTxsExec->hTestPipeW = NIL_RTPIPE;
2836
2837 /*
2838 * Let another worker function funnel output and input to the
2839 * client as well as the process exit code.
2840 */
2841 rc = txsDoExecHlp2(pTxsExec);
2842 }
2843 }
2844
2845 if (RT_FAILURE(rc))
2846 rc = txsReplyFailure(pPktHdr, "FAILED ", "Executing process \"%s\" failed with %Rrc",
2847 pszExecName, rc);
2848 }
2849 else
2850 rc = pTxsExec->rcReplySend;
2851 txsExecDestroy(pTxsExec);
2852 return rc;
2853}
2854
2855/**
2856 * Execute a program.
2857 *
2858 * @returns IPRT status code from send.
2859 * @param pPktHdr The exec packet.
2860 */
2861static int txsDoExec(PCTXSPKTHDR pPktHdr)
2862{
2863 /*
2864 * This packet has a lot of parameters, most of which are zero terminated
2865 * strings. The strings used in items 7 thru 10 are either file names,
2866 * "/dev/null" or a pipe char (|).
2867 *
2868 * Packet content:
2869 * 1. Flags reserved for future use (32-bit unsigned).
2870 * 2. The executable name (string).
2871 * 3. The argument count given as a 32-bit unsigned integer.
2872 * 4. The arguments strings.
2873 * 5. The number of environment strings (32-bit unsigned).
2874 * 6. The environment strings (var=val) to apply the environment.
2875 * 7. What to do about standard in (string).
2876 * 8. What to do about standard out (string).
2877 * 9. What to do about standard err (string).
2878 * 10. What to do about the test pipe (string).
2879 * 11. The name of the user to run the program as (string). Empty string
2880 * means running it as the current user.
2881 * 12. Process time limit in milliseconds (32-bit unsigned). Max == no limit.
2882 */
2883 size_t const cbMin = sizeof(TXSPKTHDR)
2884 + sizeof(uint32_t) /* flags */ + 2
2885 + sizeof(uint32_t) /* argc */ + 2 /* argv */
2886 + sizeof(uint32_t) + 0 /* environ */
2887 + 4 * 1
2888 + sizeof(uint32_t) /* timeout */;
2889 if (pPktHdr->cb < cbMin)
2890 return txsReplyBadMinSize(pPktHdr, cbMin);
2891
2892 /* unpack the packet */
2893 char const *pchEnd = (char const *)pPktHdr + pPktHdr->cb;
2894 char const *pch = (char const *)(pPktHdr + 1); /* cursor */
2895
2896 /* 1. flags */
2897 uint32_t const fFlags = *(uint32_t const *)pch;
2898 pch += sizeof(uint32_t);
2899 if (fFlags != 0)
2900 return txsReplyFailure(pPktHdr, "BAD FLAG", "Invalid EXEC flags %#x, expected 0", fFlags);
2901
2902 /* 2. exec name */
2903 int rc;
2904 char *pszExecName = NULL;
2905 if (!txsIsStringValid(pPktHdr, "execname", pch, &pszExecName, &pch, &rc))
2906 return rc;
2907
2908 /* 3. argc */
2909 uint32_t const cArgs = (size_t)(pchEnd - pch) > sizeof(uint32_t) ? *(uint32_t const *)pch : 0xff;
2910 pch += sizeof(uint32_t);
2911 if (cArgs * 1 >= (size_t)(pchEnd - pch))
2912 rc = txsReplyFailure(pPktHdr, "BAD ARGC", "Bad or missing argument count (%#x)", cArgs);
2913 else if (cArgs > 128)
2914 rc = txsReplyFailure(pPktHdr, "BAD ARGC", "Too many arguments (%#x)", cArgs);
2915 else
2916 {
2917 char **papszArgs = (char **)RTMemTmpAllocZ(sizeof(char *) * (cArgs + 1));
2918 if (papszArgs)
2919 {
2920 /* 4. argv */
2921 bool fOk = true;
2922 for (size_t i = 0; i < cArgs && fOk; i++)
2923 {
2924 fOk = txsIsStringValid(pPktHdr, "argvN", pch, &papszArgs[i], &pch, &rc);
2925 if (!fOk)
2926 break;
2927 }
2928 if (fOk)
2929 {
2930 /* 5. cEnvVars */
2931 uint32_t const cEnvVars = (size_t)(pchEnd - pch) > sizeof(uint32_t) ? *(uint32_t const *)pch : 0xfff;
2932 pch += sizeof(uint32_t);
2933 if (cEnvVars * 1 >= (size_t)(pchEnd - pch))
2934 rc = txsReplyFailure(pPktHdr, "BAD ENVC", "Bad or missing environment variable count (%#x)", cEnvVars);
2935 else if (cEnvVars > 256)
2936 rc = txsReplyFailure(pPktHdr, "BAD ENVC", "Too many environment variables (%#x)", cEnvVars);
2937 else
2938 {
2939 char **papszEnv = (char **)RTMemTmpAllocZ(sizeof(char *) * (cEnvVars + 1));
2940 if (papszEnv)
2941 {
2942 /* 6. environ */
2943 for (size_t i = 0; i < cEnvVars && fOk; i++)
2944 {
2945 fOk = txsIsStringValid(pPktHdr, "envN", pch, &papszEnv[i], &pch, &rc);
2946 if (!fOk) /* Bail out on error. */
2947 break;
2948 }
2949 if (fOk)
2950 {
2951 /* 7. stdout */
2952 char *pszStdIn;
2953 if (txsIsStringValid(pPktHdr, "stdin", pch, &pszStdIn, &pch, &rc))
2954 {
2955 /* 8. stdout */
2956 char *pszStdOut;
2957 if (txsIsStringValid(pPktHdr, "stdout", pch, &pszStdOut, &pch, &rc))
2958 {
2959 /* 9. stderr */
2960 char *pszStdErr;
2961 if (txsIsStringValid(pPktHdr, "stderr", pch, &pszStdErr, &pch, &rc))
2962 {
2963 /* 10. testpipe */
2964 char *pszTestPipe;
2965 if (txsIsStringValid(pPktHdr, "testpipe", pch, &pszTestPipe, &pch, &rc))
2966 {
2967 /* 11. username */
2968 char *pszUsername;
2969 if (txsIsStringValid(pPktHdr, "username", pch, &pszUsername, &pch, &rc))
2970 {
2971 /** @todo No password value? */
2972
2973 /* 12. time limit */
2974 uint32_t const cMillies = (size_t)(pchEnd - pch) >= sizeof(uint32_t)
2975 ? *(uint32_t const *)pch
2976 : 0;
2977 if ((size_t)(pchEnd - pch) > sizeof(uint32_t))
2978 rc = txsReplyFailure(pPktHdr, "BAD END ", "Timeout argument not at end of packet (%#x)", (size_t)(pchEnd - pch));
2979 else if ((size_t)(pchEnd - pch) < sizeof(uint32_t))
2980 rc = txsReplyFailure(pPktHdr, "BAD NOTO", "No timeout argument");
2981 else if (cMillies < 1000)
2982 rc = txsReplyFailure(pPktHdr, "BAD TO ", "Timeout is less than a second (%#x)", cMillies);
2983 else
2984 {
2985 pch += sizeof(uint32_t);
2986
2987 /*
2988 * Time to employ a helper here before we go way beyond
2989 * the right margin...
2990 */
2991 rc = txsDoExecHlp(pPktHdr, fFlags, pszExecName,
2992 cArgs, papszArgs,
2993 cEnvVars, papszEnv,
2994 pszStdIn, pszStdOut, pszStdErr, pszTestPipe,
2995 pszUsername,
2996 cMillies == UINT32_MAX ? RT_INDEFINITE_WAIT : cMillies);
2997 }
2998 RTStrFree(pszUsername);
2999 }
3000 RTStrFree(pszTestPipe);
3001 }
3002 RTStrFree(pszStdErr);
3003 }
3004 RTStrFree(pszStdOut);
3005 }
3006 RTStrFree(pszStdIn);
3007 }
3008 }
3009 for (size_t i = 0; i < cEnvVars; i++)
3010 RTStrFree(papszEnv[i]);
3011 RTMemTmpFree(papszEnv);
3012 }
3013 else
3014 rc = txsReplyFailure(pPktHdr, "NO MEM ", "Failed to allocate %zu bytes environ", sizeof(char *) * (cEnvVars + 1));
3015 }
3016 }
3017 for (size_t i = 0; i < cArgs; i++)
3018 RTStrFree(papszArgs[i]);
3019 RTMemTmpFree(papszArgs);
3020 }
3021 else
3022 rc = txsReplyFailure(pPktHdr, "NO MEM ", "Failed to allocate %zu bytes for argv", sizeof(char *) * (cArgs + 1));
3023 }
3024 RTStrFree(pszExecName);
3025
3026 return rc;
3027}
3028
3029/**
3030 * The main loop.
3031 *
3032 * @returns exit code.
3033 */
3034static RTEXITCODE txsMainLoop(void)
3035{
3036 RTMsgInfo("Version %s r%s %s.%s (%s %s)\n",
3037 RTBldCfgVersion(), RTBldCfgRevisionStr(), KBUILD_TARGET, KBUILD_TARGET_ARCH, __DATE__, __TIME__);
3038
3039 if (g_cVerbose > 0)
3040 RTMsgInfo("txsMainLoop: start...\n");
3041 RTEXITCODE enmExitCode = RTEXITCODE_SUCCESS;
3042 while (!g_fTerminate)
3043 {
3044 /*
3045 * Read client command packet and process it.
3046 */
3047 PTXSPKTHDR pPktHdr;
3048 int rc = txsRecvPkt(&pPktHdr, true /*fAutoRetryOnFailure*/);
3049 if (RT_FAILURE(rc))
3050 continue;
3051 if (g_cVerbose > 0)
3052 RTMsgInfo("txsMainLoop: CMD: %.8s...", pPktHdr->achOpcode);
3053
3054 /*
3055 * Do a string switch on the opcode bit.
3056 */
3057 /* Connection: */
3058 if ( txsIsSameOpcode(pPktHdr, "HOWDY "))
3059 rc = txsDoHowdy(pPktHdr);
3060 else if (txsIsSameOpcode(pPktHdr, "BYE "))
3061 rc = txsDoBye(pPktHdr);
3062 else if (txsIsSameOpcode(pPktHdr, "VER "))
3063 rc = txsDoVer(pPktHdr);
3064 else if (txsIsSameOpcode(pPktHdr, "UUID "))
3065 rc = txsDoUuid(pPktHdr);
3066 /* Process: */
3067 else if (txsIsSameOpcode(pPktHdr, "EXEC "))
3068 rc = txsDoExec(pPktHdr);
3069 /* Admin: */
3070 else if (txsIsSameOpcode(pPktHdr, "REBOOT "))
3071 rc = txsDoReboot(pPktHdr);
3072 else if (txsIsSameOpcode(pPktHdr, "SHUTDOWN"))
3073 rc = txsDoShutdown(pPktHdr);
3074 /* CD/DVD control: */
3075 else if (txsIsSameOpcode(pPktHdr, "CD EJECT"))
3076 rc = txsDoCdEject(pPktHdr);
3077 /* File system: */
3078 else if (txsIsSameOpcode(pPktHdr, "CLEANUP "))
3079 rc = txsDoCleanup(pPktHdr);
3080 else if (txsIsSameOpcode(pPktHdr, "MKDIR "))
3081 rc = txsDoMkDir(pPktHdr);
3082 else if (txsIsSameOpcode(pPktHdr, "MKDRPATH"))
3083 rc = txsDoMkDrPath(pPktHdr);
3084 else if (txsIsSameOpcode(pPktHdr, "MKSYMLNK"))
3085 rc = txsDoMkSymlnk(pPktHdr);
3086 else if (txsIsSameOpcode(pPktHdr, "RMDIR "))
3087 rc = txsDoRmDir(pPktHdr);
3088 else if (txsIsSameOpcode(pPktHdr, "RMFILE "))
3089 rc = txsDoRmFile(pPktHdr);
3090 else if (txsIsSameOpcode(pPktHdr, "RMSYMLNK"))
3091 rc = txsDoRmSymlnk(pPktHdr);
3092 else if (txsIsSameOpcode(pPktHdr, "RMTREE "))
3093 rc = txsDoRmTree(pPktHdr);
3094 else if (txsIsSameOpcode(pPktHdr, "CHMOD "))
3095 rc = txsDoChMod(pPktHdr);
3096 else if (txsIsSameOpcode(pPktHdr, "CHOWN "))
3097 rc = txsDoChOwn(pPktHdr);
3098 else if (txsIsSameOpcode(pPktHdr, "ISDIR "))
3099 rc = txsDoIsDir(pPktHdr);
3100 else if (txsIsSameOpcode(pPktHdr, "ISFILE "))
3101 rc = txsDoIsFile(pPktHdr);
3102 else if (txsIsSameOpcode(pPktHdr, "ISSYMLNK"))
3103 rc = txsDoIsSymlnk(pPktHdr);
3104 else if (txsIsSameOpcode(pPktHdr, "STAT "))
3105 rc = txsDoStat(pPktHdr);
3106 else if (txsIsSameOpcode(pPktHdr, "LSTAT "))
3107 rc = txsDoLStat(pPktHdr);
3108 else if (txsIsSameOpcode(pPktHdr, "LIST "))
3109 rc = txsDoList(pPktHdr);
3110 else if (txsIsSameOpcode(pPktHdr, "PUT FILE"))
3111 rc = txsDoPutFile(pPktHdr, false /*fHasMode*/);
3112 else if (txsIsSameOpcode(pPktHdr, "PUT2FILE"))
3113 rc = txsDoPutFile(pPktHdr, true /*fHasMode*/);
3114 else if (txsIsSameOpcode(pPktHdr, "GET FILE"))
3115 rc = txsDoGetFile(pPktHdr);
3116 else if (txsIsSameOpcode(pPktHdr, "PKFILE "))
3117 rc = txsDoPackFile(pPktHdr);
3118 else if (txsIsSameOpcode(pPktHdr, "UNPKFILE"))
3119 rc = txsDoUnpackFile(pPktHdr);
3120 /* Misc: */
3121 else if (txsIsSameOpcode(pPktHdr, "EXP STR "))
3122 rc = txsDoExpandString(pPktHdr);
3123 else
3124 rc = txsReplyUnknown(pPktHdr);
3125
3126 if (g_cVerbose > 0)
3127 RTMsgInfo("txsMainLoop: CMD: %.8s -> %Rrc", pPktHdr->achOpcode, rc);
3128 RTMemFree(pPktHdr);
3129 }
3130
3131 if (g_cVerbose > 0)
3132 RTMsgInfo("txsMainLoop: end\n");
3133 return enmExitCode;
3134}
3135
3136
3137/**
3138 * Finalizes the scratch directory, making sure it exists.
3139 *
3140 * @returns exit code.
3141 */
3142static RTEXITCODE txsFinalizeScratch(void)
3143{
3144 RTPathStripTrailingSlash(g_szScratchPath);
3145 char *pszFilename = RTPathFilename(g_szScratchPath);
3146 if (!pszFilename)
3147 return RTMsgErrorExit(RTEXITCODE_FAILURE, "cannot use root for scratch (%s)\n", g_szScratchPath);
3148
3149 int rc;
3150 if (strchr(pszFilename, 'X'))
3151 {
3152 char ch = *pszFilename;
3153 rc = RTDirCreateFullPath(g_szScratchPath, 0700);
3154 *pszFilename = ch;
3155 if (RT_SUCCESS(rc))
3156 rc = RTDirCreateTemp(g_szScratchPath, 0700);
3157 }
3158 else
3159 {
3160 if (RTDirExists(g_szScratchPath))
3161 rc = VINF_SUCCESS;
3162 else
3163 rc = RTDirCreateFullPath(g_szScratchPath, 0700);
3164 }
3165 if (RT_FAILURE(rc))
3166 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create scratch directory: %Rrc (%s)\n", rc, g_szScratchPath);
3167 return RTEXITCODE_SUCCESS;
3168}
3169
3170/**
3171 * Attempts to complete an upgrade by updating the original and relaunching
3172 * ourselves from there again.
3173 *
3174 * On failure, we'll continue running as the temporary copy.
3175 *
3176 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3177 * @param argc The number of arguments.
3178 * @param argv The argument vector.
3179 * @param pfExit For indicating exit when the exit code is zero.
3180 * @param pszUpgrading The upgraded image path.
3181 */
3182static RTEXITCODE txsAutoUpdateStage2(int argc, char **argv, bool *pfExit, const char *pszUpgrading)
3183{
3184 if (g_cVerbose > 0)
3185 RTMsgInfo("Auto update stage 2...");
3186
3187 /*
3188 * Copy the current executable onto the original.
3189 * Note that we're racing the original program on some platforms, thus the
3190 * 60 sec sleep mess.
3191 */
3192 char szUpgradePath[RTPATH_MAX];
3193 if (!RTProcGetExecutablePath(szUpgradePath, sizeof(szUpgradePath)))
3194 {
3195 RTMsgError("RTProcGetExecutablePath failed (step 2)\n");
3196 return RTEXITCODE_SUCCESS;
3197 }
3198 void *pvUpgrade;
3199 size_t cbUpgrade;
3200 int rc = RTFileReadAll(szUpgradePath, &pvUpgrade, &cbUpgrade);
3201 if (RT_FAILURE(rc))
3202 {
3203 RTMsgError("RTFileReadAllEx(\"%s\"): %Rrc (step 2)\n", szUpgradePath, rc);
3204 return RTEXITCODE_SUCCESS;
3205 }
3206
3207 uint64_t StartMilliTS = RTTimeMilliTS();
3208 RTFILE hFile;
3209 rc = RTFileOpen(&hFile, pszUpgrading,
3210 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE
3211 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3212 while ( RT_FAILURE(rc)
3213 && RTTimeMilliTS() - StartMilliTS < 60000)
3214 {
3215 RTThreadSleep(1000);
3216 rc = RTFileOpen(&hFile, pszUpgrading,
3217 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE
3218 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3219 }
3220 if (RT_SUCCESS(rc))
3221 {
3222 rc = RTFileWrite(hFile, pvUpgrade, cbUpgrade, NULL);
3223 RTFileClose(hFile);
3224 if (RT_SUCCESS(rc))
3225 {
3226 /*
3227 * Relaunch the service with the original name, foricbly barring
3228 * further upgrade cycles in case of bugs (and simplifying the code).
3229 */
3230 const char **papszArgs = (const char **)RTMemAlloc((argc + 1 + 1) * sizeof(char **));
3231 if (papszArgs)
3232 {
3233 papszArgs[0] = pszUpgrading;
3234 for (int i = 1; i < argc; i++)
3235 papszArgs[i] = argv[i];
3236 papszArgs[argc] = "--no-auto-upgrade";
3237 papszArgs[argc + 1] = NULL;
3238
3239 RTMsgInfo("Launching upgraded image: \"%s\"\n", pszUpgrading);
3240 RTPROCESS hProc;
3241 rc = RTProcCreate(pszUpgrading, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, &hProc);
3242 if (RT_SUCCESS(rc))
3243 *pfExit = true;
3244 else
3245 RTMsgError("RTProcCreate(\"%s\"): %Rrc (upgrade stage 2)\n", pszUpgrading, rc);
3246 RTMemFree(papszArgs);
3247 }
3248 else
3249 RTMsgError("RTMemAlloc failed during upgrade attempt (stage 2)\n");
3250 }
3251 else
3252 RTMsgError("RTFileWrite(%s,,%zu): %Rrc (step 2) - BAD\n", pszUpgrading, cbUpgrade, rc);
3253 }
3254 else
3255 RTMsgError("RTFileOpen(,%s,): %Rrc\n", pszUpgrading, rc);
3256 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3257 return RTEXITCODE_SUCCESS;
3258}
3259
3260/**
3261 * Checks for an upgrade and respawns if there is.
3262 *
3263 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3264 * @param argc The number of arguments.
3265 * @param argv The argument vector.
3266 * @param cSecsCdWait Number of seconds to wait on the CD.
3267 * @param pfExit For indicating exit when the exit code is zero.
3268 */
3269static RTEXITCODE txsAutoUpdateStage1(int argc, char **argv, uint32_t cSecsCdWait, bool *pfExit)
3270{
3271 if (g_cVerbose > 1)
3272 RTMsgInfo("Auto update stage 1...");
3273
3274 /*
3275 * Figure names of the current service image and the potential upgrade.
3276 */
3277 char szOrgPath[RTPATH_MAX];
3278 if (!RTProcGetExecutablePath(szOrgPath, sizeof(szOrgPath)))
3279 {
3280 RTMsgError("RTProcGetExecutablePath failed\n");
3281 return RTEXITCODE_SUCCESS;
3282 }
3283
3284 char szUpgradePath[RTPATH_MAX];
3285 int rc = RTPathJoin(szUpgradePath, sizeof(szUpgradePath), g_szCdRomPath, g_szOsSlashArchShortName);
3286 if (RT_SUCCESS(rc))
3287 rc = RTPathAppend(szUpgradePath, sizeof(szUpgradePath), RTPathFilename(szOrgPath));
3288 if (RT_FAILURE(rc))
3289 {
3290 RTMsgError("Failed to construct path to potential service upgrade: %Rrc\n", rc);
3291 return RTEXITCODE_SUCCESS;
3292 }
3293
3294 /*
3295 * Query information about the two images and read the entire potential source file.
3296 * Because the CD may take a little time to be mounted when the system boots, we
3297 * need to do some fudging here.
3298 */
3299 uint64_t nsStart = RTTimeNanoTS();
3300 RTFSOBJINFO UpgradeInfo;
3301 for (;;)
3302 {
3303 rc = RTPathQueryInfo(szUpgradePath, &UpgradeInfo, RTFSOBJATTRADD_NOTHING);
3304 if (RT_SUCCESS(rc))
3305 break;
3306 if ( rc != VERR_FILE_NOT_FOUND
3307 && rc != VERR_PATH_NOT_FOUND
3308 && rc != VERR_MEDIA_NOT_PRESENT
3309 && rc != VERR_MEDIA_NOT_RECOGNIZED)
3310 {
3311 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (upgrade)\n", szUpgradePath, rc);
3312 return RTEXITCODE_SUCCESS;
3313 }
3314 uint64_t cNsElapsed = RTTimeNanoTS() - nsStart;
3315 if (cNsElapsed >= cSecsCdWait * RT_NS_1SEC_64)
3316 {
3317 if (g_cVerbose > 0)
3318 RTMsgInfo("Auto update: Giving up waiting for media.");
3319 return RTEXITCODE_SUCCESS;
3320 }
3321 RTThreadSleep(500);
3322 }
3323
3324 RTFSOBJINFO OrgInfo;
3325 rc = RTPathQueryInfo(szOrgPath, &OrgInfo, RTFSOBJATTRADD_NOTHING);
3326 if (RT_FAILURE(rc))
3327 {
3328 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (old)\n", szOrgPath, rc);
3329 return RTEXITCODE_SUCCESS;
3330 }
3331
3332 void *pvUpgrade;
3333 size_t cbUpgrade;
3334 rc = RTFileReadAllEx(szUpgradePath, 0, UpgradeInfo.cbObject, RTFILE_RDALL_O_DENY_NONE, &pvUpgrade, &cbUpgrade);
3335 if (RT_FAILURE(rc))
3336 {
3337 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (old)\n", szOrgPath, rc);
3338 return RTEXITCODE_SUCCESS;
3339 }
3340
3341 /*
3342 * Compare and see if we've got a different service image or not.
3343 */
3344 if (OrgInfo.cbObject == UpgradeInfo.cbObject)
3345 {
3346 /* must compare bytes. */
3347 void *pvOrg;
3348 size_t cbOrg;
3349 rc = RTFileReadAllEx(szOrgPath, 0, OrgInfo.cbObject, RTFILE_RDALL_O_DENY_NONE, &pvOrg, &cbOrg);
3350 if (RT_FAILURE(rc))
3351 {
3352 RTMsgError("RTFileReadAllEx(\"%s\"): %Rrc\n", szOrgPath, rc);
3353 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3354 return RTEXITCODE_SUCCESS;
3355 }
3356 bool fSame = !memcmp(pvUpgrade, pvOrg, OrgInfo.cbObject);
3357 RTFileReadAllFree(pvOrg, cbOrg);
3358 if (fSame)
3359 {
3360 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3361 if (g_cVerbose > 0)
3362 RTMsgInfo("Auto update: Not necessary.");
3363 return RTEXITCODE_SUCCESS;
3364 }
3365 }
3366
3367 /*
3368 * Should upgrade. Start by creating an executable copy of the update
3369 * image in the scratch area.
3370 */
3371 RTEXITCODE rcExit = txsFinalizeScratch();
3372 if (rcExit == RTEXITCODE_SUCCESS)
3373 {
3374 char szTmpPath[RTPATH_MAX];
3375 rc = RTPathJoin(szTmpPath, sizeof(szTmpPath), g_szScratchPath, RTPathFilename(szOrgPath));
3376 if (RT_SUCCESS(rc))
3377 {
3378 RTFileDelete(szTmpPath); /* shouldn't hurt. */
3379
3380 RTFILE hFile;
3381 rc = RTFileOpen(&hFile, szTmpPath,
3382 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE
3383 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3384 if (RT_SUCCESS(rc))
3385 {
3386 rc = RTFileWrite(hFile, pvUpgrade, UpgradeInfo.cbObject, NULL);
3387 RTFileClose(hFile);
3388 if (RT_SUCCESS(rc))
3389 {
3390 /*
3391 * Try execute the new image and quit if it works.
3392 */
3393 const char **papszArgs = (const char **)RTMemAlloc((argc + 2 + 1) * sizeof(char **));
3394 if (papszArgs)
3395 {
3396 papszArgs[0] = szTmpPath;
3397 for (int i = 1; i < argc; i++)
3398 papszArgs[i] = argv[i];
3399 papszArgs[argc] = "--upgrading";
3400 papszArgs[argc + 1] = szOrgPath;
3401 papszArgs[argc + 2] = NULL;
3402
3403 RTMsgInfo("Launching intermediate automatic upgrade stage: \"%s\"\n", szTmpPath);
3404 RTPROCESS hProc;
3405 rc = RTProcCreate(szTmpPath, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, &hProc);
3406 if (RT_SUCCESS(rc))
3407 *pfExit = true;
3408 else
3409 RTMsgError("RTProcCreate(\"%s\"): %Rrc (upgrade stage 1)\n", szTmpPath, rc);
3410 RTMemFree(papszArgs);
3411 }
3412 else
3413 RTMsgError("RTMemAlloc failed during upgrade attempt (stage)\n");
3414 }
3415 else
3416 RTMsgError("RTFileWrite(%s,,%zu): %Rrc\n", szTmpPath, UpgradeInfo.cbObject, rc);
3417 }
3418 else
3419 RTMsgError("RTFileOpen(,%s,): %Rrc\n", szTmpPath, rc);
3420 }
3421 else
3422 RTMsgError("Failed to construct path to temporary upgrade image: %Rrc\n", rc);
3423 }
3424
3425 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3426 return rcExit;
3427}
3428
3429/**
3430 * Determines the default configuration.
3431 */
3432static void txsSetDefaults(void)
3433{
3434 /*
3435 * OS and ARCH.
3436 */
3437 AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
3438 strcpy(g_szOsShortName, KBUILD_TARGET);
3439
3440 AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
3441 strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);
3442
3443 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
3444 strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
3445 g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
3446 strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
3447
3448 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
3449 strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
3450 g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
3451 strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
3452
3453#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
3454 strcpy(g_szExeSuff, ".exe");
3455 strcpy(g_szScriptSuff, ".cmd");
3456#else
3457 strcpy(g_szExeSuff, "");
3458 strcpy(g_szScriptSuff, ".sh");
3459#endif
3460
3461 int rc = RTPathGetCurrent(g_szCwd, sizeof(g_szCwd));
3462 if (RT_FAILURE(rc))
3463 RTMsgError("RTPathGetCurrent failed: %Rrc\n", rc);
3464 g_szCwd[sizeof(g_szCwd) - 1] = '\0';
3465
3466 if (!RTProcGetExecutablePath(g_szTxsDir, sizeof(g_szTxsDir)))
3467 RTMsgError("RTProcGetExecutablePath failed!\n");
3468 g_szTxsDir[sizeof(g_szTxsDir) - 1] = '\0';
3469 RTPathStripFilename(g_szTxsDir);
3470 RTPathStripTrailingSlash(g_szTxsDir);
3471
3472 /*
3473 * The CD/DVD-ROM location.
3474 */
3475 /** @todo do a better job here :-) */
3476#ifdef RT_OS_WINDOWS
3477 strcpy(g_szDefCdRomPath, "D:/");
3478#elif defined(RT_OS_OS2)
3479 strcpy(g_szDefCdRomPath, "D:/");
3480#else
3481 if (RTDirExists("/media"))
3482 strcpy(g_szDefCdRomPath, "/media/cdrom");
3483 else
3484 strcpy(g_szDefCdRomPath, "/mnt/cdrom");
3485#endif
3486 strcpy(g_szCdRomPath, g_szDefCdRomPath);
3487
3488 /*
3489 * Temporary directory.
3490 */
3491 rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
3492 if (RT_SUCCESS(rc))
3493#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
3494 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "txs-XXXX.tmp");
3495#else
3496 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "txs-XXXXXXXXX.tmp");
3497#endif
3498 if (RT_FAILURE(rc))
3499 {
3500 RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
3501 strcpy(g_szDefScratchPath, "/tmp/txs-XXXX.tmp");
3502 }
3503 strcpy(g_szScratchPath, g_szDefScratchPath);
3504
3505 /*
3506 * The default transporter is the first one.
3507 */
3508 g_pTransport = g_apTransports[0];
3509}
3510
3511/**
3512 * Prints the usage.
3513 *
3514 * @param pStrm Where to print it.
3515 * @param pszArgv0 The program name (argv[0]).
3516 */
3517static void txsUsage(PRTSTREAM pStrm, const char *pszArgv0)
3518{
3519 RTStrmPrintf(pStrm,
3520 "Usage: %Rbn [options]\n"
3521 "\n"
3522 "Options:\n"
3523 " --cdrom <path>\n"
3524 " Where the CD/DVD-ROM will be mounted.\n"
3525 " Default: %s\n"
3526 " --scratch <path>\n"
3527 " Where to put scratch files.\n"
3528 " Default: %s \n"
3529 ,
3530 pszArgv0,
3531 g_szDefCdRomPath,
3532 g_szDefScratchPath);
3533 RTStrmPrintf(pStrm,
3534 " --transport <name>\n"
3535 " Use the specified transport layer, one of the following:\n");
3536 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3537 RTStrmPrintf(pStrm, " %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
3538 RTStrmPrintf(pStrm, " Default: %s\n", g_pTransport->szName);
3539 RTStrmPrintf(pStrm,
3540 " --auto-upgrade, --no-auto-upgrade\n"
3541 " To enable or disable the automatic upgrade mechanism where any different\n"
3542 " version found on the CD-ROM on startup will replace the initial copy.\n"
3543 " Default: --auto-upgrade\n"
3544 " --wait-cdrom <secs>\n"
3545 " Number of seconds to wait for the CD-ROM to be mounted before giving up\n"
3546 " on automatic upgrading.\n"
3547 " Default: --wait-cdrom 1; solaris: --wait-cdrom 8\n"
3548 " --upgrading <org-path>\n"
3549 " Internal use only.\n");
3550 RTStrmPrintf(pStrm,
3551 " --display-output, --no-display-output\n"
3552 " Display the output and the result of all child processes.\n");
3553 RTStrmPrintf(pStrm,
3554 " --foreground\n"
3555 " Don't daemonize, run in the foreground.\n");
3556 RTStrmPrintf(pStrm,
3557 " --verbose, -v\n"
3558 " Increases the verbosity level. Can be specified multiple times.\n");
3559 RTStrmPrintf(pStrm,
3560 " --quiet, -q\n"
3561 " Mutes any logging output.\n");
3562 RTStrmPrintf(pStrm,
3563 " --help, -h, -?\n"
3564 " Display this message and exit.\n"
3565 " --version, -V\n"
3566 " Display the version and exit.\n");
3567
3568 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3569 if (g_apTransports[i]->cOpts)
3570 {
3571 RTStrmPrintf(pStrm,
3572 "\n"
3573 "Options for %s:\n", g_apTransports[i]->szName);
3574 g_apTransports[i]->pfnUsage(g_pStdOut);
3575 }
3576}
3577
3578/**
3579 * Parses the arguments.
3580 *
3581 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3582 * @param argc The number of arguments.
3583 * @param argv The argument vector.
3584 * @param pfExit For indicating exit when the exit code is zero.
3585 */
3586static RTEXITCODE txsParseArgv(int argc, char **argv, bool *pfExit)
3587{
3588 *pfExit = false;
3589
3590 /*
3591 * Storage for locally handled options.
3592 */
3593 bool fAutoUpgrade = true;
3594 bool fDaemonize = true;
3595 bool fDaemonized = false;
3596 const char *pszUpgrading = NULL;
3597#ifdef RT_OS_SOLARIS
3598 uint32_t cSecsCdWait = 8;
3599#else
3600 uint32_t cSecsCdWait = 1;
3601#endif
3602
3603 /*
3604 * Combine the base and transport layer option arrays.
3605 */
3606 static const RTGETOPTDEF s_aBaseOptions[] =
3607 {
3608 { "--transport", 't', RTGETOPT_REQ_STRING },
3609 { "--cdrom", 'c', RTGETOPT_REQ_STRING },
3610 { "--wait-cdrom", 'w', RTGETOPT_REQ_UINT32 },
3611 { "--scratch", 's', RTGETOPT_REQ_STRING },
3612 { "--auto-upgrade", 'a', RTGETOPT_REQ_NOTHING },
3613 { "--no-auto-upgrade", 'A', RTGETOPT_REQ_NOTHING },
3614 { "--upgrading", 'U', RTGETOPT_REQ_STRING },
3615 { "--display-output", 'd', RTGETOPT_REQ_NOTHING },
3616 { "--no-display-output",'D', RTGETOPT_REQ_NOTHING },
3617 { "--foreground", 'f', RTGETOPT_REQ_NOTHING },
3618 { "--daemonized", 'Z', RTGETOPT_REQ_NOTHING },
3619 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
3620 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
3621 };
3622
3623 size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
3624 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3625 cOptions += g_apTransports[i]->cOpts;
3626
3627 PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
3628 if (!paOptions)
3629 return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");
3630
3631 memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
3632 cOptions = RT_ELEMENTS(s_aBaseOptions);
3633 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3634 {
3635 memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
3636 cOptions += g_apTransports[i]->cOpts;
3637 }
3638
3639 /*
3640 * Parse the arguments.
3641 */
3642 RTGETOPTSTATE GetState;
3643 int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
3644 AssertRC(rc);
3645
3646 int ch;
3647 RTGETOPTUNION Val;
3648 while ((ch = RTGetOpt(&GetState, &Val)))
3649 {
3650 switch (ch)
3651 {
3652 case 'a':
3653 fAutoUpgrade = true;
3654 break;
3655
3656 case 'A':
3657 fAutoUpgrade = false;
3658 break;
3659
3660 case 'c':
3661 rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
3662 if (RT_FAILURE(rc))
3663 return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
3664 break;
3665
3666 case 'd':
3667 g_fDisplayOutput = true;
3668 break;
3669
3670 case 'D':
3671 g_fDisplayOutput = false;
3672 break;
3673
3674 case 'f':
3675 fDaemonize = false;
3676 break;
3677
3678 case 'h':
3679 txsUsage(g_pStdOut, argv[0]);
3680 *pfExit = true;
3681 return RTEXITCODE_SUCCESS;
3682
3683 case 's':
3684 rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
3685 if (RT_FAILURE(rc))
3686 return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
3687 break;
3688
3689 case 't':
3690 {
3691 PCTXSTRANSPORT pTransport = NULL;
3692 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3693 if (!strcmp(g_apTransports[i]->szName, Val.psz))
3694 {
3695 pTransport = g_apTransports[i];
3696 break;
3697 }
3698 if (!pTransport)
3699 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
3700 g_pTransport = pTransport;
3701 break;
3702 }
3703
3704 case 'U':
3705 pszUpgrading = Val.psz;
3706 break;
3707
3708 case 'w':
3709 cSecsCdWait = Val.u32;
3710 break;
3711
3712 case 'q':
3713 g_cVerbose = 0;
3714 break;
3715
3716 case 'v':
3717 g_cVerbose++;
3718 break;
3719
3720 case 'V':
3721 RTPrintf("$Revision: 93732 $\n");
3722 *pfExit = true;
3723 return RTEXITCODE_SUCCESS;
3724
3725 case 'Z':
3726 fDaemonized = true;
3727 fDaemonize = false;
3728 break;
3729
3730 default:
3731 {
3732 rc = VERR_TRY_AGAIN;
3733 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3734 if (g_apTransports[i]->cOpts)
3735 {
3736 rc = g_apTransports[i]->pfnOption(ch, &Val);
3737 if (RT_SUCCESS(rc))
3738 break;
3739 if (rc != VERR_TRY_AGAIN)
3740 {
3741 *pfExit = true;
3742 return RTEXITCODE_SYNTAX;
3743 }
3744 }
3745 if (rc == VERR_TRY_AGAIN)
3746 {
3747 *pfExit = true;
3748 return RTGetOptPrintError(ch, &Val);
3749 }
3750 break;
3751 }
3752 }
3753 }
3754
3755 /*
3756 * Handle automatic upgrading of the service.
3757 */
3758 if (fAutoUpgrade && !*pfExit)
3759 {
3760 RTEXITCODE rcExit;
3761 if (pszUpgrading)
3762 rcExit = txsAutoUpdateStage2(argc, argv, pfExit, pszUpgrading);
3763 else
3764 rcExit = txsAutoUpdateStage1(argc, argv, cSecsCdWait, pfExit);
3765 if ( *pfExit
3766 || rcExit != RTEXITCODE_SUCCESS)
3767 return rcExit;
3768 }
3769
3770 /*
3771 * Daemonize ourselves if asked to.
3772 */
3773 if (fDaemonize && !*pfExit)
3774 {
3775 if (g_cVerbose > 0)
3776 RTMsgInfo("Daemonizing...");
3777 rc = RTProcDaemonize(argv, "--daemonized");
3778 if (RT_FAILURE(rc))
3779 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
3780 *pfExit = true;
3781 }
3782
3783 return RTEXITCODE_SUCCESS;
3784}
3785
3786
3787int main(int argc, char **argv)
3788{
3789 /*
3790 * Initialize the runtime.
3791 */
3792 int rc = RTR3InitExe(argc, &argv, 0);
3793 if (RT_FAILURE(rc))
3794 return RTMsgInitFailure(rc);
3795
3796 /*
3797 * Determine defaults and parse the arguments.
3798 */
3799 txsSetDefaults();
3800 bool fExit;
3801 RTEXITCODE rcExit = txsParseArgv(argc, argv, &fExit);
3802 if (rcExit != RTEXITCODE_SUCCESS || fExit)
3803 return rcExit;
3804
3805 /*
3806 * Enable (release) TxS logging to stdout + file. This is independent from the actual test cases being run.
3807 *
3808 * Keep the log file path + naming predictable (the OS' temp dir) so that we later can retrieve it
3809 * from the host side without guessing much.
3810 *
3811 * If enabling logging fails for some reason, just tell but don't bail out to not make tests fail.
3812 */
3813 char szLogFile[RTPATH_MAX];
3814 rc = RTPathTemp(szLogFile, sizeof(szLogFile));
3815 if (RT_SUCCESS(rc))
3816 {
3817 rc = RTPathAppend(szLogFile, sizeof(szLogFile), "vbox-txs-release.log");
3818 if (RT_FAILURE(rc))
3819 RTMsgError("RTPathAppend failed when constructing log file path: %Rrc\n", rc);
3820 }
3821 else
3822 RTMsgError("RTPathTemp failed when constructing log file path: %Rrc\n", rc);
3823
3824 if (RT_SUCCESS(rc))
3825 {
3826 RTUINT fFlags = RTLOGFLAGS_PREFIX_THREAD | RTLOGFLAGS_PREFIX_TIME_PROG;
3827#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
3828 fFlags |= RTLOGFLAGS_USECRLF;
3829#endif
3830 static const char * const g_apszLogGroups[] = VBOX_LOGGROUP_NAMES;
3831 rc = RTLogCreate(&g_pRelLogger, fFlags, "all.e.l", "VBOX_TXS_RELEASE_LOG",
3832 RT_ELEMENTS(g_apszLogGroups), g_apszLogGroups, RTLOGDEST_STDOUT | RTLOGDEST_FILE, szLogFile);
3833 if (RT_SUCCESS(rc))
3834 {
3835 RTLogRelSetDefaultInstance(g_pRelLogger);
3836 if (g_cVerbose)
3837 {
3838 RTMsgInfo("Setting verbosity logging to level %u\n", g_cVerbose);
3839 switch (g_cVerbose) /* Not very elegant, but has to do it for now. */
3840 {
3841 case 1:
3842 rc = RTLogGroupSettings(g_pRelLogger, "all.e.l.l2");
3843 break;
3844
3845 case 2:
3846 rc = RTLogGroupSettings(g_pRelLogger, "all.e.l.l2.l3");
3847 break;
3848
3849 case 3:
3850 rc = RTLogGroupSettings(g_pRelLogger, "all.e.l.l2.l3.l4");
3851 break;
3852
3853 case 4:
3854 RT_FALL_THROUGH();
3855 default:
3856 rc = RTLogGroupSettings(g_pRelLogger, "all.e.l.l2.l3.l4.f");
3857 break;
3858 }
3859 if (RT_FAILURE(rc))
3860 RTMsgError("Setting logging groups failed, rc=%Rrc\n", rc);
3861 }
3862 }
3863 else
3864 RTMsgError("Failed to create release logger: %Rrc", rc);
3865
3866 if (RT_SUCCESS(rc))
3867 RTMsgInfo("Log file written to '%s'\n", szLogFile);
3868
3869 LogRel((VBOX_PRODUCT " TestExecService (Validation Kit TxS) Version " VBOX_VERSION_STRING " - r%s\n"
3870 "(C) " VBOX_C_YEAR " " VBOX_VENDOR "\n"
3871 "All rights reserved.\n\n", RTBldCfgRevisionStr()));
3872 }
3873
3874 /*
3875 * Generate a UUID for this TXS instance.
3876 */
3877 rc = RTUuidCreate(&g_InstanceUuid);
3878 if (RT_FAILURE(rc))
3879 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTUuidCreate failed: %Rrc", rc);
3880 if (g_cVerbose > 0)
3881 RTMsgInfo("Instance UUID: %RTuuid", &g_InstanceUuid);
3882
3883 /*
3884 * Finalize the scratch directory and initialize the transport layer.
3885 */
3886 rcExit = txsFinalizeScratch();
3887 if (rcExit != RTEXITCODE_SUCCESS)
3888 return rcExit;
3889
3890 rc = g_pTransport->pfnInit();
3891 if (RT_FAILURE(rc))
3892 return RTEXITCODE_FAILURE;
3893
3894 /*
3895 * Ok, start working
3896 */
3897 rcExit = txsMainLoop();
3898
3899 /*
3900 * Cleanup.
3901 */
3902 g_pTransport->pfnTerm();
3903
3904 return rcExit;
3905}
3906
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette