VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceControlProcess.cpp@ 50345

Last change on this file since 50345 was 49349, checked in by vboxsync, 11 years ago

Guest Control:

  • Implemented IGuestSession::DirectoryRemove, IGuestSession::DirectoryRemoveRecursive, IGuestSession::DirectoryRename + IGuestSession::FileRename.
  • Added appropriate commands to VBoxManage (basic support for now).
  • Implemented support for proper guest session process termination via SCM.
  • Implemented support for internal anonymous wait events which are not relying on the public API's VBoxEventType_T.
  • Various bugfixes.
  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 80.0 KB
Line 
1/* $Id: VBoxServiceControlProcess.cpp 49349 2013-10-31 16:40:46Z vboxsync $ */
2/** @file
3 * VBoxServiceControlThread - Guest process handling.
4 */
5
6/*
7 * Copyright (C) 2012-2013 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/asm.h>
23#include <iprt/assert.h>
24#include <iprt/env.h>
25#include <iprt/file.h>
26#include <iprt/getopt.h>
27#include <iprt/handle.h>
28#include <iprt/mem.h>
29#include <iprt/path.h>
30#include <iprt/pipe.h>
31#include <iprt/poll.h>
32#include <iprt/process.h>
33#include <iprt/semaphore.h>
34#include <iprt/string.h>
35#include <iprt/thread.h>
36
37#include <VBox/VBoxGuestLib.h>
38#include <VBox/HostServices/GuestControlSvc.h>
39
40#include "VBoxServiceInternal.h"
41#include "VBoxServiceControl.h"
42
43using namespace guestControl;
44
45/*******************************************************************************
46* Internal Functions *
47*******************************************************************************/
48static int gstcntlProcessAssignPID(PVBOXSERVICECTRLPROCESS pThread, uint32_t uPID);
49static int gstcntlProcessLock(PVBOXSERVICECTRLPROCESS pProcess);
50static int gstcntlProcessRequest(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx, PFNRT pfnFunction, unsigned cArgs, ...);
51static int gstcntlProcessSetupPipe(const char *pszHowTo, int fd, PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe);
52static int gstcntlProcessUnlock(PVBOXSERVICECTRLPROCESS pProcess);
53/* Request handlers. */
54static DECLCALLBACK(int) gstcntlProcessOnInput(PVBOXSERVICECTRLPROCESS pThis, const PVBGLR3GUESTCTRLCMDCTX pHostCtx, bool fPendingClose, void *pvBuf, uint32_t cbBuf);
55static DECLCALLBACK(int) gstcntlProcessOnOutput(PVBOXSERVICECTRLPROCESS pThis, const PVBGLR3GUESTCTRLCMDCTX pHostCtx, uint32_t uHandle, uint32_t cbToRead, uint32_t uFlags);
56static DECLCALLBACK(int) gstcntlProcessOnTerm(PVBOXSERVICECTRLPROCESS pThis);
57
58/**
59 * Initialies the passed in thread data structure with the parameters given.
60 *
61 * @return IPRT status code.
62 * @param pProcess Process to initialize.
63 * @param pSession Guest session the process is bound to.
64 * @param pStartupInfo Startup information.
65 * @param u32ContextID The context ID bound to this request / command.
66 */
67static int gstcntlProcessInit(PVBOXSERVICECTRLPROCESS pProcess,
68 const PVBOXSERVICECTRLSESSION pSession,
69 const PVBOXSERVICECTRLPROCSTARTUPINFO pStartupInfo,
70 uint32_t u32ContextID)
71{
72 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
73 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
74 AssertPtrReturn(pStartupInfo, VERR_INVALID_POINTER);
75
76 /* General stuff. */
77 pProcess->hProcess = NIL_RTPROCESS;
78 pProcess->pSession = pSession;
79 pProcess->Node.pPrev = NULL;
80 pProcess->Node.pNext = NULL;
81
82 pProcess->fShutdown = false;
83 pProcess->fStarted = false;
84 pProcess->fStopped = false;
85
86 pProcess->uPID = 0; /* Don't have a PID yet. */
87 pProcess->cRefs = 0;
88 /*
89 * Use the initial context ID we got for starting
90 * the process to report back its status with the
91 * same context ID.
92 */
93 pProcess->uContextID = u32ContextID;
94 /*
95 * Note: pProcess->ClientID will be assigned when thread is started;
96 * every guest process has its own client ID to detect crashes on
97 * a per-guest-process level.
98 */
99
100 int rc = RTCritSectInit(&pProcess->CritSect);
101 if (RT_FAILURE(rc))
102 return rc;
103
104 pProcess->hPollSet = NIL_RTPOLLSET;
105 pProcess->hPipeStdInW = NIL_RTPIPE;
106 pProcess->hPipeStdOutR = NIL_RTPIPE;
107 pProcess->hPipeStdErrR = NIL_RTPIPE;
108 pProcess->hNotificationPipeW = NIL_RTPIPE;
109 pProcess->hNotificationPipeR = NIL_RTPIPE;
110
111 rc = RTReqQueueCreate(&pProcess->hReqQueue);
112 AssertReleaseRC(rc);
113
114 /* Copy over startup info. */
115 memcpy(&pProcess->StartupInfo, pStartupInfo, sizeof(VBOXSERVICECTRLPROCSTARTUPINFO));
116
117 /* Adjust timeout value. */
118 if ( pProcess->StartupInfo.uTimeLimitMS == UINT32_MAX
119 || pProcess->StartupInfo.uTimeLimitMS == 0)
120 pProcess->StartupInfo.uTimeLimitMS = RT_INDEFINITE_WAIT;
121
122 if (RT_FAILURE(rc)) /* Clean up on failure. */
123 GstCntlProcessFree(pProcess);
124 return rc;
125}
126
127
128/**
129 * Frees a guest process. On success, pProcess will be
130 * free'd and thus won't be available anymore.
131 *
132 * @return IPRT status code.
133 * @param pProcess Guest process to free.
134 */
135int GstCntlProcessFree(PVBOXSERVICECTRLPROCESS pProcess)
136{
137 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
138
139 VBoxServiceVerbose(3, "[PID %RU32]: Freeing (cRefs=%RU32)...\n",
140 pProcess->uPID, pProcess->cRefs);
141 Assert(pProcess->cRefs == 0);
142
143 /*
144 * Destroy other thread data.
145 */
146 if (RTCritSectIsInitialized(&pProcess->CritSect))
147 RTCritSectDelete(&pProcess->CritSect);
148
149 int rc = RTReqQueueDestroy(pProcess->hReqQueue);
150 AssertRC(rc);
151
152 /*
153 * Remove from list.
154 */
155 AssertPtr(pProcess->pSession);
156 rc = GstCntlSessionProcessRemove(pProcess->pSession, pProcess);
157 AssertRC(rc);
158
159 /*
160 * Destroy thread structure as final step.
161 */
162 RTMemFree(pProcess);
163 pProcess = NULL;
164
165 return VINF_SUCCESS;
166}
167
168
169/**
170 * Signals a guest process thread that we want it to shut down in
171 * a gentle way.
172 *
173 * @return IPRT status code.
174 * @param pProcess Process to stop.
175 */
176int GstCntlProcessStop(PVBOXSERVICECTRLPROCESS pProcess)
177{
178 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
179
180 VBoxServiceVerbose(3, "[PID %RU32]: Stopping ...\n",
181 pProcess->uPID);
182
183 /* Do *not* set pThread->fShutdown or other stuff here!
184 * The guest thread loop will clean up itself. */
185
186 return GstCntlProcessHandleTerm(pProcess);
187}
188
189
190/**
191 * Releases a previously acquired guest process (decreases the refcount).
192 *
193 * @param pProcess Process to unlock.
194 */
195void GstCntlProcessRelease(PVBOXSERVICECTRLPROCESS pProcess)
196{
197 AssertPtrReturnVoid(pProcess);
198
199 bool fShutdown = false;
200
201 int rc = RTCritSectEnter(&pProcess->CritSect);
202 if (RT_SUCCESS(rc))
203 {
204 Assert(pProcess->cRefs);
205 pProcess->cRefs--;
206 fShutdown = pProcess->fStopped; /* Has the process' thread been stopped? */
207
208 rc = RTCritSectLeave(&pProcess->CritSect);
209 AssertRC(rc);
210 }
211
212 if (fShutdown)
213 GstCntlProcessFree(pProcess);
214}
215
216
217/**
218 * Wait for a guest process thread to shut down.
219 *
220 * @return IPRT status code.
221 * @param pProcess Process to wait shutting down for.
222 * @param RTMSINTERVAL Timeout in ms to wait for shutdown.
223 * @param pRc Where to store the thread's return code. Optional.
224 */
225int GstCntlProcessWait(const PVBOXSERVICECTRLPROCESS pProcess,
226 RTMSINTERVAL msTimeout, int *pRc)
227{
228 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
229 /* pRc is optional. */
230
231 int rc = gstcntlProcessLock(pProcess);
232 if (RT_SUCCESS(rc))
233 {
234 VBoxServiceVerbose(2, "[PID %RU32]: Waiting for shutdown (%RU32ms) ...\n",
235 pProcess->uPID, msTimeout);
236
237 AssertMsgReturn(pProcess->fStarted,
238 ("Tried to wait on guest process=%p (PID %RU32) which has not been started yet\n",
239 pProcess, pProcess->uPID), VERR_INVALID_PARAMETER);
240
241 /* Guest process already has been stopped, no need to wait. */
242 if (!pProcess->fStopped)
243 {
244 /* Unlock process before waiting. */
245 rc = gstcntlProcessUnlock(pProcess);
246 AssertRC(rc);
247
248 /* Do the actual waiting. */
249 int rcThread;
250 Assert(pProcess->Thread != NIL_RTTHREAD);
251 rc = RTThreadWait(pProcess->Thread, msTimeout, &rcThread);
252 if (RT_FAILURE(rc))
253 {
254 VBoxServiceError("[PID %RU32]: Waiting for shutting down thread returned error rc=%Rrc\n",
255 pProcess->uPID, rc);
256 }
257 else
258 {
259 VBoxServiceVerbose(3, "[PID %RU32]: Thread shutdown complete, thread rc=%Rrc\n",
260 pProcess->uPID, rcThread);
261 if (pRc)
262 *pRc = rcThread;
263 }
264 }
265 else
266 {
267 VBoxServiceVerbose(3, "[PID %RU32]: Thread already shut down, no waiting needed\n",
268 pProcess->uPID);
269
270 int rc2 = gstcntlProcessUnlock(pProcess);
271 AssertRC(rc2);
272 }
273 }
274
275 VBoxServiceVerbose(3, "[PID %RU32]: Waiting resulted in rc=%Rrc\n",
276 pProcess->uPID, rc);
277 return rc;
278}
279
280
281/**
282 * Closes the stdin pipe of a guest process.
283 *
284 * @return IPRT status code.
285 * @param hPollSet The polling set.
286 * @param phStdInW The standard input pipe handle.
287 */
288static int gstcntlProcessPollsetCloseInput(PVBOXSERVICECTRLPROCESS pProcess,
289 PRTPIPE phStdInW)
290{
291 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
292 AssertPtrReturn(phStdInW, VERR_INVALID_POINTER);
293
294 int rc = RTPollSetRemove(pProcess->hPollSet, VBOXSERVICECTRLPIPEID_STDIN);
295 if (rc != VERR_POLL_HANDLE_ID_NOT_FOUND)
296 AssertRC(rc);
297
298 if (*phStdInW != NIL_RTPIPE)
299 {
300 rc = RTPipeClose(*phStdInW);
301 AssertRC(rc);
302 *phStdInW = NIL_RTPIPE;
303 }
304
305 return rc;
306}
307
308
309static const char* gstcntlProcessPollHandleToString(uint32_t idPollHnd)
310{
311 switch (idPollHnd)
312 {
313 case VBOXSERVICECTRLPIPEID_UNKNOWN:
314 return "unknown";
315 case VBOXSERVICECTRLPIPEID_STDIN:
316 return "stdin";
317 case VBOXSERVICECTRLPIPEID_STDIN_WRITABLE:
318 return "stdin_writable";
319 case VBOXSERVICECTRLPIPEID_STDOUT:
320 return "stdout";
321 case VBOXSERVICECTRLPIPEID_STDERR:
322 return "stderr";
323 case VBOXSERVICECTRLPIPEID_IPC_NOTIFY:
324 return "ipc_notify";
325 default:
326 break;
327 }
328
329 return "unknown";
330}
331
332
333/**
334 * Handle an error event on standard input.
335 *
336 * @return IPRT status code.
337 * @param pProcess Process to handle pollset for.
338 * @param fPollEvt The event mask returned by RTPollNoResume.
339 * @param phStdInW The standard input pipe handle.
340 */
341static int gstcntlProcessPollsetOnInput(PVBOXSERVICECTRLPROCESS pProcess,
342 uint32_t fPollEvt, PRTPIPE phStdInW)
343{
344 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
345
346 NOREF(fPollEvt);
347
348 return gstcntlProcessPollsetCloseInput(pProcess, phStdInW);
349}
350
351
352/**
353 * Handle pending output data or error on standard out or standard error.
354 *
355 * @returns IPRT status code from client send.
356 * @param pProcess Process to handle pollset for.
357 * @param fPollEvt The event mask returned by RTPollNoResume.
358 * @param phPipeR The pipe handle.
359 * @param idPollHnd The pipe ID to handle.
360 *
361 */
362static int gstcntlProcessHandleOutputError(PVBOXSERVICECTRLPROCESS pProcess,
363 uint32_t fPollEvt, PRTPIPE phPipeR, uint32_t idPollHnd)
364{
365 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
366
367 if (!phPipeR)
368 return VINF_SUCCESS;
369
370#ifdef DEBUG
371 VBoxServiceVerbose(4, "[PID %RU32]: Output error: idPollHnd=%s, fPollEvt=0x%x\n",
372 pProcess->uPID, gstcntlProcessPollHandleToString(idPollHnd), fPollEvt);
373#endif
374
375 /* Remove pipe from poll set. */
376 int rc2 = RTPollSetRemove(pProcess->hPollSet, idPollHnd);
377 AssertMsg(RT_SUCCESS(rc2) || rc2 == VERR_POLL_HANDLE_ID_NOT_FOUND, ("%Rrc\n", rc2));
378
379 bool fClosePipe = true; /* By default close the pipe. */
380
381 /* Check if there's remaining data to read from the pipe. */
382 if (*phPipeR != NIL_RTPIPE)
383 {
384 size_t cbReadable;
385 rc2 = RTPipeQueryReadable(*phPipeR, &cbReadable);
386 if ( RT_SUCCESS(rc2)
387 && cbReadable)
388 {
389#ifdef DEBUG
390 VBoxServiceVerbose(3, "[PID %RU32]: idPollHnd=%s has %zu bytes left, vetoing close\n",
391 pProcess->uPID, gstcntlProcessPollHandleToString(idPollHnd), cbReadable);
392#endif
393 /* Veto closing the pipe yet because there's still stuff to read
394 * from the pipe. This can happen on UNIX-y systems where on
395 * error/hangup there still can be data to be read out. */
396 fClosePipe = false;
397 }
398 }
399#ifdef DEBUG
400 else
401 VBoxServiceVerbose(3, "[PID %RU32]: idPollHnd=%s will be closed\n",
402 pProcess->uPID, gstcntlProcessPollHandleToString(idPollHnd));
403#endif
404
405 if ( *phPipeR != NIL_RTPIPE
406 && fClosePipe)
407 {
408 rc2 = RTPipeClose(*phPipeR);
409 AssertRC(rc2);
410 *phPipeR = NIL_RTPIPE;
411 }
412
413 return VINF_SUCCESS;
414}
415
416
417/**
418 * Handle pending output data or error on standard out or standard error.
419 *
420 * @returns IPRT status code from client send.
421 * @param pProcess Process to handle pollset for.
422 * @param fPollEvt The event mask returned by RTPollNoResume.
423 * @param phPipeR The pipe handle.
424 * @param idPollHnd The pipe ID to handle.
425 *
426 */
427static int gstcntlProcessPollsetOnOutput(PVBOXSERVICECTRLPROCESS pProcess,
428 uint32_t fPollEvt, PRTPIPE phPipeR, uint32_t idPollHnd)
429{
430 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
431
432#ifdef DEBUG
433 VBoxServiceVerbose(4, "[PID %RU32]: Output event phPipeR=%p, idPollHnd=%s, fPollEvt=0x%x\n",
434 pProcess->uPID, phPipeR, gstcntlProcessPollHandleToString(idPollHnd), fPollEvt);
435#endif
436
437 if (!phPipeR)
438 return VINF_SUCCESS;
439
440 int rc = VINF_SUCCESS;
441
442#ifdef DEBUG
443 if (*phPipeR != NIL_RTPIPE)
444 {
445 size_t cbReadable;
446 rc = RTPipeQueryReadable(*phPipeR, &cbReadable);
447 if ( RT_SUCCESS(rc)
448 && cbReadable)
449 {
450 VBoxServiceVerbose(4, "[PID %RU32]: Output event cbReadable=%zu\n",
451 pProcess->uPID, cbReadable);
452 }
453 }
454#endif
455
456#if 0
457 /* Push output to the host. */
458 if (fPollEvt & RTPOLL_EVT_READ)
459 {
460 size_t cbRead = 0;
461 uint8_t byData[_64K];
462 rc = RTPipeRead(*phPipeR,
463 byData, sizeof(byData), &cbRead);
464 VBoxServiceVerbose(4, "GstCntlProcessHandleOutputEvent cbRead=%u, rc=%Rrc\n",
465 cbRead, rc);
466
467 /* Make sure we go another poll round in case there was too much data
468 for the buffer to hold. */
469 fPollEvt &= RTPOLL_EVT_ERROR;
470 }
471#endif
472
473 if (fPollEvt & RTPOLL_EVT_ERROR)
474 rc = gstcntlProcessHandleOutputError(pProcess,
475 fPollEvt, phPipeR, idPollHnd);
476 return rc;
477}
478
479
480/**
481 * Execution loop which runs in a dedicated per-started-process thread and
482 * handles all pipe input/output and signalling stuff.
483 *
484 * @return IPRT status code.
485 * @param pProcess The guest process to handle.
486 */
487static int gstcntlProcessProcLoop(PVBOXSERVICECTRLPROCESS pProcess)
488{
489 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
490
491 int rc;
492 int rc2;
493 uint64_t const uMsStart = RTTimeMilliTS();
494 RTPROCSTATUS ProcessStatus = { 254, RTPROCEXITREASON_ABEND };
495 bool fProcessAlive = true;
496 bool fProcessTimedOut = false;
497 uint64_t MsProcessKilled = UINT64_MAX;
498 RTMSINTERVAL const cMsPollBase = pProcess->hPipeStdInW != NIL_RTPIPE
499 ? 100 /* Need to poll for input. */
500 : 1000; /* Need only poll for process exit and aborts. */
501 RTMSINTERVAL cMsPollCur = 0;
502
503 /*
504 * Assign PID to thread data.
505 * Also check if there already was a thread with the same PID and shut it down -- otherwise
506 * the first (stale) entry will be found and we get really weird results!
507 */
508 rc = gstcntlProcessAssignPID(pProcess, pProcess->hProcess /* Opaque PID handle */);
509 if (RT_FAILURE(rc))
510 {
511 VBoxServiceError("Unable to assign PID=%u, to new thread, rc=%Rrc\n",
512 pProcess->hProcess, rc);
513 return rc;
514 }
515
516 /*
517 * Before entering the loop, tell the host that we've started the guest
518 * and that it's now OK to send input to the process.
519 */
520 VBoxServiceVerbose(2, "[PID %RU32]: Process \"%s\" started, CID=%u, User=%s, cMsTimeout=%RU32\n",
521 pProcess->uPID, pProcess->StartupInfo.szCmd, pProcess->uContextID,
522 pProcess->StartupInfo.szUser, pProcess->StartupInfo.uTimeLimitMS);
523 VBGLR3GUESTCTRLCMDCTX ctxStart = { pProcess->uClientID, pProcess->uContextID };
524 rc = VbglR3GuestCtrlProcCbStatus(&ctxStart,
525 pProcess->uPID, PROC_STS_STARTED, 0 /* u32Flags */,
526 NULL /* pvData */, 0 /* cbData */);
527 if (RT_FAILURE(rc))
528 VBoxServiceError("[PID %RU32]: Error reporting starting status to host, rc=%Rrc\n",
529 pProcess->uPID, rc);
530
531 /*
532 * Process input, output, the test pipe and client requests.
533 */
534 while ( RT_SUCCESS(rc)
535 && RT_UNLIKELY(!pProcess->fShutdown))
536 {
537 /*
538 * Wait/Process all pending events.
539 */
540 uint32_t idPollHnd;
541 uint32_t fPollEvt;
542 rc2 = RTPollNoResume(pProcess->hPollSet, cMsPollCur, &fPollEvt, &idPollHnd);
543 if (pProcess->fShutdown)
544 continue;
545
546 cMsPollCur = 0; /* No rest until we've checked everything. */
547
548 if (RT_SUCCESS(rc2))
549 {
550 switch (idPollHnd)
551 {
552 case VBOXSERVICECTRLPIPEID_STDIN:
553 rc = gstcntlProcessPollsetOnInput(pProcess, fPollEvt,
554 &pProcess->hPipeStdInW);
555 break;
556
557 case VBOXSERVICECTRLPIPEID_STDOUT:
558 rc = gstcntlProcessPollsetOnOutput(pProcess, fPollEvt,
559 &pProcess->hPipeStdOutR, idPollHnd);
560 break;
561
562 case VBOXSERVICECTRLPIPEID_STDERR:
563 rc = gstcntlProcessPollsetOnOutput(pProcess, fPollEvt,
564 &pProcess->hPipeStdOutR, idPollHnd);
565 break;
566
567 case VBOXSERVICECTRLPIPEID_IPC_NOTIFY:
568#ifdef DEBUG_andy
569 VBoxServiceVerbose(4, "[PID %RU32]: IPC notify\n", pProcess->uPID);
570#endif
571 rc2 = gstcntlProcessLock(pProcess);
572 if (RT_SUCCESS(rc2))
573 {
574 /* Drain the notification pipe. */
575 uint8_t abBuf[8];
576 size_t cbIgnore;
577 rc2 = RTPipeRead(pProcess->hNotificationPipeR,
578 abBuf, sizeof(abBuf), &cbIgnore);
579 if (RT_FAILURE(rc2))
580 VBoxServiceError("Draining IPC notification pipe failed with rc=%Rrc\n", rc2);
581
582 /* Process all pending requests. */
583 VBoxServiceVerbose(4, "[PID %RU32]: Processing pending requests ...\n",
584 pProcess->uPID);
585 Assert(pProcess->hReqQueue != NIL_RTREQQUEUE);
586 rc2 = RTReqQueueProcess(pProcess->hReqQueue,
587 0 /* Only process all pending requests, don't wait for new ones */);
588 if ( RT_FAILURE(rc2)
589 && rc2 != VERR_TIMEOUT)
590 VBoxServiceError("Processing requests failed with with rc=%Rrc\n", rc2);
591
592 int rc3 = gstcntlProcessUnlock(pProcess);
593 AssertRC(rc3);
594#ifdef DEBUG
595 VBoxServiceVerbose(4, "[PID %RU32]: Processing pending requests done, rc=%Rrc\n",
596 pProcess->uPID, rc2);
597#endif
598 }
599
600 break;
601
602 default:
603 AssertMsgFailed(("Unknown idPollHnd=%RU32\n", idPollHnd));
604 break;
605 }
606
607 if (RT_FAILURE(rc) || rc == VINF_EOF)
608 break; /* Abort command, or client dead or something. */
609 }
610#if 0
611 VBoxServiceVerbose(4, "[PID %RU32]: Polling done, pollRc=%Rrc, pollCnt=%RU32, idPollHnd=%s, rc=%Rrc, fProcessAlive=%RTbool, fShutdown=%RTbool\n",
612 pProcess->uPID, rc2, RTPollSetGetCount(hPollSet), gstcntlProcessPollHandleToString(idPollHnd), rc, fProcessAlive, pProcess->fShutdown);
613 VBoxServiceVerbose(4, "[PID %RU32]: stdOut=%s, stdErrR=%s\n",
614 pProcess->uPID,
615 *phStdOutR == NIL_RTPIPE ? "closed" : "open",
616 *phStdErrR == NIL_RTPIPE ? "closed" : "open");
617#endif
618 if (RT_UNLIKELY(pProcess->fShutdown))
619 break; /* We were asked to shutdown. */
620
621 /*
622 * Check for process death.
623 */
624 if (fProcessAlive)
625 {
626 rc2 = RTProcWaitNoResume(pProcess->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
627#if 0
628 VBoxServiceVerbose(4, "[PID %RU32]: RTProcWaitNoResume=%Rrc\n",
629 pProcess->uPID, rc2);
630#endif
631 if (RT_SUCCESS_NP(rc2))
632 {
633 fProcessAlive = false;
634 /* Note: Don't bail out here yet. First check in the next block below
635 * if all needed pipe outputs have been consumed. */
636 }
637 else
638 {
639 if (RT_UNLIKELY(rc2 == VERR_INTERRUPTED))
640 continue;
641 if (RT_UNLIKELY(rc2 == VERR_PROCESS_NOT_FOUND))
642 {
643 fProcessAlive = false;
644 ProcessStatus.enmReason = RTPROCEXITREASON_ABEND;
645 ProcessStatus.iStatus = 255;
646 AssertFailed();
647 }
648 else
649 AssertMsg(rc2 == VERR_PROCESS_RUNNING, ("%Rrc\n", rc2));
650 }
651 }
652
653 /*
654 * If the process has terminated and all output has been consumed,
655 * we should be heading out.
656 */
657 if (!fProcessAlive)
658 {
659 if ( fProcessTimedOut
660 || ( pProcess->hPipeStdOutR == NIL_RTPIPE
661 && pProcess->hPipeStdErrR == NIL_RTPIPE)
662 )
663 {
664 break;
665 }
666 }
667
668 /*
669 * Check for timed out, killing the process.
670 */
671 uint32_t cMilliesLeft = RT_INDEFINITE_WAIT;
672 if ( pProcess->StartupInfo.uTimeLimitMS != RT_INDEFINITE_WAIT
673 && pProcess->StartupInfo.uTimeLimitMS != 0)
674 {
675 uint64_t u64Now = RTTimeMilliTS();
676 uint64_t cMsElapsed = u64Now - uMsStart;
677 if (cMsElapsed >= pProcess->StartupInfo.uTimeLimitMS)
678 {
679 fProcessTimedOut = true;
680 if ( MsProcessKilled == UINT64_MAX
681 || u64Now - MsProcessKilled > 1000)
682 {
683 if (u64Now - MsProcessKilled > 20*60*1000)
684 break; /* Give up after 20 mins. */
685
686 VBoxServiceVerbose(3, "[PID %RU32]: Timed out (%RU64ms elapsed > %RU32ms timeout), killing ...\n",
687 pProcess->uPID, cMsElapsed, pProcess->StartupInfo.uTimeLimitMS);
688
689 rc2 = RTProcTerminate(pProcess->hProcess);
690 VBoxServiceVerbose(3, "[PID %RU32]: Killing process resulted in rc=%Rrc\n",
691 pProcess->uPID, rc2);
692 MsProcessKilled = u64Now;
693 continue;
694 }
695 cMilliesLeft = 10000;
696 }
697 else
698 cMilliesLeft = pProcess->StartupInfo.uTimeLimitMS - (uint32_t)cMsElapsed;
699 }
700
701 /* Reset the polling interval since we've done all pending work. */
702 cMsPollCur = fProcessAlive
703 ? cMsPollBase
704 : RT_MS_1MIN;
705 if (cMilliesLeft < cMsPollCur)
706 cMsPollCur = cMilliesLeft;
707 }
708
709 VBoxServiceVerbose(3, "[PID %RU32]: Loop ended: rc=%Rrc, fShutdown=%RTbool, fProcessAlive=%RTbool, fProcessTimedOut=%RTbool, MsProcessKilled=%RU64\n",
710 pProcess->uPID, rc, pProcess->fShutdown, fProcessAlive, fProcessTimedOut, MsProcessKilled, MsProcessKilled);
711 VBoxServiceVerbose(3, "[PID %RU32]: *phStdOutR=%s, *phStdErrR=%s\n",
712 pProcess->uPID,
713 pProcess->hPipeStdOutR == NIL_RTPIPE ? "closed" : "open",
714 pProcess->hPipeStdErrR == NIL_RTPIPE ? "closed" : "open");
715
716 /* Signal that this thread is in progress of shutting down. */
717 ASMAtomicXchgBool(&pProcess->fShutdown, true);
718
719 /*
720 * Try killing the process if it's still alive at this point.
721 */
722 if (fProcessAlive)
723 {
724 if (MsProcessKilled == UINT64_MAX)
725 {
726 VBoxServiceVerbose(2, "[PID %RU32]: Is still alive and not killed yet\n",
727 pProcess->uPID);
728
729 MsProcessKilled = RTTimeMilliTS();
730 rc2 = RTProcTerminate(pProcess->hProcess);
731 if (rc2 == VERR_NOT_FOUND)
732 {
733 fProcessAlive = false;
734 }
735 else if (RT_FAILURE(rc2))
736 VBoxServiceError("PID %RU32]: Killing process failed with rc=%Rrc\n",
737 pProcess->uPID, rc2);
738 RTThreadSleep(500);
739 }
740
741 for (int i = 0; i < 10 && fProcessAlive; i++)
742 {
743 VBoxServiceVerbose(4, "[PID %RU32]: Kill attempt %d/10: Waiting to exit ...\n",
744 pProcess->uPID, i + 1);
745 rc2 = RTProcWait(pProcess->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
746 if (RT_SUCCESS(rc2))
747 {
748 VBoxServiceVerbose(4, "[PID %RU32]: Kill attempt %d/10: Exited\n",
749 pProcess->uPID, i + 1);
750 fProcessAlive = false;
751 break;
752 }
753 if (i >= 5)
754 {
755 VBoxServiceVerbose(4, "[PID %RU32]: Kill attempt %d/10: Trying to terminate ...\n",
756 pProcess->uPID, i + 1);
757 rc2 = RTProcTerminate(pProcess->hProcess);
758 if ( RT_FAILURE(rc)
759 && rc2 != VERR_NOT_FOUND)
760 VBoxServiceError("PID %RU32]: Killing process failed with rc=%Rrc\n",
761 pProcess->uPID, rc2);
762 }
763 RTThreadSleep(i >= 5 ? 2000 : 500);
764 }
765
766 if (fProcessAlive)
767 VBoxServiceError("[PID %RU32]: Could not be killed\n", pProcess->uPID);
768 }
769
770 /*
771 * Shutdown procedure:
772 * - Set the pProcess->fShutdown indicator to let others know we're
773 * not accepting any new requests anymore.
774 * - After setting the indicator, try to process all outstanding
775 * requests to make sure they're getting delivered.
776 *
777 * Note: After removing the process from the session's list it's not
778 * even possible for the session anymore to control what's
779 * happening to this thread, so be careful and don't mess it up.
780 */
781
782 rc2 = gstcntlProcessLock(pProcess);
783 if (RT_SUCCESS(rc2))
784 {
785 VBoxServiceVerbose(3, "[PID %RU32]: Processing outstanding requests ...\n",
786 pProcess->uPID);
787
788 /* Process all pending requests (but don't wait for new ones). */
789 Assert(pProcess->hReqQueue != NIL_RTREQQUEUE);
790 rc2 = RTReqQueueProcess(pProcess->hReqQueue, 0 /* No timeout */);
791 if ( RT_FAILURE(rc2)
792 && rc2 != VERR_TIMEOUT)
793 VBoxServiceError("[PID %RU32]: Processing outstanding requests failed with with rc=%Rrc\n",
794 pProcess->uPID, rc2);
795
796 VBoxServiceVerbose(3, "[PID %RU32]: Processing outstanding requests done, rc=%Rrc\n",
797 pProcess->uPID, rc2);
798
799 rc2 = gstcntlProcessUnlock(pProcess);
800 AssertRC(rc2);
801 }
802
803 /*
804 * If we don't have a client problem (RT_FAILURE(rc)) we'll reply to the
805 * clients exec packet now.
806 */
807 if (RT_SUCCESS(rc))
808 {
809 uint32_t uStatus = PROC_STS_UNDEFINED;
810 uint32_t uFlags = 0;
811
812 if ( fProcessTimedOut && !fProcessAlive && MsProcessKilled != UINT64_MAX)
813 {
814 VBoxServiceVerbose(3, "[PID %RU32]: Timed out and got killed\n",
815 pProcess->uPID);
816 uStatus = PROC_STS_TOK;
817 }
818 else if (fProcessTimedOut && fProcessAlive && MsProcessKilled != UINT64_MAX)
819 {
820 VBoxServiceVerbose(3, "[PID %RU32]: Timed out and did *not* get killed\n",
821 pProcess->uPID);
822 uStatus = PROC_STS_TOA;
823 }
824 else if (pProcess->fShutdown && (fProcessAlive || MsProcessKilled != UINT64_MAX))
825 {
826 VBoxServiceVerbose(3, "[PID %RU32]: Got terminated because system/service is about to shutdown\n",
827 pProcess->uPID);
828 uStatus = PROC_STS_DWN; /* Service is stopping, process was killed. */
829 uFlags = pProcess->StartupInfo.uFlags; /* Return handed-in execution flags back to the host. */
830 }
831 else if (fProcessAlive)
832 {
833 VBoxServiceError("[PID %RU32]: Is alive when it should not!\n",
834 pProcess->uPID);
835 }
836 else if (MsProcessKilled != UINT64_MAX)
837 {
838 VBoxServiceError("[PID %RU32]: Has been killed when it should not!\n",
839 pProcess->uPID);
840 }
841 else if (ProcessStatus.enmReason == RTPROCEXITREASON_NORMAL)
842 {
843 VBoxServiceVerbose(3, "[PID %RU32]: Ended with RTPROCEXITREASON_NORMAL (Exit code: %d)\n",
844 pProcess->uPID, ProcessStatus.iStatus);
845
846 uStatus = PROC_STS_TEN;
847 uFlags = ProcessStatus.iStatus;
848 }
849 else if (ProcessStatus.enmReason == RTPROCEXITREASON_SIGNAL)
850 {
851 VBoxServiceVerbose(3, "[PID %RU32]: Ended with RTPROCEXITREASON_SIGNAL (Signal: %u)\n",
852 pProcess->uPID, ProcessStatus.iStatus);
853
854 uStatus = PROC_STS_TES;
855 uFlags = ProcessStatus.iStatus;
856 }
857 else if (ProcessStatus.enmReason == RTPROCEXITREASON_ABEND)
858 {
859 /* ProcessStatus.iStatus will be undefined. */
860 VBoxServiceVerbose(3, "[PID %RU32]: Ended with RTPROCEXITREASON_ABEND\n",
861 pProcess->uPID);
862
863 uStatus = PROC_STS_TEA;
864 uFlags = ProcessStatus.iStatus;
865 }
866 else
867 VBoxServiceVerbose(1, "[PID %RU32]: Handling process status %u not implemented\n",
868 pProcess->uPID, ProcessStatus.enmReason);
869
870 VBoxServiceVerbose(2, "[PID %RU32]: Ended, ClientID=%u, CID=%u, Status=%u, Flags=0x%x\n",
871 pProcess->uPID, pProcess->uClientID, pProcess->uContextID, uStatus, uFlags);
872
873 VBGLR3GUESTCTRLCMDCTX ctxEnd = { pProcess->uClientID, pProcess->uContextID };
874 rc2 = VbglR3GuestCtrlProcCbStatus(&ctxEnd,
875 pProcess->uPID, uStatus, uFlags,
876 NULL /* pvData */, 0 /* cbData */);
877 if ( RT_FAILURE(rc2)
878 && rc2 == VERR_NOT_FOUND)
879 VBoxServiceError("[PID %RU32]: Error reporting final status to host; rc=%Rrc\n",
880 pProcess->uPID, rc2);
881 }
882
883 VBoxServiceVerbose(3, "[PID %RU32]: Process loop returned with rc=%Rrc\n",
884 pProcess->uPID, rc);
885 return rc;
886}
887
888
889/**
890 * Initializes a pipe's handle and pipe object.
891 *
892 * @return IPRT status code.
893 * @param ph The pipe's handle to initialize.
894 * @param phPipe The pipe's object to initialize.
895 */
896static int gstcntlProcessInitPipe(PRTHANDLE ph, PRTPIPE phPipe)
897{
898 AssertPtrReturn(ph, VERR_INVALID_PARAMETER);
899 AssertPtrReturn(phPipe, VERR_INVALID_PARAMETER);
900
901 ph->enmType = RTHANDLETYPE_PIPE;
902 ph->u.hPipe = NIL_RTPIPE;
903 *phPipe = NIL_RTPIPE;
904
905 return VINF_SUCCESS;
906}
907
908
909/**
910 * Sets up the redirection / pipe / nothing for one of the standard handles.
911 *
912 * @returns IPRT status code. No client replies made.
913 * @param pszHowTo How to set up this standard handle.
914 * @param fd Which standard handle it is (0 == stdin, 1 ==
915 * stdout, 2 == stderr).
916 * @param ph The generic handle that @a pph may be set
917 * pointing to. Always set.
918 * @param pph Pointer to the RTProcCreateExec argument.
919 * Always set.
920 * @param phPipe Where to return the end of the pipe that we
921 * should service.
922 */
923static int gstcntlProcessSetupPipe(const char *pszHowTo, int fd,
924 PRTHANDLE ph, PRTHANDLE *pph, PRTPIPE phPipe)
925{
926 AssertPtrReturn(ph, VERR_INVALID_POINTER);
927 AssertPtrReturn(pph, VERR_INVALID_POINTER);
928 AssertPtrReturn(phPipe, VERR_INVALID_POINTER);
929
930 int rc;
931
932 ph->enmType = RTHANDLETYPE_PIPE;
933 ph->u.hPipe = NIL_RTPIPE;
934 *pph = NULL;
935 *phPipe = NIL_RTPIPE;
936
937 if (!strcmp(pszHowTo, "|"))
938 {
939 /*
940 * Setup a pipe for forwarding to/from the client.
941 * The ph union struct will be filled with a pipe read/write handle
942 * to represent the "other" end to phPipe.
943 */
944 if (fd == 0) /* stdin? */
945 {
946 /* Connect a wrtie pipe specified by phPipe to stdin. */
947 rc = RTPipeCreate(&ph->u.hPipe, phPipe, RTPIPE_C_INHERIT_READ);
948 }
949 else /* stdout or stderr? */
950 {
951 /* Connect a read pipe specified by phPipe to stdout or stderr. */
952 rc = RTPipeCreate(phPipe, &ph->u.hPipe, RTPIPE_C_INHERIT_WRITE);
953 }
954
955 if (RT_FAILURE(rc))
956 return rc;
957
958 ph->enmType = RTHANDLETYPE_PIPE;
959 *pph = ph;
960 }
961 else if (!strcmp(pszHowTo, "/dev/null"))
962 {
963 /*
964 * Redirect to/from /dev/null.
965 */
966 RTFILE hFile;
967 rc = RTFileOpenBitBucket(&hFile, fd == 0 ? RTFILE_O_READ : RTFILE_O_WRITE);
968 if (RT_FAILURE(rc))
969 return rc;
970
971 ph->enmType = RTHANDLETYPE_FILE;
972 ph->u.hFile = hFile;
973 *pph = ph;
974 }
975 else /* Add other piping stuff here. */
976 rc = VINF_SUCCESS; /* Same as parent (us). */
977
978 return rc;
979}
980
981
982/**
983 * Expands a file name / path to its real content. This only works on Windows
984 * for now (e.g. translating "%TEMP%\foo.exe" to "C:\Windows\Temp" when starting
985 * with system / administrative rights).
986 *
987 * @return IPRT status code.
988 * @param pszPath Path to resolve.
989 * @param pszExpanded Pointer to string to store the resolved path in.
990 * @param cbExpanded Size (in bytes) of string to store the resolved path.
991 */
992static int gstcntlProcessMakeFullPath(const char *pszPath, char *pszExpanded, size_t cbExpanded)
993{
994 int rc = VINF_SUCCESS;
995#ifdef RT_OS_WINDOWS
996 if (!ExpandEnvironmentStrings(pszPath, pszExpanded, cbExpanded))
997 rc = RTErrConvertFromWin32(GetLastError());
998#else
999 /* No expansion for non-Windows yet. */
1000 rc = RTStrCopy(pszExpanded, cbExpanded, pszPath);
1001#endif
1002#ifdef DEBUG
1003 VBoxServiceVerbose(3, "VBoxServiceControlExecMakeFullPath: %s -> %s\n",
1004 pszPath, pszExpanded);
1005#endif
1006 return rc;
1007}
1008
1009
1010/**
1011 * Resolves the full path of a specified executable name. This function also
1012 * resolves internal VBoxService tools to its appropriate executable path + name if
1013 * VBOXSERVICE_NAME is specified as pszFileName.
1014 *
1015 * @return IPRT status code.
1016 * @param pszFileName File name to resolve.
1017 * @param pszResolved Pointer to a string where the resolved file name will be stored.
1018 * @param cbResolved Size (in bytes) of resolved file name string.
1019 */
1020static int gstcntlProcessResolveExecutable(const char *pszFileName,
1021 char *pszResolved, size_t cbResolved)
1022{
1023 AssertPtrReturn(pszFileName, VERR_INVALID_POINTER);
1024 AssertPtrReturn(pszResolved, VERR_INVALID_POINTER);
1025 AssertReturn(cbResolved, VERR_INVALID_PARAMETER);
1026
1027 int rc = VINF_SUCCESS;
1028
1029 char szPathToResolve[RTPATH_MAX];
1030 if ( (g_pszProgName && (RTStrICmp(pszFileName, g_pszProgName) == 0))
1031 || !RTStrICmp(pszFileName, VBOXSERVICE_NAME))
1032 {
1033 /* Resolve executable name of this process. */
1034 if (!RTProcGetExecutablePath(szPathToResolve, sizeof(szPathToResolve)))
1035 rc = VERR_FILE_NOT_FOUND;
1036 }
1037 else
1038 {
1039 /* Take the raw argument to resolve. */
1040 rc = RTStrCopy(szPathToResolve, sizeof(szPathToResolve), pszFileName);
1041 }
1042
1043 if (RT_SUCCESS(rc))
1044 {
1045 rc = gstcntlProcessMakeFullPath(szPathToResolve, pszResolved, cbResolved);
1046 if (RT_SUCCESS(rc))
1047 VBoxServiceVerbose(3, "Looked up executable: %s -> %s\n",
1048 pszFileName, pszResolved);
1049 }
1050
1051 if (RT_FAILURE(rc))
1052 VBoxServiceError("Failed to lookup executable \"%s\" with rc=%Rrc\n",
1053 pszFileName, rc);
1054 return rc;
1055}
1056
1057
1058/**
1059 * Constructs the argv command line by resolving environment variables
1060 * and relative paths.
1061 *
1062 * @return IPRT status code.
1063 * @param pszArgv0 First argument (argv0), either original or modified version. Optional.
1064 * @param papszArgs Original argv command line from the host, starting at argv[1].
1065 * @param ppapszArgv Pointer to a pointer with the new argv command line.
1066 * Needs to be freed with RTGetOptArgvFree.
1067 */
1068static int gstcntlProcessAllocateArgv(const char *pszArgv0,
1069 const char * const *papszArgs,
1070 bool fExpandArgs, char ***ppapszArgv)
1071{
1072 AssertPtrReturn(ppapszArgv, VERR_INVALID_POINTER);
1073
1074 VBoxServiceVerbose(3, "GstCntlProcessPrepareArgv: pszArgv0=%p, papszArgs=%p, fExpandArgs=%RTbool, ppapszArgv=%p\n",
1075 pszArgv0, papszArgs, fExpandArgs, ppapszArgv);
1076
1077 int rc = VINF_SUCCESS;
1078 uint32_t cArgs;
1079 for (cArgs = 0; papszArgs[cArgs]; cArgs++)
1080 {
1081 if (cArgs >= UINT32_MAX - 2)
1082 return VERR_BUFFER_OVERFLOW;
1083 }
1084
1085 /* Allocate new argv vector (adding + 2 for argv0 + termination). */
1086 size_t cbSize = (cArgs + 2) * sizeof(char*);
1087 char **papszNewArgv = (char**)RTMemAlloc(cbSize);
1088 if (!papszNewArgv)
1089 return VERR_NO_MEMORY;
1090
1091#ifdef DEBUG
1092 VBoxServiceVerbose(3, "GstCntlProcessAllocateArgv: cbSize=%RU32, cArgs=%RU32\n",
1093 cbSize, cArgs);
1094#endif
1095
1096 size_t i = 0; /* Keep the argument counter in scope for cleaning up on failure. */
1097
1098 rc = RTStrDupEx(&papszNewArgv[0], pszArgv0);
1099 if (RT_SUCCESS(rc))
1100 {
1101 for (; i < cArgs; i++)
1102 {
1103 char *pszArg;
1104#if 0 /* Arguments expansion -- untested. */
1105 if (fExpandArgs)
1106 {
1107 /* According to MSDN the limit on older Windows version is 32K, whereas
1108 * Vista+ there are no limits anymore. We still stick to 4K. */
1109 char szExpanded[_4K];
1110# ifdef RT_OS_WINDOWS
1111 if (!ExpandEnvironmentStrings(papszArgs[i], szExpanded, sizeof(szExpanded)))
1112 rc = RTErrConvertFromWin32(GetLastError());
1113# else
1114 /* No expansion for non-Windows yet. */
1115 rc = RTStrCopy(papszArgs[i], sizeof(szExpanded), szExpanded);
1116# endif
1117 if (RT_SUCCESS(rc))
1118 rc = RTStrDupEx(&pszArg, szExpanded);
1119 }
1120 else
1121#endif
1122 rc = RTStrDupEx(&pszArg, papszArgs[i]);
1123
1124 if (RT_FAILURE(rc))
1125 break;
1126
1127 papszNewArgv[i + 1] = pszArg;
1128 }
1129
1130 if (RT_SUCCESS(rc))
1131 {
1132 /* Terminate array. */
1133 papszNewArgv[cArgs + 1] = NULL;
1134
1135 *ppapszArgv = papszNewArgv;
1136 }
1137 }
1138
1139 if (RT_FAILURE(rc))
1140 {
1141 for (i; i > 0; i--)
1142 RTStrFree(papszNewArgv[i]);
1143 RTMemFree(papszNewArgv);
1144 }
1145
1146 return rc;
1147}
1148
1149
1150/**
1151 * Assigns a valid PID to a guest control thread and also checks if there already was
1152 * another (stale) guest process which was using that PID before and destroys it.
1153 *
1154 * @return IPRT status code.
1155 * @param pProcess Process to assign PID to.
1156 * @param uPID PID to assign to the specified guest control execution thread.
1157 */
1158int gstcntlProcessAssignPID(PVBOXSERVICECTRLPROCESS pProcess, uint32_t uPID)
1159{
1160 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1161 AssertReturn(uPID, VERR_INVALID_PARAMETER);
1162
1163 AssertPtr(pProcess->pSession);
1164 int rc = RTCritSectEnter(&pProcess->pSession->CritSect);
1165 if (RT_SUCCESS(rc))
1166 {
1167 /* Search old threads using the desired PID and shut them down completely -- it's
1168 * not used anymore. */
1169 PVBOXSERVICECTRLPROCESS pProcessCur;
1170 bool fTryAgain;
1171 do
1172 {
1173 fTryAgain = false;
1174 RTListForEach(&pProcess->pSession->lstProcesses, pProcessCur, VBOXSERVICECTRLPROCESS, Node)
1175 {
1176 if (pProcessCur->uPID == uPID)
1177 {
1178 Assert(pProcessCur != pProcess); /* can't happen */
1179 uint32_t uTriedPID = uPID;
1180 uPID += 391939;
1181 VBoxServiceVerbose(2, "PID %RU32 was used before (process %p), trying again with %RU32 ...\n",
1182 uTriedPID, pProcessCur, uPID);
1183 fTryAgain = true;
1184 break;
1185 }
1186 }
1187 } while (fTryAgain);
1188
1189 /* Assign PID to current thread. */
1190 pProcess->uPID = uPID;
1191
1192 rc = RTCritSectLeave(&pProcess->pSession->CritSect);
1193 AssertRC(rc);
1194 }
1195
1196 return rc;
1197}
1198
1199
1200void gstcntlProcessFreeArgv(char **papszArgv)
1201{
1202 if (papszArgv)
1203 {
1204 size_t i = 0;
1205 while (papszArgv[i])
1206 RTStrFree(papszArgv[i++]);
1207 RTMemFree(papszArgv);
1208 }
1209}
1210
1211
1212/**
1213 * Helper function to create/start a process on the guest.
1214 *
1215 * @return IPRT status code.
1216 * @param pszExec Full qualified path of process to start (without arguments).
1217 * @param papszArgs Pointer to array of command line arguments.
1218 * @param hEnv Handle to environment block to use.
1219 * @param fFlags Process execution flags.
1220 * @param phStdIn Handle for the process' stdin pipe.
1221 * @param phStdOut Handle for the process' stdout pipe.
1222 * @param phStdErr Handle for the process' stderr pipe.
1223 * @param pszAsUser User name (account) to start the process under.
1224 * @param pszPassword Password of the specified user.
1225 * @param phProcess Pointer which will receive the process handle after
1226 * successful process start.
1227 */
1228static int gstcntlProcessCreateProcess(const char *pszExec, const char * const *papszArgs, RTENV hEnv, uint32_t fFlags,
1229 PCRTHANDLE phStdIn, PCRTHANDLE phStdOut, PCRTHANDLE phStdErr, const char *pszAsUser,
1230 const char *pszPassword, PRTPROCESS phProcess)
1231{
1232 AssertPtrReturn(pszExec, VERR_INVALID_PARAMETER);
1233 AssertPtrReturn(papszArgs, VERR_INVALID_PARAMETER);
1234 AssertPtrReturn(phProcess, VERR_INVALID_PARAMETER);
1235
1236 int rc = VINF_SUCCESS;
1237 char szExecExp[RTPATH_MAX];
1238
1239 /* Do we need to expand environment variables in arguments? */
1240 bool fExpandArgs = (fFlags & EXECUTEPROCESSFLAG_EXPAND_ARGUMENTS) ? true : false;
1241
1242#ifdef RT_OS_WINDOWS
1243 /*
1244 * If sysprep should be executed do this in the context of VBoxService, which
1245 * (usually, if started by SCM) has administrator rights. Because of that a UI
1246 * won't be shown (doesn't have a desktop).
1247 */
1248 if (!RTStrICmp(pszExec, "sysprep"))
1249 {
1250 /* Use a predefined sysprep path as default. */
1251 char szSysprepCmd[RTPATH_MAX] = "C:\\sysprep\\sysprep.exe";
1252 /** @todo Check digital signature of file above before executing it? */
1253
1254 /*
1255 * On Windows Vista (and up) sysprep is located in "system32\\Sysprep\\sysprep.exe",
1256 * so detect the OS and use a different path.
1257 */
1258 OSVERSIONINFOEX OSInfoEx;
1259 RT_ZERO(OSInfoEx);
1260 OSInfoEx.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
1261 BOOL fRet = GetVersionEx((LPOSVERSIONINFO) &OSInfoEx);
1262 if ( fRet
1263 && OSInfoEx.dwPlatformId == VER_PLATFORM_WIN32_NT
1264 && OSInfoEx.dwMajorVersion >= 6 /* Vista or later */)
1265 {
1266 rc = RTEnvGetEx(RTENV_DEFAULT, "windir", szSysprepCmd, sizeof(szSysprepCmd), NULL);
1267#ifndef RT_ARCH_AMD64
1268 /* Don't execute 64-bit sysprep from a 32-bit service host! */
1269 char szSysWow64[RTPATH_MAX];
1270 if (RTStrPrintf(szSysWow64, sizeof(szSysWow64), "%s", szSysprepCmd))
1271 {
1272 rc = RTPathAppend(szSysWow64, sizeof(szSysWow64), "SysWow64");
1273 AssertRC(rc);
1274 }
1275 if ( RT_SUCCESS(rc)
1276 && RTPathExists(szSysWow64))
1277 VBoxServiceVerbose(0, "Warning: This service is 32-bit; could not execute sysprep on 64-bit OS!\n");
1278#endif
1279 if (RT_SUCCESS(rc))
1280 rc = RTPathAppend(szSysprepCmd, sizeof(szSysprepCmd), "system32\\Sysprep\\sysprep.exe");
1281 if (RT_SUCCESS(rc))
1282 RTPathChangeToDosSlashes(szSysprepCmd, false /* No forcing necessary */);
1283
1284 if (RT_FAILURE(rc))
1285 VBoxServiceError("Failed to detect sysrep location, rc=%Rrc\n", rc);
1286 }
1287 else if (!fRet)
1288 VBoxServiceError("Failed to retrieve OS information, last error=%ld\n", GetLastError());
1289
1290 VBoxServiceVerbose(3, "Sysprep executable is: %s\n", szSysprepCmd);
1291
1292 if (RT_SUCCESS(rc))
1293 {
1294 char **papszArgsExp;
1295 rc = gstcntlProcessAllocateArgv(szSysprepCmd /* argv0 */, papszArgs,
1296 fExpandArgs, &papszArgsExp);
1297 if (RT_SUCCESS(rc))
1298 {
1299 /* As we don't specify credentials for the sysprep process, it will
1300 * run under behalf of the account VBoxService was started under, most
1301 * likely local system. */
1302 rc = RTProcCreateEx(szSysprepCmd, papszArgsExp, hEnv, 0 /* fFlags */,
1303 phStdIn, phStdOut, phStdErr, NULL /* pszAsUser */,
1304 NULL /* pszPassword */, phProcess);
1305 gstcntlProcessFreeArgv(papszArgsExp);
1306 }
1307 }
1308
1309 if (RT_FAILURE(rc))
1310 VBoxServiceVerbose(3, "Starting sysprep returned rc=%Rrc\n", rc);
1311
1312 return rc;
1313 }
1314#endif /* RT_OS_WINDOWS */
1315
1316#ifdef VBOXSERVICE_TOOLBOX
1317 if (RTStrStr(pszExec, "vbox_") == pszExec)
1318 {
1319 /* We want to use the internal toolbox (all internal
1320 * tools are starting with "vbox_" (e.g. "vbox_cat"). */
1321 rc = gstcntlProcessResolveExecutable(VBOXSERVICE_NAME, szExecExp, sizeof(szExecExp));
1322 }
1323 else
1324 {
1325#endif
1326 /*
1327 * Do the environment variables expansion on executable and arguments.
1328 */
1329 rc = gstcntlProcessResolveExecutable(pszExec, szExecExp, sizeof(szExecExp));
1330#ifdef VBOXSERVICE_TOOLBOX
1331 }
1332#endif
1333 if (RT_SUCCESS(rc))
1334 {
1335 char **papszArgsExp;
1336 rc = gstcntlProcessAllocateArgv(pszExec /* Always use the unmodified executable name as argv0. */,
1337 papszArgs /* Append the rest of the argument vector (if any). */,
1338 fExpandArgs, &papszArgsExp);
1339 if (RT_FAILURE(rc))
1340 {
1341 /* Don't print any arguments -- may contain passwords or other sensible data! */
1342 VBoxServiceError("Could not prepare arguments, rc=%Rrc\n", rc);
1343 }
1344 else
1345 {
1346 uint32_t uProcFlags = 0;
1347 if (fFlags)
1348 {
1349 if (fFlags & EXECUTEPROCESSFLAG_HIDDEN)
1350 uProcFlags |= RTPROC_FLAGS_HIDDEN;
1351 if (fFlags & EXECUTEPROCESSFLAG_NO_PROFILE)
1352 uProcFlags |= RTPROC_FLAGS_NO_PROFILE;
1353 }
1354
1355 /* If no user name specified run with current credentials (e.g.
1356 * full service/system rights). This is prohibited via official Main API!
1357 *
1358 * Otherwise use the RTPROC_FLAGS_SERVICE to use some special authentication
1359 * code (at least on Windows) for running processes as different users
1360 * started from our system service. */
1361 if (pszAsUser && *pszAsUser)
1362 uProcFlags |= RTPROC_FLAGS_SERVICE;
1363#ifdef DEBUG
1364 VBoxServiceVerbose(3, "Command: %s\n", szExecExp);
1365 for (size_t i = 0; papszArgsExp[i]; i++)
1366 VBoxServiceVerbose(3, "\targv[%ld]: %s\n", i, papszArgsExp[i]);
1367#endif
1368 VBoxServiceVerbose(3, "Starting process \"%s\" ...\n", szExecExp);
1369
1370 /* Do normal execution. */
1371 rc = RTProcCreateEx(szExecExp, papszArgsExp, hEnv, uProcFlags,
1372 phStdIn, phStdOut, phStdErr,
1373 pszAsUser && *pszAsUser ? pszAsUser : NULL,
1374 pszPassword && *pszPassword ? pszPassword : NULL,
1375 phProcess);
1376
1377 VBoxServiceVerbose(3, "Starting process \"%s\" returned rc=%Rrc\n",
1378 szExecExp, rc);
1379
1380 gstcntlProcessFreeArgv(papszArgsExp);
1381 }
1382 }
1383 return rc;
1384}
1385
1386
1387#ifdef DEBUG
1388static int gstcntlProcessDumpToFile(const char *pszFileName, void *pvBuf, size_t cbBuf)
1389{
1390 AssertPtrReturn(pszFileName, VERR_INVALID_POINTER);
1391 AssertPtrReturn(pvBuf, VERR_INVALID_POINTER);
1392
1393 if (!cbBuf)
1394 return VINF_SUCCESS;
1395
1396 char szFile[RTPATH_MAX];
1397
1398 int rc = RTPathTemp(szFile, sizeof(szFile));
1399 if (RT_SUCCESS(rc))
1400 rc = RTPathAppend(szFile, sizeof(szFile), pszFileName);
1401
1402 if (RT_SUCCESS(rc))
1403 {
1404 VBoxServiceVerbose(4, "Dumping %ld bytes to \"%s\"\n", cbBuf, szFile);
1405
1406 RTFILE fh;
1407 rc = RTFileOpen(&fh, szFile, RTFILE_O_OPEN_CREATE | RTFILE_O_WRITE | RTFILE_O_DENY_WRITE);
1408 if (RT_SUCCESS(rc))
1409 {
1410 rc = RTFileWrite(fh, pvBuf, cbBuf, NULL /* pcbWritten */);
1411 RTFileClose(fh);
1412 }
1413 }
1414
1415 return rc;
1416}
1417#endif
1418
1419
1420/**
1421 * The actual worker routine (loop) for a started guest process.
1422 *
1423 * @return IPRT status code.
1424 * @param PVBOXSERVICECTRLPROCESS Guest process.
1425 */
1426static int gstcntlProcessProcessWorker(PVBOXSERVICECTRLPROCESS pProcess)
1427{
1428 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1429 VBoxServiceVerbose(3, "Thread of process pThread=0x%p = \"%s\" started\n",
1430 pProcess, pProcess->StartupInfo.szCmd);
1431
1432 int rc = VbglR3GuestCtrlConnect(&pProcess->uClientID);
1433 if (RT_FAILURE(rc))
1434 {
1435 VBoxServiceError("Process thread \"%s\" (%p) failed to connect to the guest control service, rc=%Rrc\n",
1436 pProcess->StartupInfo.szCmd, pProcess, rc);
1437 RTThreadUserSignal(RTThreadSelf());
1438 return rc;
1439 }
1440
1441 VBoxServiceVerbose(3, "Guest process \"%s\" got client ID=%u, flags=0x%x\n",
1442 pProcess->StartupInfo.szCmd, pProcess->uClientID, pProcess->StartupInfo.uFlags);
1443
1444 /* The process thread is not interested in receiving any commands;
1445 * tell the host service. */
1446 rc = VbglR3GuestCtrlMsgFilterSet(pProcess->uClientID, 0 /* Skip all */,
1447 0 /* Filter mask to add */, 0 /* Filter mask to remove */);
1448 if (RT_FAILURE(rc))
1449 {
1450 VBoxServiceError("Unable to set message filter, rc=%Rrc\n", rc);
1451 /* Non-critical. */
1452 }
1453
1454 rc = GstCntlSessionProcessAdd(pProcess->pSession, pProcess);
1455 if (RT_FAILURE(rc))
1456 {
1457 VBoxServiceError("Errorwhile adding guest process \"%s\" (%p) to session process list, rc=%Rrc\n",
1458 pProcess->StartupInfo.szCmd, pProcess, rc);
1459 RTThreadUserSignal(RTThreadSelf());
1460 return rc;
1461 }
1462
1463 bool fSignalled = false; /* Indicator whether we signalled the thread user event already. */
1464
1465 /*
1466 * Prepare argument list.
1467 */
1468 char **papszArgs;
1469 uint32_t uNumArgs = 0; /* Initialize in case of RTGetOptArgvFromString() is failing ... */
1470 rc = RTGetOptArgvFromString(&papszArgs, (int*)&uNumArgs,
1471 (pProcess->StartupInfo.uNumArgs > 0) ? pProcess->StartupInfo.szArgs : "", NULL);
1472 /* Did we get the same result? */
1473 Assert(pProcess->StartupInfo.uNumArgs == uNumArgs);
1474
1475 /*
1476 * Prepare environment variables list.
1477 */
1478 char **papszEnv = NULL;
1479 uint32_t uNumEnvVars = 0; /* Initialize in case of failing ... */
1480 if (RT_SUCCESS(rc))
1481 {
1482 /* Prepare environment list. */
1483 if (pProcess->StartupInfo.uNumEnvVars)
1484 {
1485 papszEnv = (char **)RTMemAlloc(pProcess->StartupInfo.uNumEnvVars * sizeof(char*));
1486 AssertPtr(papszEnv);
1487 uNumEnvVars = pProcess->StartupInfo.uNumEnvVars;
1488
1489 const char *pszCur = pProcess->StartupInfo.szEnv;
1490 uint32_t i = 0;
1491 uint32_t cbLen = 0;
1492 while (cbLen < pProcess->StartupInfo.cbEnv)
1493 {
1494 /* sanity check */
1495 if (i >= pProcess->StartupInfo.uNumEnvVars)
1496 {
1497 rc = VERR_INVALID_PARAMETER;
1498 break;
1499 }
1500 int cbStr = RTStrAPrintf(&papszEnv[i++], "%s", pszCur);
1501 if (cbStr < 0)
1502 {
1503 rc = VERR_NO_STR_MEMORY;
1504 break;
1505 }
1506 pszCur += cbStr + 1; /* Skip terminating '\0' */
1507 cbLen += cbStr + 1; /* Skip terminating '\0' */
1508 }
1509 Assert(i == pProcess->StartupInfo.uNumEnvVars);
1510 }
1511 }
1512
1513 /*
1514 * Create the environment.
1515 */
1516 RTENV hEnv;
1517 if (RT_SUCCESS(rc))
1518 rc = RTEnvClone(&hEnv, RTENV_DEFAULT);
1519 if (RT_SUCCESS(rc))
1520 {
1521 size_t i;
1522 for (i = 0; i < uNumEnvVars && papszEnv; i++)
1523 {
1524 rc = RTEnvPutEx(hEnv, papszEnv[i]);
1525 if (RT_FAILURE(rc))
1526 break;
1527 }
1528 if (RT_SUCCESS(rc))
1529 {
1530 /*
1531 * Setup the redirection of the standard stuff.
1532 */
1533 /** @todo consider supporting: gcc stuff.c >file 2>&1. */
1534 RTHANDLE hStdIn;
1535 PRTHANDLE phStdIn;
1536 rc = gstcntlProcessSetupPipe("|", 0 /*STDIN_FILENO*/,
1537 &hStdIn, &phStdIn, &pProcess->hPipeStdInW);
1538 if (RT_SUCCESS(rc))
1539 {
1540 RTHANDLE hStdOut;
1541 PRTHANDLE phStdOut;
1542 rc = gstcntlProcessSetupPipe( (pProcess->StartupInfo.uFlags & EXECUTEPROCESSFLAG_WAIT_STDOUT)
1543 ? "|" : "/dev/null",
1544 1 /*STDOUT_FILENO*/,
1545 &hStdOut, &phStdOut, &pProcess->hPipeStdOutR);
1546 if (RT_SUCCESS(rc))
1547 {
1548 RTHANDLE hStdErr;
1549 PRTHANDLE phStdErr;
1550 rc = gstcntlProcessSetupPipe( (pProcess->StartupInfo.uFlags & EXECUTEPROCESSFLAG_WAIT_STDERR)
1551 ? "|" : "/dev/null",
1552 2 /*STDERR_FILENO*/,
1553 &hStdErr, &phStdErr, &pProcess->hPipeStdErrR);
1554 if (RT_SUCCESS(rc))
1555 {
1556 /*
1557 * Create a poll set for the pipes and let the
1558 * transport layer add stuff to it as well.
1559 */
1560 rc = RTPollSetCreate(&pProcess->hPollSet);
1561 if (RT_SUCCESS(rc))
1562 {
1563 uint32_t uFlags = RTPOLL_EVT_ERROR;
1564#if 0
1565 /* Add reading event to pollset to get some more information. */
1566 uFlags |= RTPOLL_EVT_READ;
1567#endif
1568 /* Stdin. */
1569 if (RT_SUCCESS(rc))
1570 rc = RTPollSetAddPipe(pProcess->hPollSet,
1571 pProcess->hPipeStdInW, RTPOLL_EVT_ERROR, VBOXSERVICECTRLPIPEID_STDIN);
1572 /* Stdout. */
1573 if (RT_SUCCESS(rc))
1574 rc = RTPollSetAddPipe(pProcess->hPollSet,
1575 pProcess->hPipeStdOutR, uFlags, VBOXSERVICECTRLPIPEID_STDOUT);
1576 /* Stderr. */
1577 if (RT_SUCCESS(rc))
1578 rc = RTPollSetAddPipe(pProcess->hPollSet,
1579 pProcess->hPipeStdErrR, uFlags, VBOXSERVICECTRLPIPEID_STDERR);
1580 /* IPC notification pipe. */
1581 if (RT_SUCCESS(rc))
1582 rc = RTPipeCreate(&pProcess->hNotificationPipeR, &pProcess->hNotificationPipeW, 0 /* Flags */);
1583 if (RT_SUCCESS(rc))
1584 rc = RTPollSetAddPipe(pProcess->hPollSet,
1585 pProcess->hNotificationPipeR, RTPOLL_EVT_READ, VBOXSERVICECTRLPIPEID_IPC_NOTIFY);
1586 if (RT_SUCCESS(rc))
1587 {
1588 AssertPtr(pProcess->pSession);
1589 bool fNeedsImpersonation = !(pProcess->pSession->uFlags & VBOXSERVICECTRLSESSION_FLAG_FORK);
1590
1591 rc = gstcntlProcessCreateProcess(pProcess->StartupInfo.szCmd, papszArgs, hEnv, pProcess->StartupInfo.uFlags,
1592 phStdIn, phStdOut, phStdErr,
1593 fNeedsImpersonation ? pProcess->StartupInfo.szUser : NULL,
1594 fNeedsImpersonation ? pProcess->StartupInfo.szPassword : NULL,
1595 &pProcess->hProcess);
1596 if (RT_FAILURE(rc))
1597 VBoxServiceError("Error starting process, rc=%Rrc\n", rc);
1598 /*
1599 * Tell the session thread that it can continue
1600 * spawning guest processes. This needs to be done after the new
1601 * process has been started because otherwise signal handling
1602 * on (Open) Solaris does not work correctly (see @bugref{5068}).
1603 */
1604 int rc2 = RTThreadUserSignal(RTThreadSelf());
1605 if (RT_SUCCESS(rc))
1606 rc = rc2;
1607 fSignalled = true;
1608
1609 if (RT_SUCCESS(rc))
1610 {
1611 /*
1612 * Close the child ends of any pipes and redirected files.
1613 */
1614 rc2 = RTHandleClose(phStdIn); AssertRC(rc2);
1615 phStdIn = NULL;
1616 rc2 = RTHandleClose(phStdOut); AssertRC(rc2);
1617 phStdOut = NULL;
1618 rc2 = RTHandleClose(phStdErr); AssertRC(rc2);
1619 phStdErr = NULL;
1620
1621 /* Enter the process main loop. */
1622 rc = gstcntlProcessProcLoop(pProcess);
1623
1624 /*
1625 * The handles that are no longer in the set have
1626 * been closed by the above call in order to prevent
1627 * the guest from getting stuck accessing them.
1628 * So, NIL the handles to avoid closing them again.
1629 */
1630 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1631 VBOXSERVICECTRLPIPEID_IPC_NOTIFY, NULL)))
1632 {
1633 pProcess->hNotificationPipeR = NIL_RTPIPE;
1634 pProcess->hNotificationPipeW = NIL_RTPIPE;
1635 }
1636 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1637 VBOXSERVICECTRLPIPEID_STDERR, NULL)))
1638 pProcess->hPipeStdErrR = NIL_RTPIPE;
1639 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1640 VBOXSERVICECTRLPIPEID_STDOUT, NULL)))
1641 pProcess->hPipeStdOutR = NIL_RTPIPE;
1642 if (RT_FAILURE(RTPollSetQueryHandle(pProcess->hPollSet,
1643 VBOXSERVICECTRLPIPEID_STDIN, NULL)))
1644 pProcess->hPipeStdInW = NIL_RTPIPE;
1645 }
1646 }
1647 RTPollSetDestroy(pProcess->hPollSet);
1648
1649 RTPipeClose(pProcess->hNotificationPipeR);
1650 pProcess->hNotificationPipeR = NIL_RTPIPE;
1651 RTPipeClose(pProcess->hNotificationPipeW);
1652 pProcess->hNotificationPipeW = NIL_RTPIPE;
1653 }
1654 RTPipeClose(pProcess->hPipeStdErrR);
1655 pProcess->hPipeStdErrR = NIL_RTPIPE;
1656 RTHandleClose(phStdErr);
1657 if (phStdErr)
1658 RTHandleClose(phStdErr);
1659 }
1660 RTPipeClose(pProcess->hPipeStdOutR);
1661 pProcess->hPipeStdOutR = NIL_RTPIPE;
1662 RTHandleClose(&hStdOut);
1663 if (phStdOut)
1664 RTHandleClose(phStdOut);
1665 }
1666 RTPipeClose(pProcess->hPipeStdInW);
1667 pProcess->hPipeStdInW = NIL_RTPIPE;
1668 RTHandleClose(phStdIn);
1669 }
1670 }
1671 RTEnvDestroy(hEnv);
1672 }
1673
1674 if (pProcess->uClientID)
1675 {
1676 if (RT_FAILURE(rc))
1677 {
1678 VBGLR3GUESTCTRLCMDCTX ctx = { pProcess->uClientID, pProcess->uContextID };
1679 int rc2 = VbglR3GuestCtrlProcCbStatus(&ctx,
1680 pProcess->uPID, PROC_STS_ERROR, rc,
1681 NULL /* pvData */, 0 /* cbData */);
1682 if ( RT_FAILURE(rc2)
1683 && rc2 != VERR_NOT_FOUND)
1684 VBoxServiceError("[PID %RU32]: Could not report process failure error; rc=%Rrc (process error %Rrc)\n",
1685 pProcess->uPID, rc2, rc);
1686 }
1687
1688 /* Disconnect this client from the guest control service. This also cancels all
1689 * outstanding host requests. */
1690 VBoxServiceVerbose(3, "[PID %RU32]: Disconnecting (client ID=%u) ...\n",
1691 pProcess->uPID, pProcess->uClientID);
1692 VbglR3GuestCtrlDisconnect(pProcess->uClientID);
1693 pProcess->uClientID = 0;
1694 }
1695
1696 /* Free argument + environment variable lists. */
1697 if (uNumEnvVars)
1698 {
1699 for (uint32_t i = 0; i < uNumEnvVars; i++)
1700 RTStrFree(papszEnv[i]);
1701 RTMemFree(papszEnv);
1702 }
1703 if (uNumArgs)
1704 RTGetOptArgvFree(papszArgs);
1705
1706 /*
1707 * If something went wrong signal the user event so that others don't wait
1708 * forever on this thread.
1709 */
1710 if (RT_FAILURE(rc) && !fSignalled)
1711 RTThreadUserSignal(RTThreadSelf());
1712
1713 VBoxServiceVerbose(3, "[PID %RU32]: Thread of process \"%s\" ended with rc=%Rrc\n",
1714 pProcess->uPID, pProcess->StartupInfo.szCmd, rc);
1715
1716 /* Finally, update stopped status. */
1717 ASMAtomicXchgBool(&pProcess->fStopped, true);
1718
1719 return rc;
1720}
1721
1722
1723static int gstcntlProcessLock(PVBOXSERVICECTRLPROCESS pProcess)
1724{
1725 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1726 int rc = RTCritSectEnter(&pProcess->CritSect);
1727 AssertRC(rc);
1728 return rc;
1729}
1730
1731
1732/**
1733 * Thread main routine for a started process.
1734 *
1735 * @return IPRT status code.
1736 * @param RTTHREAD Pointer to the thread's data.
1737 * @param void* User-supplied argument pointer.
1738 *
1739 */
1740static DECLCALLBACK(int) gstcntlProcessThread(RTTHREAD ThreadSelf, void *pvUser)
1741{
1742 PVBOXSERVICECTRLPROCESS pProcess = (VBOXSERVICECTRLPROCESS*)pvUser;
1743 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1744 return gstcntlProcessProcessWorker(pProcess);
1745}
1746
1747
1748static int gstcntlProcessUnlock(PVBOXSERVICECTRLPROCESS pProcess)
1749{
1750 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1751 int rc = RTCritSectLeave(&pProcess->CritSect);
1752 AssertRC(rc);
1753 return rc;
1754}
1755
1756
1757/**
1758 * Executes (starts) a process on the guest. This causes a new thread to be created
1759 * so that this function will not block the overall program execution.
1760 *
1761 * @return IPRT status code.
1762 * @param pSession Guest session.
1763 * @param pStartupInfo Startup info.
1764 * @param uContextID Context ID to associate the process to start with.
1765
1766 */
1767int GstCntlProcessStart(const PVBOXSERVICECTRLSESSION pSession,
1768 const PVBOXSERVICECTRLPROCSTARTUPINFO pStartupInfo,
1769 uint32_t uContextID)
1770{
1771 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1772 AssertPtrReturn(pStartupInfo, VERR_INVALID_POINTER);
1773
1774 /*
1775 * Allocate new thread data and assign it to our thread list.
1776 */
1777 PVBOXSERVICECTRLPROCESS pProcess = (PVBOXSERVICECTRLPROCESS)RTMemAlloc(sizeof(VBOXSERVICECTRLPROCESS));
1778 if (!pProcess)
1779 return VERR_NO_MEMORY;
1780
1781 int rc = gstcntlProcessInit(pProcess, pSession, pStartupInfo, uContextID);
1782 if (RT_SUCCESS(rc))
1783 {
1784 static uint32_t s_uCtrlExecThread = 0;
1785 if (s_uCtrlExecThread++ == UINT32_MAX)
1786 s_uCtrlExecThread = 0; /* Wrap around to not let IPRT freak out. */
1787 rc = RTThreadCreateF(&pProcess->Thread, gstcntlProcessThread,
1788 pProcess /*pvUser*/, 0 /*cbStack*/,
1789 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctl%u", s_uCtrlExecThread);
1790 if (RT_FAILURE(rc))
1791 {
1792 VBoxServiceError("Creating thread for guest process \"%s\" failed: rc=%Rrc, pProcess=%p\n",
1793 pStartupInfo->szCmd, rc, pProcess);
1794
1795 GstCntlProcessFree(pProcess);
1796 }
1797 else
1798 {
1799 VBoxServiceVerbose(4, "Waiting for thread to initialize ...\n");
1800
1801 /* Wait for the thread to initialize. */
1802 rc = RTThreadUserWait(pProcess->Thread, 60 * 1000 /* 60 seconds max. */);
1803 AssertRC(rc);
1804 if ( ASMAtomicReadBool(&pProcess->fShutdown)
1805 || RT_FAILURE(rc))
1806 {
1807 VBoxServiceError("Thread for process \"%s\" failed to start, rc=%Rrc\n",
1808 pStartupInfo->szCmd, rc);
1809
1810 GstCntlProcessFree(pProcess);
1811 }
1812 else
1813 {
1814 ASMAtomicXchgBool(&pProcess->fStarted, true);
1815 }
1816 }
1817 }
1818
1819 return rc;
1820}
1821
1822
1823static DECLCALLBACK(int) gstcntlProcessOnInput(PVBOXSERVICECTRLPROCESS pThis,
1824 const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1825 bool fPendingClose, void *pvBuf, uint32_t cbBuf)
1826{
1827 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1828 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1829
1830 int rc;
1831
1832 size_t cbWritten = 0;
1833 if (pvBuf && cbBuf)
1834 {
1835 if (pThis->hPipeStdInW != NIL_RTPIPE)
1836 {
1837 rc = RTPipeWrite(pThis->hPipeStdInW,
1838 pvBuf, cbBuf, &cbWritten);
1839 }
1840 else
1841 rc = VINF_EOF;
1842 }
1843 else
1844 rc = VERR_INVALID_PARAMETER;
1845
1846 /*
1847 * If this is the last write + we have really have written all data
1848 * we need to close the stdin pipe on our end and remove it from
1849 * the poll set.
1850 */
1851 if ( fPendingClose
1852 && (cbBuf == cbWritten))
1853 {
1854 int rc2 = gstcntlProcessPollsetCloseInput(pThis, &pThis->hPipeStdInW);
1855 if (RT_SUCCESS(rc))
1856 rc = rc2;
1857 }
1858
1859 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status to send back to the host. */
1860 uint32_t uFlags = 0; /* No flags at the moment. */
1861 if (RT_SUCCESS(rc))
1862 {
1863 VBoxServiceVerbose(4, "[PID %RU32]: Written %RU32 bytes input, CID=%RU32, fPendingClose=%RTbool\n",
1864 pThis->uPID, cbWritten, pHostCtx->uContextID, fPendingClose);
1865 uStatus = INPUT_STS_WRITTEN;
1866 }
1867 else
1868 {
1869 if (rc == VERR_BAD_PIPE)
1870 uStatus = INPUT_STS_TERMINATED;
1871 else if (rc == VERR_BUFFER_OVERFLOW)
1872 uStatus = INPUT_STS_OVERFLOW;
1873 /* else undefined */
1874 }
1875
1876 /*
1877 * If there was an error and we did not set the host status
1878 * yet, then do it now.
1879 */
1880 if ( RT_FAILURE(rc)
1881 && uStatus == INPUT_STS_UNDEFINED)
1882 {
1883 uStatus = INPUT_STS_ERROR;
1884 uFlags = rc;
1885 }
1886 Assert(uStatus > INPUT_STS_UNDEFINED);
1887
1888#ifdef DEBUG
1889
1890#endif
1891 int rc2 = VbglR3GuestCtrlProcCbStatusInput(pHostCtx, pThis->uPID,
1892 uStatus, uFlags, (uint32_t)cbWritten);
1893 if (RT_SUCCESS(rc))
1894 rc = rc2;
1895
1896#ifdef DEBUG
1897 VBoxServiceVerbose(3, "[PID %RU32]: gstcntlProcessOnInput returned with rc=%Rrc\n",
1898 pThis->uPID, rc);
1899#endif
1900 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
1901}
1902
1903
1904static DECLCALLBACK(int) gstcntlProcessOnOutput(PVBOXSERVICECTRLPROCESS pThis,
1905 const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1906 uint32_t uHandle, uint32_t cbToRead, uint32_t uFlags)
1907{
1908 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
1909 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1910
1911 const PVBOXSERVICECTRLSESSION pSession = pThis->pSession;
1912 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1913
1914 int rc;
1915
1916 uint32_t cbBuf = cbToRead;
1917 uint8_t *pvBuf = (uint8_t *)RTMemAlloc(cbBuf);
1918 if (pvBuf)
1919 {
1920 PRTPIPE phPipe = uHandle == OUTPUT_HANDLE_ID_STDOUT
1921 ? &pThis->hPipeStdOutR
1922 : &pThis->hPipeStdErrR;
1923 AssertPtr(phPipe);
1924
1925 size_t cbRead = 0;
1926 if (*phPipe != NIL_RTPIPE)
1927 {
1928 rc = RTPipeRead(*phPipe, pvBuf, cbBuf, &cbRead);
1929 if (RT_FAILURE(rc))
1930 {
1931 RTPollSetRemove(pThis->hPollSet, uHandle == OUTPUT_HANDLE_ID_STDERR
1932 ? VBOXSERVICECTRLPIPEID_STDERR : VBOXSERVICECTRLPIPEID_STDOUT);
1933 RTPipeClose(*phPipe);
1934 *phPipe = NIL_RTPIPE;
1935 if (rc == VERR_BROKEN_PIPE)
1936 rc = VINF_EOF;
1937 }
1938 }
1939 else
1940 rc = VINF_EOF;
1941
1942#ifdef DEBUG
1943 if (RT_SUCCESS(rc))
1944 {
1945 if ( pSession->uFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT
1946 && ( uHandle == OUTPUT_HANDLE_ID_STDOUT
1947 || uHandle == OUTPUT_HANDLE_ID_STDOUT_DEPRECATED)
1948 )
1949 {
1950 char szDumpFile[RTPATH_MAX];
1951 if (!RTStrPrintf(szDumpFile, sizeof(szDumpFile), "VBoxService_Session%RU32_PID%RU32_StdOut.txt",
1952 pSession->StartupInfo.uSessionID, pThis->uPID)) rc = VERR_BUFFER_UNDERFLOW;
1953 if (RT_SUCCESS(rc))
1954 rc = gstcntlProcessDumpToFile(szDumpFile, pvBuf, cbRead);
1955 AssertRC(rc);
1956 }
1957 else if ( pSession->uFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR
1958 && uHandle == OUTPUT_HANDLE_ID_STDERR)
1959 {
1960 char szDumpFile[RTPATH_MAX];
1961 if (!RTStrPrintf(szDumpFile, sizeof(szDumpFile), "VBoxService_Session%RU32_PID%RU32_StdErr.txt",
1962 pSession->StartupInfo.uSessionID, pThis->uPID))
1963 rc = VERR_BUFFER_UNDERFLOW;
1964 if (RT_SUCCESS(rc))
1965 rc = gstcntlProcessDumpToFile(szDumpFile, pvBuf, cbRead);
1966 AssertRC(rc);
1967 }
1968 }
1969#endif
1970
1971 if (RT_SUCCESS(rc))
1972 {
1973#ifdef DEBUG
1974 VBoxServiceVerbose(3, "[PID %RU32]: Read %RU32 bytes output: uHandle=%RU32, CID=%RU32, uFlags=%x\n",
1975 pThis->uPID, cbRead, uHandle, pHostCtx->uContextID, uFlags);
1976#endif
1977 /** Note: Don't convert/touch/modify/whatever the output data here! This might be binary
1978 * data which the host needs to work with -- so just pass through all data unfiltered! */
1979
1980 /* Note: Since the context ID is unique the request *has* to be completed here,
1981 * regardless whether we got data or not! Otherwise the waiting events
1982 * on the host never will get completed! */
1983 rc = VbglR3GuestCtrlProcCbOutput(pHostCtx, pThis->uPID, uHandle, uFlags,
1984 pvBuf, cbRead);
1985 if ( RT_FAILURE(rc)
1986 && rc == VERR_NOT_FOUND) /* Not critical if guest PID is not found on the host (anymore). */
1987 rc = VINF_SUCCESS;
1988 }
1989
1990 RTMemFree(pvBuf);
1991 }
1992 else
1993 rc = VERR_NO_MEMORY;
1994
1995#ifdef DEBUG
1996 VBoxServiceVerbose(3, "[PID %RU32]: Reading output returned with rc=%Rrc\n",
1997 pThis->uPID, rc);
1998#endif
1999 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
2000}
2001
2002
2003static DECLCALLBACK(int) gstcntlProcessOnTerm(PVBOXSERVICECTRLPROCESS pThis)
2004{
2005 AssertPtrReturn(pThis, VERR_INVALID_POINTER);
2006
2007 if (!ASMAtomicXchgBool(&pThis->fShutdown, true))
2008 {
2009 VBoxServiceVerbose(3, "[PID %RU32]: Setting shutdown flag ...\n",
2010 pThis->uPID);
2011 }
2012
2013 return VINF_SUCCESS; /** @todo Return rc here as soon as RTReqQueue todos are fixed. */
2014}
2015
2016
2017int gstcntlProcessRequestExV(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2018 bool fAsync, RTMSINTERVAL uTimeoutMS, PRTREQ pReq, PFNRT pfnFunction,
2019 unsigned cArgs, va_list Args)
2020{
2021 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2022 /* pHostCtx is optional. */
2023 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2024 if (!fAsync)
2025 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2026
2027 int rc = gstcntlProcessLock(pProcess);
2028 if (RT_SUCCESS(rc))
2029 {
2030#ifdef DEBUG
2031 VBoxServiceVerbose(3, "[PID %RU32]: gstcntlProcessRequestExV fAsync=%RTbool, uTimeoutMS=%RU32, cArgs=%u\n",
2032 pProcess->uPID, fAsync, uTimeoutMS, cArgs);
2033#endif
2034 uint32_t uFlags = RTREQFLAGS_IPRT_STATUS;
2035 if (fAsync)
2036 {
2037 Assert(uTimeoutMS == 0);
2038 uFlags |= RTREQFLAGS_NO_WAIT;
2039 }
2040
2041 rc = RTReqQueueCallV(pProcess->hReqQueue, &pReq, uTimeoutMS, uFlags,
2042 pfnFunction, cArgs, Args);
2043 if (RT_SUCCESS(rc))
2044 {
2045 /* Wake up the process' notification pipe to get
2046 * the request being processed. */
2047 Assert(pProcess->hNotificationPipeW != NIL_RTPIPE);
2048 size_t cbWritten = 0;
2049 rc = RTPipeWrite(pProcess->hNotificationPipeW, "i", 1, &cbWritten);
2050 if ( RT_SUCCESS(rc)
2051 && cbWritten != 1)
2052 {
2053 VBoxServiceError("[PID %RU32]: Notification pipe got %zu bytes instead of 1\n",
2054 pProcess->uPID, cbWritten);
2055 }
2056 else if (RT_UNLIKELY(RT_FAILURE(rc)))
2057 VBoxServiceError("[PID %RU32]: Writing to notification pipe failed, rc=%Rrc\n",
2058 pProcess->uPID, rc);
2059 }
2060 else
2061 VBoxServiceError("[PID %RU32]: RTReqQueueCallV failed, rc=%Rrc\n",
2062 pProcess->uPID, rc);
2063
2064 int rc2 = gstcntlProcessUnlock(pProcess);
2065 if (RT_SUCCESS(rc))
2066 rc = rc2;
2067 }
2068
2069#ifdef DEBUG
2070 VBoxServiceVerbose(3, "[PID %RU32]: gstcntlProcessRequestExV returned rc=%Rrc\n",
2071 pProcess->uPID, rc);
2072#endif
2073 return rc;
2074}
2075
2076
2077int gstcntlProcessRequestAsync(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2078 PFNRT pfnFunction, unsigned cArgs, ...)
2079{
2080 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2081 /* pHostCtx is optional. */
2082 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2083
2084 va_list va;
2085 va_start(va, cArgs);
2086 int rc = gstcntlProcessRequestExV(pProcess, pHostCtx, true /* fAsync */, 0 /* uTimeoutMS */,
2087 NULL /* pReq */, pfnFunction, cArgs, va);
2088 va_end(va);
2089
2090 return rc;
2091}
2092
2093
2094int gstcntlProcessRequestWait(PVBOXSERVICECTRLPROCESS pProcess, const PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2095 RTMSINTERVAL uTimeoutMS, PRTREQ pReq, PFNRT pfnFunction, unsigned cArgs, ...)
2096{
2097 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2098 /* pHostCtx is optional. */
2099 AssertPtrReturn(pfnFunction, VERR_INVALID_POINTER);
2100
2101 va_list va;
2102 va_start(va, cArgs);
2103 int rc = gstcntlProcessRequestExV(pProcess, pHostCtx, false /* fAsync */, uTimeoutMS,
2104 pReq, pfnFunction, cArgs, va);
2105 va_end(va);
2106
2107 return rc;
2108}
2109
2110
2111int GstCntlProcessHandleInput(PVBOXSERVICECTRLPROCESS pProcess, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2112 bool fPendingClose, void *pvBuf, uint32_t cbBuf)
2113{
2114 if (!ASMAtomicReadBool(&pProcess->fShutdown))
2115 return gstcntlProcessRequestAsync(pProcess, pHostCtx, (PFNRT)gstcntlProcessOnInput,
2116 5 /* cArgs */, pProcess, pHostCtx, fPendingClose, pvBuf, cbBuf);
2117
2118 return gstcntlProcessOnInput(pProcess, pHostCtx, fPendingClose, pvBuf, cbBuf);
2119}
2120
2121
2122int GstCntlProcessHandleOutput(PVBOXSERVICECTRLPROCESS pProcess, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2123 uint32_t uHandle, uint32_t cbToRead, uint32_t uFlags)
2124{
2125 if (!ASMAtomicReadBool(&pProcess->fShutdown))
2126 return gstcntlProcessRequestAsync(pProcess, pHostCtx, (PFNRT)gstcntlProcessOnOutput,
2127 5 /* cArgs */, pProcess, pHostCtx, uHandle, cbToRead, uFlags);
2128
2129 return gstcntlProcessOnOutput(pProcess, pHostCtx, uHandle, cbToRead, uFlags);
2130}
2131
2132
2133int GstCntlProcessHandleTerm(PVBOXSERVICECTRLPROCESS pProcess)
2134{
2135 if (!ASMAtomicReadBool(&pProcess->fShutdown))
2136 return gstcntlProcessRequestAsync(pProcess, NULL /* pHostCtx */, (PFNRT)gstcntlProcessOnTerm,
2137 1 /* cArgs */, pProcess);
2138
2139 return gstcntlProcessOnTerm(pProcess);
2140}
2141
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