VirtualBox

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

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

VBoxService: always check the credentials

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 34.9 KB
Line 
1
2/* $Id: VBoxServiceControlExec.cpp 29627 2010-05-18 12:47:35Z 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 bool const fHavePipes = hStdInW != NIL_RTPIPE
256 || hStdOutR != NIL_RTPIPE
257 || hStdErrR != NIL_RTPIPE;
258 RTMSINTERVAL const cMsPollBase = hStdInW != NIL_RTPIPE
259 ? 100 /* need to poll for input */
260 : 1000; /* need only poll for process exit and aborts */
261 RTMSINTERVAL cMsPollCur = 0;
262
263 AssertPtr(pThread);
264
265 AssertPtr(pThread);
266 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
267 AssertPtr(pData);
268
269 /* Assign PID to thread data. */
270 pData->uPID = hProcess;
271
272 /*
273 * Before entering the loop, tell the host that we've started the guest
274 * and that it's now OK to send input to the process.
275 */
276 VBoxServiceVerbose(3, "ControlExec: Process started: PID=%u, CID=%u, User=%s, PW=%s\n",
277 pData->uPID, pThread->uContextID, pData->pszUser, pData->pszPassword);
278 rc = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID,
279 pData->uPID, PROC_STS_STARTED, 0 /* u32Flags */,
280 NULL /* pvData */, 0 /* cbData */);
281
282 /*
283 * Process input, output, the test pipe and client requests.
284 */
285 while ( RT_SUCCESS(rc)
286 && RT_UNLIKELY(!pThread->fShutdown))
287 {
288 /*
289 * Wait/Process all pending events.
290 */
291 uint32_t idPollHnd;
292 uint32_t fPollEvt;
293 rc2 = RTPollNoResume(hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
294 if (pThread->fShutdown)
295 continue;
296
297 cMsPollCur = 0; /* no rest until we've checked everything. */
298
299 if (RT_SUCCESS(rc2))
300 {
301 switch (idPollHnd)
302 {
303 case 0 /* TXSEXECHNDID_STDIN */:
304 VBoxServiceControlExecProcHandleStdInErrorEvent(hPollSet, fPollEvt, &hStdInW, &StdInBuf);
305 break;
306
307 case 1 /* TXSEXECHNDID_STDOUT */:
308 rc = VBoxServiceControlExecProcHandleOutputEvent(pThread, hPollSet, fPollEvt, &hStdOutR, &uStdOutCrc32, 1 /* TXSEXECHNDID_STDOUT */);
309 break;
310
311 case 2 /*TXSEXECHNDID_STDERR */:
312 rc = VBoxServiceControlExecProcHandleOutputEvent(pThread, hPollSet, fPollEvt, &hStdErrR, &uStdErrCrc32, 2 /*TXSEXECHNDID_STDERR */);
313 break;
314
315 case 4 /* TXSEXECHNDID_STDIN_WRITABLE */:
316 VBoxServiceControlExecProcHandleStdInWritableEvent(hPollSet, fPollEvt, &hStdInW, &StdInBuf);
317 break;
318
319 default:
320 rc = VBoxServiceControlExecProcHandleTransportEvent(hPollSet, fPollEvt, idPollHnd, &hStdInW, &StdInBuf);
321 break;
322 }
323 if (RT_FAILURE(rc) || rc == VINF_EOF)
324 break; /* abort command, or client dead or something */
325 continue;
326 }
327
328 /*
329 * Check for incoming data.
330 */
331
332 /*
333 * Check for process death.
334 */
335 if (fProcessAlive)
336 {
337 rc2 = RTProcWaitNoResume(hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
338 if (RT_SUCCESS_NP(rc2))
339 {
340 fProcessAlive = false;
341 continue;
342 }
343 if (RT_UNLIKELY(rc2 == VERR_INTERRUPTED))
344 continue;
345 if (RT_UNLIKELY(rc2 == VERR_PROCESS_NOT_FOUND))
346 {
347 fProcessAlive = false;
348 ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
349 ProcessStatus.iStatus = 255;
350 AssertFailed();
351 }
352 else
353 AssertMsg(rc2 == VERR_PROCESS_RUNNING, ("%Rrc\n", rc2));
354 }
355
356 /*
357 * If the process has terminated, we're should head out.
358 */
359 if (!fProcessAlive)
360 break;
361
362 /*
363 * Check for timed out, killing the process.
364 */
365 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
366 if (cMillies != RT_INDEFINITE_WAIT)
367 {
368 uint64_t u64Now = RTTimeMilliTS();
369 uint64_t cMsElapsed = u64Now - MsStart;
370 if (cMsElapsed >= cMillies)
371 {
372 VBoxServiceVerbose(3, "ControlExec: Process timed out (%ums elapsed > %ums timeout), killing ...", cMsElapsed, cMillies);
373
374 fProcessTimedOut = true;
375 if ( MsProcessKilled == UINT64_MAX
376 || u64Now - MsProcessKilled > 1000)
377 {
378 if (u64Now - MsProcessKilled > 20*60*1000)
379 break; /* give up after 20 mins */
380 RTProcTerminate(hProcess);
381 MsProcessKilled = u64Now;
382 continue;
383 }
384 cMilliesLeft = 10000;
385 }
386 else
387 cMilliesLeft = cMillies - (uint32_t)cMsElapsed;
388 }
389
390 /* Reset the polling interval since we've done all pending work. */
391 cMsPollCur = cMilliesLeft >= cMsPollBase ? cMsPollBase : cMilliesLeft;
392
393 /*
394 * Need to exit?
395 */
396 if (pThread->fShutdown)
397 break;
398 }
399
400 /*
401 * Try kill the process if it's still alive at this point.
402 */
403 if (fProcessAlive)
404 {
405 if (MsProcessKilled == UINT64_MAX)
406 {
407 MsProcessKilled = RTTimeMilliTS();
408 RTProcTerminate(hProcess);
409 RTThreadSleep(500);
410 }
411
412 for (size_t i = 0; i < 10; i++)
413 {
414 rc2 = RTProcWait(hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
415 if (RT_SUCCESS(rc2))
416 {
417 fProcessAlive = false;
418 break;
419 }
420 if (i >= 5)
421 RTProcTerminate(hProcess);
422 RTThreadSleep(i >= 5 ? 2000 : 500);
423 }
424 }
425
426 /*
427 * If we don't have a client problem (RT_FAILURE(rc) we'll reply to the
428 * clients exec packet now.
429 */
430 if (RT_SUCCESS(rc))
431 {
432 uint32_t uStatus = PROC_STS_UNDEFINED;
433 uint32_t uFlags = 0;
434
435 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
436 {
437 VBoxServiceVerbose(3, "ControlExec: Process timed out and got killed\n");
438 uStatus = PROC_STS_TOK;
439 }
440 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
441 {
442 VBoxServiceVerbose(3, "ControlExec: Process timed out and did *not* get killed\n");
443 uStatus = PROC_STS_TOA;
444 }
445 else if (pThread->fShutdown && (fProcessAlive || MsProcessKilled != UINT64_MAX))
446 {
447 VBoxServiceVerbose(3, "ControlExec: Process got terminated because system/service is about to shutdown\n");
448 uStatus = PROC_STS_DWN; /* Service is stopping, process was killed. */
449 }
450 else if (fProcessAlive)
451 {
452 VBoxServiceError("ControlExec: Process is alive when it should not!\n");
453 }
454 else if (MsProcessKilled != UINT64_MAX)
455 {
456 VBoxServiceError("ControlExec: Process has been killed when it should not!\n");
457 }
458 else if (ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
459 {
460 VBoxServiceVerbose(3, "ControlExec: Process ended with RTPROCEXITREASON_NORMAL\n");
461
462 uStatus = PROC_STS_TEN;
463 uFlags = ProcessStatus.iStatus;
464 }
465 else if (ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
466 {
467 VBoxServiceVerbose(3, "ControlExec: Process ended with RTPROCEXITREASON_SIGNAL\n");
468
469 uStatus = PROC_STS_TES;
470 uFlags = ProcessStatus.iStatus;
471 }
472 else if (ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
473 {
474 VBoxServiceVerbose(3, "ControlExec: Process ended with RTPROCEXITREASON_ABEND\n");
475
476 uStatus = PROC_STS_TEA;
477 uFlags = ProcessStatus.iStatus;
478 }
479 else
480 {
481 VBoxServiceError("ControlExec: Process has reached an undefined status!\n");
482 }
483
484 VBoxServiceVerbose(3, "ControlExec: Process ended: PID=%u, CID=%u, Status=%u, Flags=%u\n",
485 pData->uPID, pThread->uContextID, uStatus, uFlags);
486 rc = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID,
487 pData->uPID, uStatus, uFlags,
488 NULL /* pvData */, 0 /* cbData */);
489 }
490 RTMemFree(StdInBuf.pch);
491 VBoxServiceVerbose(3, "ControlExec: Process loop ended with rc=%Rrc\n", rc);
492 return rc;
493}
494
495
496/**
497 * Sets up the redirection / pipe / nothing for one of the standard handles.
498 *
499 * @returns IPRT status code. No client replies made.
500 * @param pszHowTo How to set up this standard handle.
501 * @param fd Which standard handle it is (0 == stdin, 1 ==
502 * stdout, 2 == stderr).
503 * @param ph The generic handle that @a pph may be set
504 * pointing to. Always set.
505 * @param pph Pointer to the RTProcCreateExec argument.
506 * Always set.
507 * @param phPipe Where to return the end of the pipe that we
508 * should service. Always set.
509 */
510static int VBoxServiceControlExecSetupPipe(int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
511{
512 AssertPtr(ph);
513 AssertPtr(pph);
514 AssertPtr(phPipe);
515
516 ph->enmType = RTHANDLETYPE_PIPE;
517 ph->u.hPipe = NIL_RTPIPE;
518 *pph = NULL;
519 *phPipe = NIL_RTPIPE;
520
521 int rc;
522
523 /*
524 * Setup a pipe for forwarding to/from the client.
525 * The ph union struct will be filled with a pipe read/write handle
526 * to represent the "other" end to phPipe.
527 */
528 if (fd == 0) /* stdin? */
529 {
530 /* Connect a wrtie pipe specified by phPipe to stdin. */
531 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
532 }
533 else /* stdout or stderr? */
534 {
535 /* Connect a read pipe specified by phPipe to stdout or stderr. */
536 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
537 }
538 if (RT_FAILURE(rc))
539 return rc;
540 ph->enmType = RTHANDLETYPE_PIPE;
541 *pph = ph;
542
543 return rc;
544}
545
546int VBoxServiceControlExecInitPipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf)
547{
548 AssertPtr(pBuf);
549
550 pBuf->pbData = (uint8_t*)RTMemAlloc(_64K); /* Start with a 64k buffer. */
551 AssertReturn(pBuf->pbData, VERR_NO_MEMORY);
552 pBuf->cbSize = 0;
553 pBuf->cbOffset = 0;
554 pBuf->cbRead = 0;
555
556 return RTCritSectInit(&pBuf->CritSect);
557}
558
559int VBoxServiceControlExecDestroyPipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf)
560{
561 if (pBuf)
562 {
563 if (pBuf->pbData)
564 RTMemFree(pBuf->pbData);
565 pBuf->pbData = NULL;
566 pBuf->cbSize = 0;
567 pBuf->cbOffset = 0;
568 pBuf->cbRead = 0;
569 }
570 return RTCritSectDelete(&pBuf->CritSect);
571}
572
573int VBoxServiceControlExecReadPipeBufferContent(PVBOXSERVICECTRLEXECPIPEBUF pBuf,
574 uint8_t *pbBuffer, uint32_t cbBuffer, uint32_t *pcbToRead)
575{
576 AssertPtr(pBuf);
577 AssertPtr(pcbToRead);
578
579 int rc = RTCritSectEnter(&pBuf->CritSect);
580 if (RT_SUCCESS(rc))
581 {
582 Assert(pBuf->cbOffset >= pBuf->cbRead);
583 if (*pcbToRead > pBuf->cbOffset - pBuf->cbRead)
584 *pcbToRead = pBuf->cbOffset - pBuf->cbRead;
585
586 if (*pcbToRead > cbBuffer)
587 *pcbToRead = cbBuffer;
588
589 if (*pcbToRead > 0)
590 {
591 memcpy(pbBuffer, pBuf->pbData + pBuf->cbRead, *pcbToRead);
592 pBuf->cbRead += *pcbToRead;
593 }
594 else
595 {
596 pbBuffer = NULL;
597 *pcbToRead = 0;
598 }
599 rc = RTCritSectLeave(&pBuf->CritSect);
600 }
601 return rc;
602}
603
604int VBoxServiceControlExecWritePipeBuffer(PVBOXSERVICECTRLEXECPIPEBUF pBuf,
605 uint8_t *pbData, uint32_t cbData)
606{
607 AssertPtr(pBuf);
608
609 int rc = RTCritSectEnter(&pBuf->CritSect);
610 if (RT_SUCCESS(rc))
611 {
612 /** @todo Use RTMemCache or RTMemObj here? */
613 uint8_t *pNewBuf;
614 while (pBuf->cbSize - pBuf->cbOffset < cbData)
615 {
616 pNewBuf = (uint8_t*)RTMemRealloc(pBuf->pbData, pBuf->cbSize + _4K);
617 if (pNewBuf == NULL)
618 break;
619 pBuf->cbSize += _4K;
620 pBuf->pbData = pNewBuf;
621 }
622
623 rc = VINF_SUCCESS;
624 if (pBuf->pbData)
625 {
626 memcpy(pBuf->pbData + pBuf->cbOffset, pbData, cbData);
627 pBuf->cbOffset += cbData;
628 /** @todo Add offset clamping! */
629 }
630 else
631 rc = VERR_NO_MEMORY;
632 int rc2 = RTCritSectLeave(&pBuf->CritSect);
633 if (RT_SUCCESS(rc))
634 rc = rc2;
635 }
636 return rc;
637}
638
639/** Allocates and gives back a thread data struct which then can be used by the worker thread. */
640int VBoxServiceControlExecAllocateThreadData(PVBOXSERVICECTRLTHREAD pThread,
641 uint32_t u32ContextID,
642 const char *pszCmd, uint32_t uFlags,
643 const char *pszArgs, uint32_t uNumArgs,
644 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
645 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
646{
647 AssertPtr(pThread);
648
649 /* General stuff. */
650 pThread->Node.pPrev = NULL;
651 pThread->Node.pNext = NULL;
652
653 pThread->fShutdown = false;
654 pThread->fStarted = false;
655 pThread->fStopped = false;
656
657 pThread->uContextID = u32ContextID;
658 /* ClientID will be assigned when thread is started! */
659
660 /* Specific stuff. */
661 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREADDATAEXEC));
662 if (pData == NULL)
663 return VERR_NO_MEMORY;
664
665 pData->uPID = 0; /* Don't have a PID yet. */
666 pData->pszCmd = RTStrDup(pszCmd);
667 pData->uFlags = uFlags;
668 pData->uNumEnvVars = 0;
669 pData->uNumArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
670
671 /* Prepare argument list. */
672 int rc = RTGetOptArgvFromString(&pData->papszArgs, (int*)&pData->uNumArgs,
673 (uNumArgs > 0) ? pszArgs : "", NULL);
674 /* Did we get the same result? */
675 Assert(uNumArgs == pData->uNumArgs);
676
677 if (RT_SUCCESS(rc))
678 {
679 /* Prepare environment list. */
680 if (uNumEnvVars)
681 {
682 pData->papszEnv = (char**)RTMemAlloc(uNumEnvVars * sizeof(char*));
683 AssertPtr(pData->papszEnv);
684 pData->uNumEnvVars = uNumEnvVars;
685
686 const char *pcCur = pszEnv;
687 uint32_t i = 0;
688 uint32_t cbLen = 0;
689 while (cbLen < cbEnv)
690 {
691 if (RTStrAPrintf(&pData->papszEnv[i++], "%s", pcCur) < 0)
692 {
693 rc = VERR_NO_MEMORY;
694 break;
695 }
696 cbLen += strlen(pcCur) + 1; /* Skip terminating zero. */
697 pcCur += cbLen;
698 }
699 }
700
701 pData->pszUser = RTStrDup(pszUser);
702 pData->pszPassword = RTStrDup(pszPassword);
703 pData->uTimeLimitMS = uTimeLimitMS;
704
705 /* Adjust time limit value. */
706 pData->uTimeLimitMS = ( (uTimeLimitMS == UINT32_MAX)
707 || (uTimeLimitMS == 0)) ?
708 RT_INDEFINITE_WAIT : uTimeLimitMS;
709
710 /* Init buffers. */
711 rc = VBoxServiceControlExecInitPipeBuffer(&pData->stdOut);
712 if (RT_SUCCESS(rc))
713 rc = VBoxServiceControlExecInitPipeBuffer(&pData->stdErr);
714 }
715
716 if (RT_FAILURE(rc))
717 {
718 VBoxServiceControlExecDestroyThreadData(pData);
719 }
720 else
721 {
722 pThread->enmType = VBoxServiceCtrlThreadDataExec;
723 pThread->pvData = pData;
724 }
725 return rc;
726}
727
728/** Frees an allocated thread data structure along with all its allocated parameters. */
729void VBoxServiceControlExecDestroyThreadData(PVBOXSERVICECTRLTHREADDATAEXEC pData)
730{
731 if (pData)
732 {
733 RTStrFree(pData->pszCmd);
734 if (pData->uNumEnvVars)
735 {
736 for (uint32_t i = 0; i < pData->uNumEnvVars; i++)
737 RTStrFree(pData->papszEnv[i]);
738 RTMemFree(pData->papszEnv);
739 }
740 RTGetOptArgvFree(pData->papszArgs);
741 RTStrFree(pData->pszUser);
742 RTStrFree(pData->pszPassword);
743
744 VBoxServiceControlExecDestroyPipeBuffer(&pData->stdOut);
745 VBoxServiceControlExecDestroyPipeBuffer(&pData->stdErr);
746
747 RTMemFree(pData);
748 pData = NULL;
749 }
750}
751
752DECLCALLBACK(int) VBoxServiceControlExecProcessWorker(PVBOXSERVICECTRLTHREAD pThread)
753{
754 AssertPtr(pThread);
755 PVBOXSERVICECTRLTHREADDATAEXEC pData = (PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData;
756 AssertPtr(pData);
757
758 /*
759 * Tell the control thread that it can continue
760 * spawning services.
761 */
762 RTThreadUserSignal(RTThreadSelf());
763 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" started\n", pData->pszCmd);
764
765 int rc = VbglR3GuestCtrlConnect(&pThread->uClientID);
766 if (RT_FAILURE(rc))
767 {
768 VBoxServiceError("ControlExec: Thread failed to connect to the guest control service, aborted! Error: %Rrc\n", rc);
769 return rc;
770 }
771
772 /*
773 * Create the environment.
774 */
775 RTENV hEnv;
776 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
777 if (RT_SUCCESS(rc))
778 {
779 size_t i;
780 for (i = 0; i < pData->uNumEnvVars && pData->papszEnv; i++)
781 {
782 rc = RTEnvPutEx(hEnv, pData->papszEnv[i]);
783 if (RT_FAILURE(rc))
784 break;
785 }
786 if (RT_SUCCESS(rc))
787 {
788 /*
789 * Setup the redirection of the standard stuff.
790 */
791 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
792 RTHANDLE hStdIn;
793 PRTHANDLE phStdIn;
794 RTPIPE hStdInW;
795 rc = VBoxServiceControlExecSetupPipe(0 /* stdin */, &hStdIn, &phStdIn, &hStdInW);
796 if (RT_SUCCESS(rc))
797 {
798 RTHANDLE hStdOut;
799 PRTHANDLE phStdOut;
800 RTPIPE hStdOutR;
801 rc = VBoxServiceControlExecSetupPipe(1 /* stdout */, &hStdOut, &phStdOut, &hStdOutR);
802 if (RT_SUCCESS(rc))
803 {
804 RTHANDLE hStdErr;
805 PRTHANDLE phStdErr;
806 RTPIPE hStdErrR;
807 rc = VBoxServiceControlExecSetupPipe(2 /* stderr */, &hStdErr, &phStdErr, &hStdErrR);
808 if (RT_SUCCESS(rc))
809 {
810 /*
811 * Create a poll set for the pipes and let the
812 * transport layer add stuff to it as well.
813 */
814 RTPOLLSET hPollSet;
815 rc = RTPollSetCreate(&hPollSet);
816 if (RT_SUCCESS(rc))
817 {
818 rc = RTPollSetAddPipe(hPollSet, hStdInW, RTPOLL_EVT_ERROR, 0 /* TXSEXECHNDID_STDIN */);
819 if (RT_SUCCESS(rc))
820 rc = RTPollSetAddPipe(hPollSet, hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 1 /* TXSEXECHNDID_STDOUT */);
821 if (RT_SUCCESS(rc))
822 rc = RTPollSetAddPipe(hPollSet, hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR, 2 /* TXSEXECHNDID_TESTPIPE */);
823 if (RT_SUCCESS(rc))
824 {
825 RTPROCESS hProcess;
826 rc = RTProcCreateEx(pData->pszCmd, pData->papszArgs, hEnv, RTPROC_FLAGS_SERVICE,
827 phStdIn, phStdOut, phStdErr,
828 strlen(pData->pszUser) ? pData->pszUser : NULL,
829 strlen(pData->pszUser) && strlen(pData->pszPassword) ? pData->pszPassword : NULL,
830 &hProcess);
831 if (RT_SUCCESS(rc))
832 {
833 /*
834 * Close the child ends of any pipes and redirected files.
835 */
836 int rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
837 phStdIn = NULL;
838 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
839 phStdOut = NULL;
840 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
841 phStdErr = NULL;
842
843 /* Enter the process loop. */
844 rc = VBoxServiceControlExecProcLoop(pThread,
845 hProcess, pData->uTimeLimitMS, hPollSet,
846 hStdInW, hStdOutR, hStdErrR);
847
848 /*
849 * The handles that are no longer in the set have
850 * been closed by the above call in order to prevent
851 * the guest from getting stuck accessing them.
852 * So, NIL the handles to avoid closing them again.
853 */
854 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 0 /* stdin */, NULL)))
855 hStdInW = NIL_RTPIPE;
856 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 1 /* stdout */, NULL)))
857 hStdOutR = NIL_RTPIPE;
858 if (RT_FAILURE(RTPollSetQueryHandle(hPollSet, 2 /* stderr */, NULL)))
859 hStdErrR = NIL_RTPIPE;
860 }
861 else /* Something went wrong; report error! */
862 {
863 VBoxServiceError("ControlExec: Could not start process '%s' (CID: %u)! Error: %Rrc\n",
864 pData->pszCmd, pThread->uContextID, rc);
865
866 int rc2 = VbglR3GuestCtrlExecReportStatus(pThread->uClientID, pThread->uContextID, pData->uPID,
867 PROC_STS_ERROR, rc,
868 NULL /* pvData */, 0 /* cbData */);
869 if (RT_FAILURE(rc2))
870 VBoxServiceError("ControlExec: Could not report process start error! Error: %Rrc (process error %Rrc)\n",
871 rc2, rc);
872 }
873 }
874 }
875 RTPipeClose(hStdErrR);
876 RTHandleClose(phStdErr);
877 }
878 RTPipeClose(hStdOutR);
879 RTHandleClose(phStdOut);
880 }
881 RTPipeClose(hStdInW);
882 RTHandleClose(phStdIn);
883 }
884 }
885 RTEnvDestroy(hEnv);
886 }
887
888 VbglR3GuestCtrlDisconnect(pThread->uClientID);
889 VBoxServiceVerbose(3, "ControlExec: Thread of process \"%s\" (PID: %u) ended with rc=%Rrc\n",
890 pData->pszCmd, pData->uPID, rc);
891 return rc;
892}
893
894static DECLCALLBACK(int) VBoxServiceControlExecThread(RTTHREAD ThreadSelf, void *pvUser)
895{
896 PVBOXSERVICECTRLTHREAD pThread = (VBOXSERVICECTRLTHREAD*)pvUser;
897 AssertPtr(pThread);
898 return VBoxServiceControlExecProcessWorker(pThread);
899}
900
901int VBoxServiceControlExecProcess(uint32_t uContextID, const char *pszCmd, uint32_t uFlags,
902 const char *pszArgs, uint32_t uNumArgs,
903 const char *pszEnv, uint32_t cbEnv, uint32_t uNumEnvVars,
904 const char *pszUser, const char *pszPassword, uint32_t uTimeLimitMS)
905{
906 PVBOXSERVICECTRLTHREAD pThread = (PVBOXSERVICECTRLTHREAD)RTMemAlloc(sizeof(VBOXSERVICECTRLTHREAD));
907
908 int rc;
909 if (pThread)
910 {
911 rc = VBoxServiceControlExecAllocateThreadData(pThread,
912 uContextID,
913 pszCmd, uFlags,
914 pszArgs, uNumArgs,
915 pszEnv, cbEnv, uNumEnvVars,
916 pszUser, pszPassword,
917 uTimeLimitMS);
918 if (RT_SUCCESS(rc))
919 {
920 rc = RTThreadCreate(&pThread->Thread, VBoxServiceControlExecThread,
921 (void *)(PVBOXSERVICECTRLTHREAD*)pThread, 0,
922 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "Exec");
923 if (RT_FAILURE(rc))
924 {
925 VBoxServiceError("ControlExec: RTThreadCreate failed, rc=%Rrc\n, pThread=%p\n",
926 rc, pThread);
927 }
928 else
929 {
930 /* Wait for the thread to initialize. */
931 RTThreadUserWait(pThread->Thread, 60 * 1000);
932 if (pThread->fShutdown)
933 {
934 VBoxServiceError("ControlExec: Thread for process \"%s\" failed to start!\n", pszCmd);
935 rc = VERR_GENERAL_FAILURE;
936 }
937 else
938 {
939 pThread->fStarted = true;
940 /*rc =*/ RTListAppend(&g_GuestControlExecThreads, &pThread->Node);
941 }
942 }
943
944 if (RT_FAILURE(rc))
945 VBoxServiceControlExecDestroyThreadData((PVBOXSERVICECTRLTHREADDATAEXEC)pThread->pvData);
946 }
947 if (RT_FAILURE(rc))
948 RTMemFree(pThread);
949 }
950 else
951 rc = VERR_NO_MEMORY;
952 return rc;
953}
954
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