VirtualBox

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

Last change on this file since 84784 was 84784, 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.2 KB
Line 
1/* $Id: TestExecService.cpp 84784 2020-06-11 07:28:56Z 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 howdy 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 howdy 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 howdy packet.
1684 */
1685static int txsDoVer(PCTXSPKTHDR pPktHdr)
1686{
1687 int rc;
1688 if (pPktHdr->cb == sizeof(TXSPKTHDR))
1689 {
1690 rc = txsReplyRC(pPktHdr, VINF_SUCCESS, "%s r%s %s%s (%s %s)",
1691 RTBldCfgVersion(), RTBldCfgRevisionStr(), KBUILD_TARGET, KBUILD_TARGET_ARCH, __DATE__, __TIME__);
1692 }
1693 else
1694 rc = txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1695 return rc;
1696}
1697
1698/**
1699 * Verifies and acknowledges a "HOWDY" request.
1700 *
1701 * @returns IPRT status code.
1702 * @param pPktHdr The howdy packet.
1703 */
1704static int txsDoHowdy(PCTXSPKTHDR pPktHdr)
1705{
1706 if (pPktHdr->cb != sizeof(TXSPKTHDR))
1707 return txsReplyBadSize(pPktHdr, sizeof(TXSPKTHDR));
1708 int rc = txsReplyAck(pPktHdr);
1709 if (RT_SUCCESS(rc))
1710 {
1711 g_pTransport->pfnNotifyHowdy();
1712 RTDirRemoveRecursive(g_szScratchPath, RTDIRRMREC_F_CONTENT_ONLY);
1713 }
1714 return rc;
1715}
1716
1717/**
1718 * Replies according to the return code.
1719 *
1720 * @returns rcOperation and pTxsExec->rcReplySend.
1721 * @param pTxsExec The TXSEXEC instance.
1722 * @param rcOperation The status code to report.
1723 * @param pszOperationFmt The operation that failed. Typically giving the
1724 * function call with important arguments.
1725 * @param ... Arguments to the format string.
1726 */
1727static int txsExecReplyRC(PTXSEXEC pTxsExec, int rcOperation, const char *pszOperationFmt, ...)
1728{
1729 AssertStmt(RT_FAILURE_NP(rcOperation), rcOperation = VERR_IPE_UNEXPECTED_INFO_STATUS);
1730
1731 char szOperation[128];
1732 va_list va;
1733 va_start(va, pszOperationFmt);
1734 RTStrPrintfV(szOperation, sizeof(szOperation), pszOperationFmt, va);
1735 va_end(va);
1736
1737 pTxsExec->rcReplySend = txsReplyFailure(pTxsExec->pPktHdr, "FAILED ",
1738 "%s failed with rc=%Rrc (opcode '%.8s')",
1739 szOperation, rcOperation, pTxsExec->pPktHdr->achOpcode);
1740 return rcOperation;
1741}
1742
1743
1744/**
1745 * Sends the process exit status reply to the TXS client.
1746 *
1747 * @returns IPRT status code of the send.
1748 * @param pTxsExec The TXSEXEC instance.
1749 * @param fProcessAlive Whether the process is still alive (against our
1750 * will).
1751 * @param fProcessTimedOut Whether the process timed out.
1752 * @param MsProcessKilled When the process was killed, UINT64_MAX if not.
1753 */
1754static int txsExecSendExitStatus(PTXSEXEC pTxsExec, bool fProcessAlive, bool fProcessTimedOut, uint64_t MsProcessKilled)
1755{
1756 int rc;
1757 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
1758 {
1759 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC TOK");
1760 if (g_fDisplayOutput)
1761 RTPrintf("txs: Process timed out and was killed\n");
1762 }
1763 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
1764 {
1765 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC TOA");
1766 if (g_fDisplayOutput)
1767 RTPrintf("txs: Process timed out and was not killed successfully\n");
1768 }
1769 else if (g_fTerminate && (fProcessAlive || MsProcessKilled != UINT64_MAX))
1770 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC DWN");
1771 else if (fProcessAlive)
1772 {
1773 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "Doofus! process is alive when it should not");
1774 AssertFailed();
1775 }
1776 else if (MsProcessKilled != UINT64_MAX)
1777 {
1778 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "Doofus! process has been killed when it should not");
1779 AssertFailed();
1780 }
1781 else if ( pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL
1782 && pTxsExec->ProcessStatus.iStatus == 0)
1783 {
1784 rc = txsReplySimple(pTxsExec->pPktHdr, "PROC OK ");
1785 if (g_fDisplayOutput)
1786 RTPrintf("txs: Process exited with status: 0\n");
1787 }
1788 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
1789 {
1790 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC NOK", "%d", pTxsExec->ProcessStatus.iStatus);
1791 if (g_fDisplayOutput)
1792 RTPrintf("txs: Process exited with status: %d\n", pTxsExec->ProcessStatus.iStatus);
1793 }
1794 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
1795 {
1796 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC SIG", "%d", pTxsExec->ProcessStatus.iStatus);
1797 if (g_fDisplayOutput)
1798 RTPrintf("txs: Process exited with status: signal %d\n", pTxsExec->ProcessStatus.iStatus);
1799 }
1800 else if (pTxsExec->ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
1801 {
1802 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC ABD", "");
1803 if (g_fDisplayOutput)
1804 RTPrintf("txs: Process exited with status: abend\n");
1805 }
1806 else
1807 {
1808 rc = txsReplyFailure(pTxsExec->pPktHdr, "PROC DOO", "enmReason=%d iStatus=%d",
1809 pTxsExec->ProcessStatus.enmReason, pTxsExec->ProcessStatus.iStatus);
1810 AssertMsgFailed(("enmReason=%d iStatus=%d", pTxsExec->ProcessStatus.enmReason, pTxsExec->ProcessStatus.iStatus));
1811 }
1812 return rc;
1813}
1814
1815/**
1816 * Handle pending output data or error on standard out, standard error or the
1817 * test pipe.
1818 *
1819 * @returns IPRT status code from client send.
1820 * @param hPollSet The polling set.
1821 * @param fPollEvt The event mask returned by RTPollNoResume.
1822 * @param phPipeR The pipe handle.
1823 * @param puCrc32 The current CRC-32 of the stream. (In/Out)
1824 * @param enmHndId The handle ID.
1825 * @param pszOpcode The opcode for the data upload.
1826 *
1827 * @todo Put the last 4 parameters into a struct!
1828 */
1829static int txsDoExecHlpHandleOutputEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phPipeR,
1830 uint32_t *puCrc32, TXSEXECHNDID enmHndId, const char *pszOpcode)
1831{
1832 Log(("txsDoExecHlpHandleOutputEvent: %s fPollEvt=%#x\n", pszOpcode, fPollEvt));
1833
1834 /*
1835 * Try drain the pipe before acting on any errors.
1836 */
1837 int rc = VINF_SUCCESS;
1838 struct
1839 {
1840 TXSPKTHDR Hdr;
1841 uint32_t uCrc32;
1842 char abBuf[_64K];
1843 char abPadding[TXSPKT_ALIGNMENT];
1844 } Pkt;
1845 size_t cbRead;
1846 int rc2 = RTPipeRead(*phPipeR, Pkt.abBuf, sizeof(Pkt.abBuf), &cbRead);
1847 if (RT_SUCCESS(rc2) && cbRead)
1848 {
1849 Log(("Crc32=%#x ", *puCrc32));
1850 *puCrc32 = RTCrc32Process(*puCrc32, Pkt.abBuf, cbRead);
1851 Log(("cbRead=%#x Crc32=%#x \n", cbRead, *puCrc32));
1852 Pkt.uCrc32 = RTCrc32Finish(*puCrc32);
1853 if (g_fDisplayOutput)
1854 {
1855 if (enmHndId == TXSEXECHNDID_STDOUT)
1856 RTStrmPrintf(g_pStdErr, "%.*s", cbRead, Pkt.abBuf);
1857 else if (enmHndId == TXSEXECHNDID_STDERR)
1858 RTStrmPrintf(g_pStdErr, "%.*s", cbRead, Pkt.abBuf);
1859 }
1860
1861 rc = txsReplyInternal(&Pkt.Hdr, pszOpcode, cbRead + sizeof(uint32_t));
1862
1863 /* Make sure we go another poll round in case there was too much data
1864 for the buffer to hold. */
1865 fPollEvt &= RTPOLL_EVT_ERROR;
1866 }
1867 else if (RT_FAILURE(rc2))
1868 {
1869 fPollEvt |= RTPOLL_EVT_ERROR;
1870 AssertMsg(rc2 == VERR_BROKEN_PIPE, ("%Rrc\n", rc));
1871 }
1872
1873 /*
1874 * If an error was raised signalled,
1875 */
1876 if (fPollEvt & RTPOLL_EVT_ERROR)
1877 {
1878 rc2 = RTPollSetRemove(hPollSet, enmHndId);
1879 AssertRC(rc2);
1880
1881 rc2 = RTPipeClose(*phPipeR);
1882 AssertRC(rc2);
1883 *phPipeR = NIL_RTPIPE;
1884 }
1885 return rc;
1886}
1887
1888/**
1889 * Try write some more data to the standard input of the child.
1890 *
1891 * @returns IPRT status code.
1892 * @param pStdInBuf The standard input buffer.
1893 * @param hStdInW The standard input pipe.
1894 */
1895static int txsDoExecHlpWriteStdIn(PTXSEXECSTDINBUF pStdInBuf, RTPIPE hStdInW)
1896{
1897 size_t cbToWrite = pStdInBuf->cb - pStdInBuf->off;
1898 size_t cbWritten;
1899 int rc = RTPipeWrite(hStdInW, &pStdInBuf->pch[pStdInBuf->off], cbToWrite, &cbWritten);
1900 if (RT_SUCCESS(rc))
1901 {
1902 Assert(cbWritten == cbToWrite);
1903 pStdInBuf->off += cbWritten;
1904 }
1905 return rc;
1906}
1907
1908/**
1909 * Handle an error event on standard input.
1910 *
1911 * @param hPollSet The polling set.
1912 * @param fPollEvt The event mask returned by RTPollNoResume.
1913 * @param phStdInW The standard input pipe handle.
1914 * @param pStdInBuf The standard input buffer.
1915 */
1916static void txsDoExecHlpHandleStdInErrorEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
1917 PTXSEXECSTDINBUF pStdInBuf)
1918{
1919 NOREF(fPollEvt);
1920 int rc2;
1921 if (pStdInBuf->off < pStdInBuf->cb)
1922 {
1923 rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1924 AssertRC(rc2);
1925 }
1926
1927 rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN);
1928 AssertRC(rc2);
1929
1930 rc2 = RTPipeClose(*phStdInW);
1931 AssertRC(rc2);
1932 *phStdInW = NIL_RTPIPE;
1933
1934 RTMemFree(pStdInBuf->pch);
1935 pStdInBuf->pch = NULL;
1936 pStdInBuf->off = 0;
1937 pStdInBuf->cb = 0;
1938 pStdInBuf->cbAllocated = 0;
1939 pStdInBuf->fBitBucket = true;
1940}
1941
1942/**
1943 * Handle an event indicating we can write to the standard input pipe of the
1944 * child process.
1945 *
1946 * @param hPollSet The polling set.
1947 * @param fPollEvt The event mask returned by RTPollNoResume.
1948 * @param phStdInW The standard input pipe.
1949 * @param pStdInBuf The standard input buffer.
1950 */
1951static void txsDoExecHlpHandleStdInWritableEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
1952 PTXSEXECSTDINBUF pStdInBuf)
1953{
1954 int rc;
1955 if (!(fPollEvt & RTPOLL_EVT_ERROR))
1956 {
1957 rc = txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
1958 if (RT_FAILURE(rc) && rc != VERR_BAD_PIPE)
1959 {
1960 /** @todo do we need to do something about this error condition? */
1961 AssertRC(rc);
1962 }
1963
1964 if (pStdInBuf->off < pStdInBuf->cb)
1965 {
1966 rc = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
1967 AssertRC(rc);
1968 }
1969 }
1970 else
1971 txsDoExecHlpHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
1972}
1973
1974/**
1975 * Handle a transport event or successful pfnPollIn() call.
1976 *
1977 * @returns IPRT status code from client send.
1978 * @retval VINF_EOF indicates ABORT command.
1979 *
1980 * @param hPollSet The polling set.
1981 * @param fPollEvt The event mask returned by RTPollNoResume.
1982 * @param idPollHnd The handle ID.
1983 * @param phStdInW The standard input pipe.
1984 * @param pStdInBuf The standard input buffer.
1985 */
1986static int txsDoExecHlpHandleTransportEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, uint32_t idPollHnd,
1987 PRTPIPE phStdInW, PTXSEXECSTDINBUF pStdInBuf)
1988{
1989 /* ASSUMES the transport layer will detect or clear any error condition. */
1990 NOREF(fPollEvt); NOREF(idPollHnd);
1991 Log(("txsDoExecHlpHandleTransportEvent\n"));
1992 /** @todo Use a callback for this case? */
1993
1994 /*
1995 * Read client command packet and process it.
1996 */
1997 /** @todo Sometimes this hangs on windows because there isn't any data pending.
1998 * We probably get woken up at the wrong time or in the wrong way, i.e. RTPoll()
1999 * is busted for sockets.
2000 *
2001 * Temporary workaround: Poll for input before trying to read it. */
2002 if (!g_pTransport->pfnPollIn())
2003 {
2004 Log(("Bad transport event\n"));
2005 RTThreadYield();
2006 return VINF_SUCCESS;
2007 }
2008 PTXSPKTHDR pPktHdr;
2009 int rc = txsRecvPkt(&pPktHdr, false /*fAutoRetryOnFailure*/);
2010 if (RT_FAILURE(rc))
2011 return rc;
2012 Log(("Bad transport event\n"));
2013
2014 /*
2015 * The most common thing here would be a STDIN request with data
2016 * for the child process.
2017 */
2018 if (txsIsSameOpcode(pPktHdr, "STDIN"))
2019 {
2020 if ( !pStdInBuf->fBitBucket
2021 && pPktHdr->cb >= sizeof(TXSPKTHDR) + sizeof(uint32_t))
2022 {
2023 uint32_t uCrc32 = *(uint32_t *)(pPktHdr + 1);
2024 const char *pch = (const char *)(pPktHdr + 1) + sizeof(uint32_t);
2025 size_t cb = pPktHdr->cb - sizeof(TXSPKTHDR) - sizeof(uint32_t);
2026
2027 /* Check the CRC */
2028 pStdInBuf->uCrc32 = RTCrc32Process(pStdInBuf->uCrc32, pch, cb);
2029 if (RTCrc32Finish(pStdInBuf->uCrc32) == uCrc32)
2030 {
2031
2032 /* Rewind the buffer if it's empty. */
2033 size_t cbInBuf = pStdInBuf->cb - pStdInBuf->off;
2034 bool const fAddToSet = cbInBuf == 0;
2035 if (fAddToSet)
2036 pStdInBuf->cb = pStdInBuf->off = 0;
2037
2038 /* Try and see if we can simply append the data. */
2039 if (cb + pStdInBuf->cb <= pStdInBuf->cbAllocated)
2040 {
2041 memcpy(&pStdInBuf->pch[pStdInBuf->cb], pch, cb);
2042 pStdInBuf->cb += cb;
2043 rc = txsReplyAck(pPktHdr);
2044 }
2045 else
2046 {
2047 /* Try write a bit or two before we move+realloc the buffer. */
2048 if (cbInBuf > 0)
2049 txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
2050
2051 /* Move any buffered data to the front. */
2052 cbInBuf = pStdInBuf->cb - pStdInBuf->off;
2053 if (cbInBuf == 0)
2054 pStdInBuf->cb = pStdInBuf->off = 0;
2055 else
2056 {
2057 memmove(pStdInBuf->pch, &pStdInBuf->pch[pStdInBuf->off], cbInBuf);
2058 pStdInBuf->cb = cbInBuf;
2059 pStdInBuf->off = 0;
2060 }
2061
2062 /* Do we need to grow the buffer? */
2063 if (cb + pStdInBuf->cb > pStdInBuf->cbAllocated)
2064 {
2065 size_t cbAlloc = pStdInBuf->cb + cb;
2066 cbAlloc = RT_ALIGN_Z(cbAlloc, _64K);
2067 void *pvNew = RTMemRealloc(pStdInBuf->pch, cbAlloc);
2068 if (pvNew)
2069 {
2070 pStdInBuf->pch = (char *)pvNew;
2071 pStdInBuf->cbAllocated = cbAlloc;
2072 }
2073 }
2074
2075 /* Finally, copy the data. */
2076 if (cb + pStdInBuf->cb <= pStdInBuf->cbAllocated)
2077 {
2078 memcpy(&pStdInBuf->pch[pStdInBuf->cb], pch, cb);
2079 pStdInBuf->cb += cb;
2080 rc = txsReplyAck(pPktHdr);
2081 }
2082 else
2083 rc = txsReplySimple(pPktHdr, "STDINMEM");
2084 }
2085
2086 /*
2087 * Flush the buffered data and add/remove the standard input
2088 * handle from the set.
2089 */
2090 txsDoExecHlpWriteStdIn(pStdInBuf, *phStdInW);
2091 if (fAddToSet && pStdInBuf->off < pStdInBuf->cb)
2092 {
2093 int rc2 = RTPollSetAddPipe(hPollSet, *phStdInW, RTPOLL_EVT_WRITE, TXSEXECHNDID_STDIN_WRITABLE);
2094 AssertRC(rc2);
2095 }
2096 else if (!fAddToSet && pStdInBuf->off >= pStdInBuf->cb)
2097 {
2098 int rc2 = RTPollSetRemove(hPollSet, TXSEXECHNDID_STDIN_WRITABLE);
2099 AssertRC(rc2);
2100 }
2101 }
2102 else
2103 rc = txsReplyFailure(pPktHdr, "STDINCRC", "Invalid CRC checksum expected %#x got %#x",
2104 pStdInBuf->uCrc32, uCrc32);
2105 }
2106 else if (pPktHdr->cb < sizeof(TXSPKTHDR) + sizeof(uint32_t))
2107 rc = txsReplySimple(pPktHdr, "STDINBAD");
2108 else
2109 rc = txsReplySimple(pPktHdr, "STDINIGN");
2110 }
2111 /*
2112 * Marks the end of the stream for stdin.
2113 */
2114 else if (txsIsSameOpcode(pPktHdr, "STDINEOS"))
2115 {
2116 if (RT_LIKELY(pPktHdr->cb == sizeof(TXSPKTHDR)))
2117 {
2118 /* Close the pipe. */
2119 txsDoExecHlpHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
2120 rc = txsReplyAck(pPktHdr);
2121 }
2122 else
2123 rc = txsReplySimple(pPktHdr, "STDINBAD");
2124 }
2125 /*
2126 * The only other two requests are connection oriented and we return a error
2127 * code so that we unwind the whole EXEC shebang and start afresh.
2128 */
2129 else if (txsIsSameOpcode(pPktHdr, "BYE"))
2130 {
2131 rc = txsDoBye(pPktHdr);
2132 if (RT_SUCCESS(rc))
2133 rc = VERR_NET_NOT_CONNECTED;
2134 }
2135 else if (txsIsSameOpcode(pPktHdr, "HOWDY"))
2136 {
2137 rc = txsDoHowdy(pPktHdr);
2138 if (RT_SUCCESS(rc))
2139 rc = VERR_NET_NOT_CONNECTED;
2140 }
2141 else if (txsIsSameOpcode(pPktHdr, "ABORT"))
2142 {
2143 rc = txsReplyAck(pPktHdr);
2144 if (RT_SUCCESS(rc))
2145 rc = VINF_EOF; /* this is but ugly! */
2146 }
2147 else
2148 rc = txsReplyFailure(pPktHdr, "UNKNOWN ", "Opcode '%.8s' is not known or not recognized during EXEC", pPktHdr->achOpcode);
2149
2150 RTMemFree(pPktHdr);
2151 return rc;
2152}
2153
2154/**
2155 * Handles the output and input of the process, waits for it finish up.
2156 *
2157 * @returns IPRT status code from reply send.
2158 * @param pTxsExec The TXSEXEC instance.
2159 */
2160static int txsDoExecHlp2(PTXSEXEC pTxsExec)
2161{
2162 int rc; /* client send. */
2163 int rc2;
2164 TXSEXECSTDINBUF StdInBuf = { 0, 0, NULL, 0, pTxsExec->hStdInW == NIL_RTPIPE, RTCrc32Start() };
2165 uint32_t uStdOutCrc32 = RTCrc32Start();
2166 uint32_t uStdErrCrc32 = uStdOutCrc32;
2167 uint32_t uTestPipeCrc32 = uStdOutCrc32;
2168 uint64_t const MsStart = RTTimeMilliTS();
2169 bool fProcessTimedOut = false;
2170 uint64_t MsProcessKilled = UINT64_MAX;
2171 RTMSINTERVAL const cMsPollBase = g_pTransport->pfnPollSetAdd || pTxsExec->hStdInW == NIL_RTPIPE
2172 ? 5000 : 100;
2173 RTMSINTERVAL cMsPollCur = 0;
2174
2175 /*
2176 * Before entering the loop, tell the client that we've started the guest
2177 * and that it's now OK to send input to the process. (This is not the
2178 * final ACK, so the packet header is NULL ... kind of bogus.)
2179 */
2180 rc = txsReplyAck(NULL);
2181
2182 /*
2183 * Process input, output, the test pipe and client requests.
2184 */
2185 while ( RT_SUCCESS(rc)
2186 && RT_UNLIKELY(!g_fTerminate))
2187 {
2188 /*
2189 * Wait/Process all pending events.
2190 */
2191 uint32_t idPollHnd;
2192 uint32_t fPollEvt;
2193 Log3(("Calling RTPollNoResume(,%u,)...\n", cMsPollCur));
2194 rc2 = RTPollNoResume(pTxsExec->hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
2195 Log3(("RTPollNoResume -> fPollEvt=%#x idPollHnd=%u\n", fPollEvt, idPollHnd));
2196 if (g_fTerminate)
2197 continue;
2198 cMsPollCur = 0; /* no rest until we've checked everything. */
2199
2200 if (RT_SUCCESS(rc2))
2201 {
2202 switch (idPollHnd)
2203 {
2204 case TXSEXECHNDID_STDOUT:
2205 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdOutR, &uStdOutCrc32,
2206 TXSEXECHNDID_STDOUT, "STDOUT ");
2207 break;
2208
2209 case TXSEXECHNDID_STDERR:
2210 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdErrR, &uStdErrCrc32,
2211 TXSEXECHNDID_STDERR, "STDERR ");
2212 break;
2213
2214 case TXSEXECHNDID_TESTPIPE:
2215 rc = txsDoExecHlpHandleOutputEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hTestPipeR, &uTestPipeCrc32,
2216 TXSEXECHNDID_TESTPIPE, "TESTPIPE");
2217 break;
2218
2219 case TXSEXECHNDID_STDIN:
2220 txsDoExecHlpHandleStdInErrorEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdInW, &StdInBuf);
2221 break;
2222
2223 case TXSEXECHNDID_STDIN_WRITABLE:
2224 txsDoExecHlpHandleStdInWritableEvent(pTxsExec->hPollSet, fPollEvt, &pTxsExec->hStdInW, &StdInBuf);
2225 break;
2226
2227 case TXSEXECHNDID_THREAD:
2228 rc2 = RTPollSetRemove(pTxsExec->hPollSet, TXSEXECHNDID_THREAD); AssertRC(rc2);
2229 break;
2230
2231 default:
2232 rc = txsDoExecHlpHandleTransportEvent(pTxsExec->hPollSet, fPollEvt, idPollHnd, &pTxsExec->hStdInW,
2233 &StdInBuf);
2234 break;
2235 }
2236 if (RT_FAILURE(rc) || rc == VINF_EOF)
2237 break; /* abort command, or client dead or something */
2238 continue;
2239 }
2240
2241 /*
2242 * Check for incoming data.
2243 */
2244 if (g_pTransport->pfnPollIn())
2245 {
2246 rc = txsDoExecHlpHandleTransportEvent(pTxsExec->hPollSet, 0, UINT32_MAX, &pTxsExec->hStdInW, &StdInBuf);
2247 if (RT_FAILURE(rc) || rc == VINF_EOF)
2248 break; /* abort command, or client dead or something */
2249 continue;
2250 }
2251
2252 /*
2253 * If the process has terminated, we're should head out.
2254 */
2255 if (!ASMAtomicReadBool(&pTxsExec->fProcessAlive))
2256 break;
2257
2258 /*
2259 * Check for timed out, killing the process.
2260 */
2261 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
2262 if (pTxsExec->cMsTimeout != RT_INDEFINITE_WAIT)
2263 {
2264 uint64_t u64Now = RTTimeMilliTS();
2265 uint64_t cMsElapsed = u64Now - MsStart;
2266 if (cMsElapsed >= pTxsExec->cMsTimeout)
2267 {
2268 fProcessTimedOut = true;
2269 if ( MsProcessKilled == UINT64_MAX
2270 || u64Now - MsProcessKilled > 1000)
2271 {
2272 if (u64Now - MsProcessKilled > 20*60*1000)
2273 break; /* give up after 20 mins */
2274 RTCritSectEnter(&pTxsExec->CritSect);
2275 if (pTxsExec->fProcessAlive)
2276 RTProcTerminate(pTxsExec->hProcess);
2277 RTCritSectLeave(&pTxsExec->CritSect);
2278 MsProcessKilled = u64Now;
2279 continue;
2280 }
2281 cMilliesLeft = 10000;
2282 }
2283 else
2284 cMilliesLeft = pTxsExec->cMsTimeout - (uint32_t)cMsElapsed;
2285 }
2286
2287 /* Reset the polling interval since we've done all pending work. */
2288 cMsPollCur = cMilliesLeft >= cMsPollBase ? cMsPollBase : cMilliesLeft;
2289 }
2290
2291 /*
2292 * At this point we should hopefully only have to wait 0 ms on the thread
2293 * to release the handle... But if for instance the process refuses to die,
2294 * we'll have to try kill it again. Bothersome.
2295 */
2296 for (size_t i = 0; i < 22; i++)
2297 {
2298 rc2 = RTThreadWait(pTxsExec->hThreadWaiter, 500, NULL);
2299 if (RT_SUCCESS(rc))
2300 {
2301 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2302 Assert(!pTxsExec->fProcessAlive);
2303 break;
2304 }
2305 if (i == 0 || i == 10 || i == 15 || i == 18 || i > 20)
2306 {
2307 RTCritSectEnter(&pTxsExec->CritSect);
2308 if (pTxsExec->fProcessAlive)
2309 RTProcTerminate(pTxsExec->hProcess);
2310 RTCritSectLeave(&pTxsExec->CritSect);
2311 }
2312 }
2313
2314 /*
2315 * If we don't have a client problem (RT_FAILURE(rc) we'll reply to the
2316 * clients exec packet now.
2317 */
2318 if (RT_SUCCESS(rc))
2319 rc = txsExecSendExitStatus(pTxsExec, pTxsExec->fProcessAlive, fProcessTimedOut, MsProcessKilled);
2320
2321 RTMemFree(StdInBuf.pch);
2322 return rc;
2323}
2324
2325/**
2326 * Creates a poll set for the pipes and let the transport layer add stuff to it
2327 * as well.
2328 *
2329 * @returns IPRT status code, reply to client made on error.
2330 * @param pTxsExec The TXSEXEC instance.
2331 */
2332static int txsExecSetupPollSet(PTXSEXEC pTxsExec)
2333{
2334 int rc = RTPollSetCreate(&pTxsExec->hPollSet);
2335 if (RT_FAILURE(rc))
2336 return txsExecReplyRC(pTxsExec, rc, "RTPollSetCreate");
2337
2338 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdInW, RTPOLL_EVT_ERROR, TXSEXECHNDID_STDIN);
2339 if (RT_FAILURE(rc))
2340 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stdin");
2341
2342 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2343 TXSEXECHNDID_STDOUT);
2344 if (RT_FAILURE(rc))
2345 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stdout");
2346
2347 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2348 TXSEXECHNDID_STDERR);
2349 if (RT_FAILURE(rc))
2350 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/stderr");
2351
2352 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hTestPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2353 TXSEXECHNDID_TESTPIPE);
2354 if (RT_FAILURE(rc))
2355 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/test");
2356
2357 rc = RTPollSetAddPipe(pTxsExec->hPollSet, pTxsExec->hWakeUpPipeR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
2358 TXSEXECHNDID_THREAD);
2359 if (RT_FAILURE(rc))
2360 return txsExecReplyRC(pTxsExec, rc, "RTPollSetAddPipe/wakeup");
2361
2362 if (g_pTransport->pfnPollSetAdd)
2363 {
2364 rc = g_pTransport->pfnPollSetAdd(pTxsExec->hPollSet, TXSEXECHNDID_TRANSPORT);
2365 if (RT_FAILURE(rc))
2366 return txsExecReplyRC(pTxsExec, rc, "%s->pfnPollSetAdd/stdin", g_pTransport->szName);
2367 }
2368
2369 return VINF_SUCCESS;
2370}
2371
2372/**
2373 * Thread that calls RTProcWait and signals the main thread when it returns.
2374 *
2375 * The thread is created before the process is started and is waiting for a user
2376 * signal from the main thread before it calls RTProcWait.
2377 *
2378 * @returns VINF_SUCCESS (ignored).
2379 * @param hThreadSelf The thread handle.
2380 * @param pvUser The TXEEXEC structure.
2381 */
2382static DECLCALLBACK(int) txsExecWaitThreadProc(RTTHREAD hThreadSelf, void *pvUser)
2383{
2384 PTXSEXEC pTxsExec = (PTXSEXEC)pvUser;
2385
2386 /* Wait for the go ahead... */
2387 int rc = RTThreadUserWait(hThreadSelf, RT_INDEFINITE_WAIT); AssertRC(rc);
2388
2389 RTCritSectEnter(&pTxsExec->CritSect);
2390 for (;;)
2391 {
2392 RTCritSectLeave(&pTxsExec->CritSect);
2393 rc = RTProcWaitNoResume(pTxsExec->hProcess, RTPROCWAIT_FLAGS_BLOCK, &pTxsExec->ProcessStatus);
2394 RTCritSectEnter(&pTxsExec->CritSect);
2395
2396 /* If the pipe is NIL, the destructor wants us to get lost ASAP. */
2397 if (pTxsExec->hWakeUpPipeW == NIL_RTPIPE)
2398 break;
2399
2400 if (RT_FAILURE(rc))
2401 {
2402 rc = RTProcWait(pTxsExec->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &pTxsExec->ProcessStatus);
2403 if (rc == VERR_PROCESS_RUNNING)
2404 continue;
2405
2406 if (RT_FAILURE(rc))
2407 {
2408 AssertRC(rc);
2409 pTxsExec->ProcessStatus.iStatus = rc;
2410 pTxsExec->ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
2411 }
2412 }
2413
2414 /* The process finished, signal the main thread over the pipe. */
2415 ASMAtomicWriteBool(&pTxsExec->fProcessAlive, false);
2416 size_t cbIgnored;
2417 RTPipeWrite(pTxsExec->hWakeUpPipeW, "done", 4, &cbIgnored);
2418 RTPipeClose(pTxsExec->hWakeUpPipeW);
2419 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2420 break;
2421 }
2422 RTCritSectLeave(&pTxsExec->CritSect);
2423
2424 return VINF_SUCCESS;
2425}
2426
2427/**
2428 * Sets up the thread that waits for the process to complete.
2429 *
2430 * @returns IPRT status code, reply to client made on error.
2431 * @param pTxsExec The TXSEXEC instance.
2432 */
2433static int txsExecSetupThread(PTXSEXEC pTxsExec)
2434{
2435 int rc = RTPipeCreate(&pTxsExec->hWakeUpPipeR, &pTxsExec->hWakeUpPipeW, 0 /*fFlags*/);
2436 if (RT_FAILURE(rc))
2437 {
2438 pTxsExec->hWakeUpPipeR = pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2439 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/wait");
2440 }
2441
2442 rc = RTThreadCreate(&pTxsExec->hThreadWaiter, txsExecWaitThreadProc,
2443 pTxsExec, 0 /*cbStack */, RTTHREADTYPE_DEFAULT,
2444 RTTHREADFLAGS_WAITABLE, "TxsProcW");
2445 if (RT_FAILURE(rc))
2446 {
2447 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2448 return txsExecReplyRC(pTxsExec, rc, "RTThreadCreate");
2449 }
2450
2451 return VINF_SUCCESS;
2452}
2453
2454/**
2455 * Sets up the test pipe.
2456 *
2457 * @returns IPRT status code, reply to client made on error.
2458 * @param pTxsExec The TXSEXEC instance.
2459 * @param pszTestPipe How to set up the test pipe.
2460 */
2461static int txsExecSetupTestPipe(PTXSEXEC pTxsExec, const char *pszTestPipe)
2462{
2463 if (strcmp(pszTestPipe, "|"))
2464 return VINF_SUCCESS;
2465
2466 int rc = RTPipeCreate(&pTxsExec->hTestPipeR, &pTxsExec->hTestPipeW, RTPIPE_C_INHERIT_WRITE);
2467 if (RT_FAILURE(rc))
2468 {
2469 pTxsExec->hTestPipeR = pTxsExec->hTestPipeW = NIL_RTPIPE;
2470 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/test/%s", pszTestPipe);
2471 }
2472
2473 char szVal[64];
2474 RTStrPrintf(szVal, sizeof(szVal), "%#llx", (uint64_t)RTPipeToNative(pTxsExec->hTestPipeW));
2475 rc = RTEnvSetEx(pTxsExec->hEnv, "IPRT_TEST_PIPE", szVal);
2476 if (RT_FAILURE(rc))
2477 return txsExecReplyRC(pTxsExec, rc, "RTEnvSetEx/test/%s", pszTestPipe);
2478
2479 return VINF_SUCCESS;
2480}
2481
2482/**
2483 * Sets up the redirection / pipe / nothing for one of the standard handles.
2484 *
2485 * @returns IPRT status code, reply to client made on error.
2486 * @param pTxsExec The TXSEXEC instance.
2487 * @param pszHowTo How to set up this standard handle.
2488 * @param pszStdWhat For what to setup redirection (stdin/stdout/stderr).
2489 * @param fd Which standard handle it is (0 == stdin, 1 ==
2490 * stdout, 2 == stderr).
2491 * @param ph The generic handle that @a pph may be set
2492 * pointing to. Always set.
2493 * @param pph Pointer to the RTProcCreateExec argument.
2494 * Always set.
2495 * @param phPipe Where to return the end of the pipe that we
2496 * should service. Always set.
2497 */
2498static int txsExecSetupRedir(PTXSEXEC pTxsExec, const char *pszHowTo, const char *pszStdWhat, int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
2499{
2500 ph->enmType = RTHANDLETYPE_PIPE;
2501 ph->u.hPipe = NIL_RTPIPE;
2502 *pph = NULL;
2503 *phPipe = NIL_RTPIPE;
2504
2505 int rc;
2506 if (!strcmp(pszHowTo, "|"))
2507 {
2508 /*
2509 * Setup a pipe for forwarding to/from the client.
2510 */
2511 if (fd == 0)
2512 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
2513 else
2514 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
2515 if (RT_FAILURE(rc))
2516 return txsExecReplyRC(pTxsExec, rc, "RTPipeCreate/%s/%s", pszStdWhat, pszHowTo);
2517 ph->enmType = RTHANDLETYPE_PIPE;
2518 *pph = ph;
2519 }
2520 else if (!strcmp(pszHowTo, "/dev/null"))
2521 {
2522 /*
2523 * Redirect to/from /dev/null.
2524 */
2525 RTFILE hFile;
2526 rc = RTFileOpenBitBucket(&hFile, fd == 0 ? RTFILE_O_READ : RTFILE_O_WRITE);
2527 if (RT_FAILURE(rc))
2528 return txsExecReplyRC(pTxsExec, rc, "RTFileOpenBitBucket/%s/%s", pszStdWhat, pszHowTo);
2529
2530 ph->enmType = RTHANDLETYPE_FILE;
2531 ph->u.hFile = hFile;
2532 *pph = ph;
2533 }
2534 else if (*pszHowTo)
2535 {
2536 /*
2537 * Redirect to/from file.
2538 */
2539 uint32_t fFlags;
2540 if (fd == 0)
2541 fFlags = RTFILE_O_READ | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN;
2542 else
2543 {
2544 if (pszHowTo[0] != '>' || pszHowTo[1] != '>')
2545 fFlags = RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE;
2546 else
2547 {
2548 /* append */
2549 pszHowTo += 2;
2550 fFlags = RTFILE_O_WRITE | RTFILE_O_DENY_NONE | RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND;
2551 }
2552 }
2553
2554 RTFILE hFile;
2555 rc = RTFileOpen(&hFile, pszHowTo, fFlags);
2556 if (RT_FAILURE(rc))
2557 return txsExecReplyRC(pTxsExec, rc, "RTFileOpen/%s/%s", pszStdWhat, pszHowTo);
2558
2559 ph->enmType = RTHANDLETYPE_FILE;
2560 ph->u.hFile = hFile;
2561 *pph = ph;
2562 }
2563 else
2564 /* same as parent (us) */
2565 rc = VINF_SUCCESS;
2566 return rc;
2567}
2568
2569/**
2570 * Create the environment.
2571 *
2572 * @returns IPRT status code, reply to client made on error.
2573 * @param pTxsExec The TXSEXEC instance.
2574 * @param cEnvVars The number of environment variables.
2575 * @param papszEnv The environment variables (var=value).
2576 */
2577static int txsExecSetupEnv(PTXSEXEC pTxsExec, uint32_t cEnvVars, const char * const *papszEnv)
2578{
2579 /*
2580 * Create the environment.
2581 */
2582 int rc = RTEnvClone(&pTxsExec->hEnv, RTENV_DEFAULT);
2583 if (RT_FAILURE(rc))
2584 return txsExecReplyRC(pTxsExec, rc, "RTEnvClone");
2585
2586 for (size_t i = 0; i < cEnvVars; i++)
2587 {
2588 rc = RTEnvPutEx(pTxsExec->hEnv, papszEnv[i]);
2589 if (RT_FAILURE(rc))
2590 return txsExecReplyRC(pTxsExec, rc, "RTEnvPutEx(,'%s')", papszEnv[i]);
2591 }
2592 return VINF_SUCCESS;
2593}
2594
2595/**
2596 * Deletes the TXSEXEC structure and frees the memory backing it.
2597 *
2598 * @param pTxsExec The structure to destroy.
2599 */
2600static void txsExecDestroy(PTXSEXEC pTxsExec)
2601{
2602 int rc2;
2603
2604 rc2 = RTEnvDestroy(pTxsExec->hEnv); AssertRC(rc2);
2605 pTxsExec->hEnv = NIL_RTENV;
2606 rc2 = RTPipeClose(pTxsExec->hTestPipeW); AssertRC(rc2);
2607 pTxsExec->hTestPipeW = NIL_RTPIPE;
2608 rc2 = RTHandleClose(pTxsExec->StdErr.phChild); AssertRC(rc2);
2609 pTxsExec->StdErr.phChild = NULL;
2610 rc2 = RTHandleClose(pTxsExec->StdOut.phChild); AssertRC(rc2);
2611 pTxsExec->StdOut.phChild = NULL;
2612 rc2 = RTHandleClose(pTxsExec->StdIn.phChild); AssertRC(rc2);
2613 pTxsExec->StdIn.phChild = NULL;
2614
2615 rc2 = RTPipeClose(pTxsExec->hTestPipeR); AssertRC(rc2);
2616 pTxsExec->hTestPipeR = NIL_RTPIPE;
2617 rc2 = RTPipeClose(pTxsExec->hStdErrR); AssertRC(rc2);
2618 pTxsExec->hStdErrR = NIL_RTPIPE;
2619 rc2 = RTPipeClose(pTxsExec->hStdOutR); AssertRC(rc2);
2620 pTxsExec->hStdOutR = NIL_RTPIPE;
2621 rc2 = RTPipeClose(pTxsExec->hStdInW); AssertRC(rc2);
2622 pTxsExec->hStdInW = NIL_RTPIPE;
2623
2624 RTPollSetDestroy(pTxsExec->hPollSet);
2625 pTxsExec->hPollSet = NIL_RTPOLLSET;
2626
2627 /*
2628 * If the process is still running we're in a bit of a fix... Try kill it,
2629 * although that's potentially racing process termination and reusage of
2630 * the pid.
2631 */
2632 RTCritSectEnter(&pTxsExec->CritSect);
2633
2634 RTPipeClose(pTxsExec->hWakeUpPipeW);
2635 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2636 RTPipeClose(pTxsExec->hWakeUpPipeR);
2637 pTxsExec->hWakeUpPipeR = NIL_RTPIPE;
2638
2639 if ( pTxsExec->hProcess != NIL_RTPROCESS
2640 && pTxsExec->fProcessAlive)
2641 RTProcTerminate(pTxsExec->hProcess);
2642
2643 RTCritSectLeave(&pTxsExec->CritSect);
2644
2645 int rcThread = VINF_SUCCESS;
2646 if (pTxsExec->hThreadWaiter != NIL_RTTHREAD)
2647 rcThread = RTThreadWait(pTxsExec->hThreadWaiter, 5000, NULL);
2648 if (RT_SUCCESS(rcThread))
2649 {
2650 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2651 RTCritSectDelete(&pTxsExec->CritSect);
2652 RTMemFree(pTxsExec);
2653 }
2654 /* else: leak it or RTThreadWait may cause heap corruption later. */
2655}
2656
2657/**
2658 * Initializes the TXSEXEC structure.
2659 *
2660 * @returns VINF_SUCCESS and non-NULL *ppTxsExec on success, reply send status
2661 * and *ppTxsExec set to NULL on failure.
2662 * @param pPktHdr The exec packet.
2663 * @param cMsTimeout The time parameter.
2664 * @param ppTxsExec Where to return the structure.
2665 */
2666static int txsExecCreate(PCTXSPKTHDR pPktHdr, RTMSINTERVAL cMsTimeout, PTXSEXEC *ppTxsExec)
2667{
2668 *ppTxsExec = NULL;
2669
2670 /*
2671 * Allocate the basic resources.
2672 */
2673 PTXSEXEC pTxsExec = (PTXSEXEC)RTMemAlloc(sizeof(*pTxsExec));
2674 if (!pTxsExec)
2675 return txsReplyRC(pPktHdr, VERR_NO_MEMORY, "RTMemAlloc(%zu)", sizeof(*pTxsExec));
2676 int rc = RTCritSectInit(&pTxsExec->CritSect);
2677 if (RT_FAILURE(rc))
2678 {
2679 RTMemFree(pTxsExec);
2680 return txsReplyRC(pPktHdr, rc, "RTCritSectInit");
2681 }
2682
2683 /*
2684 * Initialize the member to NIL values.
2685 */
2686 pTxsExec->pPktHdr = pPktHdr;
2687 pTxsExec->cMsTimeout = cMsTimeout;
2688 pTxsExec->rcReplySend = VINF_SUCCESS;
2689
2690 pTxsExec->hPollSet = NIL_RTPOLLSET;
2691 pTxsExec->hStdInW = NIL_RTPIPE;
2692 pTxsExec->hStdOutR = NIL_RTPIPE;
2693 pTxsExec->hStdErrR = NIL_RTPIPE;
2694 pTxsExec->hTestPipeR = NIL_RTPIPE;
2695 pTxsExec->hWakeUpPipeR = NIL_RTPIPE;
2696 pTxsExec->hThreadWaiter = NIL_RTTHREAD;
2697
2698 pTxsExec->StdIn.phChild = NULL;
2699 pTxsExec->StdOut.phChild = NULL;
2700 pTxsExec->StdErr.phChild = NULL;
2701 pTxsExec->hTestPipeW = NIL_RTPIPE;
2702 pTxsExec->hEnv = NIL_RTENV;
2703
2704 pTxsExec->hProcess = NIL_RTPROCESS;
2705 pTxsExec->ProcessStatus.iStatus = 254;
2706 pTxsExec->ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
2707 pTxsExec->fProcessAlive = false;
2708 pTxsExec->hWakeUpPipeW = NIL_RTPIPE;
2709
2710 *ppTxsExec = pTxsExec;
2711 return VINF_SUCCESS;
2712}
2713
2714/**
2715 * txsDoExec helper that takes over when txsDoExec has expanded the packet.
2716 *
2717 * @returns IPRT status code from send.
2718 * @param pPktHdr The exec packet.
2719 * @param fFlags Flags, reserved for future use.
2720 * @param pszExecName The executable name.
2721 * @param cArgs The argument count.
2722 * @param papszArgs The arguments.
2723 * @param cEnvVars The environment variable count.
2724 * @param papszEnv The environment variables.
2725 * @param pszStdIn How to deal with standard in.
2726 * @param pszStdOut How to deal with standard out.
2727 * @param pszStdErr How to deal with standard err.
2728 * @param pszTestPipe How to deal with the test pipe.
2729 * @param pszUsername The user to run the program as.
2730 * @param cMillies The process time limit in milliseconds.
2731 */
2732static int txsDoExecHlp(PCTXSPKTHDR pPktHdr, uint32_t fFlags, const char *pszExecName,
2733 uint32_t cArgs, const char * const *papszArgs,
2734 uint32_t cEnvVars, const char * const *papszEnv,
2735 const char *pszStdIn, const char *pszStdOut, const char *pszStdErr, const char *pszTestPipe,
2736 const char *pszUsername, RTMSINTERVAL cMillies)
2737{
2738 int rc2;
2739 RT_NOREF_PV(fFlags);
2740
2741 /*
2742 * Input validation, filter out things we don't yet support..
2743 */
2744 Assert(!fFlags);
2745 if (!*pszExecName)
2746 return txsReplyFailure(pPktHdr, "STR ZERO", "Executable name is empty");
2747 if (!*pszStdIn)
2748 return txsReplyFailure(pPktHdr, "STR ZERO", "The stdin howto is empty");
2749 if (!*pszStdOut)
2750 return txsReplyFailure(pPktHdr, "STR ZERO", "The stdout howto is empty");
2751 if (!*pszStdErr)
2752 return txsReplyFailure(pPktHdr, "STR ZERO", "The stderr howto is empty");
2753 if (!*pszTestPipe)
2754 return txsReplyFailure(pPktHdr, "STR ZERO", "The testpipe howto is empty");
2755 if (strcmp(pszTestPipe, "|") && strcmp(pszTestPipe, "/dev/null"))
2756 return txsReplyFailure(pPktHdr, "BAD TSTP", "Only \"|\" and \"/dev/null\" are allowed as testpipe howtos ('%s')",
2757 pszTestPipe);
2758 if (*pszUsername)
2759 return txsReplyFailure(pPktHdr, "NOT IMPL", "Executing as a specific user is not implemented ('%s')", pszUsername);
2760
2761 /*
2762 * Prepare for process launch.
2763 */
2764 PTXSEXEC pTxsExec;
2765 int rc = txsExecCreate(pPktHdr, cMillies, &pTxsExec);
2766 if (pTxsExec == NULL)
2767 return rc;
2768 rc = txsExecSetupEnv(pTxsExec, cEnvVars, papszEnv);
2769 if (RT_SUCCESS(rc))
2770 rc = txsExecSetupRedir(pTxsExec, pszStdIn, "StdIn", 0, &pTxsExec->StdIn.hChild, &pTxsExec->StdIn.phChild, &pTxsExec->hStdInW);
2771 if (RT_SUCCESS(rc))
2772 rc = txsExecSetupRedir(pTxsExec, pszStdOut, "StdOut", 1, &pTxsExec->StdOut.hChild, &pTxsExec->StdOut.phChild, &pTxsExec->hStdOutR);
2773 if (RT_SUCCESS(rc))
2774 rc = txsExecSetupRedir(pTxsExec, pszStdErr, "StdErr", 2, &pTxsExec->StdErr.hChild, &pTxsExec->StdErr.phChild, &pTxsExec->hStdErrR);
2775 if (RT_SUCCESS(rc))
2776 rc = txsExecSetupTestPipe(pTxsExec, pszTestPipe);
2777 if (RT_SUCCESS(rc))
2778 rc = txsExecSetupThread(pTxsExec);
2779 if (RT_SUCCESS(rc))
2780 rc = txsExecSetupPollSet(pTxsExec);
2781 if (RT_SUCCESS(rc))
2782 {
2783 /*
2784 * Create the process.
2785 */
2786 if (g_fDisplayOutput)
2787 {
2788 RTPrintf("txs: Executing \"%s\": ", pszExecName);
2789 for (uint32_t i = 0; i < cArgs; i++)
2790 RTPrintf(" \"%s\"", papszArgs[i]);
2791 RTPrintf("\n");
2792 }
2793 rc = RTProcCreateEx(pszExecName, papszArgs, pTxsExec->hEnv, 0 /*fFlags*/,
2794 pTxsExec->StdIn.phChild, pTxsExec->StdOut.phChild, pTxsExec->StdErr.phChild,
2795 *pszUsername ? pszUsername : NULL, NULL, NULL,
2796 &pTxsExec->hProcess);
2797 if (RT_SUCCESS(rc))
2798 {
2799 ASMAtomicWriteBool(&pTxsExec->fProcessAlive, true);
2800 rc2 = RTThreadUserSignal(pTxsExec->hThreadWaiter); AssertRC(rc2);
2801
2802 /*
2803 * Close the child ends of any pipes and redirected files.
2804 */
2805 rc2 = RTHandleClose(pTxsExec->StdIn.phChild); AssertRC(rc2);
2806 pTxsExec->StdIn.phChild = NULL;
2807 rc2 = RTHandleClose(pTxsExec->StdOut.phChild); AssertRC(rc2);
2808 pTxsExec->StdOut.phChild = NULL;
2809 rc2 = RTHandleClose(pTxsExec->StdErr.phChild); AssertRC(rc2);
2810 pTxsExec->StdErr.phChild = NULL;
2811 rc2 = RTPipeClose(pTxsExec->hTestPipeW); AssertRC(rc2);
2812 pTxsExec->hTestPipeW = NIL_RTPIPE;
2813
2814 /*
2815 * Let another worker function funnel output and input to the
2816 * client as well as the process exit code.
2817 */
2818 rc = txsDoExecHlp2(pTxsExec);
2819 }
2820 else
2821 rc = txsReplyFailure(pPktHdr, "FAILED ", "Executing process \"%s\" failed with %Rrc",
2822 pszExecName, rc);
2823 }
2824 else
2825 rc = pTxsExec->rcReplySend;
2826 txsExecDestroy(pTxsExec);
2827 return rc;
2828}
2829
2830/**
2831 * Execute a program.
2832 *
2833 * @returns IPRT status code from send.
2834 * @param pPktHdr The exec packet.
2835 */
2836static int txsDoExec(PCTXSPKTHDR pPktHdr)
2837{
2838 /*
2839 * This packet has a lot of parameters, most of which are zero terminated
2840 * strings. The strings used in items 7 thru 10 are either file names,
2841 * "/dev/null" or a pipe char (|).
2842 *
2843 * Packet content:
2844 * 1. Flags reserved for future use (32-bit unsigned).
2845 * 2. The executable name (string).
2846 * 3. The argument count given as a 32-bit unsigned integer.
2847 * 4. The arguments strings.
2848 * 5. The number of environment strings (32-bit unsigned).
2849 * 6. The environment strings (var=val) to apply the environment.
2850 * 7. What to do about standard in (string).
2851 * 8. What to do about standard out (string).
2852 * 9. What to do about standard err (string).
2853 * 10. What to do about the test pipe (string).
2854 * 11. The name of the user to run the program as (string). Empty string
2855 * means running it as the current user.
2856 * 12. Process time limit in milliseconds (32-bit unsigned). Max == no limit.
2857 */
2858 size_t const cbMin = sizeof(TXSPKTHDR)
2859 + sizeof(uint32_t) /* flags */ + 2
2860 + sizeof(uint32_t) /* argc */ + 2 /* argv */
2861 + sizeof(uint32_t) + 0 /* environ */
2862 + 4 * 1
2863 + sizeof(uint32_t) /* timeout */;
2864 if (pPktHdr->cb < cbMin)
2865 return txsReplyBadMinSize(pPktHdr, cbMin);
2866
2867 /* unpack the packet */
2868 char const *pchEnd = (char const *)pPktHdr + pPktHdr->cb;
2869 char const *pch = (char const *)(pPktHdr + 1); /* cursor */
2870
2871 /* 1. flags */
2872 uint32_t const fFlags = *(uint32_t const *)pch;
2873 pch += sizeof(uint32_t);
2874 if (fFlags != 0)
2875 return txsReplyFailure(pPktHdr, "BAD FLAG", "Invalid EXEC flags %#x, expected 0", fFlags);
2876
2877 /* 2. exec name */
2878 int rc;
2879 char *pszExecName = NULL;
2880 if (!txsIsStringValid(pPktHdr, "execname", pch, &pszExecName, &pch, &rc))
2881 return rc;
2882
2883 /* 3. argc */
2884 uint32_t const cArgs = (size_t)(pchEnd - pch) > sizeof(uint32_t) ? *(uint32_t const *)pch : 0xff;
2885 pch += sizeof(uint32_t);
2886 if (cArgs * 1 >= (size_t)(pchEnd - pch))
2887 rc = txsReplyFailure(pPktHdr, "BAD ARGC", "Bad or missing argument count (%#x)", cArgs);
2888 else if (cArgs > 128)
2889 rc = txsReplyFailure(pPktHdr, "BAD ARGC", "Too many arguments (%#x)", cArgs);
2890 else
2891 {
2892 char **papszArgs = (char **)RTMemTmpAllocZ(sizeof(char *) * (cArgs + 1));
2893 if (papszArgs)
2894 {
2895 /* 4. argv */
2896 bool fOk = true;
2897 for (size_t i = 0; i < cArgs && fOk; i++)
2898 {
2899 fOk = txsIsStringValid(pPktHdr, "argvN", pch, &papszArgs[i], &pch, &rc);
2900 if (!fOk)
2901 break;
2902 }
2903 if (fOk)
2904 {
2905 /* 5. cEnvVars */
2906 uint32_t const cEnvVars = (size_t)(pchEnd - pch) > sizeof(uint32_t) ? *(uint32_t const *)pch : 0xfff;
2907 pch += sizeof(uint32_t);
2908 if (cEnvVars * 1 >= (size_t)(pchEnd - pch))
2909 rc = txsReplyFailure(pPktHdr, "BAD ENVC", "Bad or missing environment variable count (%#x)", cEnvVars);
2910 else if (cEnvVars > 256)
2911 rc = txsReplyFailure(pPktHdr, "BAD ENVC", "Too many environment variables (%#x)", cEnvVars);
2912 else
2913 {
2914 char **papszEnv = (char **)RTMemTmpAllocZ(sizeof(char *) * (cEnvVars + 1));
2915 if (papszEnv)
2916 {
2917 /* 6. environ */
2918 for (size_t i = 0; i < cEnvVars && fOk; i++)
2919 {
2920 fOk = txsIsStringValid(pPktHdr, "envN", pch, &papszEnv[i], &pch, &rc);
2921 if (!fOk) /* Bail out on error. */
2922 break;
2923 }
2924 if (fOk)
2925 {
2926 /* 7. stdout */
2927 char *pszStdIn;
2928 if (txsIsStringValid(pPktHdr, "stdin", pch, &pszStdIn, &pch, &rc))
2929 {
2930 /* 8. stdout */
2931 char *pszStdOut;
2932 if (txsIsStringValid(pPktHdr, "stdout", pch, &pszStdOut, &pch, &rc))
2933 {
2934 /* 9. stderr */
2935 char *pszStdErr;
2936 if (txsIsStringValid(pPktHdr, "stderr", pch, &pszStdErr, &pch, &rc))
2937 {
2938 /* 10. testpipe */
2939 char *pszTestPipe;
2940 if (txsIsStringValid(pPktHdr, "testpipe", pch, &pszTestPipe, &pch, &rc))
2941 {
2942 /* 11. username */
2943 char *pszUsername;
2944 if (txsIsStringValid(pPktHdr, "username", pch, &pszUsername, &pch, &rc))
2945 {
2946 /** @todo No password value? */
2947
2948 /* 12. time limit */
2949 uint32_t const cMillies = (size_t)(pchEnd - pch) >= sizeof(uint32_t)
2950 ? *(uint32_t const *)pch
2951 : 0;
2952 if ((size_t)(pchEnd - pch) > sizeof(uint32_t))
2953 rc = txsReplyFailure(pPktHdr, "BAD END ", "Timeout argument not at end of packet (%#x)", (size_t)(pchEnd - pch));
2954 else if ((size_t)(pchEnd - pch) < sizeof(uint32_t))
2955 rc = txsReplyFailure(pPktHdr, "BAD NOTO", "No timeout argument");
2956 else if (cMillies < 1000)
2957 rc = txsReplyFailure(pPktHdr, "BAD TO ", "Timeout is less than a second (%#x)", cMillies);
2958 else
2959 {
2960 pch += sizeof(uint32_t);
2961
2962 /*
2963 * Time to employ a helper here before we go way beyond
2964 * the right margin...
2965 */
2966 rc = txsDoExecHlp(pPktHdr, fFlags, pszExecName,
2967 cArgs, papszArgs,
2968 cEnvVars, papszEnv,
2969 pszStdIn, pszStdOut, pszStdErr, pszTestPipe,
2970 pszUsername,
2971 cMillies == UINT32_MAX ? RT_INDEFINITE_WAIT : cMillies);
2972 }
2973 RTStrFree(pszUsername);
2974 }
2975 RTStrFree(pszTestPipe);
2976 }
2977 RTStrFree(pszStdErr);
2978 }
2979 RTStrFree(pszStdOut);
2980 }
2981 RTStrFree(pszStdIn);
2982 }
2983 }
2984 for (size_t i = 0; i < cEnvVars; i++)
2985 RTStrFree(papszEnv[i]);
2986 RTMemTmpFree(papszEnv);
2987 }
2988 else
2989 rc = txsReplyFailure(pPktHdr, "NO MEM ", "Failed to allocate %zu bytes environ", sizeof(char *) * (cEnvVars + 1));
2990 }
2991 }
2992 for (size_t i = 0; i < cArgs; i++)
2993 RTStrFree(papszArgs[i]);
2994 RTMemTmpFree(papszArgs);
2995 }
2996 else
2997 rc = txsReplyFailure(pPktHdr, "NO MEM ", "Failed to allocate %zu bytes for argv", sizeof(char *) * (cArgs + 1));
2998 }
2999 RTStrFree(pszExecName);
3000
3001 return rc;
3002}
3003
3004/**
3005 * The main loop.
3006 *
3007 * @returns exit code.
3008 */
3009static RTEXITCODE txsMainLoop(void)
3010{
3011 RTMsgInfo("Version %s r%s %s%s (%s %s)\n",
3012 RTBldCfgVersion(), RTBldCfgRevisionStr(), KBUILD_TARGET, KBUILD_TARGET_ARCH, __DATE__, __TIME__);
3013
3014 if (g_cVerbose > 0)
3015 RTMsgInfo("txsMainLoop: start...\n");
3016 RTEXITCODE enmExitCode = RTEXITCODE_SUCCESS;
3017 while (!g_fTerminate)
3018 {
3019 /*
3020 * Read client command packet and process it.
3021 */
3022 PTXSPKTHDR pPktHdr;
3023 int rc = txsRecvPkt(&pPktHdr, true /*fAutoRetryOnFailure*/);
3024 if (RT_FAILURE(rc))
3025 continue;
3026 if (g_cVerbose > 0)
3027 RTMsgInfo("txsMainLoop: CMD: %.8s...", pPktHdr->achOpcode);
3028
3029 /*
3030 * Do a string switch on the opcode bit.
3031 */
3032 /* Connection: */
3033 if ( txsIsSameOpcode(pPktHdr, "HOWDY "))
3034 rc = txsDoHowdy(pPktHdr);
3035 else if (txsIsSameOpcode(pPktHdr, "BYE "))
3036 rc = txsDoBye(pPktHdr);
3037 else if (txsIsSameOpcode(pPktHdr, "VER "))
3038 rc = txsDoVer(pPktHdr);
3039 else if (txsIsSameOpcode(pPktHdr, "UUID "))
3040 rc = txsDoUuid(pPktHdr);
3041 /* Process: */
3042 else if (txsIsSameOpcode(pPktHdr, "EXEC "))
3043 rc = txsDoExec(pPktHdr);
3044 /* Admin: */
3045 else if (txsIsSameOpcode(pPktHdr, "REBOOT "))
3046 rc = txsDoReboot(pPktHdr);
3047 else if (txsIsSameOpcode(pPktHdr, "SHUTDOWN"))
3048 rc = txsDoShutdown(pPktHdr);
3049 /* CD/DVD control: */
3050 else if (txsIsSameOpcode(pPktHdr, "CD EJECT"))
3051 rc = txsDoCdEject(pPktHdr);
3052 /* File system: */
3053 else if (txsIsSameOpcode(pPktHdr, "CLEANUP "))
3054 rc = txsDoCleanup(pPktHdr);
3055 else if (txsIsSameOpcode(pPktHdr, "MKDIR "))
3056 rc = txsDoMkDir(pPktHdr);
3057 else if (txsIsSameOpcode(pPktHdr, "MKDRPATH"))
3058 rc = txsDoMkDrPath(pPktHdr);
3059 else if (txsIsSameOpcode(pPktHdr, "MKSYMLNK"))
3060 rc = txsDoMkSymlnk(pPktHdr);
3061 else if (txsIsSameOpcode(pPktHdr, "RMDIR "))
3062 rc = txsDoRmDir(pPktHdr);
3063 else if (txsIsSameOpcode(pPktHdr, "RMFILE "))
3064 rc = txsDoRmFile(pPktHdr);
3065 else if (txsIsSameOpcode(pPktHdr, "RMSYMLNK"))
3066 rc = txsDoRmSymlnk(pPktHdr);
3067 else if (txsIsSameOpcode(pPktHdr, "RMTREE "))
3068 rc = txsDoRmTree(pPktHdr);
3069 else if (txsIsSameOpcode(pPktHdr, "CHMOD "))
3070 rc = txsDoChMod(pPktHdr);
3071 else if (txsIsSameOpcode(pPktHdr, "CHOWN "))
3072 rc = txsDoChOwn(pPktHdr);
3073 else if (txsIsSameOpcode(pPktHdr, "ISDIR "))
3074 rc = txsDoIsDir(pPktHdr);
3075 else if (txsIsSameOpcode(pPktHdr, "ISFILE "))
3076 rc = txsDoIsFile(pPktHdr);
3077 else if (txsIsSameOpcode(pPktHdr, "ISSYMLNK"))
3078 rc = txsDoIsSymlnk(pPktHdr);
3079 else if (txsIsSameOpcode(pPktHdr, "STAT "))
3080 rc = txsDoStat(pPktHdr);
3081 else if (txsIsSameOpcode(pPktHdr, "LSTAT "))
3082 rc = txsDoLStat(pPktHdr);
3083 else if (txsIsSameOpcode(pPktHdr, "LIST "))
3084 rc = txsDoList(pPktHdr);
3085 else if (txsIsSameOpcode(pPktHdr, "PUT FILE"))
3086 rc = txsDoPutFile(pPktHdr, false /*fHasMode*/);
3087 else if (txsIsSameOpcode(pPktHdr, "PUT2FILE"))
3088 rc = txsDoPutFile(pPktHdr, true /*fHasMode*/);
3089 else if (txsIsSameOpcode(pPktHdr, "GET FILE"))
3090 rc = txsDoGetFile(pPktHdr);
3091 else if (txsIsSameOpcode(pPktHdr, "PKFILE "))
3092 rc = txsDoPackFile(pPktHdr);
3093 else if (txsIsSameOpcode(pPktHdr, "UNPKFILE"))
3094 rc = txsDoUnpackFile(pPktHdr);
3095 /* Misc: */
3096 else if (txsIsSameOpcode(pPktHdr, "EXP STR "))
3097 rc = txsDoExpandString(pPktHdr);
3098 else
3099 rc = txsReplyUnknown(pPktHdr);
3100
3101 if (g_cVerbose > 0)
3102 RTMsgInfo("txsMainLoop: CMD: %.8s -> %Rrc", pPktHdr->achOpcode, rc);
3103 RTMemFree(pPktHdr);
3104 }
3105
3106 if (g_cVerbose > 0)
3107 RTMsgInfo("txsMainLoop: end\n");
3108 return enmExitCode;
3109}
3110
3111
3112/**
3113 * Finalizes the scratch directory, making sure it exists.
3114 *
3115 * @returns exit code.
3116 */
3117static RTEXITCODE txsFinalizeScratch(void)
3118{
3119 RTPathStripTrailingSlash(g_szScratchPath);
3120 char *pszFilename = RTPathFilename(g_szScratchPath);
3121 if (!pszFilename)
3122 return RTMsgErrorExit(RTEXITCODE_FAILURE, "cannot use root for scratch (%s)\n", g_szScratchPath);
3123
3124 int rc;
3125 if (strchr(pszFilename, 'X'))
3126 {
3127 char ch = *pszFilename;
3128 rc = RTDirCreateFullPath(g_szScratchPath, 0700);
3129 *pszFilename = ch;
3130 if (RT_SUCCESS(rc))
3131 rc = RTDirCreateTemp(g_szScratchPath, 0700);
3132 }
3133 else
3134 {
3135 if (RTDirExists(g_szScratchPath))
3136 rc = VINF_SUCCESS;
3137 else
3138 rc = RTDirCreateFullPath(g_szScratchPath, 0700);
3139 }
3140 if (RT_FAILURE(rc))
3141 return RTMsgErrorExit(RTEXITCODE_FAILURE, "failed to create scratch directory: %Rrc (%s)\n", rc, g_szScratchPath);
3142 return RTEXITCODE_SUCCESS;
3143}
3144
3145/**
3146 * Attempts to complete an upgrade by updating the original and relaunching
3147 * ourselves from there again.
3148 *
3149 * On failure, we'll continue running as the temporary copy.
3150 *
3151 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3152 * @param argc The number of arguments.
3153 * @param argv The argument vector.
3154 * @param pfExit For indicating exit when the exit code is zero.
3155 * @param pszUpgrading The upgraded image path.
3156 */
3157static RTEXITCODE txsAutoUpdateStage2(int argc, char **argv, bool *pfExit, const char *pszUpgrading)
3158{
3159 if (g_cVerbose > 0)
3160 RTMsgInfo("Auto update stage 2...");
3161
3162 /*
3163 * Copy the current executable onto the original.
3164 * Note that we're racing the original program on some platforms, thus the
3165 * 60 sec sleep mess.
3166 */
3167 char szUpgradePath[RTPATH_MAX];
3168 if (!RTProcGetExecutablePath(szUpgradePath, sizeof(szUpgradePath)))
3169 {
3170 RTMsgError("RTProcGetExecutablePath failed (step 2)\n");
3171 return RTEXITCODE_SUCCESS;
3172 }
3173 void *pvUpgrade;
3174 size_t cbUpgrade;
3175 int rc = RTFileReadAll(szUpgradePath, &pvUpgrade, &cbUpgrade);
3176 if (RT_FAILURE(rc))
3177 {
3178 RTMsgError("RTFileReadAllEx(\"%s\"): %Rrc (step 2)\n", szUpgradePath, rc);
3179 return RTEXITCODE_SUCCESS;
3180 }
3181
3182 uint64_t StartMilliTS = RTTimeMilliTS();
3183 RTFILE hFile;
3184 rc = RTFileOpen(&hFile, pszUpgrading,
3185 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE
3186 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3187 while ( RT_FAILURE(rc)
3188 && RTTimeMilliTS() - StartMilliTS < 60000)
3189 {
3190 RTThreadSleep(1000);
3191 rc = RTFileOpen(&hFile, pszUpgrading,
3192 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_TRUNCATE
3193 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3194 }
3195 if (RT_SUCCESS(rc))
3196 {
3197 rc = RTFileWrite(hFile, pvUpgrade, cbUpgrade, NULL);
3198 RTFileClose(hFile);
3199 if (RT_SUCCESS(rc))
3200 {
3201 /*
3202 * Relaunch the service with the original name, foricbly barring
3203 * further upgrade cycles in case of bugs (and simplifying the code).
3204 */
3205 const char **papszArgs = (const char **)RTMemAlloc((argc + 1 + 1) * sizeof(char **));
3206 if (papszArgs)
3207 {
3208 papszArgs[0] = pszUpgrading;
3209 for (int i = 1; i < argc; i++)
3210 papszArgs[i] = argv[i];
3211 papszArgs[argc] = "--no-auto-upgrade";
3212 papszArgs[argc + 1] = NULL;
3213
3214 RTMsgInfo("Launching upgraded image: \"%s\"\n", pszUpgrading);
3215 RTPROCESS hProc;
3216 rc = RTProcCreate(pszUpgrading, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, &hProc);
3217 if (RT_SUCCESS(rc))
3218 *pfExit = true;
3219 else
3220 RTMsgError("RTProcCreate(\"%s\"): %Rrc (upgrade stage 2)\n", pszUpgrading, rc);
3221 RTMemFree(papszArgs);
3222 }
3223 else
3224 RTMsgError("RTMemAlloc failed during upgrade attempt (stage 2)\n");
3225 }
3226 else
3227 RTMsgError("RTFileWrite(%s,,%zu): %Rrc (step 2) - BAD\n", pszUpgrading, cbUpgrade, rc);
3228 }
3229 else
3230 RTMsgError("RTFileOpen(,%s,): %Rrc\n", pszUpgrading, rc);
3231 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3232 return RTEXITCODE_SUCCESS;
3233}
3234
3235/**
3236 * Checks for an upgrade and respawns if there is.
3237 *
3238 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3239 * @param argc The number of arguments.
3240 * @param argv The argument vector.
3241 * @param cSecsCdWait Number of seconds to wait on the CD.
3242 * @param pfExit For indicating exit when the exit code is zero.
3243 */
3244static RTEXITCODE txsAutoUpdateStage1(int argc, char **argv, uint32_t cSecsCdWait, bool *pfExit)
3245{
3246 if (g_cVerbose > 1)
3247 RTMsgInfo("Auto update stage 1...");
3248
3249 /*
3250 * Figure names of the current service image and the potential upgrade.
3251 */
3252 char szOrgPath[RTPATH_MAX];
3253 if (!RTProcGetExecutablePath(szOrgPath, sizeof(szOrgPath)))
3254 {
3255 RTMsgError("RTProcGetExecutablePath failed\n");
3256 return RTEXITCODE_SUCCESS;
3257 }
3258
3259 char szUpgradePath[RTPATH_MAX];
3260 int rc = RTPathJoin(szUpgradePath, sizeof(szUpgradePath), g_szCdRomPath, g_szOsSlashArchShortName);
3261 if (RT_SUCCESS(rc))
3262 rc = RTPathAppend(szUpgradePath, sizeof(szUpgradePath), RTPathFilename(szOrgPath));
3263 if (RT_FAILURE(rc))
3264 {
3265 RTMsgError("Failed to construct path to potential service upgrade: %Rrc\n", rc);
3266 return RTEXITCODE_SUCCESS;
3267 }
3268
3269 /*
3270 * Query information about the two images and read the entire potential source file.
3271 * Because the CD may take a little time to be mounted when the system boots, we
3272 * need to do some fudging here.
3273 */
3274 uint64_t nsStart = RTTimeNanoTS();
3275 RTFSOBJINFO UpgradeInfo;
3276 for (;;)
3277 {
3278 rc = RTPathQueryInfo(szUpgradePath, &UpgradeInfo, RTFSOBJATTRADD_NOTHING);
3279 if (RT_SUCCESS(rc))
3280 break;
3281 if ( rc != VERR_FILE_NOT_FOUND
3282 && rc != VERR_PATH_NOT_FOUND
3283 && rc != VERR_MEDIA_NOT_PRESENT
3284 && rc != VERR_MEDIA_NOT_RECOGNIZED)
3285 {
3286 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (upgrade)\n", szUpgradePath, rc);
3287 return RTEXITCODE_SUCCESS;
3288 }
3289 uint64_t cNsElapsed = RTTimeNanoTS() - nsStart;
3290 if (cNsElapsed >= cSecsCdWait * RT_NS_1SEC_64)
3291 {
3292 if (g_cVerbose > 0)
3293 RTMsgInfo("Auto update: Giving up waiting for media.");
3294 return RTEXITCODE_SUCCESS;
3295 }
3296 RTThreadSleep(500);
3297 }
3298
3299 RTFSOBJINFO OrgInfo;
3300 rc = RTPathQueryInfo(szOrgPath, &OrgInfo, RTFSOBJATTRADD_NOTHING);
3301 if (RT_FAILURE(rc))
3302 {
3303 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (old)\n", szOrgPath, rc);
3304 return RTEXITCODE_SUCCESS;
3305 }
3306
3307 void *pvUpgrade;
3308 size_t cbUpgrade;
3309 rc = RTFileReadAllEx(szUpgradePath, 0, UpgradeInfo.cbObject, RTFILE_RDALL_O_DENY_NONE, &pvUpgrade, &cbUpgrade);
3310 if (RT_FAILURE(rc))
3311 {
3312 RTMsgError("RTPathQueryInfo(\"%s\"): %Rrc (old)\n", szOrgPath, rc);
3313 return RTEXITCODE_SUCCESS;
3314 }
3315
3316 /*
3317 * Compare and see if we've got a different service image or not.
3318 */
3319 if (OrgInfo.cbObject == UpgradeInfo.cbObject)
3320 {
3321 /* must compare bytes. */
3322 void *pvOrg;
3323 size_t cbOrg;
3324 rc = RTFileReadAllEx(szOrgPath, 0, OrgInfo.cbObject, RTFILE_RDALL_O_DENY_NONE, &pvOrg, &cbOrg);
3325 if (RT_FAILURE(rc))
3326 {
3327 RTMsgError("RTFileReadAllEx(\"%s\"): %Rrc\n", szOrgPath, rc);
3328 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3329 return RTEXITCODE_SUCCESS;
3330 }
3331 bool fSame = !memcmp(pvUpgrade, pvOrg, OrgInfo.cbObject);
3332 RTFileReadAllFree(pvOrg, cbOrg);
3333 if (fSame)
3334 {
3335 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3336 if (g_cVerbose > 0)
3337 RTMsgInfo("Auto update: Not necessary.");
3338 return RTEXITCODE_SUCCESS;
3339 }
3340 }
3341
3342 /*
3343 * Should upgrade. Start by creating an executable copy of the update
3344 * image in the scratch area.
3345 */
3346 RTEXITCODE rcExit = txsFinalizeScratch();
3347 if (rcExit == RTEXITCODE_SUCCESS)
3348 {
3349 char szTmpPath[RTPATH_MAX];
3350 rc = RTPathJoin(szTmpPath, sizeof(szTmpPath), g_szScratchPath, RTPathFilename(szOrgPath));
3351 if (RT_SUCCESS(rc))
3352 {
3353 RTFileDelete(szTmpPath); /* shouldn't hurt. */
3354
3355 RTFILE hFile;
3356 rc = RTFileOpen(&hFile, szTmpPath,
3357 RTFILE_O_WRITE | RTFILE_O_DENY_WRITE | RTFILE_O_CREATE_REPLACE
3358 | (0755 << RTFILE_O_CREATE_MODE_SHIFT));
3359 if (RT_SUCCESS(rc))
3360 {
3361 rc = RTFileWrite(hFile, pvUpgrade, UpgradeInfo.cbObject, NULL);
3362 RTFileClose(hFile);
3363 if (RT_SUCCESS(rc))
3364 {
3365 /*
3366 * Try execute the new image and quit if it works.
3367 */
3368 const char **papszArgs = (const char **)RTMemAlloc((argc + 2 + 1) * sizeof(char **));
3369 if (papszArgs)
3370 {
3371 papszArgs[0] = szTmpPath;
3372 for (int i = 1; i < argc; i++)
3373 papszArgs[i] = argv[i];
3374 papszArgs[argc] = "--upgrading";
3375 papszArgs[argc + 1] = szOrgPath;
3376 papszArgs[argc + 2] = NULL;
3377
3378 RTMsgInfo("Launching intermediate automatic upgrade stage: \"%s\"\n", szTmpPath);
3379 RTPROCESS hProc;
3380 rc = RTProcCreate(szTmpPath, papszArgs, RTENV_DEFAULT, 0 /*fFlags*/, &hProc);
3381 if (RT_SUCCESS(rc))
3382 *pfExit = true;
3383 else
3384 RTMsgError("RTProcCreate(\"%s\"): %Rrc (upgrade stage 1)\n", szTmpPath, rc);
3385 RTMemFree(papszArgs);
3386 }
3387 else
3388 RTMsgError("RTMemAlloc failed during upgrade attempt (stage)\n");
3389 }
3390 else
3391 RTMsgError("RTFileWrite(%s,,%zu): %Rrc\n", szTmpPath, UpgradeInfo.cbObject, rc);
3392 }
3393 else
3394 RTMsgError("RTFileOpen(,%s,): %Rrc\n", szTmpPath, rc);
3395 }
3396 else
3397 RTMsgError("Failed to construct path to temporary upgrade image: %Rrc\n", rc);
3398 }
3399
3400 RTFileReadAllFree(pvUpgrade, cbUpgrade);
3401 return rcExit;
3402}
3403
3404/**
3405 * Determines the default configuration.
3406 */
3407static void txsSetDefaults(void)
3408{
3409 /*
3410 * OS and ARCH.
3411 */
3412 AssertCompile(sizeof(KBUILD_TARGET) <= sizeof(g_szOsShortName));
3413 strcpy(g_szOsShortName, KBUILD_TARGET);
3414
3415 AssertCompile(sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szArchShortName));
3416 strcpy(g_szArchShortName, KBUILD_TARGET_ARCH);
3417
3418 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsDotArchShortName));
3419 strcpy(g_szOsDotArchShortName, KBUILD_TARGET);
3420 g_szOsDotArchShortName[sizeof(KBUILD_TARGET) - 1] = '.';
3421 strcpy(&g_szOsDotArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
3422
3423 AssertCompile(sizeof(KBUILD_TARGET) + sizeof(KBUILD_TARGET_ARCH) <= sizeof(g_szOsSlashArchShortName));
3424 strcpy(g_szOsSlashArchShortName, KBUILD_TARGET);
3425 g_szOsSlashArchShortName[sizeof(KBUILD_TARGET) - 1] = '/';
3426 strcpy(&g_szOsSlashArchShortName[sizeof(KBUILD_TARGET)], KBUILD_TARGET_ARCH);
3427
3428#if defined(RT_OS_WINDOWS) || defined(RT_OS_OS2)
3429 strcpy(g_szExeSuff, ".exe");
3430 strcpy(g_szScriptSuff, ".cmd");
3431#else
3432 strcpy(g_szExeSuff, "");
3433 strcpy(g_szScriptSuff, ".sh");
3434#endif
3435
3436 int rc = RTPathGetCurrent(g_szCwd, sizeof(g_szCwd));
3437 if (RT_FAILURE(rc))
3438 RTMsgError("RTPathGetCurrent failed: %Rrc\n", rc);
3439 g_szCwd[sizeof(g_szCwd) - 1] = '\0';
3440
3441 if (!RTProcGetExecutablePath(g_szTxsDir, sizeof(g_szTxsDir)))
3442 RTMsgError("RTProcGetExecutablePath failed!\n");
3443 g_szTxsDir[sizeof(g_szTxsDir) - 1] = '\0';
3444 RTPathStripFilename(g_szTxsDir);
3445 RTPathStripTrailingSlash(g_szTxsDir);
3446
3447 /*
3448 * The CD/DVD-ROM location.
3449 */
3450 /** @todo do a better job here :-) */
3451#ifdef RT_OS_WINDOWS
3452 strcpy(g_szDefCdRomPath, "D:/");
3453#elif defined(RT_OS_OS2)
3454 strcpy(g_szDefCdRomPath, "D:/");
3455#else
3456 if (RTDirExists("/media"))
3457 strcpy(g_szDefCdRomPath, "/media/cdrom");
3458 else
3459 strcpy(g_szDefCdRomPath, "/mnt/cdrom");
3460#endif
3461 strcpy(g_szCdRomPath, g_szDefCdRomPath);
3462
3463 /*
3464 * Temporary directory.
3465 */
3466 rc = RTPathTemp(g_szDefScratchPath, sizeof(g_szDefScratchPath));
3467 if (RT_SUCCESS(rc))
3468#if defined(RT_OS_OS2) || defined(RT_OS_WINDOWS) || defined(RT_OS_DOS)
3469 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "txs-XXXX.tmp");
3470#else
3471 rc = RTPathAppend(g_szDefScratchPath, sizeof(g_szDefScratchPath), "txs-XXXXXXXXX.tmp");
3472#endif
3473 if (RT_FAILURE(rc))
3474 {
3475 RTMsgError("RTPathTemp/Append failed when constructing scratch path: %Rrc\n", rc);
3476 strcpy(g_szDefScratchPath, "/tmp/txs-XXXX.tmp");
3477 }
3478 strcpy(g_szScratchPath, g_szDefScratchPath);
3479
3480 /*
3481 * The default transporter is the first one.
3482 */
3483 g_pTransport = g_apTransports[0];
3484}
3485
3486/**
3487 * Prints the usage.
3488 *
3489 * @param pStrm Where to print it.
3490 * @param pszArgv0 The program name (argv[0]).
3491 */
3492static void txsUsage(PRTSTREAM pStrm, const char *pszArgv0)
3493{
3494 RTStrmPrintf(pStrm,
3495 "Usage: %Rbn [options]\n"
3496 "\n"
3497 "Options:\n"
3498 " --cdrom <path>\n"
3499 " Where the CD/DVD-ROM will be mounted.\n"
3500 " Default: %s\n"
3501 " --scratch <path>\n"
3502 " Where to put scratch files.\n"
3503 " Default: %s \n"
3504 ,
3505 pszArgv0,
3506 g_szDefCdRomPath,
3507 g_szDefScratchPath);
3508 RTStrmPrintf(pStrm,
3509 " --transport <name>\n"
3510 " Use the specified transport layer, one of the following:\n");
3511 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3512 RTStrmPrintf(pStrm, " %s - %s\n", g_apTransports[i]->szName, g_apTransports[i]->pszDesc);
3513 RTStrmPrintf(pStrm, " Default: %s\n", g_pTransport->szName);
3514 RTStrmPrintf(pStrm,
3515 " --auto-upgrade, --no-auto-upgrade\n"
3516 " To enable or disable the automatic upgrade mechanism where any different\n"
3517 " version found on the CD-ROM on startup will replace the initial copy.\n"
3518 " Default: --auto-upgrade\n"
3519 " --wait-cdrom <secs>\n"
3520 " Number of seconds to wait for the CD-ROM to be mounted before giving up\n"
3521 " on automatic upgrading.\n"
3522 " Default: --wait-cdrom 1; solaris: --wait-cdrom 8\n"
3523 " --upgrading <org-path>\n"
3524 " Internal use only.\n");
3525 RTStrmPrintf(pStrm,
3526 " --display-output, --no-display-output\n"
3527 " Display the output and the result of all child processes.\n");
3528 RTStrmPrintf(pStrm,
3529 " --foreground\n"
3530 " Don't daemonize, run in the foreground.\n");
3531 RTStrmPrintf(pStrm,
3532 " --verbose, -v\n"
3533 " Increases the verbosity level. Can be specified multiple times.\n");
3534 RTStrmPrintf(pStrm,
3535 " --quiet, -q\n"
3536 " Mutes any logging output.\n");
3537 RTStrmPrintf(pStrm,
3538 " --help, -h, -?\n"
3539 " Display this message and exit.\n"
3540 " --version, -V\n"
3541 " Display the version and exit.\n");
3542
3543 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3544 if (g_apTransports[i]->cOpts)
3545 {
3546 RTStrmPrintf(pStrm,
3547 "\n"
3548 "Options for %s:\n", g_apTransports[i]->szName);
3549 g_apTransports[i]->pfnUsage(g_pStdOut);
3550 }
3551}
3552
3553/**
3554 * Parses the arguments.
3555 *
3556 * @returns Exit code. Exit if this is non-zero or @a *pfExit is set.
3557 * @param argc The number of arguments.
3558 * @param argv The argument vector.
3559 * @param pfExit For indicating exit when the exit code is zero.
3560 */
3561static RTEXITCODE txsParseArgv(int argc, char **argv, bool *pfExit)
3562{
3563 *pfExit = false;
3564
3565 /*
3566 * Storage for locally handled options.
3567 */
3568 bool fAutoUpgrade = true;
3569 bool fDaemonize = true;
3570 bool fDaemonized = false;
3571 const char *pszUpgrading = NULL;
3572#ifdef RT_OS_SOLARIS
3573 uint32_t cSecsCdWait = 8;
3574#else
3575 uint32_t cSecsCdWait = 1;
3576#endif
3577
3578 /*
3579 * Combine the base and transport layer option arrays.
3580 */
3581 static const RTGETOPTDEF s_aBaseOptions[] =
3582 {
3583 { "--transport", 't', RTGETOPT_REQ_STRING },
3584 { "--cdrom", 'c', RTGETOPT_REQ_STRING },
3585 { "--wait-cdrom", 'w', RTGETOPT_REQ_UINT32 },
3586 { "--scratch", 's', RTGETOPT_REQ_STRING },
3587 { "--auto-upgrade", 'a', RTGETOPT_REQ_NOTHING },
3588 { "--no-auto-upgrade", 'A', RTGETOPT_REQ_NOTHING },
3589 { "--upgrading", 'U', RTGETOPT_REQ_STRING },
3590 { "--display-output", 'd', RTGETOPT_REQ_NOTHING },
3591 { "--no-display-output",'D', RTGETOPT_REQ_NOTHING },
3592 { "--foreground", 'f', RTGETOPT_REQ_NOTHING },
3593 { "--daemonized", 'Z', RTGETOPT_REQ_NOTHING },
3594 { "--quiet", 'q', RTGETOPT_REQ_NOTHING },
3595 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
3596 };
3597
3598 size_t cOptions = RT_ELEMENTS(s_aBaseOptions);
3599 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3600 cOptions += g_apTransports[i]->cOpts;
3601
3602 PRTGETOPTDEF paOptions = (PRTGETOPTDEF)alloca(cOptions * sizeof(RTGETOPTDEF));
3603 if (!paOptions)
3604 return RTMsgErrorExit(RTEXITCODE_FAILURE, "alloca failed\n");
3605
3606 memcpy(paOptions, s_aBaseOptions, sizeof(s_aBaseOptions));
3607 cOptions = RT_ELEMENTS(s_aBaseOptions);
3608 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3609 {
3610 memcpy(&paOptions[cOptions], g_apTransports[i]->paOpts, g_apTransports[i]->cOpts * sizeof(RTGETOPTDEF));
3611 cOptions += g_apTransports[i]->cOpts;
3612 }
3613
3614 /*
3615 * Parse the arguments.
3616 */
3617 RTGETOPTSTATE GetState;
3618 int rc = RTGetOptInit(&GetState, argc, argv, paOptions, cOptions, 1, 0 /* fFlags */);
3619 AssertRC(rc);
3620
3621 int ch;
3622 RTGETOPTUNION Val;
3623 while ((ch = RTGetOpt(&GetState, &Val)))
3624 {
3625 switch (ch)
3626 {
3627 case 'a':
3628 fAutoUpgrade = true;
3629 break;
3630
3631 case 'A':
3632 fAutoUpgrade = false;
3633 break;
3634
3635 case 'c':
3636 rc = RTStrCopy(g_szCdRomPath, sizeof(g_szCdRomPath), Val.psz);
3637 if (RT_FAILURE(rc))
3638 return RTMsgErrorExit(RTEXITCODE_FAILURE, "CD/DVD-ROM is path too long (%Rrc)\n", rc);
3639 break;
3640
3641 case 'd':
3642 g_fDisplayOutput = true;
3643 break;
3644
3645 case 'D':
3646 g_fDisplayOutput = false;
3647 break;
3648
3649 case 'f':
3650 fDaemonize = false;
3651 break;
3652
3653 case 'h':
3654 txsUsage(g_pStdOut, argv[0]);
3655 *pfExit = true;
3656 return RTEXITCODE_SUCCESS;
3657
3658 case 's':
3659 rc = RTStrCopy(g_szScratchPath, sizeof(g_szScratchPath), Val.psz);
3660 if (RT_FAILURE(rc))
3661 return RTMsgErrorExit(RTEXITCODE_FAILURE, "scratch path is too long (%Rrc)\n", rc);
3662 break;
3663
3664 case 't':
3665 {
3666 PCTXSTRANSPORT pTransport = NULL;
3667 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3668 if (!strcmp(g_apTransports[i]->szName, Val.psz))
3669 {
3670 pTransport = g_apTransports[i];
3671 break;
3672 }
3673 if (!pTransport)
3674 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown transport layer name '%s'\n", Val.psz);
3675 g_pTransport = pTransport;
3676 break;
3677 }
3678
3679 case 'U':
3680 pszUpgrading = Val.psz;
3681 break;
3682
3683 case 'w':
3684 cSecsCdWait = Val.u32;
3685 break;
3686
3687 case 'q':
3688 g_cVerbose = 0;
3689 break;
3690
3691 case 'v':
3692 g_cVerbose++;
3693 break;
3694
3695 case 'V':
3696 RTPrintf("$Revision: 84784 $\n");
3697 *pfExit = true;
3698 return RTEXITCODE_SUCCESS;
3699
3700 case 'Z':
3701 fDaemonized = true;
3702 fDaemonize = false;
3703 break;
3704
3705 default:
3706 {
3707 rc = VERR_TRY_AGAIN;
3708 for (size_t i = 0; i < RT_ELEMENTS(g_apTransports); i++)
3709 if (g_apTransports[i]->cOpts)
3710 {
3711 rc = g_apTransports[i]->pfnOption(ch, &Val);
3712 if (RT_SUCCESS(rc))
3713 break;
3714 if (rc != VERR_TRY_AGAIN)
3715 {
3716 *pfExit = true;
3717 return RTEXITCODE_SYNTAX;
3718 }
3719 }
3720 if (rc == VERR_TRY_AGAIN)
3721 {
3722 *pfExit = true;
3723 return RTGetOptPrintError(ch, &Val);
3724 }
3725 break;
3726 }
3727 }
3728 }
3729
3730 /*
3731 * Handle automatic upgrading of the service.
3732 */
3733 if (fAutoUpgrade && !*pfExit)
3734 {
3735 RTEXITCODE rcExit;
3736 if (pszUpgrading)
3737 rcExit = txsAutoUpdateStage2(argc, argv, pfExit, pszUpgrading);
3738 else
3739 rcExit = txsAutoUpdateStage1(argc, argv, cSecsCdWait, pfExit);
3740 if ( *pfExit
3741 || rcExit != RTEXITCODE_SUCCESS)
3742 return rcExit;
3743 }
3744
3745 /*
3746 * Daemonize ourselves if asked to.
3747 */
3748 if (fDaemonize && !*pfExit)
3749 {
3750 if (g_cVerbose > 0)
3751 RTMsgInfo("Daemonizing...");
3752 rc = RTProcDaemonize(argv, "--daemonized");
3753 if (RT_FAILURE(rc))
3754 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTProcDaemonize: %Rrc\n", rc);
3755 *pfExit = true;
3756 }
3757
3758 return RTEXITCODE_SUCCESS;
3759}
3760
3761
3762int main(int argc, char **argv)
3763{
3764 /*
3765 * Initialize the runtime.
3766 */
3767 int rc = RTR3InitExe(argc, &argv, 0);
3768 if (RT_FAILURE(rc))
3769 return RTMsgInitFailure(rc);
3770
3771 /*
3772 * Determine defaults and parse the arguments.
3773 */
3774 txsSetDefaults();
3775 bool fExit;
3776 RTEXITCODE rcExit = txsParseArgv(argc, argv, &fExit);
3777 if (rcExit != RTEXITCODE_SUCCESS || fExit)
3778 return rcExit;
3779
3780 /*
3781 * Generate a UUID for this TXS instance.
3782 */
3783 rc = RTUuidCreate(&g_InstanceUuid);
3784 if (RT_FAILURE(rc))
3785 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTUuidCreate failed: %Rrc", rc);
3786 if (g_cVerbose > 0)
3787 RTMsgInfo("Instance UUID: %RTuuid", &g_InstanceUuid);
3788
3789 /*
3790 * Finalize the scratch directory and initialize the transport layer.
3791 */
3792 rcExit = txsFinalizeScratch();
3793 if (rcExit != RTEXITCODE_SUCCESS)
3794 return rcExit;
3795
3796 rc = g_pTransport->pfnInit();
3797 if (RT_FAILURE(rc))
3798 return RTEXITCODE_FAILURE;
3799
3800 /*
3801 * Ok, start working
3802 */
3803 rcExit = txsMainLoop();
3804
3805 /*
3806 * Cleanup.
3807 */
3808 g_pTransport->pfnTerm();
3809
3810 return rcExit;
3811}
3812
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