VirtualBox

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

Last change on this file since 84787 was 84787, checked in by vboxsync, 5 years ago

Validation Kit/TXS: Added new opcode VER to display TXS' version; also print version information on start.

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