VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceControlExec.cpp@ 28800

Last change on this file since 28800 was 28800, checked in by vboxsync, 15 years ago

Automated rebranding to Oracle copyright/license strings via filemuncher

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 33.5 KB
Line 
1
2/* $Id: VBoxServiceControlExec.cpp 28800 2010-04-27 08:22:32Z vboxsync $ */
3/** @file
4 * VBoxServiceControlExec - Utility functions for process execution.
5 */
6
7/*
8 * Copyright (C) 2010 Oracle Corporation
9 *
10 * This file is part of VirtualBox Open Source Edition (OSE), as
11 * available from http://www.virtualbox.org. This file is free software;
12 * you can redistribute it and/or modify it under the terms of the GNU
13 * General Public License (GPL) as published by the Free Software
14 * Foundation, in version 2 as it comes in the "COPYING" file of the
15 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
16 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
17 */
18
19
20/*******************************************************************************
21* Header Files *
22*******************************************************************************/
23#include <iprt/assert.h>
24#include <iprt/crc32.h>
25#include <iprt/ctype.h>
26#include <iprt/env.h>
27#include <iprt/file.h>
28#include <iprt/getopt.h>
29#include <iprt/handle.h>
30#include <iprt/mem.h>
31#include <iprt/path.h>
32#include <iprt/param.h>
33#include <iprt/pipe.h>
34#include <iprt/poll.h>
35#include <iprt/process.h>
36#include <iprt/string.h>
37#include <iprt/semaphore.h>
38#include <iprt/stream.h>
39#include <iprt/thread.h>
40#include <VBox/version.h>
41#include <VBox/VBoxGuestLib.h>
42#include <VBox/HostServices/GuestControlSvc.h>
43#include "VBoxServiceInternal.h"
44#include "VBoxServiceUtils.h"
45
46using namespace guestControl;
47
48extern RTLISTNODE g_GuestControlExecThreads;
49
50/**
51 * Handle an error event on standard input.
52 *
53 * @param hPollSet The polling set.
54 * @param fPollEvt The event mask returned by RTPollNoResume.
55 * @param phStdInW The standard input pipe handle.
56 * @param pStdInBuf The standard input buffer.
57 */
58static void VBoxServiceControlExecProcHandleStdInErrorEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
59 PVBOXSERVICECTRLSTDINBUF pStdInBuf)
60{
61 int rc2;
62 if (pStdInBuf->off < pStdInBuf->cb)
63 {
64 rc2 = RTPollSetRemove(hPollSet, 4 /*TXSEXECHNDID_STDIN_WRITABLE*/);
65 AssertRC(rc2);
66 }
67
68 rc2 = RTPollSetRemove(hPollSet, 0 /*TXSEXECHNDID_STDIN*/);
69 AssertRC(rc2);
70
71 rc2 = RTPipeClose(*phStdInW);
72 AssertRC(rc2);
73 *phStdInW = NIL_RTPIPE;
74
75 RTMemFree(pStdInBuf->pch);
76 pStdInBuf->pch = NULL;
77 pStdInBuf->off = 0;
78 pStdInBuf->cb = 0;
79 pStdInBuf->cbAllocated = 0;
80 pStdInBuf->fBitBucket = true;
81}
82
83
84/**
85 * Try write some more data to the standard input of the child.
86 *
87 * @returns IPRT status code.
88 * @param pStdInBuf The standard input buffer.
89 * @param hStdInW The standard input pipe.
90 */
91static int VBoxServiceControlExecProcWriteStdIn(PVBOXSERVICECTRLSTDINBUF pStdInBuf, RTPIPE hStdInW)
92{
93 size_t cbToWrite = pStdInBuf->cb - pStdInBuf->off;
94 size_t cbWritten;
95 int rc = RTPipeWrite(hStdInW, &pStdInBuf->pch[pStdInBuf->off], cbToWrite, &cbWritten);
96 if (RT_SUCCESS(rc))
97 {
98 Assert(cbWritten == cbToWrite);
99 pStdInBuf->off += cbWritten;
100 }
101 return rc;
102}
103
104
105/**
106 * Handle an event indicating we can write to the standard input pipe of the
107 * child process.
108 *
109 * @param hPollSet The polling set.
110 * @param fPollEvt The event mask returned by RTPollNoResume.
111 * @param phStdInW The standard input pipe.
112 * @param pStdInBuf The standard input buffer.
113 */
114static void VBoxServiceControlExecProcHandleStdInWritableEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
115 PVBOXSERVICECTRLSTDINBUF pStdInBuf)
116{
117 int rc;
118 if (!(fPollEvt & RTPOLL_EVT_ERROR))
119 {
120 rc = VBoxServiceControlExecProcWriteStdIn(pStdInBuf, *phStdInW);
121 if (RT_FAILURE(rc) && rc != VERR_BAD_PIPE)
122 {
123 /** @todo do we need to do something about this error condition? */
124 AssertRC(rc);
125 }
126
127 if (pStdInBuf->off < pStdInBuf->cb)
128 {
129 rc = RTPollSetRemove(hPollSet, 4 /*TXSEXECHNDID_STDIN_WRITABLE*/);
130 AssertRC(rc);
131 }
132 }
133 else
134 VBoxServiceControlExecProcHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
135}
136
137
138/**
139 * Handle pending output data or error on standard out, standard error or the
140 * test pipe.
141 *
142 * @returns IPRT status code from client send.
143 * @param pThread The thread specific data.
144 * @param hPollSet The polling set.
145 * @param fPollEvt The event mask returned by RTPollNoResume.
146 * @param phPipeR The pipe handle.
147 * @param pu32Crc The current CRC-32 of the stream. (In/Out)
148 * @param uHandleId The handle ID.
149 * @param pszOpcode The opcode for the data upload.
150 *
151 * @todo Put the last 4 parameters into a struct!
152 */
153static int VBoxServiceControlExecProcHandleOutputEvent(PVBOXSERVICECTRLTHREAD pThread,
154 RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phPipeR,
155 uint32_t *puCrc32 , uint32_t uHandleId)
156{
157 Log(("VBoxServiceControlExecProcHandleOutputEvent: fPollEvt=%#x\n", fPollEvt));
158
159 /*
160 * Try drain the pipe before acting on any errors.
161 */
162 int rc = VINF_SUCCESS;
163 size_t cbRead;
164 uint8_t abBuf[_64K];
165
166 AssertPtr(pThread);
167 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
168 AssertPtr(pData);
169
170 int rc2 = RTPipeRead(*phPipeR, abBuf, sizeof(abBuf), &cbRead);
171 if (RT_SUCCESS(rc2) && cbRead)
172 {
173#if 0
174 /* Only used for "real-time" stdout/stderr data; gets sent immediately (later)! */
175 rc = VbglR3GuestCtrlExecSendOut(pThread->uClientID, pThread->uContextID,
176 pData->uPID, uHandleId, 0 /* u32Flags */,
177 abBuf, cbRead);
178#endif
179 rc = VBoxServiceControlExecWritePipeBuffer(&pData->stdOut, abBuf, cbRead);
180 if (RT_SUCCESS(rc))
181 {
182 /* Make sure we go another poll round in case there was too much data
183 for the buffer to hold. */
184 fPollEvt &= RTPOLL_EVT_ERROR;
185 }
186 }
187 else if (RT_FAILURE(rc2))
188 {
189 fPollEvt |= RTPOLL_EVT_ERROR;
190 AssertMsg(rc2 == VERR_BROKEN_PIPE, ("%Rrc\n", rc));
191 }
192
193 /*
194 * If an error was raised signalled,
195 */
196 if (fPollEvt & RTPOLL_EVT_ERROR)
197 {
198 rc2 = RTPollSetRemove(hPollSet, uHandleId);
199 AssertRC(rc2);
200
201 rc2 = RTPipeClose(*phPipeR);
202 AssertRC(rc2);
203 *phPipeR = NIL_RTPIPE;
204 }
205 return rc;
206}
207
208
209/**
210 * Handle a transport event or successful pfnPollIn() call.
211 *
212 * @returns IPRT status code from client send.
213 * @retval VINF_EOF indicates ABORT command.
214 *
215 * @param hPollSet The polling set.
216 * @param fPollEvt The event mask returned by RTPollNoResume.
217 * @param idPollHnd The handle ID.
218 * @param hStdInW The standard input pipe.
219 * @param pStdInBuf The standard input buffer.
220 */
221static int VBoxServiceControlExecProcHandleTransportEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, uint32_t idPollHnd,
222 PRTPIPE phStdInW, PVBOXSERVICECTRLSTDINBUF pStdInBuf)
223{
224
225 int rc = RTPollSetAddPipe(hPollSet, *phStdInW, RTPOLL_EVT_WRITE, 4 /*TXSEXECHNDID_STDIN_WRITABLE*/);
226
227 return rc;
228}
229
230
231static int VBoxServiceControlExecProcLoop(PVBOXSERVICECTRLTHREAD pThread,
232 RTPROCESS hProcess, RTMSINTERVAL cMillies, RTPOLLSET hPollSet,
233 RTPIPE hStdInW, RTPIPE hStdOutR, RTPIPE hStdErrR)
234{
235 int rc;
236 int rc2;
237 VBOXSERVICECTRLSTDINBUF StdInBuf = { 0, 0, NULL, 0, hStdInW == NIL_RTPIPE, RTCrc32Start() };
238 uint32_t uStdOutCrc32 = RTCrc32Start();
239 uint32_t uStdErrCrc32 = uStdOutCrc32;
240 uint64_t const MsStart = RTTimeMilliTS();
241 RTPROCSTATUS ProcessStatus = { 254, RTPROCEXITREASON_ABEND };
242 bool fProcessAlive = true;
243 bool fProcessTimedOut = false;
244 uint64_t MsProcessKilled = UINT64_MAX;
245 bool const fHavePipes = hStdInW != NIL_RTPIPE
246 || hStdOutR != NIL_RTPIPE
247 || hStdErrR != NIL_RTPIPE;
248 RTMSINTERVAL const cMsPollBase = hStdInW != NIL_RTPIPE
249 ? 100 /* need to poll for input */
250 : 1000; /* need only poll for process exit and aborts */
251 RTMSINTERVAL cMsPollCur = 0;
252
253 AssertPtr(pThread);
254
255 AssertPtr(pThread);
256 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
257 AssertPtr(pData);
258
259 /* Assign PID to thread data. */
260 pData->uPID = hProcess;
261
262 /*
263 * Before entering the loop, tell the host that we've started the guest
264 * and that it's now OK to send input to the process.
265 */
266 VBoxServiceVerbose(3, "Control: Process started: PID=%u, CID=%u\n",
267 pData->uPID, pThread->uContextID);
268 rc = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID,
269 pData->uPID, PROC_STS_STARTED, 0 /* u32Flags */,
270 NULL /* pvData */, 0 /* cbData */);
271
272 /*
273 * Process input, output, the test pipe and client requests.
274 */
275 while ( RT_SUCCESS(rc)
276 && RT_UNLIKELY(!pThread->fShutdown))
277 {
278 /*
279 * Wait/Process all pending events.
280 */
281 uint32_t idPollHnd;
282 uint32_t fPollEvt;
283 rc2 = RTPollNoResume(hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
284 if (pThread->fShutdown)
285 continue;
286
287 cMsPollCur = 0; /* no rest until we've checked everything. */
288
289 if (RT_SUCCESS(rc2))
290 {
291 switch (idPollHnd)
292 {
293 case 0 /* TXSEXECHNDID_STDIN */:
294 VBoxServiceControlExecProcHandleStdInErrorEvent(hPollSet, fPollEvt, &hStdInW, &StdInBuf);
295 break;
296
297 case 1 /* TXSEXECHNDID_STDOUT */:
298 rc = VBoxServiceControlExecProcHandleOutputEvent(pThread, hPollSet, fPollEvt, &hStdOutR, &uStdOutCrc32, 1 /* TXSEXECHNDID_STDOUT */);
299 break;
300
301 case 2 /*TXSEXECHNDID_STDERR */:
302 rc = VBoxServiceControlExecProcHandleOutputEvent(pThread, hPollSet, fPollEvt, &hStdErrR, &uStdErrCrc32, 2 /*TXSEXECHNDID_STDERR */);
303 break;
304
305 case 4 /* TXSEXECHNDID_STDIN_WRITABLE */:
306 VBoxServiceControlExecProcHandleStdInWritableEvent(hPollSet, fPollEvt, &hStdInW, &StdInBuf);
307 break;
308
309 default:
310 rc = VBoxServiceControlExecProcHandleTransportEvent(hPollSet, fPollEvt, idPollHnd, &hStdInW, &StdInBuf);
311 break;
312 }
313 if (RT_FAILURE(rc) || rc == VINF_EOF)
314 break; /* abort command, or client dead or something */
315 continue;
316 }
317
318 /*
319 * Check for incoming data.
320 */
321
322 /*
323 * Check for process death.
324 */
325 if (fProcessAlive)
326 {
327 rc2 = RTProcWaitNoResume(hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
328 if (RT_SUCCESS_NP(rc2))
329 {
330 fProcessAlive = false;
331 continue;
332 }
333 if (RT_UNLIKELY(rc2 == VERR_INTERRUPTED))
334 continue;
335 if (RT_UNLIKELY(rc2 == VERR_PROCESS_NOT_FOUND))
336 {
337 fProcessAlive = false;
338 ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
339 ProcessStatus.iStatus = 255;
340 AssertFailed();
341 }
342 else
343 AssertMsg(rc2 == VERR_PROCESS_RUNNING, ("%Rrc\n", rc2));
344 }
345
346 /*
347 * If the process has terminated, we're should head out.
348 */
349 if (!fProcessAlive)
350 break;
351
352 /*
353 * Check for timed out, killing the process.
354 */
355 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
356 if (cMillies != RT_INDEFINITE_WAIT)
357 {
358 uint64_t u64Now = RTTimeMilliTS();
359 uint64_t cMsElapsed = u64Now - MsStart;
360 if (cMsElapsed >= cMillies)
361 {
362 VBoxServiceVerbose(3, "Control: Process timed out (%ums elapsed > %ums timeout), killing ...", cMsElapsed, cMillies);
363
364 fProcessTimedOut = true;
365 if ( MsProcessKilled == UINT64_MAX
366 || u64Now - MsProcessKilled > 1000)
367 {
368 if (u64Now - MsProcessKilled > 20*60*1000)
369 break; /* give up after 20 mins */
370 RTProcTerminate(hProcess);
371 MsProcessKilled = u64Now;
372 continue;
373 }
374 cMilliesLeft = 10000;
375 }
376 else
377 cMilliesLeft = cMillies - (uint32_t)cMsElapsed;
378 }
379
380 /* Reset the polling interval since we've done all pending work. */
381 cMsPollCur = cMilliesLeft >= cMsPollBase ? cMsPollBase : cMilliesLeft;
382
383 /*
384 * Need to exit?
385 */
386 if (pThread->fShutdown)
387 break;
388 }
389
390 /*
391 * Try kill the process if it's still alive at this point.
392 */
393 if (fProcessAlive)
394 {
395 if (MsProcessKilled == UINT64_MAX)
396 {
397 MsProcessKilled = RTTimeMilliTS();
398 RTProcTerminate(hProcess);
399 RTThreadSleep(500);
400 }
401
402 for (size_t i = 0; i < 10; i++)
403 {
404 rc2 = RTProcWait(hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
405 if (RT_SUCCESS(rc2))
406 {
407 fProcessAlive = false;
408 break;
409 }
410 if (i >= 5)
411 RTProcTerminate(hProcess);
412 RTThreadSleep(i >= 5 ? 2000 : 500);
413 }
414 }
415
416 /*
417 * If we don't have a client problem (RT_FAILURE(rc) we'll reply to the
418 * clients exec packet now.
419 */
420 if (RT_SUCCESS(rc))
421 {
422 uint32_t uStatus = PROC_STS_UNDEFINED;
423 uint32_t uFlags = 0;
424
425 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
426 {
427 uStatus = PROC_STS_TOK;
428 }
429 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
430 {
431 uStatus = PROC_STS_TOA;
432 }
433 else if (pThread->fShutdown && (fProcessAlive || MsProcessKilled != UINT64_MAX))
434 {
435 uStatus = PROC_STS_DWN; /* Service is stopping, process was killed. */
436 }
437 else if (fProcessAlive)
438 {
439 VBoxServiceError("Control: Process is alive when it should not!\n");
440 }
441 else if (MsProcessKilled != UINT64_MAX)
442 {
443 VBoxServiceError("Control: Process has been killed when it should not!\n");
444 }
445 else if (ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
446 {
447 uStatus = PROC_STS_TEN;
448 uFlags = ProcessStatus.iStatus;
449 }
450 else if (ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
451 {
452 uStatus = PROC_STS_TES;
453 uFlags = ProcessStatus.iStatus;
454 }
455 else if (ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
456 {
457 uStatus = PROC_STS_TEA;
458 uFlags = ProcessStatus.iStatus;
459 }
460 else
461 {
462 VBoxServiceError("Control: Process has reached an undefined status!\n");
463 }
464
465 VBoxServiceVerbose(3, "Control: Process ended: PID=%u, CID=%u, Status=%u, Flags=%u\n",
466 pData->uPID, pThread->uContextID, uStatus, uFlags);
467 rc = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID,
468 pData->uPID, uStatus, uFlags,
469 NULL /* pvData */, 0 /* cbData */);
470 }
471 RTMemFree(StdInBuf.pch);
472 VBoxServiceVerbose(3, "Control: Process loop ended with rc=%Rrc\n", rc);
473 return rc;
474}
475
476
477/**
478 * Sets up the redirection / pipe / nothing for one of the standard handles.
479 *
480 * @returns IPRT status code. No client replies made.
481 * @param pszHowTo How to set up this standard handle.
482 * @param fd Which standard handle it is (0 == stdin, 1 ==
483 * stdout, 2 == stderr).
484 * @param ph The generic handle that @a pph may be set
485 * pointing to. Always set.
486 * @param pph Pointer to the RTProcCreateExec argument.
487 * Always set.
488 * @param phPipe Where to return the end of the pipe that we
489 * should service. Always set.
490 */
491static int VBoxServiceControlExecSetupPipe(int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
492{
493 AssertPtr(ph);
494 AssertPtr(pph);
495 AssertPtr(phPipe);
496
497 ph->enmType = RTHANDLETYPE_PIPE;
498 ph->u.hPipe = NIL_RTPIPE;
499 *pph = NULL;
500 *phPipe = NIL_RTPIPE;
501
502 int rc;
503
504 /*
505 * Setup a pipe for forwarding to/from the client.
506 * The ph union struct will be filled with a pipe read/write handle
507 * to represent the "other" end to phPipe.
508 */
509 if (fd == 0) /* stdin? */
510 {
511 /* Connect a wrtie pipe specified by phPipe to stdin. */
512 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
513 }
514 else /* stdout or stderr? */
515 {
516 /* Connect a read pipe specified by phPipe to stdout or stderr. */
517 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
518 }
519 if (RT_FAILURE(rc))
520 return rc;
521 ph->enmType = RTHANDLETYPE_PIPE;
522 *pph = ph;
523
524 return rc;
525}
526
527int VBoxServiceControlExecReadPipeBufferContent(PVBOXSERVICECTRLEXECPIPEBUF pBuf,
528 uint8_t *pbBuffer, uint32_t cbBuffer, uint32_t *pcbToRead)
529{
530 AssertPtr(pcbToRead);
531
532// LOCKING
533
534 Assert(pBuf->cbOffset >= pBuf->cbRead);
535 if (*pcbToRead > pBuf->cbOffset - pBuf->cbRead)
536 *pcbToRead = pBuf->cbOffset - pBuf->cbRead;
537
538 if (*pcbToRead > cbBuffer)
539 *pcbToRead = cbBuffer;
540
541 if (*pcbToRead > 0)
542 {
543 memcpy(pbBuffer, pBuf->pbData + pBuf->cbRead, *pcbToRead);
544 pBuf->cbRead += *pcbToRead;
545 }
546 else
547 pbBuffer = NULL;
548 return VINF_SUCCESS;
549}
550
551int VBoxServiceControlExecWritePipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf,
552 uint8_t *pbData, uint32_t cbData)
553{
554 AssertPtr(pBuf);
555
556// LOCKING
557
558 /** @todo Use RTMemCache or RTMemObj here? */
559 uint8_t *pNewBuf;
560 while (pBuf->cbSize - pBuf->cbOffset < cbData)
561 {
562 pNewBuf = (uint8_t*)RTMemRealloc(pBuf->pbData, pBuf->cbSize + _4K);
563 if (pNewBuf == NULL)
564 break;
565 pBuf->cbSize += _4K;
566 pBuf->pbData = pNewBuf;
567 }
568
569 int rc = VINF_SUCCESS;
570 if (pBuf->pbData)
571 {
572 memcpy(pBuf->pbData + pBuf->cbOffset, pbData, cbData);
573 pBuf->cbOffset += cbData;
574 /** @todo Add offset clamping! */
575 }
576 else
577 rc = VERR_NO_MEMORY;
578 return rc;
579}
580
581/** Allocates and gives back a thread data struct which then can be used by the worker thread. */
582int VBoxServiceControlExecAllocateThreadData(PVBOXSERVICECTRLTHREAD pThread,
583 uint32_t u32ContextID,
584 const char *pszCmd, uint32_t uFlags,
585 const char *pszArgs, uint32_t uNumArgs,
586 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
587 const char *pszStdIn, const char *pszStdOut, const char *pszStdErr,
588 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
589{
590 AssertPtr(pThread);
591
592 /* General stuff. */
593 pThread->Node.pPrev = NULL;
594 pThread->Node.pNext = NULL;
595
596 pThread->fShutdown = false;
597 pThread->fStarted = false;
598 pThread->fStopped = false;
599
600 pThread->uContextID = u32ContextID;
601 /* ClientID will be assigned when thread is started! */
602
603 /* Specific stuff. */
604 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREADDATAEXEC));
605 if (pData == NULL)
606 return VERR_NO_MEMORY;
607
608 pData->uPID = 0; /* Don't have a PID yet. */
609 pData->pszCmd = RTStrDup(pszCmd);
610 pData->uFlags = uFlags;
611 pData->uNumEnvVars = 0;
612 pData->uNumArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
613
614 /* Prepare argument list. */
615 int rc = RTGetOptArgvFromString(&pData->papszArgs, (int*)&pData->uNumArgs,
616 (uNumArgs > 0) ? pszArgs : "", NULL);
617 /* Did we get the same result? */
618 Assert(uNumArgs == pData->uNumArgs);
619
620 if (RT_SUCCESS(rc))
621 {
622 /* Prepare environment list. */
623 if (uNumEnvVars)
624 {
625 pData->papszEnv = (char**)RTMemAlloc(uNumEnvVars * sizeof(char*));
626 AssertPtr(pData->papszEnv);
627 pData->uNumEnvVars = uNumEnvVars;
628
629 const char *pcCur = pszEnv;
630 uint32_t i = 0;
631 uint32_t cbLen = 0;
632 while (cbLen < cbEnv)
633 {
634 if (RTStrAPrintf(&pData->papszEnv[i++], "%s", pcCur) < 0)
635 {
636 rc = VERR_NO_MEMORY;
637 break;
638 }
639 cbLen += strlen(pcCur) + 1; /* Skip terminating zero. */
640 pcCur += cbLen;
641 }
642 }
643
644 pData->pszStdIn = RTStrDup(pszStdIn);
645 pData->pszStdOut = RTStrDup(pszStdOut);
646 pData->pszStdErr = RTStrDup(pszStdErr);
647 pData->pszUser = RTStrDup(pszUser);
648 pData->pszPassword = RTStrDup(pszPassword);
649 pData->uTimeLimitMS = uTimeLimitMS;
650
651 /* Adjust time limit value. */
652 pData->uTimeLimitMS = ( (uTimeLimitMS == UINT32_MAX)
653 || (uTimeLimitMS == 0)) ?
654 RT_INDEFINITE_WAIT : uTimeLimitMS;
655
656 /* Init buffers. */
657 pData->stdOut.pbData = NULL;
658 pData->stdOut.cbSize = 0;
659 pData->stdOut.cbOffset = 0;
660 pData->stdOut.cbRead = 0;
661
662 pData->stdErr.pbData = NULL;
663 pData->stdErr.cbSize = 0;
664 pData->stdErr.cbOffset = 0;
665 pData->stdErr.cbRead = 0;
666 }
667
668 if (RT_FAILURE(rc))
669 {
670 VBoxServiceControlExecDestroyThreadData(pData);
671 }
672 else
673 {
674 pThread->enmType = VBoxServiceCtrlThreadDataExec;
675 pThread->pvData = pData;
676 }
677 return rc;
678}
679
680void VBoxServiceControlExecDestroyPipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf)
681{
682 if (pBuf)
683 {
684 if (pBuf->pbData)
685 RTMemFree(pBuf->pbData);
686 pBuf->pbData = NULL;
687 pBuf->cbSize = 0;
688 pBuf->cbOffset = 0;
689 pBuf->cbRead = 0;
690 }
691}
692
693/** Frees an allocated thread data structure along with all its allocated parameters. */
694void VBoxServiceControlExecDestroyThreadData(PVBOXSERVICECTRLTHREADDATAEXEC pData)
695{
696 if (pData)
697 {
698 RTStrFree(pData->pszCmd);
699 if (pData->uNumEnvVars)
700 {
701 for (uint32_t i = 0; i < pData->uNumEnvVars; i++)
702 RTStrFree(pData->papszEnv[i]);
703 RTMemFree(pData->papszEnv);
704 }
705 RTGetOptArgvFree(pData->papszArgs);
706 RTStrFree(pData->pszStdIn);
707 RTStrFree(pData->pszStdOut);
708 RTStrFree(pData->pszStdErr);
709 RTStrFree(pData->pszUser);
710 RTStrFree(pData->pszPassword);
711
712 VBoxServiceControlExecDestroyPipeBuffer(&pData->stdOut);
713 VBoxServiceControlExecDestroyPipeBuffer(&pData->stdErr);
714
715 RTMemFree(pData);
716 pData = NULL;
717 }
718}
719
720DECLCALLBACK(int) VBoxServiceControlExecProcessWorker(PVBOXSERVICECTRLTHREAD pThread)
721{
722 AssertPtr(pThread);
723 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
724 AssertPtr(pData);
725
726 /*
727 * Tell the control thread that it can continue
728 * spawning services.
729 */
730 RTThreadUserSignal(RTThreadSelf());
731 VBoxServiceVerbose(3, "Control: Thread of process \"%s\" started\n", pData->pszCmd);
732
733 int rc = VbglR3GuestCtrlConnect(&pThread->uClientID);
734 if (RT_FAILURE(rc))
735 {
736 VBoxServiceError("Control: Thread failed to connect to the guest control service, aborted! Error: %Rrc\n", rc);
737 return rc;
738 }
739
740 /*
741 * Create the environment.
742 */
743 RTENV hEnv;
744 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
745 if (RT_SUCCESS(rc))
746 {
747 size_t i;
748 for (i = 0; i < pData->uNumEnvVars && pData->papszEnv; i++)
749 {
750 rc = RTEnvPutEx(hEnv, pData->papszEnv[i]);
751 if (RT_FAILURE(rc))
752 break;
753 }
754 if (RT_SUCCESS(rc))
755 {
756 /*
757 * Setup the redirection of the standard stuff.
758 */
759 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
760 RTHANDLE hStdIn;
761 PRTHANDLE phStdIn;
762 RTPIPE hStdInW;
763 rc = VBoxServiceControlExecSetupPipe(0 /* stdin */, &hStdIn, &phStdIn, &hStdInW);
764 if (RT_SUCCESS(rc))
765 {
766 RTHANDLE hStdOut;
767 PRTHANDLE phStdOut;
768 RTPIPE hStdOutR;
769 rc = VBoxServiceControlExecSetupPipe(1 /* stdout */, &hStdOut, &phStdOut, &hStdOutR);
770 if (RT_SUCCESS(rc))
771 {
772 RTHANDLE hStdErr;
773 PRTHANDLE phStdErr;
774 RTPIPE hStdErrR;
775 rc = VBoxServiceControlExecSetupPipe(2 /* stderr */, &hStdErr, &phStdErr, &hStdErrR);
776 if (RT_SUCCESS(rc))
777 {
778 /*
779 * Create a poll set for the pipes and let the
780 * transport layer add stuff to it as well.
781 */
782 RTPOLLSET hPollSet;
783 rc = RTPollSetCreate(&hPollSet);
784 if (RT_SUCCESS(rc))
785 {
786 rc = RTPollSetAddPipe(hPollSet, hStdInW, RTPOLL_EVT_ERROR, 0 /* TXSEXECHNDID_STDIN */);
787 if (RT_SUCCESS(rc))
788 rc = RTPollSetAddPipe(hPollSet, hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 1 /* TXSEXECHNDID_STDOUT */);
789 if (RT_SUCCESS(rc))
790 rc = RTPollSetAddPipe(hPollSet, hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 2 /* TXSEXECHNDID_TESTPIPE */);
791 if (RT_SUCCESS(rc))
792 {
793 RTPROCESS hProcess;
794 rc = RTProcCreateEx(pData->pszCmd, pData->papszArgs, hEnv, pData->uFlags,
795 phStdIn, phStdOut, phStdErr,
796 strlen(pData->pszUser) ? pData->pszUser : NULL,
797 strlen(pData->pszUser) && strlen(pData->pszPassword) ? pData->pszPassword : NULL,
798 &hProcess);
799 if (RT_SUCCESS(rc))
800 {
801 /*
802 * Close the child ends of any pipes and redirected files.
803 */
804 int rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
805 phStdIn = NULL;
806 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
807 phStdOut = NULL;
808 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
809 phStdErr = NULL;
810
811 /* Enter the process loop. */
812 rc = VBoxServiceControlExecProcLoop(pThread,
813 hProcess, pData->uTimeLimitMS, hPollSet,
814 hStdInW, hStdOutR, hStdErrR);
815
816 /*
817 * The handles that are no longer in the set have
818 * been closed by the above call in order to prevent
819 * the guest from getting stuck accessing them.
820 * So, NIL the handles to avoid closing them again.
821 */
822 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 0 /* stdin */, NULL)))
823 hStdInW = NIL_RTPIPE;
824 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 1 /* stdout */, NULL)))
825 hStdOutR = NIL_RTPIPE;
826 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 2 /* stderr */, NULL)))
827 hStdErrR = NIL_RTPIPE;
828 }
829 else /* Something went wrong; report error! */
830 {
831 int rc2 = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID, pData->uPID,
832 PROC_STS_ERROR, rc,
833 NULL /* pvData */, 0 /* cbData */);
834 if (RT_FAILURE(rc2))
835 VBoxServiceError("Control: Could not report process start error! Error: %Rrc (process error %Rrc)\n",
836 rc2, rc);
837 }
838 }
839 }
840 RTPipeClose(hStdErrR);
841 RTHandleClose(phStdErr);
842 }
843 RTPipeClose(hStdOutR);
844 RTHandleClose(phStdOut);
845 }
846 RTPipeClose(hStdInW);
847 RTHandleClose(phStdIn);
848 }
849 }
850 RTEnvDestroy(hEnv);
851 }
852
853 VbglR3GuestCtrlDisconnect(pThread->uClientID);
854 VBoxServiceVerbose(3, "Control: Thread of process \"%s\" (PID: %u) ended with rc=%Rrc\n",
855 pData->pszCmd, pData->uPID, rc);
856 return rc;
857}
858
859static DECLCALLBACK(int) VBoxServiceControlExecThread(RTTHREAD ThreadSelf, void *pvUser)
860{
861 PVBOXSERVICECTRLTHREAD pThread = (VBOXSERVICECTRLTHREAD*)pvUser;
862 AssertPtr(pThread);
863 return VBoxServiceControlExecProcessWorker(pThread);
864}
865
866int VBoxServiceControlExecProcess(uint32_t uContextID, const char *pszCmd, uint32_t uFlags,
867 const char *pszArgs, uint32_t uNumArgs,
868 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
869 const char *pszStdIn, const char *pszStdOut, const char *pszStdErr,
870 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
871{
872 PVBOXSERVICECTRLTHREAD pThread = (PVBOXSERVICECTRLTHREAD)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREAD));
873
874 int rc;
875 if (pThread)
876 {
877 rc = VBoxServiceControlExecAllocateThreadData(pThread,
878 uContextID,
879 pszCmd, uFlags,
880 pszArgs, uNumArgs,
881 pszEnv, cbEnv, uNumEnvVars,
882 pszStdIn, pszStdOut, pszStdErr,
883 pszUser, pszPassword,
884 uTimeLimitMS);
885 if (RT_SUCCESS(rc))
886 {
887 rc = RTThreadCreate(&pThread->Thread, VBoxServiceControlExecThread,
888 (void *)(PVBOXSERVICECTRLTHREAD*)pThread, 0,
889 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "Exec");
890 if (RT_FAILURE(rc))
891 {
892 VBoxServiceError("Control: RTThreadCreate failed, rc=%Rrc\n, pThread=%p\n",
893 rc, pThread);
894 }
895 else
896 {
897 /* Wait for the thread to initialize. */
898 RTThreadUserWait(pThread->Thread, 60 * 1000);
899 if (pThread->fShutdown)
900 {
901 VBoxServiceError("Control: Thread for process \"%s\" failed to start!\n", pszCmd);
902 rc = VERR_GENERAL_FAILURE;
903 }
904 else
905 {
906 pThread->fStarted = true;
907 /*rc =*/ RTListAppend(&g_GuestControlExecThreads, &pThread->Node);
908 }
909 }
910
911 if (RT_FAILURE(rc))
912 VBoxServiceControlExecDestroyThreadData((PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData);
913 }
914 if (RT_FAILURE(rc))
915 RTMemFree(pThread);
916 }
917 else
918 rc = VERR_NO_MEMORY;
919 return rc;
920}
921
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