VirtualBox

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

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

Comments, some logging.

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