VirtualBox

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

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

Additions: s/BYTE/uint8_t/g

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