VirtualBox

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

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

VBoxService/GuestExec: Logging.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette