VirtualBox

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

Last change on this file since 37447 was 37447, checked in by vboxsync, 14 years ago

GuestCtrl/Execute: Added NoProfile flag for executing processes without loading the user's profile.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.4 KB
Line 
1/* $Id: VBoxServiceControlExec.cpp 37447 2011-06-14 15:46:03Z vboxsync $ */
2/** @file
3 * VBoxServiceControlExec - Utility functions for process execution.
4 */
5
6/*
7 * Copyright (C) 2011 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
18
19/*******************************************************************************
20* Header Files *
21*******************************************************************************/
22#include <iprt/assert.h>
23#include <iprt/crc.h>
24#include <iprt/ctype.h>
25#include <iprt/env.h>
26#include <iprt/file.h>
27#include <iprt/getopt.h>
28#include <iprt/handle.h>
29#include <iprt/mem.h>
30#include <iprt/path.h>
31#include <iprt/param.h>
32#include <iprt/pipe.h>
33#include <iprt/poll.h>
34#include <iprt/process.h>
35#include <iprt/string.h>
36#include <iprt/stream.h>
37#include <iprt/thread.h>
38#include <VBox/version.h>
39#include <VBox/VBoxGuestLib.h>
40#include <VBox/HostServices/GuestControlSvc.h>
41
42#include "VBoxServiceInternal.h"
43#include "VBoxServiceUtils.h"
44#include "VBoxServicePipeBuf.h"
45#include "VBoxServiceControlExecThread.h"
46
47using namespace guestControl;
48
49extern RTLISTNODE g_GuestControlExecThreads;
50extern RTCRITSECT g_GuestControlExecThreadsCritSect;
51
52
53/**
54 * Handle an error event on standard input.
55 *
56 * @returns IPRT status code.
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 int VBoxServiceControlExecProcHandleStdInErrorEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
63 PVBOXSERVICECTRLEXECPIPEBUF pStdInBuf)
64{
65 int rc = RTPollSetRemove(hPollSet, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE);
66 /* Don't assert if writable handle is not in poll set anymore. */
67 if ( RT_FAILURE(rc)
68 && rc != VERR_POLL_HANDLE_ID_NOT_FOUND)
69 {
70 AssertRC(rc);
71 }
72
73 /* Close writable stdin pipe. */
74 rc = RTPipeClose(*phStdInW);
75 AssertRC(rc);
76 *phStdInW = NIL_RTPIPE;
77
78 /* Mark the stdin buffer as dead; we're not using it anymore. */
79 rc = VBoxServicePipeBufSetStatus(pStdInBuf, false /* Disabled */);
80 AssertRC(rc);
81
82 /* Remove stdin error handle from set. */
83 rc = RTPollSetRemove(hPollSet, VBOXSERVICECTRLPIPEID_STDIN_ERROR);
84 /* Don't assert if writable handle is not in poll set anymore. */
85 if ( RT_FAILURE(rc)
86 && rc != VERR_POLL_HANDLE_ID_NOT_FOUND)
87 {
88 AssertRC(rc);
89 }
90 else
91 rc = VINF_SUCCESS;
92
93 return rc;
94}
95
96
97/**
98 * Try write some more data to the standard input of the child.
99 *
100 * @returns IPRT status code.
101 * @retval VINF_TRY_AGAIN if there is still data left in the buffer.
102 *
103 * @param hPollSet The polling set.
104 * @param pStdInBuf The standard input buffer.
105 * @param hStdInW The standard input pipe.
106 * @param pfClose Pointer to a flag whether the pipe needs to be closed afterwards.
107 */
108static int VBoxServiceControlExecProcWriteStdIn(RTPOLLSET hPollSet, PVBOXSERVICECTRLEXECPIPEBUF pStdInBuf, RTPIPE hStdInW,
109 size_t *pcbWritten, bool *pfClose)
110{
111 AssertPtrReturn(pStdInBuf, VERR_INVALID_PARAMETER);
112 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
113 AssertPtrReturn(pfClose, VERR_INVALID_PARAMETER);
114
115 size_t cbLeft;
116 int rc = VBoxServicePipeBufWriteToPipe(pStdInBuf, hStdInW, pcbWritten, &cbLeft);
117
118 /* If we have written all data which is in the buffer set the close flag. */
119 *pfClose = (cbLeft == 0) && VBoxServicePipeBufIsClosing(pStdInBuf);
120
121 if ( !*pcbWritten
122 && VBoxServicePipeBufIsEnabled(pStdInBuf))
123 {
124 /*
125 * Nothing else left to write now? Remove the writable event from the poll set
126 * to not trigger too high CPU loads.
127 */
128 int rc2 = RTPollSetRemove(hPollSet, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE);
129 AssertRC(rc2);
130 }
131
132 VBoxServiceVerbose(3, "VBoxServiceControlExecProcWriteStdIn: Written=%u, Left=%u, rc=%Rrc\n",
133 *pcbWritten, cbLeft, rc);
134 return rc;
135}
136
137
138/**
139 * Handle an event indicating we can write to the standard input pipe of the
140 * child process.
141 *
142 * @returns IPRT status code.
143 * @param hPollSet The polling set.
144 * @param fPollEvt The event mask returned by RTPollNoResume.
145 * @param phStdInW The standard input pipe.
146 * @param pStdInBuf The standard input buffer.
147 * @param pcbWritten Where to return the number of bytes written.
148 */
149static int VBoxServiceControlExecProcHandleStdInWritableEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phStdInW,
150 PVBOXSERVICECTRLEXECPIPEBUF pStdInBuf, size_t *pcbWritten)
151{
152 AssertPtrReturn(pcbWritten, VERR_INVALID_PARAMETER);
153 int rc;
154 if (!(fPollEvt & RTPOLL_EVT_ERROR))
155 {
156 bool fClose;
157 rc = VBoxServiceControlExecProcWriteStdIn(hPollSet,
158 pStdInBuf, *phStdInW,
159 pcbWritten, &fClose);
160 if ( rc == VINF_TRY_AGAIN
161 || rc == VERR_MORE_DATA)
162 rc = VINF_SUCCESS;
163 if (RT_FAILURE(rc))
164 {
165 if ( rc == VERR_BAD_PIPE
166 || rc == VERR_BROKEN_PIPE)
167 {
168 rc = RTPollSetRemove(hPollSet, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE);
169 AssertRC(rc);
170 }
171 else
172 {
173 /** @todo Do we need to do something about this error condition? */
174 AssertRC(rc);
175 }
176 }
177 else if (fClose)
178 {
179 /* If the pipe needs to be closed, do so. */
180 rc = VBoxServiceControlExecProcHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
181 }
182 }
183 else
184 {
185 *pcbWritten = 0;
186 rc = VBoxServiceControlExecProcHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, pStdInBuf);
187 }
188 return rc;
189}
190
191
192/**
193 * Handle pending output data/error on standard out or standard error.
194 *
195 * @return IPRT status code.
196 * @param hPollSet The polling set.
197 * @param fPollEvt The event mask returned by RTPollNoResume.
198 * @param phPipeR The pipe to be read from.
199 * @param uHandleId Handle ID of the pipe to be read from.
200 * @param pBuf Pointer to pipe buffer to store the read data into.
201 */
202static int VBoxServiceControlExecProcHandleOutputEvent(RTPOLLSET hPollSet, uint32_t fPollEvt, PRTPIPE phPipeR,
203 uint32_t uHandleId, PVBOXSERVICECTRLEXECPIPEBUF pBuf)
204{
205 AssertPtrReturn(phPipeR, VERR_INVALID_POINTER);
206 AssertPtrReturn(pBuf, VERR_INVALID_POINTER);
207
208#ifdef DEBUG
209 VBoxServiceVerbose(4, "ControlExec: HandleOutputEvent: fPollEvt=%#x, uHandle=%u\n",
210 fPollEvt, uHandleId);
211#endif
212
213 /*
214 * Try drain the pipe before acting on any errors.
215 */
216 int rc = VINF_SUCCESS;
217 size_t cbRead;
218 uint8_t abBuf[_64K];
219
220 int rc2 = RTPipeRead(*phPipeR, abBuf, sizeof(abBuf), &cbRead);
221 if (RT_SUCCESS(rc2) && cbRead)
222 {
223 uint32_t cbWritten;
224 rc = VBoxServicePipeBufWriteToBuf(pBuf, abBuf,
225 cbRead, false /* Pending close */, &cbWritten);
226 if (RT_SUCCESS(rc))
227 {
228 Assert(cbRead == cbWritten);
229 /* Make sure we go another poll round in case there was too much data
230 for the buffer to hold. */
231 fPollEvt &= RTPOLL_EVT_ERROR;
232 }
233 }
234 else if (RT_FAILURE(rc2))
235 {
236 fPollEvt |= RTPOLL_EVT_ERROR;
237 AssertMsg(rc2 == VERR_BROKEN_PIPE, ("%Rrc\n", rc));
238 }
239
240 /*
241 * If an error was signalled, close reading stdout/stderr pipe.
242 */
243 if (fPollEvt & RTPOLL_EVT_ERROR)
244 {
245 rc2 = RTPollSetRemove(hPollSet, uHandleId);
246 AssertRC(rc2);
247
248 rc2 = RTPipeClose(*phPipeR);
249 AssertRC(rc2);
250 *phPipeR = NIL_RTPIPE;
251 }
252 return rc;
253}
254
255
256int VBoxServiceControlExecProcHandleStdInputNotify(RTPOLLSET hPollSet,
257 PRTPIPE phNotificationPipeR, PRTPIPE phInputPipeW)
258{
259#ifdef DEBUG
260 VBoxServiceVerbose(4, "ControlExec: HandleStdInputNotify\n");
261#endif
262 /* Drain the notification pipe. */
263 uint8_t abBuf[8];
264 size_t cbIgnore;
265 int rc = RTPipeRead(*phNotificationPipeR, abBuf, sizeof(abBuf), &cbIgnore);
266 if (RT_SUCCESS(rc))
267 {
268 /*
269 * When the writable handle previously was removed from the poll set we need to add
270 * it here again so that writable events from the started procecss get handled correctly.
271 */
272 RTHANDLE hWritableIgnored;
273 rc = RTPollSetQueryHandle(hPollSet, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE, &hWritableIgnored);
274 if (rc == VERR_POLL_HANDLE_ID_NOT_FOUND)
275 rc = RTPollSetAddPipe(hPollSet, *phInputPipeW, RTPOLL_EVT_WRITE, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE);
276 }
277 return rc;
278}
279
280
281/**
282 * Execution loop which runs in a dedicated per-started-process thread and
283 * handles all pipe input/output and signalling stuff.
284 *
285 * @return IPRT status code.
286 * @param pThread The process' thread handle.
287 * @param hProcess The actual process handle.
288 * @param cMsTimeout Time limit (in ms) of the process' life time.
289 * @param hPollSet The poll set to use.
290 * @param hStdInW Handle to the process' stdin write end.
291 * @param hStdOutR Handle to the process' stdout read end.
292 * @param hStdErrR Handle to the process' stderr read end.
293 */
294static int VBoxServiceControlExecProcLoop(PVBOXSERVICECTRLTHREAD pThread,
295 RTPROCESS hProcess, RTMSINTERVAL cMsTimeout, RTPOLLSET hPollSet,
296 PRTPIPE phStdInW, PRTPIPE phStdOutR, PRTPIPE phStdErrR)
297{
298 AssertPtrReturn(phStdInW, VERR_INVALID_PARAMETER);
299 AssertPtrReturn(phStdOutR, VERR_INVALID_PARAMETER);
300 AssertPtrReturn(phStdErrR, VERR_INVALID_PARAMETER);
301
302 int rc;
303 int rc2;
304 uint64_t const MsStart = RTTimeMilliTS();
305 RTPROCSTATUS ProcessStatus = { 254, RTPROCEXITREASON_ABEND };
306 bool fProcessAlive = true;
307 bool fProcessTimedOut = false;
308 uint64_t MsProcessKilled = UINT64_MAX;
309 RTMSINTERVAL const cMsPollBase = *phStdInW != NIL_RTPIPE
310 ? 100 /* Need to poll for input. */
311 : 1000; /* Need only poll for process exit and aborts. */
312 RTMSINTERVAL cMsPollCur = 0;
313
314 AssertPtr(pThread);
315 Assert(pThread->enmType == kVBoxServiceCtrlThreadDataExec);
316 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
317 AssertPtr(pData);
318
319 /* Assign PID to thread data. */
320 pData->uPID = hProcess;
321
322 /*
323 * Before entering the loop, tell the host that we've started the guest
324 * and that it's now OK to send input to the process.
325 */
326 VBoxServiceVerbose(3, "ControlExec: Process started: PID=%u, CID=%u, User=%s\n",
327 pData->uPID, pThread->uContextID, pData->pszUser);
328 rc = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID,
329 pData->uPID, PROC_STS_STARTED, 0 /* u32Flags */,
330 NULL /* pvData */, 0 /* cbData */);
331
332 /*
333 * Process input, output, the test pipe and client requests.
334 */
335 while ( RT_SUCCESS(rc)
336 && RT_UNLIKELY(!pThread->fShutdown))
337 {
338 /*
339 * Wait/Process all pending events.
340 */
341 uint32_t idPollHnd;
342 uint32_t fPollEvt;
343 rc2 = RTPollNoResume(hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
344 if (pThread->fShutdown)
345 continue;
346
347 cMsPollCur = 0; /* No rest until we've checked everything. */
348
349 if (RT_SUCCESS(rc2))
350 {
351 VBoxServiceVerbose(4, "ControlExec: RTPollNoResume idPollHnd=%u\n", idPollHnd);
352 switch (idPollHnd)
353 {
354 case VBOXSERVICECTRLPIPEID_STDIN_ERROR:
355 rc = VBoxServiceControlExecProcHandleStdInErrorEvent(hPollSet, fPollEvt, phStdInW, &pData->stdIn);
356 break;
357
358 case VBOXSERVICECTRLPIPEID_STDIN_INPUT_NOTIFY:
359 rc = VBoxServiceControlExecProcHandleStdInputNotify(hPollSet,
360 &pData->stdIn.hNotificationPipeR, &pData->pipeStdInW);
361 AssertRC(rc);
362 /* Fall through. */
363 case VBOXSERVICECTRLPIPEID_STDIN_WRITABLE:
364 {
365 size_t cbWritten;
366 rc = VBoxServiceControlExecProcHandleStdInWritableEvent(hPollSet, fPollEvt, phStdInW,
367 &pData->stdIn, &cbWritten);
368 break;
369 }
370
371 case VBOXSERVICECTRLPIPEID_STDOUT:
372 rc = VBoxServiceControlExecProcHandleOutputEvent(hPollSet, fPollEvt, phStdOutR,
373 VBOXSERVICECTRLPIPEID_STDOUT, &pData->stdOut);
374 break;
375
376 case VBOXSERVICECTRLPIPEID_STDERR:
377 rc = VBoxServiceControlExecProcHandleOutputEvent(hPollSet, fPollEvt, phStdErrR,
378 VBOXSERVICECTRLPIPEID_STDERR, &pData->stdErr);
379 break;
380
381 default:
382 AssertMsgFailed(("idPollHnd=%u fPollEvt=%#x\n", idPollHnd, fPollEvt));
383 break;
384 }
385 if (RT_FAILURE(rc) || rc == VINF_EOF)
386 break; /* Abort command, or client dead or something. */
387 continue;
388 }
389
390 /*
391 * Check for process death.
392 */
393 if (fProcessAlive)
394 {
395 rc2 = RTProcWaitNoResume(hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
396 if (RT_SUCCESS_NP(rc2))
397 {
398 fProcessAlive = false;
399 continue;
400 }
401 if (RT_UNLIKELY(rc2 == VERR_INTERRUPTED))
402 continue;
403 if (RT_UNLIKELY(rc2 == VERR_PROCESS_NOT_FOUND))
404 {
405 fProcessAlive = false;
406 ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
407 ProcessStatus.iStatus = 255;
408 AssertFailed();
409 }
410 else
411 AssertMsg(rc2 == VERR_PROCESS_RUNNING, ("%Rrc\n", rc2));
412 }
413
414 /*
415 * If the process has terminated, we're should head out.
416 */
417 if (!fProcessAlive)
418 break;
419
420 /*
421 * Check for timed out, killing the process.
422 */
423 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
424 if (cMsTimeout != RT_INDEFINITE_WAIT)
425 {
426 uint64_t u64Now = RTTimeMilliTS();
427 uint64_t cMsElapsed = u64Now - MsStart;
428 if (cMsElapsed >= cMsTimeout)
429 {
430 VBoxServiceVerbose(3, "ControlExec: Process timed out (%ums elapsed > %ums timeout), killing ...", cMsElapsed, cMsTimeout);
431
432 fProcessTimedOut = true;
433 if ( MsProcessKilled == UINT64_MAX
434 || u64Now - MsProcessKilled > 1000)
435 {
436 if (u64Now - MsProcessKilled > 20*60*1000)
437 break; /* Give up after 20 mins. */
438 RTProcTerminate(hProcess);
439 MsProcessKilled = u64Now;
440 continue;
441 }
442 cMilliesLeft = 10000;
443 }
444 else
445 cMilliesLeft = cMsTimeout - (uint32_t)cMsElapsed;
446 }
447
448 /* Reset the polling interval since we've done all pending work. */
449 cMsPollCur = cMilliesLeft >= cMsPollBase ? cMsPollBase : cMilliesLeft;
450
451 /*
452 * Need to exit?
453 */
454 if (pThread->fShutdown)
455 break;
456 }
457
458 /*
459 * Try kill the process if it's still alive at this point.
460 */
461 if (fProcessAlive)
462 {
463 if (MsProcessKilled == UINT64_MAX)
464 {
465 VBoxServiceVerbose(3, "ControlExec: Process (PID=%u) is still alive and not killed yet\n",
466 pData->uPID);
467
468 MsProcessKilled = RTTimeMilliTS();
469 RTProcTerminate(hProcess);
470 RTThreadSleep(500);
471 }
472
473 for (size_t i = 0; i < 10; i++)
474 {
475 VBoxServiceVerbose(4, "ControlExec: Kill attempt %d/10: Waiting for process (PID=%u) exit ...\n",
476 i + 1, pData->uPID);
477 rc2 = RTProcWait(hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
478 if (RT_SUCCESS(rc2))
479 {
480 VBoxServiceVerbose(4, "ControlExec: Kill attempt %d/10: Process (PID=%u) exited\n",
481 i + 1, pData->uPID);
482 fProcessAlive = false;
483 break;
484 }
485 if (i >= 5)
486 {
487 VBoxServiceVerbose(4, "ControlExec: Kill attempt %d/10: Try to terminate (PID=%u) ...\n",
488 i + 1, pData->uPID);
489 RTProcTerminate(hProcess);
490 }
491 RTThreadSleep(i >= 5 ? 2000 : 500);
492 }
493
494 if (fProcessAlive)
495 VBoxServiceVerbose(3, "ControlExec: Process (PID=%u) could not be killed\n", pData->uPID);
496 }
497
498 /*
499 * If we don't have a client problem (RT_FAILURE(rc) we'll reply to the
500 * clients exec packet now.
501 */
502 if (RT_SUCCESS(rc))
503 {
504 VBoxServicePipeBufSetStatus(&pData->stdIn, false /* Disabled */);
505 VBoxServicePipeBufSetStatus(&pData->stdOut, false /* Disabled */);
506 VBoxServicePipeBufSetStatus(&pData->stdErr, false /* Disabled */);
507
508 /* Since the process is not alive anymore, destroy its local
509 * stdin pipe buffer - it's not used anymore and can eat up quite
510 * a bit of memory. */
511 VBoxServicePipeBufDestroy(&pData->stdIn);
512
513 uint32_t uStatus = PROC_STS_UNDEFINED;
514 uint32_t uFlags = 0;
515
516 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
517 {
518 VBoxServiceVerbose(3, "ControlExec: Process timed out and got killed\n");
519 uStatus = PROC_STS_TOK;
520 }
521 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
522 {
523 VBoxServiceVerbose(3, "ControlExec: Process timed out and did *not* get killed\n");
524 uStatus = PROC_STS_TOA;
525 }
526 else if (pThread->fShutdown && (fProcessAlive || MsProcessKilled != UINT64_MAX))
527 {
528 VBoxServiceVerbose(3, "ControlExec: Process got terminated because system/service is about to shutdown\n");
529 uStatus = PROC_STS_DWN; /* Service is stopping, process was killed. */
530 uFlags = pData->uFlags; /* Return handed-in execution flags back to the host. */
531 }
532 else if (fProcessAlive)
533 {
534 VBoxServiceError("ControlExec: Process is alive when it should not!\n");
535 }
536 else if (MsProcessKilled != UINT64_MAX)
537 {
538 VBoxServiceError("ControlExec: Process has been killed when it should not!\n");
539 }
540 else if (ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
541 {
542 VBoxServiceVerbose(3, "ControlExec: Process ended with RTPROCEXITREASON_NORMAL (%u)\n",
543 ProcessStatus.iStatus);
544
545 uStatus = PROC_STS_TEN;
546 uFlags = ProcessStatus.iStatus;
547 }
548 else if (ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
549 {
550 VBoxServiceVerbose(3, "ControlExec: Process ended with RTPROCEXITREASON_SIGNAL (%u)\n",
551 ProcessStatus.iStatus);
552
553 uStatus = PROC_STS_TES;
554 uFlags = ProcessStatus.iStatus;
555 }
556 else if (ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
557 {
558 VBoxServiceVerbose(3, "ControlExec: Process ended with RTPROCEXITREASON_ABEND (%u)\n",
559 ProcessStatus.iStatus);
560
561 uStatus = PROC_STS_TEA;
562 uFlags = ProcessStatus.iStatus;
563 }
564 else
565 {
566 VBoxServiceError("ControlExec: Process has reached an undefined status!\n");
567 }
568
569 VBoxServiceVerbose(3, "ControlExec: Process ended: PID=%u, CID=%u, Status=%u, Flags=%u\n",
570 pData->uPID, pThread->uContextID, uStatus, uFlags);
571 rc = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID,
572 pData->uPID, uStatus, uFlags,
573 NULL /* pvData */, 0 /* cbData */);
574 VBoxServiceVerbose(3, "ControlExec: Process loop ended with rc=%Rrc\n", rc);
575
576 /*
577 * Dump stdout for debugging purposes.
578 * Only do that on *very* high verbosity (5+).
579 */
580 if (g_cVerbosity >= 5)
581 {
582 uint8_t szBuf[_64K];
583 uint32_t cbOffset = 0;
584 uint32_t cbRead, cbLeft;
585 while ( RT_SUCCESS(VBoxServicePipeBufPeek(&pData->stdOut, szBuf, sizeof(szBuf),
586 cbOffset, &cbRead, &cbLeft))
587 && cbRead)
588 {
589 VBoxServiceVerbose(5, "[%u]: %s\n", pData->uPID, szBuf);
590 cbOffset += cbRead;
591 if (!cbLeft)
592 break;
593 }
594 }
595 }
596 else
597 VBoxServiceError("ControlExec: Process loop failed with rc=%Rrc\n", rc);
598 return rc;
599}
600
601
602/**
603 * Sets up the redirection / pipe / nothing for one of the standard handles.
604 *
605 * @returns IPRT status code. No client replies made.
606 * @param fd Which standard handle it is (0 == stdin, 1 ==
607 * stdout, 2 == stderr).
608 * @param ph The generic handle that @a pph may be set
609 * pointing to. Always set.
610 * @param pph Pointer to the RTProcCreateExec argument.
611 * Always set.
612 * @param phPipe Where to return the end of the pipe that we
613 * should service. Always set.
614 */
615static int VBoxServiceControlExecSetupPipe(int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
616{
617 AssertPtrReturn(ph, VERR_INVALID_PARAMETER);
618 AssertPtrReturn(pph, VERR_INVALID_PARAMETER);
619 AssertPtrReturn(phPipe, VERR_INVALID_PARAMETER);
620
621 ph->enmType = RTHANDLETYPE_PIPE;
622 ph->u.hPipe = NIL_RTPIPE;
623 *pph = NULL;
624 *phPipe = NIL_RTPIPE;
625
626 int rc;
627
628 /*
629 * Setup a pipe for forwarding to/from the client.
630 * The ph union struct will be filled with a pipe read/write handle
631 * to represent the "other" end to phPipe.
632 */
633 if (fd == 0) /* stdin? */
634 {
635 /* Connect a wrtie pipe specified by phPipe to stdin. */
636 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
637 }
638 else /* stdout or stderr? */
639 {
640 /* Connect a read pipe specified by phPipe to stdout or stderr. */
641 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
642 }
643 if (RT_FAILURE(rc))
644 return rc;
645 ph->enmType = RTHANDLETYPE_PIPE;
646 *pph = ph;
647
648 return rc;
649}
650
651
652/**
653 * Expands a file name / path to its real content. This only works on Windows
654 * for now (e.g. translating "%TEMP%\foo.exe" to "C:\Windows\Temp" when starting
655 * with system / administrative rights).
656 *
657 * @return IPRT status code.
658 * @param pszPath Path to resolve.
659 * @param pszExpanded Pointer to string to store the resolved path in.
660 * @param cbExpanded Size (in bytes) of string to store the resolved path.
661 */
662static int VBoxServiceControlExecMakeFullPath(const char *pszPath, char *pszExpanded, size_t cbExpanded)
663{
664 int rc = VINF_SUCCESS;
665#ifdef RT_OS_WINDOWS
666 if (!ExpandEnvironmentStrings(pszPath, pszExpanded, cbExpanded))
667 rc = RTErrConvertFromWin32(GetLastError());
668#else
669 /* No expansion for non-Windows yet. */
670 rc = RTStrCopy(pszExpanded, cbExpanded, pszPath);
671#endif
672#ifdef DEBUG
673 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecMakeFullPath: %s -> %s\n",
674 pszPath, pszExpanded);
675#endif
676 return rc;
677}
678
679
680/**
681 * Resolves the full path of a specified executable name. This function also
682 * resolves internal VBoxService tools to its appropriate executable path + name.
683 *
684 * @return IPRT status code.
685 * @param pszFileName File name to resovle.
686 * @param pszResolved Pointer to a string where the resolved file name will be stored.
687 * @param cbResolved Size (in bytes) of resolved file name string.
688 */
689static int VBoxServiceControlExecResolveExecutable(const char *pszFileName, char *pszResolved, size_t cbResolved)
690{
691 int rc = VINF_SUCCESS;
692
693 /* Search the path of our executable. */
694 char szVBoxService[RTPATH_MAX];
695 if (RTProcGetExecutablePath(szVBoxService, sizeof(szVBoxService)))
696 {
697 char *pszExecResolved = NULL;
698 if ( (g_pszProgName && RTStrICmp(pszFileName, g_pszProgName) == 0)
699 || !RTStrICmp(pszFileName, VBOXSERVICE_NAME))
700 {
701 /* We just want to execute VBoxService (no toolbox). */
702 pszExecResolved = RTStrDup(szVBoxService);
703 }
704 else /* Nothing to resolve, copy original. */
705 pszExecResolved = RTStrDup(pszFileName);
706 AssertPtr(pszExecResolved);
707
708 rc = VBoxServiceControlExecMakeFullPath(pszExecResolved, pszResolved, cbResolved);
709#ifdef DEBUG
710 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecResolveExecutable: %s -> %s\n",
711 pszFileName, pszResolved);
712#endif
713 RTStrFree(pszExecResolved);
714 }
715 return rc;
716}
717
718
719/**
720 * Constructs the argv command line by resolving environment variables
721 * and relative paths.
722 *
723 * @return IPRT status code.
724 * @param pszArgv0 First argument (argv0), either original or modified version.
725 * @param papszArgs Original argv command line from the host, starting at argv[1].
726 * @param ppapszArgv Pointer to a pointer with the new argv command line.
727 * Needs to be freed with RTGetOptArgvFree.
728 */
729static int VBoxServiceControlExecPrepareArgv(const char *pszArgv0,
730 const char * const *papszArgs, char ***ppapszArgv)
731{
732/** @todo RTGetOptArgvToString converts to MSC quoted string, while
733 * RTGetOptArgvFromString takes bourne shell according to the docs...
734 * Actually, converting to and from here is a very roundabout way of prepending
735 * an entry (pszFilename) to an array (*ppapszArgv). */
736 int rc = VINF_SUCCESS;
737 char *pszNewArgs = NULL;
738 if (pszArgv0)
739 rc = RTStrAAppend(&pszNewArgs, pszArgv0);
740 if ( RT_SUCCESS(rc)
741 && papszArgs)
742
743 {
744 char *pszArgs;
745 rc = RTGetOptArgvToString(&pszArgs, papszArgs,
746 RTGETOPTARGV_CNV_QUOTE_MS_CRT); /* RTGETOPTARGV_CNV_QUOTE_BOURNE_SH */
747 if (RT_SUCCESS(rc))
748 {
749 rc = RTStrAAppend(&pszNewArgs, " ");
750 if (RT_SUCCESS(rc))
751 rc = RTStrAAppend(&pszNewArgs, pszArgs);
752 }
753 }
754
755 if (RT_SUCCESS(rc))
756 {
757 int iNumArgsIgnored;
758 rc = RTGetOptArgvFromString(ppapszArgv, &iNumArgsIgnored,
759 pszNewArgs ? pszNewArgs : "", NULL /* Use standard separators. */);
760 }
761
762 if (pszNewArgs)
763 RTStrFree(pszNewArgs);
764 return rc;
765}
766
767
768/**
769 * Helper function to create/start a process on the guest.
770 *
771 * @return IPRT status code.
772 * @param pszExec Full qualified path of process to start (without arguments).
773 * @param papszArgs Pointer to array of command line arguments.
774 * @param hEnv Handle to environment block to use.
775 * @param fFlags Process execution flags.
776 * @param phStdIn Handle for the process' stdin pipe.
777 * @param phStdOut Handle for the process' stdout pipe.
778 * @param phStdErr Handle for the process' stderr pipe.
779 * @param pszAsUser User name (account) to start the process under.
780 * @param pszPassword Password of the specified user.
781 * @param phProcess Pointer which will receive the process handle after
782 * successful process start.
783 */
784static int VBoxServiceControlExecCreateProcess(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
785 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr, const char *pszAsUser,
786 const char *pszPassword, PRTPROCESS phProcess)
787{
788 AssertPtrReturn(pszExec, VERR_INVALID_PARAMETER);
789 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
790 AssertPtrReturn(phProcess, VERR_INVALID_PARAMETER);
791
792 int rc = VINF_SUCCESS;
793 char szExecExp[RTPATH_MAX];
794#ifdef RT_OS_WINDOWS
795 /*
796 * If sysprep should be executed do this in the context of VBoxService, which
797 * (usually, if started by SCM) has administrator rights. Because of that a UI
798 * won't be shown (doesn't have a desktop).
799 */
800 if (RTStrICmp(pszExec, "sysprep") == 0)
801 {
802 /* Use a predefined sysprep path as default. */
803 char szSysprepCmd[RTPATH_MAX] = "C:\\sysprep\\sysprep.exe";
804
805 /*
806 * On Windows Vista (and up) sysprep is located in "system32\\sysprep\\sysprep.exe",
807 * so detect the OS and use a different path.
808 */
809 OSVERSIONINFOEX OSInfoEx;
810 RT_ZERO(OSInfoEx);
811 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
812 if ( GetVersionEx((LPOSVERSIONINFO) &OSInfoEx)
813 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
814 && OSInfoEx.dwMajorVersion >= 6 /* Vista or later */)
815 {
816 rc = RTEnvGetEx(RTENV_DEFAULT, "windir", szSysprepCmd, sizeof(szSysprepCmd), NULL);
817 if (RT_SUCCESS(rc))
818 rc = RTPathAppend(szSysprepCmd, sizeof(szSysprepCmd), "system32\\sysprep\\sysprep.exe");
819 }
820
821 if (RT_SUCCESS(rc))
822 {
823 char **papszArgsExp;
824 rc = VBoxServiceControlExecPrepareArgv(szSysprepCmd /* argv0 */, papszArgs, &papszArgsExp);
825 if (RT_SUCCESS(rc))
826 {
827 rc = RTProcCreateEx(szSysprepCmd, papszArgsExp, hEnv, 0 /* fFlags */,
828 phStdIn, phStdOut, phStdErr, NULL /* pszAsUser */,
829 NULL /* pszPassword */, phProcess);
830 }
831 RTGetOptArgvFree(papszArgsExp);
832 }
833 return rc;
834 }
835#endif /* RT_OS_WINDOWS */
836
837#ifdef VBOXSERVICE_TOOLBOX
838 if (RTStrStr(pszExec, "vbox_") == pszExec)
839 {
840 /* We want to use the internal toolbox (all internal
841 * tools are starting with "vbox_" (e.g. "vbox_cat"). */
842 rc = VBoxServiceControlExecResolveExecutable(VBOXSERVICE_NAME, szExecExp, sizeof(szExecExp));
843 }
844 else
845 {
846#endif
847 /*
848 * Do the environment variables expansion on executable and arguments.
849 */
850 rc = VBoxServiceControlExecResolveExecutable(pszExec, szExecExp, sizeof(szExecExp));
851#ifdef VBOXSERVICE_TOOLBOX
852 }
853#endif
854 if (RT_SUCCESS(rc))
855 {
856 char **papszArgsExp;
857 rc = VBoxServiceControlExecPrepareArgv(pszExec /* Always use the unmodified executable name as argv0. */,
858 papszArgs /* Append the rest of the argument vector (if any). */, &papszArgsExp);
859 if (RT_SUCCESS(rc))
860 {
861 uint32_t uProcFlags = 0;
862 if (fFlags)
863 {
864 /* Process Main flag "ExecuteProcessFlag_Hidden". */
865 if (fFlags & RT_BIT(2))
866 uProcFlags = RTPROC_FLAGS_HIDDEN;
867 /* Process Main flag "ExecuteProcessFlag_NoProfile". */
868 if (fFlags & RT_BIT(3))
869 uProcFlags = RTPROC_FLAGS_NO_PROFILE;
870 }
871
872 /* If no user name specified run with current credentials (e.g.
873 * full service/system rights). This is prohibited via official Main API!
874 *
875 * Otherwise use the RTPROC_FLAGS_SERVICE to use some special authentication
876 * code (at least on Windows) for running processes as different users
877 * started from our system service. */
878 if (*pszAsUser)
879 uProcFlags |= RTPROC_FLAGS_SERVICE;
880#ifdef DEBUG
881 VBoxServiceVerbose(3, "Command: %s\n", szExecExp);
882 for (size_t i = 0; papszArgsExp[i]; i++)
883 VBoxServiceVerbose(3, "\targv[%ld]: %s\n", i, papszArgsExp[i]);
884#endif
885 /* Do normal execution. */
886 rc = RTProcCreateEx(szExecExp, papszArgsExp, hEnv, uProcFlags,
887 phStdIn, phStdOut, phStdErr,
888 *pszAsUser ? pszAsUser : NULL,
889 *pszPassword ? pszPassword : NULL,
890 phProcess);
891 RTGetOptArgvFree(papszArgsExp);
892 }
893 }
894 return rc;
895}
896
897/**
898 * The actual worker routine (lopp) for a started guest process.
899 *
900 * @return IPRT status code.
901 * @param PVBOXSERVICECTRLTHREAD Thread data associated with a started process.
902 */
903static DECLCALLBACK(int) VBoxServiceControlExecProcessWorker(PVBOXSERVICECTRLTHREAD pThread)
904{
905 AssertPtr(pThread);
906 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
907 AssertPtr(pData);
908
909 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" started\n", pData->pszCmd);
910
911 int rc = VbglR3GuestCtrlConnect(&pThread->uClientID);
912 if (RT_FAILURE(rc))
913 {
914 VBoxServiceError("ControlExec: Thread failed to connect to the guest control service, aborted! Error: %Rrc\n", rc);
915 RTThreadUserSignal(RTThreadSelf());
916 return rc;
917 }
918
919 bool fSignalled = false; /* Indicator whether we signalled the thread user event already. */
920
921 /*
922 * Create the environment.
923 */
924 RTENV hEnv;
925 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
926 if (RT_SUCCESS(rc))
927 {
928 size_t i;
929 for (i = 0; i < pData->uNumEnvVars && pData->papszEnv; i++)
930 {
931 rc = RTEnvPutEx(hEnv, pData->papszEnv[i]);
932 if (RT_FAILURE(rc))
933 break;
934 }
935 if (RT_SUCCESS(rc))
936 {
937 /*
938 * Setup the redirection of the standard stuff.
939 */
940 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
941 RTHANDLE hStdIn;
942 PRTHANDLE phStdIn;
943 rc = VBoxServiceControlExecSetupPipe(0 /*STDIN_FILENO*/, &hStdIn, &phStdIn, &pData->pipeStdInW);
944 if (RT_SUCCESS(rc))
945 {
946 RTHANDLE hStdOut;
947 PRTHANDLE phStdOut;
948 RTPIPE hStdOutR;
949 rc = VBoxServiceControlExecSetupPipe(1 /*STDOUT_FILENO*/, &hStdOut, &phStdOut, &hStdOutR);
950 if (RT_SUCCESS(rc))
951 {
952 RTHANDLE hStdErr;
953 PRTHANDLE phStdErr;
954 RTPIPE hStdErrR;
955 rc = VBoxServiceControlExecSetupPipe(2 /*STDERR_FILENO*/, &hStdErr, &phStdErr, &hStdErrR);
956 if (RT_SUCCESS(rc))
957 {
958 /*
959 * Create a poll set for the pipes and let the
960 * transport layer add stuff to it as well.
961 */
962 RTPOLLSET hPollSet;
963 rc = RTPollSetCreate(&hPollSet);
964 if (RT_SUCCESS(rc))
965 {
966 rc = RTPollSetAddPipe(hPollSet, pData->pipeStdInW, RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDIN_ERROR);
967 if (RT_SUCCESS(rc))
968 rc = RTPollSetAddPipe(hPollSet, hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDOUT);
969 if (RT_SUCCESS(rc))
970 rc = RTPollSetAddPipe(hPollSet, hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDERR);
971 if (RT_SUCCESS(rc))
972 rc = RTPollSetAddPipe(hPollSet, pData->pipeStdInW, RTPOLL_EVT_WRITE, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE);
973 if (RT_SUCCESS(rc))
974 rc = RTPollSetAddPipe(hPollSet, pData->stdIn.hNotificationPipeR, RTPOLL_EVT_READ, VBOXSERVICECTRLPIPEID_STDIN_INPUT_NOTIFY);
975 if (RT_SUCCESS(rc))
976 {
977 RTPROCESS hProcess;
978 rc = VBoxServiceControlExecCreateProcess(pData->pszCmd, pData->papszArgs, hEnv, pData->uFlags,
979 phStdIn, phStdOut, phStdErr,
980 pData->pszUser, pData->pszPassword,
981 &hProcess);
982 if (RT_FAILURE(rc))
983 VBoxServiceError("ControlExec: Error starting process, rc=%Rrc\n", rc);
984 /*
985 * Tell the control thread that it can continue
986 * spawning services. This needs to be done after the new
987 * process has been started because otherwise signal handling
988 * on (Open) Solaris does not work correctly (see #5068).
989 */
990 int rc2 = RTThreadUserSignal(RTThreadSelf());
991 if (RT_FAILURE(rc2))
992 rc = rc2;
993 fSignalled = true;
994
995 if (RT_SUCCESS(rc))
996 {
997 /*
998 * Close the child ends of any pipes and redirected files.
999 */
1000 rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
1001 phStdIn = NULL;
1002 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
1003 phStdOut = NULL;
1004 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
1005 phStdErr = NULL;
1006
1007 /* Enter the process loop. */
1008 rc = VBoxServiceControlExecProcLoop(pThread,
1009 hProcess, pData->uTimeLimitMS, hPollSet,
1010 &pData->pipeStdInW, &hStdOutR, &hStdErrR);
1011
1012 /*
1013 * The handles that are no longer in the set have
1014 * been closed by the above call in order to prevent
1015 * the guest from getting stuck accessing them.
1016 * So, NIL the handles to avoid closing them again.
1017 */
1018 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 0 /* stdin */, NULL)))
1019 pData->pipeStdInW = NIL_RTPIPE;
1020 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 1 /* stdout */, NULL)))
1021 hStdOutR = NIL_RTPIPE;
1022 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 2 /* stderr */, NULL)))
1023 hStdErrR = NIL_RTPIPE;
1024 }
1025 else /* Something went wrong; report error! */
1026 {
1027 VBoxServiceError("ControlExec: Could not start process '%s' (CID: %u)! Error: %Rrc\n",
1028 pData->pszCmd, pThread->uContextID, rc);
1029
1030 rc2 = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID, pData->uPID,
1031 PROC_STS_ERROR, rc,
1032 NULL /* pvData */, 0 /* cbData */);
1033 if (RT_FAILURE(rc2))
1034 VBoxServiceError("ControlExec: Could not report process start error! Error: %Rrc (process error %Rrc)\n",
1035 rc2, rc);
1036 }
1037 }
1038 RTPollSetDestroy(hPollSet);
1039 }
1040 RTPipeClose(hStdErrR);
1041 RTHandleClose(phStdErr);
1042 }
1043 RTPipeClose(hStdOutR);
1044 RTHandleClose(phStdOut);
1045 }
1046 RTPipeClose(pData->pipeStdInW);
1047 RTHandleClose(phStdIn);
1048 }
1049 }
1050 RTEnvDestroy(hEnv);
1051 }
1052
1053 VbglR3GuestCtrlDisconnect(pThread->uClientID);
1054 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" (PID: %u) ended with rc=%Rrc\n",
1055 pData->pszCmd, pData->uPID, rc);
1056
1057 /*
1058 * If something went wrong signal the user event so that others don't wait
1059 * forever on this thread.
1060 */
1061 if (RT_FAILURE(rc) && !fSignalled)
1062 RTThreadUserSignal(RTThreadSelf());
1063 return rc;
1064}
1065
1066
1067/**
1068 * Thread main routine for a started process.
1069 *
1070 * @return IPRT status code.
1071 * @param RTTHREAD Pointer to the thread's data.
1072 * @param void* User-supplied argument pointer.
1073 *
1074 */
1075static DECLCALLBACK(int) VBoxServiceControlExecThread(RTTHREAD ThreadSelf, void *pvUser)
1076{
1077 PVBOXSERVICECTRLTHREAD pThread = (VBOXSERVICECTRLTHREAD*)pvUser;
1078 AssertPtr(pThread);
1079 return VBoxServiceControlExecProcessWorker(pThread);
1080}
1081
1082
1083/**
1084 * Executes (starts) a process on the guest. This causes a new thread to be created
1085 * so that this function will not block the overall program execution.
1086 *
1087 * @return IPRT status code.
1088 * @param uContextID Context ID to associate the process to start with.
1089 * @param pszCmd Full qualified path of process to start (without arguments).
1090 * @param uFlags Process execution flags.
1091 * @param pszArgs String of arguments to pass to the process to start.
1092 * @param uNumArgs Number of arguments specified in pszArgs.
1093 * @param pszEnv String of environment variables ("FOO=BAR") to pass to the process
1094 * to start.
1095 * @param cbEnv Size (in bytes) of environment variables.
1096 * @param uNumEnvVars Number of environment variables specified in pszEnv.
1097 * @param pszUser User name (account) to start the process under.
1098 * @param pszPassword Password of specified user name (account).
1099 * @param uTimeLimitMS Time limit (in ms) of the process' life time.
1100 */
1101int VBoxServiceControlExecProcess(uint32_t uContextID, const char *pszCmd, uint32_t uFlags,
1102 const char *pszArgs, uint32_t uNumArgs,
1103 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
1104 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
1105{
1106 int rc;
1107
1108 PVBOXSERVICECTRLTHREAD pThread = (PVBOXSERVICECTRLTHREAD)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREAD));
1109 if (pThread)
1110 {
1111 rc = VBoxServiceControlExecThreadAlloc(pThread,
1112 uContextID,
1113 pszCmd, uFlags,
1114 pszArgs, uNumArgs,
1115 pszEnv, cbEnv, uNumEnvVars,
1116 pszUser, pszPassword,
1117 uTimeLimitMS);
1118 if (RT_SUCCESS(rc))
1119 {
1120 rc = RTThreadCreate(&pThread->Thread, VBoxServiceControlExecThread,
1121 (void *)(PVBOXSERVICECTRLTHREAD*)pThread, 0,
1122 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "Exec");
1123 if (RT_FAILURE(rc))
1124 {
1125 VBoxServiceError("ControlExec: RTThreadCreate failed, rc=%Rrc\n, pThread=%p\n",
1126 rc, pThread);
1127 }
1128 else
1129 {
1130 VBoxServiceVerbose(4, "ControlExec: Waiting for thread to initialize ...\n");
1131
1132 /* Wait for the thread to initialize. */
1133 RTThreadUserWait(pThread->Thread, 60 * 1000);
1134 if (pThread->fShutdown)
1135 {
1136 VBoxServiceError("ControlExec: Thread for process \"%s\" failed to start!\n", pszCmd);
1137 rc = VERR_GENERAL_FAILURE;
1138 }
1139 else
1140 {
1141 pThread->fStarted = true;
1142 /*rc =*/ RTListAppend(&g_GuestControlExecThreads, &pThread->Node);
1143 }
1144 }
1145
1146 if (RT_FAILURE(rc))
1147 VBoxServiceControlExecThreadDestroy((PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData);
1148 }
1149 if (RT_FAILURE(rc))
1150 RTMemFree(pThread);
1151 }
1152 else
1153 rc = VERR_NO_MEMORY;
1154 return rc;
1155}
1156
1157
1158/**
1159 * Handles starting processes on the guest.
1160 *
1161 * @returns IPRT status code.
1162 * @param u32ClientId The HGCM client session ID.
1163 * @param uNumParms The number of parameters the host is offering.
1164 */
1165int VBoxServiceControlExecHandleCmdStartProcess(uint32_t u32ClientId, uint32_t uNumParms)
1166{
1167 uint32_t uContextID;
1168 char szCmd[_1K];
1169 uint32_t uFlags;
1170 char szArgs[_1K];
1171 uint32_t uNumArgs;
1172 char szEnv[_64K];
1173 uint32_t cbEnv = sizeof(szEnv);
1174 uint32_t uNumEnvVars;
1175 char szUser[128];
1176 char szPassword[128];
1177 uint32_t uTimeLimitMS;
1178
1179#if 0 /* for valgrind */
1180 RT_ZERO(szCmd);
1181 RT_ZERO(szArgs);
1182 RT_ZERO(szEnv);
1183 RT_ZERO(szUser);
1184 RT_ZERO(szPassword);
1185#endif
1186
1187 if (uNumParms != 11)
1188 return VERR_INVALID_PARAMETER;
1189
1190 int rc = VbglR3GuestCtrlExecGetHostCmd(u32ClientId,
1191 uNumParms,
1192 &uContextID,
1193 /* Command */
1194 szCmd, sizeof(szCmd),
1195 /* Flags */
1196 &uFlags,
1197 /* Arguments */
1198 szArgs, sizeof(szArgs), &uNumArgs,
1199 /* Environment */
1200 szEnv, &cbEnv, &uNumEnvVars,
1201 /* Credentials */
1202 szUser, sizeof(szUser),
1203 szPassword, sizeof(szPassword),
1204 /* Timelimit */
1205 &uTimeLimitMS);
1206#ifdef DEBUG
1207 VBoxServiceVerbose(3, "ControlExec: Start process szCmd=%s, uFlags=%u, szArgs=%s, szEnv=%s, szUser=%s, szPW=%s, uTimeout=%u\n",
1208 szCmd, uFlags, uNumArgs ? szArgs : "<None>", uNumEnvVars ? szEnv : "<None>", szUser, szPassword, uTimeLimitMS);
1209#endif
1210 if (RT_SUCCESS(rc))
1211 {
1212 rc = VBoxServiceControlExecProcess(uContextID, szCmd, uFlags, szArgs, uNumArgs,
1213 szEnv, cbEnv, uNumEnvVars,
1214 szUser, szPassword, uTimeLimitMS);
1215 }
1216 else
1217 VBoxServiceError("ControlExec: Failed to retrieve exec start command! Error: %Rrc\n", rc);
1218 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecHandleCmdStartProcess returned with %Rrc\n", rc);
1219 return rc;
1220}
1221
1222
1223/**
1224 * Handles input for a started process by copying the received data into its
1225 * stdin pipe.
1226 *
1227 * @returns IPRT status code.
1228 * @param u32ClientId The HGCM client session ID.
1229 * @param uNumParms The number of parameters the host is offering.
1230 * @param cMaxBufSize The maximum buffer size for retrieving the input data.
1231 */
1232int VBoxServiceControlExecHandleCmdSetInput(uint32_t u32ClientId, uint32_t uNumParms, size_t cbMaxBufSize)
1233{
1234 uint32_t uContextID;
1235 uint32_t uPID;
1236 uint32_t uFlags;
1237 uint32_t cbSize;
1238
1239 AssertReturn(RT_IS_POWER_OF_TWO(cbMaxBufSize), VERR_INVALID_PARAMETER);
1240 uint8_t *pabBuffer = (uint8_t*)RTMemAlloc(cbMaxBufSize);
1241 AssertPtrReturn(pabBuffer, VERR_NO_MEMORY);
1242
1243 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status sent back to the host. */
1244 uint32_t cbWritten = 0; /* Number of bytes written to the guest. */
1245
1246 /*
1247 * Ask the host for the input data.
1248 */
1249 int rc = VbglR3GuestCtrlExecGetHostCmdInput(u32ClientId, uNumParms,
1250 &uContextID, &uPID, &uFlags,
1251 pabBuffer, cbMaxBufSize, &cbSize);
1252 if (RT_FAILURE(rc))
1253 {
1254 VBoxServiceError("ControlExec: Failed to retrieve exec input command! Error: %Rrc\n", rc);
1255 }
1256 else if (cbSize > cbMaxBufSize)
1257 {
1258 VBoxServiceError("ControlExec: Maximum input buffer size is too small! cbSize=%u, cbMaxBufSize=%u\n",
1259 cbSize, cbMaxBufSize);
1260 rc = VERR_INVALID_PARAMETER;
1261 }
1262 else
1263 {
1264 /*
1265 * Is this the last input block we need to deliver? Then let the pipe know ...
1266 */
1267 bool fPendingClose = false;
1268 if (uFlags & INPUT_FLAG_EOF)
1269 {
1270 fPendingClose = true;
1271 VBoxServiceVerbose(4, "ControlExec: Got last input block (PID %u) of size %u ...\n", uPID, cbSize);
1272 }
1273
1274 rc = VBoxServiceControlExecThreadSetInput(uPID, fPendingClose, pabBuffer,
1275 cbSize, &cbWritten);
1276 VBoxServiceVerbose(4, "ControlExec: Written input (PID %u): rc=%Rrc, uFlags=0x%x, fPendingClose=%d, cbSize=%u, cbWritten=%u\n",
1277 uPID, rc, uFlags, fPendingClose, cbSize, cbWritten);
1278 if (RT_SUCCESS(rc))
1279 {
1280 if (cbWritten || !cbSize) /* Did we write something or was there anything to write at all? */
1281 {
1282 uStatus = INPUT_STS_WRITTEN;
1283 uFlags = 0;
1284 }
1285 }
1286 else
1287 {
1288 if (rc == VERR_BAD_PIPE)
1289 uStatus = INPUT_STS_TERMINATED;
1290 else if (rc == VERR_BUFFER_OVERFLOW)
1291 uStatus = INPUT_STS_OVERFLOW;
1292 }
1293 }
1294 RTMemFree(pabBuffer);
1295
1296 /*
1297 * If there was an error and we did not set the host status
1298 * yet, then do it now.
1299 */
1300 if ( RT_FAILURE(rc)
1301 && uStatus == INPUT_STS_UNDEFINED)
1302 {
1303 uStatus = INPUT_STS_ERROR;
1304 uFlags = rc;
1305 }
1306 Assert(uStatus > INPUT_STS_UNDEFINED);
1307
1308 VBoxServiceVerbose(3, "ControlExec: Input processed (PID %u), Status=%u, Flags=0x%x, cbWritten=%u\n",
1309 uPID, uStatus, uFlags, cbWritten);
1310
1311 /* Note: Since the context ID is unique the request *has* to be completed here,
1312 * regardless whether we got data or not! Otherwise the progress object
1313 * on the host never will get completed! */
1314 rc = VbglR3GuestCtrlExecReportStatusIn(u32ClientId, uContextID, uPID,
1315 uStatus, uFlags, (uint32_t)cbWritten);
1316
1317 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecHandleCmdSetInput returned with %Rrc\n", rc);
1318 return rc;
1319}
1320
1321
1322/**
1323 * Handles the guest control output command.
1324 *
1325 * @return IPRT status code.
1326 * @param u32ClientId idClient The HGCM client session ID.
1327 * @param uNumParms cParms The number of parameters the host is
1328 * offering.
1329 */
1330int VBoxServiceControlExecHandleCmdGetOutput(uint32_t u32ClientId, uint32_t uNumParms)
1331{
1332 uint32_t uContextID;
1333 uint32_t uPID;
1334 uint32_t uHandleID;
1335 uint32_t uFlags;
1336
1337 int rc = VbglR3GuestCtrlExecGetHostCmdOutput(u32ClientId, uNumParms,
1338 &uContextID, &uPID, &uHandleID, &uFlags);
1339 if (RT_SUCCESS(rc))
1340 {
1341 uint32_t cbRead;
1342 uint8_t *pBuf = (uint8_t*)RTMemAlloc(_64K);
1343 if (pBuf)
1344 {
1345 rc = VBoxServiceControlExecThreadGetOutput(uPID, uHandleID, RT_INDEFINITE_WAIT /* Timeout */,
1346 pBuf, _64K /* cbSize */, &cbRead);
1347 if (RT_SUCCESS(rc))
1348 {
1349 /* Note: Since the context ID is unique the request *has* to be completed here,
1350 * regardless whether we got data or not! Otherwise the progress object
1351 * on the host never will get completed! */
1352 /* cbRead now contains actual size. */
1353 rc = VbglR3GuestCtrlExecSendOut(u32ClientId, uContextID, uPID, uHandleID, uFlags,
1354 pBuf, cbRead);
1355 }
1356 RTMemFree(pBuf);
1357 }
1358 else
1359 rc = VERR_NO_MEMORY;
1360 }
1361 else
1362 VBoxServiceError("ControlExec: Failed to retrieve exec output command! Error: %Rrc\n", rc);
1363 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecHandleCmdGetOutput returned with %Rrc\n", rc);
1364 return rc;
1365}
1366
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