VirtualBox

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

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

indent.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 54.2 KB
Line 
1/* $Id: VBoxServiceControlExec.cpp 37020 2011-05-10 09:23:27Z 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 }
868
869 /* If no user name specified run with current credentials (e.g.
870 * full service/system rights). This is prohibited via official Main API!
871 *
872 * Otherwise use the RTPROC_FLAGS_SERVICE to use some special authentication
873 * code (at least on Windows) for running processes as different users
874 * started from our system service. */
875 if (*pszAsUser)
876 uProcFlags |= RTPROC_FLAGS_SERVICE;
877#ifdef DEBUG
878 VBoxServiceVerbose(3, "Command: %s\n", szExecExp);
879 for (size_t i = 0; papszArgsExp[i]; i++)
880 VBoxServiceVerbose(3, "\targv[%ld]: %s\n", i, papszArgsExp[i]);
881#endif
882 /* Do normal execution. */
883 rc = RTProcCreateEx(szExecExp, papszArgsExp, hEnv, uProcFlags,
884 phStdIn, phStdOut, phStdErr,
885 *pszAsUser ? pszAsUser : NULL,
886 *pszPassword ? pszPassword : NULL,
887 phProcess);
888 RTGetOptArgvFree(papszArgsExp);
889 }
890 }
891 return rc;
892}
893
894/**
895 * The actual worker routine (lopp) for a started guest process.
896 *
897 * @return IPRT status code.
898 * @param PVBOXSERVICECTRLTHREAD Thread data associated with a started process.
899 */
900static DECLCALLBACK(int) VBoxServiceControlExecProcessWorker(PVBOXSERVICECTRLTHREAD pThread)
901{
902 AssertPtr(pThread);
903 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
904 AssertPtr(pData);
905
906 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" started\n", pData->pszCmd);
907
908 int rc = VbglR3GuestCtrlConnect(&pThread->uClientID);
909 if (RT_FAILURE(rc))
910 {
911 VBoxServiceError("ControlExec: Thread failed to connect to the guest control service, aborted! Error: %Rrc\n", rc);
912 RTThreadUserSignal(RTThreadSelf());
913 return rc;
914 }
915
916 bool fSignalled = false; /* Indicator whether we signalled the thread user event already. */
917
918 /*
919 * Create the environment.
920 */
921 RTENV hEnv;
922 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
923 if (RT_SUCCESS(rc))
924 {
925 size_t i;
926 for (i = 0; i < pData->uNumEnvVars && pData->papszEnv; i++)
927 {
928 rc = RTEnvPutEx(hEnv, pData->papszEnv[i]);
929 if (RT_FAILURE(rc))
930 break;
931 }
932 if (RT_SUCCESS(rc))
933 {
934 /*
935 * Setup the redirection of the standard stuff.
936 */
937 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
938 RTHANDLE hStdIn;
939 PRTHANDLE phStdIn;
940 rc = VBoxServiceControlExecSetupPipe(0 /*STDIN_FILENO*/, &hStdIn, &phStdIn, &pData->pipeStdInW);
941 if (RT_SUCCESS(rc))
942 {
943 RTHANDLE hStdOut;
944 PRTHANDLE phStdOut;
945 RTPIPE hStdOutR;
946 rc = VBoxServiceControlExecSetupPipe(1 /*STDOUT_FILENO*/, &hStdOut, &phStdOut, &hStdOutR);
947 if (RT_SUCCESS(rc))
948 {
949 RTHANDLE hStdErr;
950 PRTHANDLE phStdErr;
951 RTPIPE hStdErrR;
952 rc = VBoxServiceControlExecSetupPipe(2 /*STDERR_FILENO*/, &hStdErr, &phStdErr, &hStdErrR);
953 if (RT_SUCCESS(rc))
954 {
955 /*
956 * Create a poll set for the pipes and let the
957 * transport layer add stuff to it as well.
958 */
959 RTPOLLSET hPollSet;
960 rc = RTPollSetCreate(&hPollSet);
961 if (RT_SUCCESS(rc))
962 {
963 rc = RTPollSetAddPipe(hPollSet, pData->pipeStdInW, RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDIN_ERROR);
964 if (RT_SUCCESS(rc))
965 rc = RTPollSetAddPipe(hPollSet, hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDOUT);
966 if (RT_SUCCESS(rc))
967 rc = RTPollSetAddPipe(hPollSet, hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDERR);
968 if (RT_SUCCESS(rc))
969 rc = RTPollSetAddPipe(hPollSet, pData->pipeStdInW, RTPOLL_EVT_WRITE, VBOXSERVICECTRLPIPEID_STDIN_WRITABLE);
970 if (RT_SUCCESS(rc))
971 rc = RTPollSetAddPipe(hPollSet, pData->stdIn.hNotificationPipeR, RTPOLL_EVT_READ, VBOXSERVICECTRLPIPEID_STDIN_INPUT_NOTIFY);
972 if (RT_SUCCESS(rc))
973 {
974 RTPROCESS hProcess;
975 rc = VBoxServiceControlExecCreateProcess(pData->pszCmd, pData->papszArgs, hEnv, pData->uFlags,
976 phStdIn, phStdOut, phStdErr,
977 pData->pszUser, pData->pszPassword,
978 &hProcess);
979 if (RT_FAILURE(rc))
980 VBoxServiceError("ControlExec: Error starting process, rc=%Rrc\n", rc);
981 /*
982 * Tell the control thread that it can continue
983 * spawning services. This needs to be done after the new
984 * process has been started because otherwise signal handling
985 * on (Open) Solaris does not work correctly (see #5068).
986 */
987 int rc2 = RTThreadUserSignal(RTThreadSelf());
988 if (RT_FAILURE(rc2))
989 rc = rc2;
990 fSignalled = true;
991
992 if (RT_SUCCESS(rc))
993 {
994 /*
995 * Close the child ends of any pipes and redirected files.
996 */
997 rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
998 phStdIn = NULL;
999 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
1000 phStdOut = NULL;
1001 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
1002 phStdErr = NULL;
1003
1004 /* Enter the process loop. */
1005 rc = VBoxServiceControlExecProcLoop(pThread,
1006 hProcess, pData->uTimeLimitMS, hPollSet,
1007 &pData->pipeStdInW, &hStdOutR, &hStdErrR);
1008
1009 /*
1010 * The handles that are no longer in the set have
1011 * been closed by the above call in order to prevent
1012 * the guest from getting stuck accessing them.
1013 * So, NIL the handles to avoid closing them again.
1014 */
1015 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 0 /* stdin */, NULL)))
1016 pData->pipeStdInW = NIL_RTPIPE;
1017 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 1 /* stdout */, NULL)))
1018 hStdOutR = NIL_RTPIPE;
1019 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 2 /* stderr */, NULL)))
1020 hStdErrR = NIL_RTPIPE;
1021 }
1022 else /* Something went wrong; report error! */
1023 {
1024 VBoxServiceError("ControlExec: Could not start process '%s' (CID: %u)! Error: %Rrc\n",
1025 pData->pszCmd, pThread->uContextID, rc);
1026
1027 rc2 = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID, pData->uPID,
1028 PROC_STS_ERROR, rc,
1029 NULL /* pvData */, 0 /* cbData */);
1030 if (RT_FAILURE(rc2))
1031 VBoxServiceError("ControlExec: Could not report process start error! Error: %Rrc (process error %Rrc)\n",
1032 rc2, rc);
1033 }
1034 }
1035 RTPollSetDestroy(hPollSet);
1036 }
1037 RTPipeClose(hStdErrR);
1038 RTHandleClose(phStdErr);
1039 }
1040 RTPipeClose(hStdOutR);
1041 RTHandleClose(phStdOut);
1042 }
1043 RTPipeClose(pData->pipeStdInW);
1044 RTHandleClose(phStdIn);
1045 }
1046 }
1047 RTEnvDestroy(hEnv);
1048 }
1049
1050 VbglR3GuestCtrlDisconnect(pThread->uClientID);
1051 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" (PID: %u) ended with rc=%Rrc\n",
1052 pData->pszCmd, pData->uPID, rc);
1053
1054 /*
1055 * If something went wrong signal the user event so that others don't wait
1056 * forever on this thread.
1057 */
1058 if (RT_FAILURE(rc) && !fSignalled)
1059 RTThreadUserSignal(RTThreadSelf());
1060 return rc;
1061}
1062
1063
1064/**
1065 * Thread main routine for a started process.
1066 *
1067 * @return IPRT status code.
1068 * @param RTTHREAD Pointer to the thread's data.
1069 * @param void* User-supplied argument pointer.
1070 *
1071 */
1072static DECLCALLBACK(int) VBoxServiceControlExecThread(RTTHREAD ThreadSelf, void *pvUser)
1073{
1074 PVBOXSERVICECTRLTHREAD pThread = (VBOXSERVICECTRLTHREAD*)pvUser;
1075 AssertPtr(pThread);
1076 return VBoxServiceControlExecProcessWorker(pThread);
1077}
1078
1079
1080/**
1081 * Executes (starts) a process on the guest. This causes a new thread to be created
1082 * so that this function will not block the overall program execution.
1083 *
1084 * @return IPRT status code.
1085 * @param uContextID Context ID to associate the process to start with.
1086 * @param pszCmd Full qualified path of process to start (without arguments).
1087 * @param uFlags Process execution flags.
1088 * @param pszArgs String of arguments to pass to the process to start.
1089 * @param uNumArgs Number of arguments specified in pszArgs.
1090 * @param pszEnv String of environment variables ("FOO=BAR") to pass to the process
1091 * to start.
1092 * @param cbEnv Size (in bytes) of environment variables.
1093 * @param uNumEnvVars Number of environment variables specified in pszEnv.
1094 * @param pszUser User name (account) to start the process under.
1095 * @param pszPassword Password of specified user name (account).
1096 * @param uTimeLimitMS Time limit (in ms) of the process' life time.
1097 */
1098int VBoxServiceControlExecProcess(uint32_t uContextID, const char *pszCmd, uint32_t uFlags,
1099 const char *pszArgs, uint32_t uNumArgs,
1100 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
1101 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
1102{
1103 int rc;
1104
1105 PVBOXSERVICECTRLTHREAD pThread = (PVBOXSERVICECTRLTHREAD)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREAD));
1106 if (pThread)
1107 {
1108 rc = VBoxServiceControlExecThreadAlloc(pThread,
1109 uContextID,
1110 pszCmd, uFlags,
1111 pszArgs, uNumArgs,
1112 pszEnv, cbEnv, uNumEnvVars,
1113 pszUser, pszPassword,
1114 uTimeLimitMS);
1115 if (RT_SUCCESS(rc))
1116 {
1117 rc = RTThreadCreate(&pThread->Thread, VBoxServiceControlExecThread,
1118 (void *)(PVBOXSERVICECTRLTHREAD*)pThread, 0,
1119 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "Exec");
1120 if (RT_FAILURE(rc))
1121 {
1122 VBoxServiceError("ControlExec: RTThreadCreate failed, rc=%Rrc\n, pThread=%p\n",
1123 rc, pThread);
1124 }
1125 else
1126 {
1127 VBoxServiceVerbose(4, "ControlExec: Waiting for thread to initialize ...\n");
1128
1129 /* Wait for the thread to initialize. */
1130 RTThreadUserWait(pThread->Thread, 60 * 1000);
1131 if (pThread->fShutdown)
1132 {
1133 VBoxServiceError("ControlExec: Thread for process \"%s\" failed to start!\n", pszCmd);
1134 rc = VERR_GENERAL_FAILURE;
1135 }
1136 else
1137 {
1138 pThread->fStarted = true;
1139 /*rc =*/ RTListAppend(&g_GuestControlExecThreads, &pThread->Node);
1140 }
1141 }
1142
1143 if (RT_FAILURE(rc))
1144 VBoxServiceControlExecThreadDestroy((PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData);
1145 }
1146 if (RT_FAILURE(rc))
1147 RTMemFree(pThread);
1148 }
1149 else
1150 rc = VERR_NO_MEMORY;
1151 return rc;
1152}
1153
1154
1155/**
1156 * Handles starting processes on the guest.
1157 *
1158 * @returns IPRT status code.
1159 * @param u32ClientId The HGCM client session ID.
1160 * @param uNumParms The number of parameters the host is offering.
1161 */
1162int VBoxServiceControlExecHandleCmdStartProcess(uint32_t u32ClientId, uint32_t uNumParms)
1163{
1164 uint32_t uContextID;
1165 char szCmd[_1K];
1166 uint32_t uFlags;
1167 char szArgs[_1K];
1168 uint32_t uNumArgs;
1169 char szEnv[_64K];
1170 uint32_t cbEnv = sizeof(szEnv);
1171 uint32_t uNumEnvVars;
1172 char szUser[128];
1173 char szPassword[128];
1174 uint32_t uTimeLimitMS;
1175
1176#if 0 /* for valgrind */
1177 RT_ZERO(szCmd);
1178 RT_ZERO(szArgs);
1179 RT_ZERO(szEnv);
1180 RT_ZERO(szUser);
1181 RT_ZERO(szPassword);
1182#endif
1183
1184 if (uNumParms != 11)
1185 return VERR_INVALID_PARAMETER;
1186
1187 int rc = VbglR3GuestCtrlExecGetHostCmd(u32ClientId,
1188 uNumParms,
1189 &uContextID,
1190 /* Command */
1191 szCmd, sizeof(szCmd),
1192 /* Flags */
1193 &uFlags,
1194 /* Arguments */
1195 szArgs, sizeof(szArgs), &uNumArgs,
1196 /* Environment */
1197 szEnv, &cbEnv, &uNumEnvVars,
1198 /* Credentials */
1199 szUser, sizeof(szUser),
1200 szPassword, sizeof(szPassword),
1201 /* Timelimit */
1202 &uTimeLimitMS);
1203#ifdef DEBUG
1204 VBoxServiceVerbose(3, "ControlExec: Start process szCmd=%s, uFlags=%u, szArgs=%s, szEnv=%s, szUser=%s, szPW=%s, uTimeout=%u\n",
1205 szCmd, uFlags, uNumArgs ? szArgs : "<None>", uNumEnvVars ? szEnv : "<None>", szUser, szPassword, uTimeLimitMS);
1206#endif
1207 if (RT_SUCCESS(rc))
1208 {
1209 rc = VBoxServiceControlExecProcess(uContextID, szCmd, uFlags, szArgs, uNumArgs,
1210 szEnv, cbEnv, uNumEnvVars,
1211 szUser, szPassword, uTimeLimitMS);
1212 }
1213 else
1214 VBoxServiceError("ControlExec: Failed to retrieve exec start command! Error: %Rrc\n", rc);
1215 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecHandleCmdStartProcess returned with %Rrc\n", rc);
1216 return rc;
1217}
1218
1219
1220/**
1221 * Handles input for a started process by copying the received data into its
1222 * stdin pipe.
1223 *
1224 * @returns IPRT status code.
1225 * @param u32ClientId The HGCM client session ID.
1226 * @param uNumParms The number of parameters the host is offering.
1227 * @param cMaxBufSize The maximum buffer size for retrieving the input data.
1228 */
1229int VBoxServiceControlExecHandleCmdSetInput(uint32_t u32ClientId, uint32_t uNumParms, size_t cbMaxBufSize)
1230{
1231 uint32_t uContextID;
1232 uint32_t uPID;
1233 uint32_t uFlags;
1234 uint32_t cbSize;
1235
1236 AssertReturn(RT_IS_POWER_OF_TWO(cbMaxBufSize), VERR_INVALID_PARAMETER);
1237 uint8_t *pabBuffer = (uint8_t*)RTMemAlloc(cbMaxBufSize);
1238 AssertPtrReturn(pabBuffer, VERR_NO_MEMORY);
1239
1240 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status sent back to the host. */
1241 uint32_t cbWritten = 0; /* Number of bytes written to the guest. */
1242
1243 /*
1244 * Ask the host for the input data.
1245 */
1246 int rc = VbglR3GuestCtrlExecGetHostCmdInput(u32ClientId, uNumParms,
1247 &uContextID, &uPID, &uFlags,
1248 pabBuffer, cbMaxBufSize, &cbSize);
1249 if (RT_FAILURE(rc))
1250 {
1251 VBoxServiceError("ControlExec: Failed to retrieve exec input command! Error: %Rrc\n", rc);
1252 }
1253 else if (cbSize > cbMaxBufSize)
1254 {
1255 VBoxServiceError("ControlExec: Maximum input buffer size is too small! cbSize=%u, cbMaxBufSize=%u\n",
1256 cbSize, cbMaxBufSize);
1257 rc = VERR_INVALID_PARAMETER;
1258 }
1259 else
1260 {
1261 /*
1262 * Is this the last input block we need to deliver? Then let the pipe know ...
1263 */
1264 bool fPendingClose = false;
1265 if (uFlags & INPUT_FLAG_EOF)
1266 {
1267 fPendingClose = true;
1268 VBoxServiceVerbose(4, "ControlExec: Got last input block (PID %u) of size %u ...\n", uPID, cbSize);
1269 }
1270
1271 rc = VBoxServiceControlExecThreadSetInput(uPID, fPendingClose, pabBuffer,
1272 cbSize, &cbWritten);
1273 VBoxServiceVerbose(4, "ControlExec: Written input (PID %u): rc=%Rrc, uFlags=0x%x, fPendingClose=%d, cbSize=%u, cbWritten=%u\n",
1274 uPID, rc, uFlags, fPendingClose, cbSize, cbWritten);
1275 if (RT_SUCCESS(rc))
1276 {
1277 if (cbWritten || !cbSize) /* Did we write something or was there anything to write at all? */
1278 {
1279 uStatus = INPUT_STS_WRITTEN;
1280 uFlags = 0;
1281 }
1282 }
1283 else
1284 {
1285 if (rc == VERR_BAD_PIPE)
1286 uStatus = INPUT_STS_TERMINATED;
1287 else if (rc == VERR_BUFFER_OVERFLOW)
1288 uStatus = INPUT_STS_OVERFLOW;
1289 }
1290 }
1291 RTMemFree(pabBuffer);
1292
1293 /*
1294 * If there was an error and we did not set the host status
1295 * yet, then do it now.
1296 */
1297 if ( RT_FAILURE(rc)
1298 && uStatus == INPUT_STS_UNDEFINED)
1299 {
1300 uStatus = INPUT_STS_ERROR;
1301 uFlags = rc;
1302 }
1303 Assert(uStatus > INPUT_STS_UNDEFINED);
1304
1305 VBoxServiceVerbose(3, "ControlExec: Input processed (PID %u), Status=%u, Flags=0x%x, cbWritten=%u\n",
1306 uPID, uStatus, uFlags, cbWritten);
1307
1308 /* Note: Since the context ID is unique the request *has* to be completed here,
1309 * regardless whether we got data or not! Otherwise the progress object
1310 * on the host never will get completed! */
1311 rc = VbglR3GuestCtrlExecReportStatusIn(u32ClientId, uContextID, uPID,
1312 uStatus, uFlags, (uint32_t)cbWritten);
1313
1314 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecHandleCmdSetInput returned with %Rrc\n", rc);
1315 return rc;
1316}
1317
1318
1319/**
1320 * Handles the guest control output command.
1321 *
1322 * @return IPRT status code.
1323 * @param u32ClientId idClient The HGCM client session ID.
1324 * @param uNumParms cParms The number of parameters the host is
1325 * offering.
1326 */
1327int VBoxServiceControlExecHandleCmdGetOutput(uint32_t u32ClientId, uint32_t uNumParms)
1328{
1329 uint32_t uContextID;
1330 uint32_t uPID;
1331 uint32_t uHandleID;
1332 uint32_t uFlags;
1333
1334 int rc = VbglR3GuestCtrlExecGetHostCmdOutput(u32ClientId, uNumParms,
1335 &uContextID, &uPID, &uHandleID, &uFlags);
1336 if (RT_SUCCESS(rc))
1337 {
1338 uint32_t cbRead;
1339 uint8_t *pBuf = (uint8_t*)RTMemAlloc(_64K);
1340 if (pBuf)
1341 {
1342 rc = VBoxServiceControlExecThreadGetOutput(uPID, uHandleID, RT_INDEFINITE_WAIT /* Timeout */,
1343 pBuf, _64K /* cbSize */, &cbRead);
1344 if (RT_SUCCESS(rc))
1345 {
1346 /* Note: Since the context ID is unique the request *has* to be completed here,
1347 * regardless whether we got data or not! Otherwise the progress object
1348 * on the host never will get completed! */
1349 /* cbRead now contains actual size. */
1350 rc = VbglR3GuestCtrlExecSendOut(u32ClientId, uContextID, uPID, uHandleID, uFlags,
1351 pBuf, cbRead);
1352 }
1353 RTMemFree(pBuf);
1354 }
1355 else
1356 rc = VERR_NO_MEMORY;
1357 }
1358 else
1359 VBoxServiceError("ControlExec: Failed to retrieve exec output command! Error: %Rrc\n", rc);
1360 VBoxServiceVerbose(3, "ControlExec: VBoxServiceControlExecHandleCmdGetOutput returned with %Rrc\n", rc);
1361 return rc;
1362}
1363
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