VirtualBox

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

Last change on this file since 92660 was 92660, checked in by vboxsync, 3 years ago

VBoxService: Made vgsvcGstCtrlProcessMakeFullPath do the same thing everywhere, as the ExpandEnvironmentStrings call is the wrong approach here (see ancient @todo) and works on ANSI strings where as our strings are UTF-8 and this would prevent executables with non-ASCII characters in them from running. bugref:10153

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

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