VirtualBox

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

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

VBoxService/GuestCtrl: Update.

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