VirtualBox

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

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

scm cleanup.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 36.4 KB
Line 
1
2/* $Id: VBoxServiceControlExec.cpp 30013 2010-06-03 14:40:59Z 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 }
487 RTMemFree(StdInBuf.pch);
488 VBoxServiceVerbose(3, "ControlExec: Process loop ended with rc=%Rrc\n", rc);
489 return rc;
490}
491
492
493/**
494 * Sets up the redirection / pipe / nothing for one of the standard handles.
495 *
496 * @returns IPRT status code. No client replies made.
497 * @param pszHowTo How to set up this standard handle.
498 * @param fd Which standard handle it is (0 == stdin, 1 ==
499 * stdout, 2 == stderr).
500 * @param ph The generic handle that @a pph may be set
501 * pointing to. Always set.
502 * @param pph Pointer to the RTProcCreateExec argument.
503 * Always set.
504 * @param phPipe Where to return the end of the pipe that we
505 * should service. Always set.
506 */
507static int VBoxServiceControlExecSetupPipe(int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
508{
509 AssertPtr(ph);
510 AssertPtr(pph);
511 AssertPtr(phPipe);
512
513 ph->enmType = RTHANDLETYPE_PIPE;
514 ph->u.hPipe = NIL_RTPIPE;
515 *pph = NULL;
516 *phPipe = NIL_RTPIPE;
517
518 int rc;
519
520 /*
521 * Setup a pipe for forwarding to/from the client.
522 * The ph union struct will be filled with a pipe read/write handle
523 * to represent the "other" end to phPipe.
524 */
525 if (fd == 0) /* stdin? */
526 {
527 /* Connect a wrtie pipe specified by phPipe to stdin. */
528 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
529 }
530 else /* stdout or stderr? */
531 {
532 /* Connect a read pipe specified by phPipe to stdout or stderr. */
533 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
534 }
535 if (RT_FAILURE(rc))
536 return rc;
537 ph->enmType = RTHANDLETYPE_PIPE;
538 *pph = ph;
539
540 return rc;
541}
542
543int VBoxServiceControlExecInitPipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf)
544{
545 AssertPtr(pBuf);
546
547 pBuf->pbData = (uint8_t*)RTMemAlloc(_64K); /* Start with a 64k buffer. */
548 AssertReturn(pBuf->pbData, VERR_NO_MEMORY);
549 pBuf->cbSize = 0;
550 pBuf->cbOffset = 0;
551 pBuf->cbRead = 0;
552
553 return RTCritSectInit(&pBuf->CritSect);
554}
555
556int VBoxServiceControlExecDestroyPipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf)
557{
558 if (pBuf)
559 {
560 if (pBuf->pbData)
561 RTMemFree(pBuf->pbData);
562 pBuf->pbData = NULL;
563 pBuf->cbSize = 0;
564 pBuf->cbOffset = 0;
565 pBuf->cbRead = 0;
566 }
567 return RTCritSectDelete(&pBuf->CritSect);
568}
569
570int VBoxServiceControlExecReadPipeBufferContent(PVBOXSERVICECTRLEXECPIPEBUF pBuf,
571 uint8_t *pbBuffer, uint32_t cbBuffer, uint32_t *pcbToRead)
572{
573 AssertPtr(pBuf);
574 AssertPtr(pcbToRead);
575
576 int rc = RTCritSectEnter(&pBuf->CritSect);
577 if (RT_SUCCESS(rc))
578 {
579 Assert(pBuf->cbOffset >= pBuf->cbRead);
580 if (*pcbToRead > pBuf->cbOffset - pBuf->cbRead)
581 *pcbToRead = pBuf->cbOffset - pBuf->cbRead;
582
583 if (*pcbToRead > cbBuffer)
584 *pcbToRead = cbBuffer;
585
586 if (*pcbToRead > 0)
587 {
588 memcpy(pbBuffer, pBuf->pbData + pBuf->cbRead, *pcbToRead);
589 pBuf->cbRead += *pcbToRead;
590 }
591 else
592 {
593 pbBuffer = NULL;
594 *pcbToRead = 0;
595 }
596 rc = RTCritSectLeave(&pBuf->CritSect);
597 }
598 return rc;
599}
600
601int VBoxServiceControlExecWritePipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf,
602 uint8_t *pbData, uint32_t cbData)
603{
604 AssertPtr(pBuf);
605
606 int rc = RTCritSectEnter(&pBuf->CritSect);
607 if (RT_SUCCESS(rc))
608 {
609 /** @todo Use RTMemCache or RTMemObj here? */
610 uint8_t *pNewBuf;
611 while (pBuf->cbSize - pBuf->cbOffset < cbData)
612 {
613 pNewBuf = (uint8_t*)RTMemRealloc(pBuf->pbData, pBuf->cbSize + _4K);
614 if (pNewBuf == NULL)
615 break;
616 pBuf->cbSize += _4K;
617 pBuf->pbData = pNewBuf;
618 }
619
620 rc = VINF_SUCCESS;
621 if (pBuf->pbData)
622 {
623 memcpy(pBuf->pbData + pBuf->cbOffset, pbData, cbData);
624 pBuf->cbOffset += cbData;
625 /** @todo Add offset clamping! */
626 }
627 else
628 rc = VERR_NO_MEMORY;
629 int rc2 = RTCritSectLeave(&pBuf->CritSect);
630 if (RT_SUCCESS(rc))
631 rc = rc2;
632 }
633 return rc;
634}
635
636/** Allocates and gives back a thread data struct which then can be used by the worker thread. */
637int VBoxServiceControlExecAllocateThreadData(PVBOXSERVICECTRLTHREAD pThread,
638 uint32_t u32ContextID,
639 const char *pszCmd, uint32_t uFlags,
640 const char *pszArgs, uint32_t uNumArgs,
641 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
642 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
643{
644 AssertPtr(pThread);
645
646 /* General stuff. */
647 pThread->Node.pPrev = NULL;
648 pThread->Node.pNext = NULL;
649
650 pThread->fShutdown = false;
651 pThread->fStarted = false;
652 pThread->fStopped = false;
653
654 pThread->uContextID = u32ContextID;
655 /* ClientID will be assigned when thread is started! */
656
657 /* Specific stuff. */
658 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREADDATAEXEC));
659 if (pData == NULL)
660 return VERR_NO_MEMORY;
661
662 pData->uPID = 0; /* Don't have a PID yet. */
663 pData->pszCmd = RTStrDup(pszCmd);
664 pData->uFlags = uFlags;
665 pData->uNumEnvVars = 0;
666 pData->uNumArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
667
668 /* Prepare argument list. */
669 int rc = RTGetOptArgvFromString(&pData->papszArgs, (int*)&pData->uNumArgs,
670 (uNumArgs > 0) ? pszArgs : "", NULL);
671 /* Did we get the same result? */
672 Assert(uNumArgs == pData->uNumArgs);
673
674 if (RT_SUCCESS(rc))
675 {
676 /* Prepare environment list. */
677 if (uNumEnvVars)
678 {
679 pData->papszEnv = (char**)RTMemAlloc(uNumEnvVars * sizeof(char*));
680 AssertPtr(pData->papszEnv);
681 pData->uNumEnvVars = uNumEnvVars;
682
683 const char *pcCur = pszEnv;
684 uint32_t i = 0;
685 uint32_t cbLen = 0;
686 while (cbLen < cbEnv)
687 {
688 if (RTStrAPrintf(&pData->papszEnv[i++], "%s", pcCur) < 0)
689 {
690 rc = VERR_NO_MEMORY;
691 break;
692 }
693 cbLen += strlen(pcCur) + 1; /* Skip terminating zero. */
694 pcCur += cbLen;
695 }
696 }
697
698 pData->pszUser = RTStrDup(pszUser);
699 pData->pszPassword = RTStrDup(pszPassword);
700 pData->uTimeLimitMS = uTimeLimitMS;
701
702 /* Adjust time limit value. */
703 pData->uTimeLimitMS = ( (uTimeLimitMS == UINT32_MAX)
704 || (uTimeLimitMS == 0)) ?
705 RT_INDEFINITE_WAIT : uTimeLimitMS;
706
707 /* Init buffers. */
708 rc = VBoxServiceControlExecInitPipeBuffer(&pData->stdOut);
709 if (RT_SUCCESS(rc))
710 rc = VBoxServiceControlExecInitPipeBuffer(&pData->stdErr);
711 }
712
713 if (RT_FAILURE(rc))
714 {
715 VBoxServiceControlExecDestroyThreadData(pData);
716 }
717 else
718 {
719 pThread->enmType = VBoxServiceCtrlThreadDataExec;
720 pThread->pvData = pData;
721 }
722 return rc;
723}
724
725/** Frees an allocated thread data structure along with all its allocated parameters. */
726void VBoxServiceControlExecDestroyThreadData(PVBOXSERVICECTRLTHREADDATAEXEC pData)
727{
728 if (pData)
729 {
730 RTStrFree(pData->pszCmd);
731 if (pData->uNumEnvVars)
732 {
733 for (uint32_t i = 0; i < pData->uNumEnvVars; i++)
734 RTStrFree(pData->papszEnv[i]);
735 RTMemFree(pData->papszEnv);
736 }
737 RTGetOptArgvFree(pData->papszArgs);
738 RTStrFree(pData->pszUser);
739 RTStrFree(pData->pszPassword);
740
741 VBoxServiceControlExecDestroyPipeBuffer(&pData->stdOut);
742 VBoxServiceControlExecDestroyPipeBuffer(&pData->stdErr);
743
744 RTMemFree(pData);
745 pData = NULL;
746 }
747}
748
749int VBoxServiceControlExecCreateProcess(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
750 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr, const char *pszAsUser,
751 const char *pszPassword, PRTPROCESS phProcess)
752{
753 int rc = VINF_SUCCESS;
754#ifdef RT_OS_WINDOWS
755 /*
756 * If sysprep should be executed do this in the context of VBoxService, which
757 * (usually, if started by SCM) has administrator rights. Because of that a UI
758 * won't be shown (doesn't have a desktop).
759 */
760 if (stricmp(pszExec, "sysprep") == 0)
761 {
762 /* Get the predefined path of sysprep.exe (depending on Windows OS). */
763 char szSysprepCmd[RTPATH_MAX] = "C:\\sysprep\\sysprep.exe";
764 OSVERSIONINFOEX OSInfoEx;
765 RT_ZERO(OSInfoEx);
766 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
767 if ( GetVersionEx((LPOSVERSIONINFO) &OSInfoEx)
768 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
769 && OSInfoEx.dwMajorVersion >= 6 /* Vista or later */)
770 {
771 rc = RTEnvGetEx(RTENV_DEFAULT, "windir", szSysprepCmd, sizeof(szSysprepCmd), NULL);
772 if (RT_SUCCESS(rc))
773 rc = RTPathAppend(szSysprepCmd, sizeof(szSysprepCmd), "system32\\sysprep\\sysprep.exe");
774 }
775 rc = RTProcCreateEx(szSysprepCmd, papszArgs, hEnv, 0 /* fFlags */,
776 phStdIn, phStdOut, phStdErr, NULL /* pszAsUser */,
777 NULL /* pszPassword */, phProcess);
778 }
779 else
780 {
781#endif
782 /* Do normal execution. */
783 rc = RTProcCreateEx(pszExec, papszArgs, hEnv, fFlags,
784 phStdIn, phStdOut, phStdErr, pszAsUser,
785 pszPassword, phProcess);
786#ifdef RT_OS_WINDOWS
787 }
788#endif
789 return rc;
790}
791
792DECLCALLBACK(int) VBoxServiceControlExecProcessWorker(PVBOXSERVICECTRLTHREAD pThread)
793{
794 AssertPtr(pThread);
795 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
796 AssertPtr(pData);
797
798 /*
799 * Tell the control thread that it can continue
800 * spawning services.
801 */
802 RTThreadUserSignal(RTThreadSelf());
803 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" started\n", pData->pszCmd);
804
805 int rc = VbglR3GuestCtrlConnect(&pThread->uClientID);
806 if (RT_FAILURE(rc))
807 {
808 VBoxServiceError("ControlExec: Thread failed to connect to the guest control service, aborted! Error: %Rrc\n", rc);
809 return rc;
810 }
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 if (RT_SUCCESS(rc))
871 {
872 /*
873 * Close the child ends of any pipes and redirected files.
874 */
875 int rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
876 phStdIn = NULL;
877 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
878 phStdOut = NULL;
879 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
880 phStdErr = NULL;
881
882 /* Enter the process loop. */
883 rc = VBoxServiceControlExecProcLoop(pThread,
884 hProcess, pData->uTimeLimitMS, hPollSet,
885 hStdInW, hStdOutR, hStdErrR);
886
887 /*
888 * The handles that are no longer in the set have
889 * been closed by the above call in order to prevent
890 * the guest from getting stuck accessing them.
891 * So, NIL the handles to avoid closing them again.
892 */
893 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 0 /* stdin */, NULL)))
894 hStdInW = NIL_RTPIPE;
895 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 1 /* stdout */, NULL)))
896 hStdOutR = NIL_RTPIPE;
897 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 2 /* stderr */, NULL)))
898 hStdErrR = NIL_RTPIPE;
899 }
900 else /* Something went wrong; report error! */
901 {
902 VBoxServiceError("ControlExec: Could not start process '%s' (CID: %u)! Error: %Rrc\n",
903 pData->pszCmd, pThread->uContextID, rc);
904
905 int rc2 = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID, pData->uPID,
906 PROC_STS_ERROR, rc,
907 NULL /* pvData */, 0 /* cbData */);
908 if (RT_FAILURE(rc2))
909 VBoxServiceError("ControlExec: Could not report process start error! Error: %Rrc (process error %Rrc)\n",
910 rc2, rc);
911 }
912 }
913 }
914 RTPipeClose(hStdErrR);
915 RTHandleClose(phStdErr);
916 }
917 RTPipeClose(hStdOutR);
918 RTHandleClose(phStdOut);
919 }
920 RTPipeClose(hStdInW);
921 RTHandleClose(phStdIn);
922 }
923 }
924 RTEnvDestroy(hEnv);
925 }
926
927 VbglR3GuestCtrlDisconnect(pThread->uClientID);
928 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" (PID: %u) ended with rc=%Rrc\n",
929 pData->pszCmd, pData->uPID, rc);
930 return rc;
931}
932
933static DECLCALLBACK(int) VBoxServiceControlExecThread(RTTHREAD ThreadSelf, void *pvUser)
934{
935 PVBOXSERVICECTRLTHREAD pThread = (VBOXSERVICECTRLTHREAD*)pvUser;
936 AssertPtr(pThread);
937 return VBoxServiceControlExecProcessWorker(pThread);
938}
939
940int VBoxServiceControlExecProcess(uint32_t uContextID, const char *pszCmd, uint32_t uFlags,
941 const char *pszArgs, uint32_t uNumArgs,
942 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
943 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
944{
945 PVBOXSERVICECTRLTHREAD pThread = (PVBOXSERVICECTRLTHREAD)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREAD));
946
947 int rc;
948 if (pThread)
949 {
950 rc = VBoxServiceControlExecAllocateThreadData(pThread,
951 uContextID,
952 pszCmd, uFlags,
953 pszArgs, uNumArgs,
954 pszEnv, cbEnv, uNumEnvVars,
955 pszUser, pszPassword,
956 uTimeLimitMS);
957 if (RT_SUCCESS(rc))
958 {
959 rc = RTThreadCreate(&pThread->Thread, VBoxServiceControlExecThread,
960 (void *)(PVBOXSERVICECTRLTHREAD*)pThread, 0,
961 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "Exec");
962 if (RT_FAILURE(rc))
963 {
964 VBoxServiceError("ControlExec: RTThreadCreate failed, rc=%Rrc\n, pThread=%p\n",
965 rc, pThread);
966 }
967 else
968 {
969 /* Wait for the thread to initialize. */
970 RTThreadUserWait(pThread->Thread, 60 * 1000);
971 if (pThread->fShutdown)
972 {
973 VBoxServiceError("ControlExec: Thread for process \"%s\" failed to start!\n", pszCmd);
974 rc = VERR_GENERAL_FAILURE;
975 }
976 else
977 {
978 pThread->fStarted = true;
979 /*rc =*/ RTListAppend(&g_GuestControlExecThreads, &pThread->Node);
980 }
981 }
982
983 if (RT_FAILURE(rc))
984 VBoxServiceControlExecDestroyThreadData((PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData);
985 }
986 if (RT_FAILURE(rc))
987 RTMemFree(pThread);
988 }
989 else
990 rc = VERR_NO_MEMORY;
991 return rc;
992}
993
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