VirtualBox

source: vbox/trunk/src/VBox/Additions/common/VBoxService/VBoxServiceControlSession.cpp@ 84548

Last change on this file since 84548 was 84548, checked in by vboxsync, 5 years ago

Guest Control: Implemented guest side support for gracefully rebooting / shutting down the guest. Untested. bugref:9320

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 102.4 KB
Line 
1/* $Id: VBoxServiceControlSession.cpp 84548 2020-05-26 17:43:31Z vboxsync $ */
2/** @file
3 * VBoxServiceControlSession - Guest session handling. Also handles the spawned session processes.
4 */
5
6/*
7 * Copyright (C) 2013-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/dir.h>
25#include <iprt/env.h>
26#include <iprt/file.h>
27#include <iprt/getopt.h>
28#include <iprt/handle.h>
29#include <iprt/mem.h>
30#include <iprt/message.h>
31#include <iprt/path.h>
32#include <iprt/pipe.h>
33#include <iprt/poll.h>
34#include <iprt/process.h>
35#include <iprt/rand.h>
36#include <iprt/system.h> /* For RTShutdown. */
37
38#include "VBoxServiceInternal.h"
39#include "VBoxServiceUtils.h"
40#include "VBoxServiceControl.h"
41
42using namespace guestControl;
43
44
45/*********************************************************************************************************************************
46* Structures and Typedefs *
47*********************************************************************************************************************************/
48/** Generic option indices for session spawn arguments. */
49enum
50{
51 VBOXSERVICESESSIONOPT_FIRST = 1000, /* For initialization. */
52 VBOXSERVICESESSIONOPT_DOMAIN,
53#ifdef DEBUG
54 VBOXSERVICESESSIONOPT_DUMP_STDOUT,
55 VBOXSERVICESESSIONOPT_DUMP_STDERR,
56#endif
57 VBOXSERVICESESSIONOPT_LOG_FILE,
58 VBOXSERVICESESSIONOPT_USERNAME,
59 VBOXSERVICESESSIONOPT_SESSION_ID,
60 VBOXSERVICESESSIONOPT_SESSION_PROTO,
61 VBOXSERVICESESSIONOPT_THREAD_ID
62};
63
64
65static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession);
66static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess);
67
68
69/**
70 * Helper that grows the scratch buffer.
71 * @returns Success indicator.
72 */
73static bool vgsvcGstCtrlSessionGrowScratchBuf(void **ppvScratchBuf, uint32_t *pcbScratchBuf, uint32_t cbMinBuf)
74{
75 uint32_t cbNew = *pcbScratchBuf * 2;
76 if ( cbNew <= VMMDEV_MAX_HGCM_DATA_SIZE
77 && cbMinBuf <= VMMDEV_MAX_HGCM_DATA_SIZE)
78 {
79 while (cbMinBuf > cbNew)
80 cbNew *= 2;
81 void *pvNew = RTMemRealloc(*ppvScratchBuf, cbNew);
82 if (pvNew)
83 {
84 *ppvScratchBuf = pvNew;
85 *pcbScratchBuf = cbNew;
86 return true;
87 }
88 }
89 return false;
90}
91
92
93
94static int vgsvcGstCtrlSessionFileFree(PVBOXSERVICECTRLFILE pFile)
95{
96 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
97
98 int rc = RTFileClose(pFile->hFile);
99 if (RT_SUCCESS(rc))
100 {
101 RTStrFree(pFile->pszName);
102
103 /* Remove file entry in any case. */
104 RTListNodeRemove(&pFile->Node);
105 /* Destroy this object. */
106 RTMemFree(pFile);
107 }
108
109 return rc;
110}
111
112
113/** @todo No locking done yet! */
114static PVBOXSERVICECTRLFILE vgsvcGstCtrlSessionFileGetLocked(const PVBOXSERVICECTRLSESSION pSession, uint32_t uHandle)
115{
116 AssertPtrReturn(pSession, NULL);
117
118 /** @todo Use a map later! */
119 PVBOXSERVICECTRLFILE pFileCur;
120 RTListForEach(&pSession->lstFiles, pFileCur, VBOXSERVICECTRLFILE, Node)
121 {
122 if (pFileCur->uHandle == uHandle)
123 return pFileCur;
124 }
125
126 return NULL;
127}
128
129
130/**
131 * Recursion worker for vgsvcGstCtrlSessionHandleDirRemove.
132 * Only (recursively) removes directory structures which are not empty. Will fail if not empty.
133 *
134 * @returns IPRT status code.
135 * @param pszDir The directory buffer, RTPATH_MAX in length.
136 * Contains the abs path to the directory to
137 * recurse into. Trailing slash.
138 * @param cchDir The length of the directory we're recursing into,
139 * including the trailing slash.
140 * @param pDirEntry The dir entry buffer. (Shared to save stack.)
141 */
142static int vgsvcGstCtrlSessionHandleDirRemoveSub(char *pszDir, size_t cchDir, PRTDIRENTRY pDirEntry)
143{
144 RTDIR hDir;
145 int rc = RTDirOpen(&hDir, pszDir);
146 if (RT_FAILURE(rc))
147 {
148 /* Ignore non-existing directories like RTDirRemoveRecursive does: */
149 if (rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND)
150 return VINF_SUCCESS;
151 return rc;
152 }
153
154 for (;;)
155 {
156 rc = RTDirRead(hDir, pDirEntry, NULL);
157 if (RT_FAILURE(rc))
158 {
159 if (rc == VERR_NO_MORE_FILES)
160 rc = VINF_SUCCESS;
161 break;
162 }
163
164 if (!RTDirEntryIsStdDotLink(pDirEntry))
165 {
166 /* Construct the full name of the entry. */
167 if (cchDir + pDirEntry->cbName + 1 /* dir slash */ < RTPATH_MAX)
168 memcpy(&pszDir[cchDir], pDirEntry->szName, pDirEntry->cbName + 1);
169 else
170 {
171 rc = VERR_FILENAME_TOO_LONG;
172 break;
173 }
174
175 /* Make sure we've got the entry type. */
176 if (pDirEntry->enmType == RTDIRENTRYTYPE_UNKNOWN)
177 RTDirQueryUnknownType(pszDir, false /*fFollowSymlinks*/, &pDirEntry->enmType);
178
179 /* Recurse into subdirs and remove them: */
180 if (pDirEntry->enmType == RTDIRENTRYTYPE_DIRECTORY)
181 {
182 size_t cchSubDir = cchDir + pDirEntry->cbName;
183 pszDir[cchSubDir++] = RTPATH_SLASH;
184 pszDir[cchSubDir] = '\0';
185 rc = vgsvcGstCtrlSessionHandleDirRemoveSub(pszDir, cchSubDir, pDirEntry);
186 if (RT_SUCCESS(rc))
187 {
188 pszDir[cchSubDir] = '\0';
189 rc = RTDirRemove(pszDir);
190 if (RT_FAILURE(rc))
191 break;
192 }
193 else
194 break;
195 }
196 /* Not a subdirectory - fail: */
197 else
198 {
199 rc = VERR_DIR_NOT_EMPTY;
200 break;
201 }
202 }
203 }
204
205 RTDirClose(hDir);
206 return rc;
207}
208
209
210static int vgsvcGstCtrlSessionHandleDirRemove(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
211{
212 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
213 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
214
215 /*
216 * Retrieve the message.
217 */
218 char szDir[RTPATH_MAX];
219 uint32_t fFlags; /* DIRREMOVE_FLAG_XXX */
220 int rc = VbglR3GuestCtrlDirGetRemove(pHostCtx, szDir, sizeof(szDir), &fFlags);
221 if (RT_SUCCESS(rc))
222 {
223 /*
224 * Do some validating before executing the job.
225 */
226 if (!(fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK))
227 {
228 if (fFlags & DIRREMOVEREC_FLAG_RECURSIVE)
229 {
230 if (fFlags & (DIRREMOVEREC_FLAG_CONTENT_AND_DIR | DIRREMOVEREC_FLAG_CONTENT_ONLY))
231 {
232 uint32_t fFlagsRemRec = fFlags & DIRREMOVEREC_FLAG_CONTENT_AND_DIR
233 ? RTDIRRMREC_F_CONTENT_AND_DIR : RTDIRRMREC_F_CONTENT_ONLY;
234 rc = RTDirRemoveRecursive(szDir, fFlagsRemRec);
235 }
236 else /* Only remove empty directory structures. Will fail if non-empty. */
237 {
238 RTDIRENTRY DirEntry;
239 RTPathEnsureTrailingSeparator(szDir, sizeof(szDir));
240 rc = vgsvcGstCtrlSessionHandleDirRemoveSub(szDir, strlen(szDir), &DirEntry);
241 }
242 VGSvcVerbose(4, "[Dir %s]: rmdir /s (%#x) -> rc=%Rrc\n", szDir, fFlags, rc);
243 }
244 else
245 {
246 /* Only delete directory if not empty. */
247 rc = RTDirRemove(szDir);
248 VGSvcVerbose(4, "[Dir %s]: rmdir (%#x), rc=%Rrc\n", szDir, fFlags, rc);
249 }
250 }
251 else
252 {
253 VGSvcError("[Dir %s]: Unsupported flags: %#x (all %#x)\n", szDir, (fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK), fFlags);
254 rc = VERR_NOT_SUPPORTED;
255 }
256
257 /*
258 * Report result back to host.
259 */
260 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
261 if (RT_FAILURE(rc2))
262 {
263 VGSvcError("[Dir %s]: Failed to report removing status, rc=%Rrc\n", szDir, rc2);
264 if (RT_SUCCESS(rc))
265 rc = rc2;
266 }
267 }
268 else
269 {
270 VGSvcError("Error fetching parameters for rmdir operation: %Rrc\n", rc);
271 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
272 }
273
274 VGSvcVerbose(6, "Removing directory '%s' returned rc=%Rrc\n", szDir, rc);
275 return rc;
276}
277
278
279static int vgsvcGstCtrlSessionHandleFileOpen(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
280{
281 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
282 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
283
284 /*
285 * Retrieve the message.
286 */
287 char szFile[RTPATH_MAX];
288 char szAccess[64];
289 char szDisposition[64];
290 char szSharing[64];
291 uint32_t uCreationMode = 0;
292 uint64_t offOpen = 0;
293 uint32_t uHandle = 0;
294 int rc = VbglR3GuestCtrlFileGetOpen(pHostCtx,
295 /* File to open. */
296 szFile, sizeof(szFile),
297 /* Open mode. */
298 szAccess, sizeof(szAccess),
299 /* Disposition. */
300 szDisposition, sizeof(szDisposition),
301 /* Sharing. */
302 szSharing, sizeof(szSharing),
303 /* Creation mode. */
304 &uCreationMode,
305 /* Offset. */
306 &offOpen);
307 VGSvcVerbose(4, "[File %s]: szAccess=%s, szDisposition=%s, szSharing=%s, offOpen=%RU64, rc=%Rrc\n",
308 szFile, szAccess, szDisposition, szSharing, offOpen, rc);
309 if (RT_SUCCESS(rc))
310 {
311 PVBOXSERVICECTRLFILE pFile = (PVBOXSERVICECTRLFILE)RTMemAllocZ(sizeof(VBOXSERVICECTRLFILE));
312 if (pFile)
313 {
314 pFile->hFile = NIL_RTFILE; /* Not zero or NULL! */
315 if (szFile[0])
316 {
317 pFile->pszName = RTStrDup(szFile);
318 if (!pFile->pszName)
319 rc = VERR_NO_MEMORY;
320/** @todo
321 * Implement szSharing!
322 */
323 uint64_t fFlags;
324 if (RT_SUCCESS(rc))
325 {
326 rc = RTFileModeToFlagsEx(szAccess, szDisposition, NULL /* pszSharing, not used yet */, &fFlags);
327 VGSvcVerbose(4, "[File %s] Opening with fFlags=%#RX64 -> rc=%Rrc\n", pFile->pszName, fFlags, rc);
328 }
329
330 if (RT_SUCCESS(rc))
331 {
332 fFlags |= (uCreationMode << RTFILE_O_CREATE_MODE_SHIFT) & RTFILE_O_CREATE_MODE_MASK;
333 /* If we're opening a file in read-only mode, strip truncation mode.
334 * rtFileRecalcAndValidateFlags() will validate it anyway, but avoid asserting in debug builds. */
335 if (fFlags & RTFILE_O_READ)
336 fFlags &= ~RTFILE_O_TRUNCATE;
337 rc = RTFileOpen(&pFile->hFile, pFile->pszName, fFlags);
338 if (RT_SUCCESS(rc))
339 {
340 RTFSOBJINFO objInfo;
341 rc = RTFileQueryInfo(pFile->hFile, &objInfo, RTFSOBJATTRADD_NOTHING);
342 if (RT_SUCCESS(rc))
343 {
344 /* Make sure that we only open stuff we really support.
345 * Only POSIX / UNIX we could open stuff like directories and sockets as well. */
346 if ( RT_LIKELY(RTFS_IS_FILE(objInfo.Attr.fMode))
347 || RTFS_IS_SYMLINK(objInfo.Attr.fMode))
348 {
349 /* Seeking is optional. However, the whole operation
350 * will fail if we don't succeed seeking to the wanted position. */
351 if (offOpen)
352 rc = RTFileSeek(pFile->hFile, (int64_t)offOpen, RTFILE_SEEK_BEGIN, NULL /* Current offset */);
353 if (RT_SUCCESS(rc))
354 {
355 /*
356 * Succeeded!
357 */
358 uHandle = VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pHostCtx->uContextID);
359 pFile->uHandle = uHandle;
360 pFile->fOpen = fFlags;
361 RTListAppend(&pSession->lstFiles, &pFile->Node);
362 VGSvcVerbose(2, "[File %s] Opened (ID=%RU32)\n", pFile->pszName, pFile->uHandle);
363 }
364 else
365 VGSvcError("[File %s] Seeking to offset %RU64 failed: rc=%Rrc\n", pFile->pszName, offOpen, rc);
366 }
367 else
368 {
369 VGSvcError("[File %s] Unsupported mode %#x\n", pFile->pszName, objInfo.Attr.fMode);
370 rc = VERR_NOT_SUPPORTED;
371 }
372 }
373 else
374 VGSvcError("[File %s] Getting mode failed with rc=%Rrc\n", pFile->pszName, rc);
375 }
376 else
377 VGSvcError("[File %s] Opening failed with rc=%Rrc\n", pFile->pszName, rc);
378 }
379 }
380 else
381 {
382 VGSvcError("[File %s] empty filename!\n", szFile);
383 rc = VERR_INVALID_NAME;
384 }
385
386 /* clean up if we failed. */
387 if (RT_FAILURE(rc))
388 {
389 RTStrFree(pFile->pszName);
390 if (pFile->hFile != NIL_RTFILE)
391 RTFileClose(pFile->hFile);
392 RTMemFree(pFile);
393 }
394 }
395 else
396 rc = VERR_NO_MEMORY;
397
398 /*
399 * Report result back to host.
400 */
401 int rc2 = VbglR3GuestCtrlFileCbOpen(pHostCtx, rc, uHandle);
402 if (RT_FAILURE(rc2))
403 {
404 VGSvcError("[File %s]: Failed to report file open status, rc=%Rrc\n", szFile, rc2);
405 if (RT_SUCCESS(rc))
406 rc = rc2;
407 }
408 }
409 else
410 {
411 VGSvcError("Error fetching parameters for open file operation: %Rrc\n", rc);
412 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
413 }
414
415 VGSvcVerbose(4, "[File %s] Opening (open mode='%s', disposition='%s', creation mode=0x%x) returned rc=%Rrc\n",
416 szFile, szAccess, szDisposition, uCreationMode, rc);
417 return rc;
418}
419
420
421static int vgsvcGstCtrlSessionHandleFileClose(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
422{
423 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
424 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
425
426 /*
427 * Retrieve the message.
428 */
429 uint32_t uHandle = 0;
430 int rc = VbglR3GuestCtrlFileGetClose(pHostCtx, &uHandle /* File handle to close */);
431 if (RT_SUCCESS(rc))
432 {
433 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
434 if (pFile)
435 {
436 VGSvcVerbose(2, "[File %s] Closing (handle=%RU32)\n", pFile ? pFile->pszName : "<Not found>", uHandle);
437 rc = vgsvcGstCtrlSessionFileFree(pFile);
438 }
439 else
440 {
441 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
442 rc = VERR_NOT_FOUND;
443 }
444
445 /*
446 * Report result back to host.
447 */
448 int rc2 = VbglR3GuestCtrlFileCbClose(pHostCtx, rc);
449 if (RT_FAILURE(rc2))
450 {
451 VGSvcError("Failed to report file close status, rc=%Rrc\n", rc2);
452 if (RT_SUCCESS(rc))
453 rc = rc2;
454 }
455 }
456 else
457 {
458 VGSvcError("Error fetching parameters for close file operation: %Rrc\n", rc);
459 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
460 }
461 return rc;
462}
463
464
465static int vgsvcGstCtrlSessionHandleFileRead(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
466 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
467{
468 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
469 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
470
471 /*
472 * Retrieve the request.
473 */
474 uint32_t uHandle = 0;
475 uint32_t cbToRead;
476 int rc = VbglR3GuestCtrlFileGetRead(pHostCtx, &uHandle, &cbToRead);
477 if (RT_SUCCESS(rc))
478 {
479 /*
480 * Locate the file and do the reading.
481 *
482 * If the request is larger than our scratch buffer, try grow it - just
483 * ignore failure as the host better respect our buffer limits.
484 */
485 uint32_t offNew = 0;
486 size_t cbRead = 0;
487 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
488 if (pFile)
489 {
490 if (*pcbScratchBuf < cbToRead)
491 vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToRead);
492
493 rc = RTFileRead(pFile->hFile, *ppvScratchBuf, RT_MIN(cbToRead, *pcbScratchBuf), &cbRead);
494 offNew = (int64_t)RTFileTell(pFile->hFile);
495 VGSvcVerbose(5, "[File %s] Read %zu/%RU32 bytes, rc=%Rrc, offNew=%RI64\n", pFile->pszName, cbRead, cbToRead, rc, offNew);
496 }
497 else
498 {
499 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
500 rc = VERR_NOT_FOUND;
501 }
502
503 /*
504 * Report result and data back to the host.
505 */
506 int rc2;
507 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
508 rc2 = VbglR3GuestCtrlFileCbReadOffset(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead, offNew);
509 else
510 rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead);
511 if (RT_FAILURE(rc2))
512 {
513 VGSvcError("Failed to report file read status, rc=%Rrc\n", rc2);
514 if (RT_SUCCESS(rc))
515 rc = rc2;
516 }
517 }
518 else
519 {
520 VGSvcError("Error fetching parameters for file read operation: %Rrc\n", rc);
521 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
522 }
523 return rc;
524}
525
526
527static int vgsvcGstCtrlSessionHandleFileReadAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
528 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
529{
530 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
531 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
532
533 /*
534 * Retrieve the request.
535 */
536 uint32_t uHandle = 0;
537 uint32_t cbToRead;
538 uint64_t offReadAt;
539 int rc = VbglR3GuestCtrlFileGetReadAt(pHostCtx, &uHandle, &cbToRead, &offReadAt);
540 if (RT_SUCCESS(rc))
541 {
542 /*
543 * Locate the file and do the reading.
544 *
545 * If the request is larger than our scratch buffer, try grow it - just
546 * ignore failure as the host better respect our buffer limits.
547 */
548 int64_t offNew = 0;
549 size_t cbRead = 0;
550 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
551 if (pFile)
552 {
553 if (*pcbScratchBuf < cbToRead)
554 vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToRead);
555
556 rc = RTFileReadAt(pFile->hFile, (RTFOFF)offReadAt, *ppvScratchBuf, RT_MIN(cbToRead, *pcbScratchBuf), &cbRead);
557 if (RT_SUCCESS(rc))
558 {
559 offNew = offReadAt + cbRead;
560 RTFileSeek(pFile->hFile, offNew, RTFILE_SEEK_BEGIN, NULL); /* RTFileReadAt does not always change position. */
561 }
562 else
563 offNew = (int64_t)RTFileTell(pFile->hFile);
564 VGSvcVerbose(5, "[File %s] Read %zu bytes @ %RU64, rc=%Rrc, offNew=%RI64\n", pFile->pszName, cbRead, offReadAt, rc, offNew);
565 }
566 else
567 {
568 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
569 rc = VERR_NOT_FOUND;
570 }
571
572 /*
573 * Report result and data back to the host.
574 */
575 int rc2;
576 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
577 rc2 = VbglR3GuestCtrlFileCbReadOffset(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead, offNew);
578 else
579 rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead);
580 if (RT_FAILURE(rc2))
581 {
582 VGSvcError("Failed to report file read at status, rc=%Rrc\n", rc2);
583 if (RT_SUCCESS(rc))
584 rc = rc2;
585 }
586 }
587 else
588 {
589 VGSvcError("Error fetching parameters for file read at operation: %Rrc\n", rc);
590 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
591 }
592 return rc;
593}
594
595
596static int vgsvcGstCtrlSessionHandleFileWrite(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
597 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
598{
599 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
600 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
601
602 /*
603 * Retrieve the request and data to write.
604 */
605 uint32_t uHandle = 0;
606 uint32_t cbToWrite;
607 int rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite);
608 if ( rc == VERR_BUFFER_OVERFLOW
609 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToWrite))
610 rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite);
611 if (RT_SUCCESS(rc))
612 {
613 /*
614 * Locate the file and do the writing.
615 */
616 int64_t offNew = 0;
617 size_t cbWritten = 0;
618 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
619 if (pFile)
620 {
621 rc = RTFileWrite(pFile->hFile, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), &cbWritten);
622 offNew = (int64_t)RTFileTell(pFile->hFile);
623 VGSvcVerbose(5, "[File %s] Writing %p LB %RU32 => %Rrc, cbWritten=%zu, offNew=%RI64\n",
624 pFile->pszName, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), rc, cbWritten, offNew);
625 }
626 else
627 {
628 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
629 rc = VERR_NOT_FOUND;
630 }
631
632 /*
633 * Report result back to host.
634 */
635 int rc2;
636 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
637 rc2 = VbglR3GuestCtrlFileCbWriteOffset(pHostCtx, rc, (uint32_t)cbWritten, offNew);
638 else
639 rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
640 if (RT_FAILURE(rc2))
641 {
642 VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
643 if (RT_SUCCESS(rc))
644 rc = rc2;
645 }
646 }
647 else
648 {
649 VGSvcError("Error fetching parameters for file write operation: %Rrc\n", rc);
650 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
651 }
652 return rc;
653}
654
655
656static int vgsvcGstCtrlSessionHandleFileWriteAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
657 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
658{
659 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
660 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
661
662 /*
663 * Retrieve the request and data to write.
664 */
665 uint32_t uHandle = 0;
666 uint32_t cbToWrite;
667 uint64_t offWriteAt;
668 int rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite, &offWriteAt);
669 if ( rc == VERR_BUFFER_OVERFLOW
670 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToWrite))
671 rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite, &offWriteAt);
672 if (RT_SUCCESS(rc))
673 {
674 /*
675 * Locate the file and do the writing.
676 */
677 int64_t offNew = 0;
678 size_t cbWritten = 0;
679 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
680 if (pFile)
681 {
682 rc = RTFileWriteAt(pFile->hFile, (RTFOFF)offWriteAt, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), &cbWritten);
683 if (RT_SUCCESS(rc))
684 {
685 offNew = offWriteAt + cbWritten;
686
687 /* RTFileWriteAt does not always change position: */
688 if (!(pFile->fOpen & RTFILE_O_APPEND))
689 RTFileSeek(pFile->hFile, offNew, RTFILE_SEEK_BEGIN, NULL);
690 else
691 RTFileSeek(pFile->hFile, 0, RTFILE_SEEK_END, (uint64_t *)&offNew);
692 }
693 else
694 offNew = (int64_t)RTFileTell(pFile->hFile);
695 VGSvcVerbose(5, "[File %s] Writing %p LB %RU32 @ %RU64 => %Rrc, cbWritten=%zu, offNew=%RI64\n",
696 pFile->pszName, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), offWriteAt, rc, cbWritten, offNew);
697 }
698 else
699 {
700 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
701 rc = VERR_NOT_FOUND;
702 }
703
704 /*
705 * Report result back to host.
706 */
707 int rc2;
708 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
709 rc2 = VbglR3GuestCtrlFileCbWriteOffset(pHostCtx, rc, (uint32_t)cbWritten, offNew);
710 else
711 rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
712 if (RT_FAILURE(rc2))
713 {
714 VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
715 if (RT_SUCCESS(rc))
716 rc = rc2;
717 }
718 }
719 else
720 {
721 VGSvcError("Error fetching parameters for file write at operation: %Rrc\n", rc);
722 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
723 }
724 return rc;
725}
726
727
728static int vgsvcGstCtrlSessionHandleFileSeek(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
729{
730 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
731 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
732
733 /*
734 * Retrieve the request.
735 */
736 uint32_t uHandle = 0;
737 uint32_t uSeekMethod;
738 uint64_t offSeek; /* Will be converted to int64_t. */
739 int rc = VbglR3GuestCtrlFileGetSeek(pHostCtx, &uHandle, &uSeekMethod, &offSeek);
740 if (RT_SUCCESS(rc))
741 {
742 uint64_t offActual = 0;
743
744 /*
745 * Validate and convert the seek method to IPRT speak.
746 */
747 static const uint8_t s_abMethods[GUEST_FILE_SEEKTYPE_END + 1] =
748 {
749 UINT8_MAX, RTFILE_SEEK_BEGIN, UINT8_MAX, UINT8_MAX, RTFILE_SEEK_CURRENT,
750 UINT8_MAX, UINT8_MAX, UINT8_MAX, RTFILE_SEEK_END
751 };
752 if ( uSeekMethod < RT_ELEMENTS(s_abMethods)
753 && s_abMethods[uSeekMethod] != UINT8_MAX)
754 {
755 /*
756 * Locate the file and do the seek.
757 */
758 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
759 if (pFile)
760 {
761 rc = RTFileSeek(pFile->hFile, (int64_t)offSeek, s_abMethods[uSeekMethod], &offActual);
762 VGSvcVerbose(5, "[File %s]: Seeking to offSeek=%RI64, uSeekMethodIPRT=%u, rc=%Rrc\n",
763 pFile->pszName, offSeek, s_abMethods[uSeekMethod], rc);
764 }
765 else
766 {
767 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
768 rc = VERR_NOT_FOUND;
769 }
770 }
771 else
772 {
773 VGSvcError("Invalid seek method: %#x\n", uSeekMethod);
774 rc = VERR_NOT_SUPPORTED;
775 }
776
777 /*
778 * Report result back to host.
779 */
780 int rc2 = VbglR3GuestCtrlFileCbSeek(pHostCtx, rc, offActual);
781 if (RT_FAILURE(rc2))
782 {
783 VGSvcError("Failed to report file seek status, rc=%Rrc\n", rc2);
784 if (RT_SUCCESS(rc))
785 rc = rc2;
786 }
787 }
788 else
789 {
790 VGSvcError("Error fetching parameters for file seek operation: %Rrc\n", rc);
791 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
792 }
793 return rc;
794}
795
796
797static int vgsvcGstCtrlSessionHandleFileTell(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
798{
799 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
800 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
801
802 /*
803 * Retrieve the request.
804 */
805 uint32_t uHandle = 0;
806 int rc = VbglR3GuestCtrlFileGetTell(pHostCtx, &uHandle);
807 if (RT_SUCCESS(rc))
808 {
809 /*
810 * Locate the file and ask for the current position.
811 */
812 uint64_t offCurrent = 0;
813 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
814 if (pFile)
815 {
816 offCurrent = RTFileTell(pFile->hFile);
817 VGSvcVerbose(5, "[File %s]: Telling offCurrent=%RU64\n", pFile->pszName, offCurrent);
818 }
819 else
820 {
821 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
822 rc = VERR_NOT_FOUND;
823 }
824
825 /*
826 * Report result back to host.
827 */
828 int rc2 = VbglR3GuestCtrlFileCbTell(pHostCtx, rc, offCurrent);
829 if (RT_FAILURE(rc2))
830 {
831 VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
832 if (RT_SUCCESS(rc))
833 rc = rc2;
834 }
835 }
836 else
837 {
838 VGSvcError("Error fetching parameters for file tell operation: %Rrc\n", rc);
839 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
840 }
841 return rc;
842}
843
844
845static int vgsvcGstCtrlSessionHandleFileSetSize(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
846{
847 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
848 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
849
850 /*
851 * Retrieve the request.
852 */
853 uint32_t uHandle = 0;
854 uint64_t cbNew = 0;
855 int rc = VbglR3GuestCtrlFileGetSetSize(pHostCtx, &uHandle, &cbNew);
856 if (RT_SUCCESS(rc))
857 {
858 /*
859 * Locate the file and ask for the current position.
860 */
861 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
862 if (pFile)
863 {
864 rc = RTFileSetSize(pFile->hFile, cbNew);
865 VGSvcVerbose(5, "[File %s]: Changing size to %RU64 (%#RX64), rc=%Rrc\n", pFile->pszName, cbNew, cbNew, rc);
866 }
867 else
868 {
869 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
870 cbNew = UINT64_MAX;
871 rc = VERR_NOT_FOUND;
872 }
873
874 /*
875 * Report result back to host.
876 */
877 int rc2 = VbglR3GuestCtrlFileCbSetSize(pHostCtx, rc, cbNew);
878 if (RT_FAILURE(rc2))
879 {
880 VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
881 if (RT_SUCCESS(rc))
882 rc = rc2;
883 }
884 }
885 else
886 {
887 VGSvcError("Error fetching parameters for file tell operation: %Rrc\n", rc);
888 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
889 }
890 return rc;
891}
892
893
894static int vgsvcGstCtrlSessionHandlePathRename(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
895{
896 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
897 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
898
899 /*
900 * Retrieve the request.
901 */
902 char szSource[RTPATH_MAX];
903 char szDest[RTPATH_MAX];
904 uint32_t fFlags = 0; /* PATHRENAME_FLAG_XXX */
905 int rc = VbglR3GuestCtrlPathGetRename(pHostCtx, szSource, sizeof(szSource), szDest, sizeof(szDest), &fFlags);
906 if (RT_SUCCESS(rc))
907 {
908 /*
909 * Validate the flags (kudos for using the same as IPRT), then do the renaming.
910 */
911 AssertCompile(PATHRENAME_FLAG_NO_REPLACE == RTPATHRENAME_FLAGS_NO_REPLACE);
912 AssertCompile(PATHRENAME_FLAG_REPLACE == RTPATHRENAME_FLAGS_REPLACE);
913 AssertCompile(PATHRENAME_FLAG_NO_SYMLINKS == RTPATHRENAME_FLAGS_NO_SYMLINKS);
914 AssertCompile(PATHRENAME_FLAG_VALID_MASK == (RTPATHRENAME_FLAGS_NO_REPLACE | RTPATHRENAME_FLAGS_REPLACE | RTPATHRENAME_FLAGS_NO_SYMLINKS));
915 if (!(fFlags & ~PATHRENAME_FLAG_VALID_MASK))
916 {
917 VGSvcVerbose(4, "Renaming '%s' to '%s', fFlags=%#x, rc=%Rrc\n", szSource, szDest, fFlags, rc);
918 rc = RTPathRename(szSource, szDest, fFlags);
919 }
920 else
921 {
922 VGSvcError("Invalid rename flags: %#x\n", fFlags);
923 rc = VERR_NOT_SUPPORTED;
924 }
925
926 /*
927 * Report result back to host.
928 */
929 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
930 if (RT_FAILURE(rc2))
931 {
932 VGSvcError("Failed to report renaming status, rc=%Rrc\n", rc2);
933 if (RT_SUCCESS(rc))
934 rc = rc2;
935 }
936 }
937 else
938 {
939 VGSvcError("Error fetching parameters for rename operation: %Rrc\n", rc);
940 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
941 }
942 VGSvcVerbose(5, "Renaming '%s' to '%s' returned rc=%Rrc\n", szSource, szDest, rc);
943 return rc;
944}
945
946
947/**
948 * Handles getting the user's documents directory.
949 *
950 * @returns VBox status code.
951 * @param pSession Guest session.
952 * @param pHostCtx Host context.
953 */
954static int vgsvcGstCtrlSessionHandlePathUserDocuments(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
955{
956 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
957 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
958
959 /*
960 * Retrieve the request.
961 */
962 int rc = VbglR3GuestCtrlPathGetUserDocuments(pHostCtx);
963 if (RT_SUCCESS(rc))
964 {
965 /*
966 * Get the path and pass it back to the host..
967 */
968 char szPath[RTPATH_MAX];
969 rc = RTPathUserDocuments(szPath, sizeof(szPath));
970#ifdef DEBUG
971 VGSvcVerbose(2, "User documents is '%s', rc=%Rrc\n", szPath, rc);
972#endif
973
974 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
975 RT_SUCCESS(rc) ? (uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
976 if (RT_FAILURE(rc2))
977 {
978 VGSvcError("Failed to report user documents, rc=%Rrc\n", rc2);
979 if (RT_SUCCESS(rc))
980 rc = rc2;
981 }
982 }
983 else
984 {
985 VGSvcError("Error fetching parameters for user documents path request: %Rrc\n", rc);
986 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
987 }
988 return rc;
989}
990
991
992/**
993 * Handles shutting down / rebooting the guest OS.
994 *
995 * @returns VBox status code.
996 * @param pSession Guest session.
997 * @param pHostCtx Host context.
998 */
999static int vgsvcGstCtrlSessionHandleShutdown(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1000{
1001 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1002 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1003
1004 /*
1005 * Retrieve the request.
1006 */
1007 uint32_t fAction;
1008 int rc = VbglR3GuestCtrlGetShutdown(pHostCtx, &fAction);
1009 if (RT_SUCCESS(rc))
1010 {
1011 VGSvcVerbose(1, "Host requested to %s system ...\n", (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "reboot" : "shutdown");
1012
1013 /* Reply first to the host, in order to avoid host hangs when issuing the guest shutdown. */
1014 rc = VbglR3GuestCtrlMsgReply(pHostCtx, VINF_SUCCESS);
1015 if (RT_FAILURE(rc))
1016 {
1017 VGSvcError("Failed to reply to shutdown / reboot request, rc=%Rrc\n", rc);
1018 }
1019 else
1020 {
1021 rc = RTSystemShutdown(0 /*cMsDelay*/,
1022 fAction | RTSYSTEM_SHUTDOWN_PLANNED,
1023 "VBoxService");
1024 if (RT_FAILURE(rc))
1025 VGSvcError("%s system failed with %Rrc\n", (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "Rebooting" : "Shuting down");
1026 }
1027 }
1028 else
1029 {
1030 VGSvcError("Error fetching parameters for shutdown / reboot request: %Rrc\n", rc);
1031 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1032 }
1033
1034 return rc;
1035}
1036
1037
1038/**
1039 * Handles getting the user's home directory.
1040 *
1041 * @returns VBox status code.
1042 * @param pSession Guest session.
1043 * @param pHostCtx Host context.
1044 */
1045static int vgsvcGstCtrlSessionHandlePathUserHome(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1046{
1047 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1048 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1049
1050 /*
1051 * Retrieve the request.
1052 */
1053 int rc = VbglR3GuestCtrlPathGetUserHome(pHostCtx);
1054 if (RT_SUCCESS(rc))
1055 {
1056 /*
1057 * Get the path and pass it back to the host..
1058 */
1059 char szPath[RTPATH_MAX];
1060 rc = RTPathUserHome(szPath, sizeof(szPath));
1061
1062#ifdef DEBUG
1063 VGSvcVerbose(2, "User home is '%s', rc=%Rrc\n", szPath, rc);
1064#endif
1065 /* Report back in any case. */
1066 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
1067 RT_SUCCESS(rc) ?(uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
1068 if (RT_FAILURE(rc2))
1069 {
1070 VGSvcError("Failed to report user home, rc=%Rrc\n", rc2);
1071 if (RT_SUCCESS(rc))
1072 rc = rc2;
1073 }
1074 }
1075 else
1076 {
1077 VGSvcError("Error fetching parameters for user home directory path request: %Rrc\n", rc);
1078 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1079 }
1080 return rc;
1081}
1082
1083/**
1084 * Handles starting a guest processes.
1085 *
1086 * @returns VBox status code.
1087 * @param pSession Guest session.
1088 * @param pHostCtx Host context.
1089 */
1090static int vgsvcGstCtrlSessionHandleProcExec(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1091{
1092 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1093 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1094
1095/** @todo this hardcoded stuff needs redoing. */
1096
1097 /* Initialize maximum environment block size -- needed as input
1098 * parameter to retrieve the stuff from the host. On output this then
1099 * will contain the actual block size. */
1100 PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo;
1101 int rc = VbglR3GuestCtrlProcGetStart(pHostCtx, &pStartupInfo);
1102 if (RT_SUCCESS(rc))
1103 {
1104 VGSvcVerbose(3, "Request to start process szCmd=%s, fFlags=0x%x, szArgs=%s, szEnv=%s, uTimeout=%RU32\n",
1105 pStartupInfo->pszCmd, pStartupInfo->fFlags,
1106 pStartupInfo->cArgs ? pStartupInfo->pszArgs : "<None>",
1107 pStartupInfo->cEnvVars ? pStartupInfo->pszEnv : "<None>",
1108 pStartupInfo->uTimeLimitMS);
1109
1110 bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
1111 rc = VGSvcGstCtrlSessionProcessStartAllowed(pSession, &fStartAllowed);
1112 if (RT_SUCCESS(rc))
1113 {
1114 vgsvcGstCtrlSessionCleanupProcesses(pSession);
1115
1116 if (fStartAllowed)
1117 rc = VGSvcGstCtrlProcessStart(pSession, pStartupInfo, pHostCtx->uContextID);
1118 else
1119 rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
1120 }
1121
1122 /* We're responsible for signaling errors to the host (it will wait for ever otherwise). */
1123 if (RT_FAILURE(rc))
1124 {
1125 VGSvcError("Starting process failed with rc=%Rrc, protocol=%RU32, parameters=%RU32\n",
1126 rc, pHostCtx->uProtocol, pHostCtx->uNumParms);
1127 int rc2 = VbglR3GuestCtrlProcCbStatus(pHostCtx, 0 /*nil-PID*/, PROC_STS_ERROR, rc, NULL /*pvData*/, 0 /*cbData*/);
1128 if (RT_FAILURE(rc2))
1129 VGSvcError("Error sending start process status to host, rc=%Rrc\n", rc2);
1130 }
1131
1132 VbglR3GuestCtrlProcStartupInfoFree(pStartupInfo);
1133 pStartupInfo = NULL;
1134 }
1135 else
1136 {
1137 VGSvcError("Failed to retrieve parameters for process start: %Rrc (cParms=%u)\n", rc, pHostCtx->uNumParms);
1138 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1139 }
1140
1141 return rc;
1142}
1143
1144
1145/**
1146 * Sends stdin input to a specific guest process.
1147 *
1148 * @returns VBox status code.
1149 * @param pSession The session which is in charge.
1150 * @param pHostCtx The host context to use.
1151 * @param ppvScratchBuf The scratch buffer, we may grow it.
1152 * @param pcbScratchBuf The scratch buffer size for retrieving the input
1153 * data.
1154 */
1155static int vgsvcGstCtrlSessionHandleProcInput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1156 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
1157{
1158 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1159 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1160
1161 /*
1162 * Retrieve the data from the host.
1163 */
1164 uint32_t uPID;
1165 uint32_t fFlags;
1166 uint32_t cbInput;
1167 int rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1168 if ( rc == VERR_BUFFER_OVERFLOW
1169 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbInput))
1170 rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1171 if (RT_SUCCESS(rc))
1172 {
1173 if (fFlags & INPUT_FLAG_EOF)
1174 VGSvcVerbose(4, "Got last process input block for PID=%RU32 (%RU32 bytes) ...\n", uPID, cbInput);
1175
1176 /*
1177 * Locate the process and feed it.
1178 */
1179 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1180 if (pProcess)
1181 {
1182 rc = VGSvcGstCtrlProcessHandleInput(pProcess, pHostCtx, RT_BOOL(fFlags & INPUT_FLAG_EOF),
1183 *ppvScratchBuf, RT_MIN(cbInput, *pcbScratchBuf));
1184 if (RT_FAILURE(rc))
1185 VGSvcError("Error handling input message for PID=%RU32, rc=%Rrc\n", uPID, rc);
1186 VGSvcGstCtrlProcessRelease(pProcess);
1187 }
1188 else
1189 {
1190 VGSvcError("Could not find PID %u for feeding %u bytes to it.\n", uPID, cbInput);
1191 rc = VERR_PROCESS_NOT_FOUND;
1192 VbglR3GuestCtrlProcCbStatusInput(pHostCtx, uPID, INPUT_STS_ERROR, rc, 0);
1193 }
1194 }
1195 else
1196 {
1197 VGSvcError("Failed to retrieve parameters for process input: %Rrc (scratch %u bytes)\n", rc, *pcbScratchBuf);
1198 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1199 }
1200
1201 VGSvcVerbose(6, "Feeding input to PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1202 return rc;
1203}
1204
1205
1206/**
1207 * Gets stdout/stderr output of a specific guest process.
1208 *
1209 * @returns VBox status code.
1210 * @param pSession The session which is in charge.
1211 * @param pHostCtx The host context to use.
1212 */
1213static int vgsvcGstCtrlSessionHandleProcOutput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1214{
1215 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1216 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1217
1218 /*
1219 * Retrieve the request.
1220 */
1221 uint32_t uPID;
1222 uint32_t uHandleID;
1223 uint32_t fFlags;
1224 int rc = VbglR3GuestCtrlProcGetOutput(pHostCtx, &uPID, &uHandleID, &fFlags);
1225#ifdef DEBUG_andy
1226 VGSvcVerbose(4, "Getting output for PID=%RU32, CID=%RU32, uHandleID=%RU32, fFlags=%RU32\n",
1227 uPID, pHostCtx->uContextID, uHandleID, fFlags);
1228#endif
1229 if (RT_SUCCESS(rc))
1230 {
1231 /*
1232 * Locate the process and hand it the output request.
1233 */
1234 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1235 if (pProcess)
1236 {
1237 rc = VGSvcGstCtrlProcessHandleOutput(pProcess, pHostCtx, uHandleID, _64K /* cbToRead */, fFlags);
1238 if (RT_FAILURE(rc))
1239 VGSvcError("Error getting output for PID=%RU32, rc=%Rrc\n", uPID, rc);
1240 VGSvcGstCtrlProcessRelease(pProcess);
1241 }
1242 else
1243 {
1244 VGSvcError("Could not find PID %u for draining handle %u (%#x).\n", uPID, uHandleID, uHandleID);
1245 rc = VERR_PROCESS_NOT_FOUND;
1246/** @todo r=bird:
1247 *
1248 * No way to report status status code for output requests?
1249 *
1250 */
1251 }
1252 }
1253 else
1254 {
1255 VGSvcError("Error fetching parameters for process output request: %Rrc\n", rc);
1256 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1257 }
1258
1259#ifdef DEBUG_andy
1260 VGSvcVerbose(4, "Getting output for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1261#endif
1262 return rc;
1263}
1264
1265
1266/**
1267 * Tells a guest process to terminate.
1268 *
1269 * @returns VBox status code.
1270 * @param pSession The session which is in charge.
1271 * @param pHostCtx The host context to use.
1272 */
1273static int vgsvcGstCtrlSessionHandleProcTerminate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1274{
1275 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1276 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1277
1278 /*
1279 * Retrieve the request.
1280 */
1281 uint32_t uPID;
1282 int rc = VbglR3GuestCtrlProcGetTerminate(pHostCtx, &uPID);
1283 if (RT_SUCCESS(rc))
1284 {
1285 /*
1286 * Locate the process and terminate it.
1287 */
1288 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1289 if (pProcess)
1290 {
1291 rc = VGSvcGstCtrlProcessHandleTerm(pProcess);
1292 if (RT_FAILURE(rc))
1293 VGSvcError("Error terminating PID=%RU32, rc=%Rrc\n", uPID, rc);
1294
1295 VGSvcGstCtrlProcessRelease(pProcess);
1296 }
1297 else
1298 {
1299 VGSvcError("Could not find PID %u for termination.\n", uPID);
1300 rc = VERR_PROCESS_NOT_FOUND;
1301 }
1302 }
1303 else
1304 {
1305 VGSvcError("Error fetching parameters for process termination request: %Rrc\n", rc);
1306 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1307 }
1308#ifdef DEBUG_andy
1309 VGSvcVerbose(4, "Terminating PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1310#endif
1311 return rc;
1312}
1313
1314
1315static int vgsvcGstCtrlSessionHandleProcWaitFor(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1316{
1317 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1318 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1319
1320 /*
1321 * Retrieve the request.
1322 */
1323 uint32_t uPID;
1324 uint32_t uWaitFlags;
1325 uint32_t uTimeoutMS;
1326 int rc = VbglR3GuestCtrlProcGetWaitFor(pHostCtx, &uPID, &uWaitFlags, &uTimeoutMS);
1327 if (RT_SUCCESS(rc))
1328 {
1329 /*
1330 * Locate the process and the realize that this call makes no sense
1331 * since we'll notify the host when a process terminates anyway and
1332 * hopefully don't need any additional encouragement.
1333 */
1334 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1335 if (pProcess)
1336 {
1337 rc = VERR_NOT_IMPLEMENTED; /** @todo */
1338 VGSvcGstCtrlProcessRelease(pProcess);
1339 }
1340 else
1341 rc = VERR_NOT_FOUND;
1342 }
1343 else
1344 {
1345 VGSvcError("Error fetching parameters for process wait request: %Rrc\n", rc);
1346 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1347 }
1348 return rc;
1349}
1350
1351
1352int VGSvcGstCtrlSessionHandler(PVBOXSERVICECTRLSESSION pSession, uint32_t uMsg, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1353 void **ppvScratchBuf, uint32_t *pcbScratchBuf, volatile bool *pfShutdown)
1354{
1355 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1356 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1357 AssertPtrReturn(*ppvScratchBuf, VERR_INVALID_POINTER);
1358 AssertPtrReturn(pfShutdown, VERR_INVALID_POINTER);
1359
1360
1361 /*
1362 * Only anonymous sessions (that is, sessions which run with local
1363 * service privileges) or spawned session processes can do certain
1364 * operations.
1365 */
1366 bool const fImpersonated = RT_BOOL(pSession->fFlags & ( VBOXSERVICECTRLSESSION_FLAG_SPAWN
1367 | VBOXSERVICECTRLSESSION_FLAG_ANONYMOUS));
1368 int rc = VERR_NOT_SUPPORTED; /* Play safe by default. */
1369
1370 switch (uMsg)
1371 {
1372 case HOST_MSG_SESSION_CLOSE:
1373 /* Shutdown (this spawn). */
1374 rc = VGSvcGstCtrlSessionClose(pSession);
1375 *pfShutdown = true; /* Shutdown in any case. */
1376 break;
1377
1378 case HOST_MSG_DIR_REMOVE:
1379 if (fImpersonated)
1380 rc = vgsvcGstCtrlSessionHandleDirRemove(pSession, pHostCtx);
1381 break;
1382
1383 case HOST_MSG_EXEC_CMD:
1384 rc = vgsvcGstCtrlSessionHandleProcExec(pSession, pHostCtx);
1385 break;
1386
1387 case HOST_MSG_EXEC_SET_INPUT:
1388 rc = vgsvcGstCtrlSessionHandleProcInput(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1389 break;
1390
1391 case HOST_MSG_EXEC_GET_OUTPUT:
1392 rc = vgsvcGstCtrlSessionHandleProcOutput(pSession, pHostCtx);
1393 break;
1394
1395 case HOST_MSG_EXEC_TERMINATE:
1396 rc = vgsvcGstCtrlSessionHandleProcTerminate(pSession, pHostCtx);
1397 break;
1398
1399 case HOST_MSG_EXEC_WAIT_FOR:
1400 rc = vgsvcGstCtrlSessionHandleProcWaitFor(pSession, pHostCtx);
1401 break;
1402
1403 case HOST_MSG_FILE_OPEN:
1404 if (fImpersonated)
1405 rc = vgsvcGstCtrlSessionHandleFileOpen(pSession, pHostCtx);
1406 break;
1407
1408 case HOST_MSG_FILE_CLOSE:
1409 if (fImpersonated)
1410 rc = vgsvcGstCtrlSessionHandleFileClose(pSession, pHostCtx);
1411 break;
1412
1413 case HOST_MSG_FILE_READ:
1414 if (fImpersonated)
1415 rc = vgsvcGstCtrlSessionHandleFileRead(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1416 break;
1417
1418 case HOST_MSG_FILE_READ_AT:
1419 if (fImpersonated)
1420 rc = vgsvcGstCtrlSessionHandleFileReadAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1421 break;
1422
1423 case HOST_MSG_FILE_WRITE:
1424 if (fImpersonated)
1425 rc = vgsvcGstCtrlSessionHandleFileWrite(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1426 break;
1427
1428 case HOST_MSG_FILE_WRITE_AT:
1429 if (fImpersonated)
1430 rc = vgsvcGstCtrlSessionHandleFileWriteAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1431 break;
1432
1433 case HOST_MSG_FILE_SEEK:
1434 if (fImpersonated)
1435 rc = vgsvcGstCtrlSessionHandleFileSeek(pSession, pHostCtx);
1436 break;
1437
1438 case HOST_MSG_FILE_TELL:
1439 if (fImpersonated)
1440 rc = vgsvcGstCtrlSessionHandleFileTell(pSession, pHostCtx);
1441 break;
1442
1443 case HOST_MSG_FILE_SET_SIZE:
1444 if (fImpersonated)
1445 rc = vgsvcGstCtrlSessionHandleFileSetSize(pSession, pHostCtx);
1446 break;
1447
1448 case HOST_MSG_PATH_RENAME:
1449 if (fImpersonated)
1450 rc = vgsvcGstCtrlSessionHandlePathRename(pSession, pHostCtx);
1451 break;
1452
1453 case HOST_MSG_PATH_USER_DOCUMENTS:
1454 if (fImpersonated)
1455 rc = vgsvcGstCtrlSessionHandlePathUserDocuments(pSession, pHostCtx);
1456 break;
1457
1458 case HOST_MSG_PATH_USER_HOME:
1459 if (fImpersonated)
1460 rc = vgsvcGstCtrlSessionHandlePathUserHome(pSession, pHostCtx);
1461 break;
1462
1463 case HOST_MSG_SHUTDOWN:
1464 rc = vgsvcGstCtrlSessionHandleShutdown(pSession, pHostCtx);
1465 break;
1466
1467 default: /* Not supported, see next code block. */
1468 break;
1469 }
1470 if (RT_SUCCESS(rc))
1471 { /* likely */ }
1472 else if (rc != VERR_NOT_SUPPORTED) /* Note: Reply to host must must be sent by above handler. */
1473 VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);
1474 else
1475 {
1476 /* We must skip and notify host here as best we can... */
1477 VGSvcVerbose(1, "Unsupported message (uMsg=%RU32, cParms=%RU32) from host, skipping\n", uMsg, pHostCtx->uNumParms);
1478 if (VbglR3GuestCtrlSupportsOptimizations(pHostCtx->uClientID))
1479 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, VERR_NOT_SUPPORTED, uMsg);
1480 else
1481 VbglR3GuestCtrlMsgSkipOld(pHostCtx->uClientID);
1482 rc = VINF_SUCCESS;
1483 }
1484
1485 if (RT_FAILURE(rc))
1486 VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);
1487
1488 return rc;
1489}
1490
1491
1492/**
1493 * Thread main routine for a spawned guest session process.
1494 *
1495 * This thread runs in the main executable to control the spawned session process.
1496 *
1497 * @returns VBox status code.
1498 * @param hThreadSelf Thread handle.
1499 * @param pvUser Pointer to a VBOXSERVICECTRLSESSIONTHREAD structure.
1500 *
1501 */
1502static DECLCALLBACK(int) vgsvcGstCtrlSessionThread(RTTHREAD hThreadSelf, void *pvUser)
1503{
1504 PVBOXSERVICECTRLSESSIONTHREAD pThread = (PVBOXSERVICECTRLSESSIONTHREAD)pvUser;
1505 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
1506
1507 uint32_t const idSession = pThread->pStartupInfo->uSessionID;
1508 uint32_t const idClient = g_idControlSvcClient;
1509 VGSvcVerbose(3, "Session ID=%RU32 thread running\n", idSession);
1510
1511 /* Let caller know that we're done initializing, regardless of the result. */
1512 int rc2 = RTThreadUserSignal(hThreadSelf);
1513 AssertRC(rc2);
1514
1515 /*
1516 * Wait for the child process to stop or the shutdown flag to be signalled.
1517 */
1518 RTPROCSTATUS ProcessStatus = { 0, RTPROCEXITREASON_NORMAL };
1519 bool fProcessAlive = true;
1520 bool fSessionCancelled = VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient);
1521 uint32_t cMsShutdownTimeout = 30 * 1000; /** @todo Make this configurable. Later. */
1522 uint64_t msShutdownStart = 0;
1523 uint64_t const msStart = RTTimeMilliTS();
1524 size_t offSecretKey = 0;
1525 int rcWait;
1526 for (;;)
1527 {
1528 /* Secret key feeding. */
1529 if (offSecretKey < sizeof(pThread->abKey))
1530 {
1531 size_t cbWritten = 0;
1532 rc2 = RTPipeWrite(pThread->hKeyPipe, &pThread->abKey[offSecretKey], sizeof(pThread->abKey) - offSecretKey, &cbWritten);
1533 if (RT_SUCCESS(rc2))
1534 offSecretKey += cbWritten;
1535 }
1536
1537 /* Poll child process status. */
1538 rcWait = RTProcWaitNoResume(pThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
1539 if ( rcWait == VINF_SUCCESS
1540 || rcWait == VERR_PROCESS_NOT_FOUND)
1541 {
1542 fProcessAlive = false;
1543 break;
1544 }
1545 AssertMsgBreak(rcWait == VERR_PROCESS_RUNNING || rcWait == VERR_INTERRUPTED,
1546 ("Got unexpected rc=%Rrc while waiting for session process termination\n", rcWait));
1547
1548 /* Shutting down? */
1549 if (ASMAtomicReadBool(&pThread->fShutdown))
1550 {
1551 if (!msShutdownStart)
1552 {
1553 VGSvcVerbose(3, "Notifying guest session process (PID=%RU32, session ID=%RU32) ...\n",
1554 pThread->hProcess, idSession);
1555
1556 VBGLR3GUESTCTRLCMDCTX hostCtx =
1557 {
1558 /* .idClient = */ idClient,
1559 /* .idContext = */ VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
1560 /* .uProtocol = */ pThread->pStartupInfo->uProtocol,
1561 /* .cParams = */ 2
1562 };
1563 rc2 = VbglR3GuestCtrlSessionClose(&hostCtx, 0 /* fFlags */);
1564 if (RT_FAILURE(rc2))
1565 {
1566 VGSvcError("Unable to notify guest session process (PID=%RU32, session ID=%RU32), rc=%Rrc\n",
1567 pThread->hProcess, idSession, rc2);
1568
1569 if (rc2 == VERR_NOT_SUPPORTED)
1570 {
1571 /* Terminate guest session process in case it's not supported by a too old host. */
1572 rc2 = RTProcTerminate(pThread->hProcess);
1573 VGSvcVerbose(3, "Terminating guest session process (PID=%RU32) ended with rc=%Rrc\n",
1574 pThread->hProcess, rc2);
1575 }
1576 break;
1577 }
1578
1579 VGSvcVerbose(3, "Guest session ID=%RU32 thread was asked to terminate, waiting for session process to exit (%RU32 ms timeout) ...\n",
1580 idSession, cMsShutdownTimeout);
1581 msShutdownStart = RTTimeMilliTS();
1582 continue; /* Don't waste time on waiting. */
1583 }
1584 if (RTTimeMilliTS() - msShutdownStart > cMsShutdownTimeout)
1585 {
1586 VGSvcVerbose(3, "Guest session ID=%RU32 process did not shut down within time\n", idSession);
1587 break;
1588 }
1589 }
1590
1591 /* Cancel the prepared session stuff after 30 seconds. */
1592 if ( !fSessionCancelled
1593 && RTTimeMilliTS() - msStart >= 30000)
1594 {
1595 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
1596 fSessionCancelled = true;
1597 }
1598
1599/** @todo r=bird: This 100ms sleep is _extremely_ sucky! */
1600 RTThreadSleep(100); /* Wait a bit. */
1601 }
1602
1603 if (!fSessionCancelled)
1604 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
1605
1606 if (!fProcessAlive)
1607 {
1608 VGSvcVerbose(2, "Guest session process (ID=%RU32) terminated with rc=%Rrc, reason=%d, status=%d\n",
1609 idSession, rcWait, ProcessStatus.enmReason, ProcessStatus.iStatus);
1610 if (ProcessStatus.iStatus == RTEXITCODE_INIT)
1611 {
1612 VGSvcError("Guest session process (ID=%RU32) failed to initialize. Here some hints:\n", idSession);
1613 VGSvcError("- Is logging enabled and the output directory is read-only by the guest session user?\n");
1614 /** @todo Add more here. */
1615 }
1616 }
1617
1618 uint32_t uSessionStatus = GUEST_SESSION_NOTIFYTYPE_UNDEFINED;
1619 uint32_t uSessionRc = VINF_SUCCESS; /** uint32_t vs. int. */
1620
1621 if (fProcessAlive)
1622 {
1623 for (int i = 0; i < 3; i++)
1624 {
1625 if (i)
1626 RTThreadSleep(3000);
1627
1628 VGSvcVerbose(2, "Guest session ID=%RU32 process still alive, killing attempt %d/3\n", idSession, i + 1);
1629
1630 rc2 = RTProcTerminate(pThread->hProcess);
1631 if (RT_SUCCESS(rc2))
1632 break;
1633 }
1634
1635 VGSvcVerbose(2, "Guest session ID=%RU32 process termination resulted in rc=%Rrc\n", idSession, rc2);
1636 uSessionStatus = RT_SUCCESS(rc2) ? GUEST_SESSION_NOTIFYTYPE_TOK : GUEST_SESSION_NOTIFYTYPE_TOA;
1637 }
1638 else if (RT_SUCCESS(rcWait))
1639 {
1640 switch (ProcessStatus.enmReason)
1641 {
1642 case RTPROCEXITREASON_NORMAL:
1643 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
1644 break;
1645
1646 case RTPROCEXITREASON_ABEND:
1647 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
1648 break;
1649
1650 case RTPROCEXITREASON_SIGNAL:
1651 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TES;
1652 break;
1653
1654 default:
1655 AssertMsgFailed(("Unhandled process termination reason (%d)\n", ProcessStatus.enmReason));
1656 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
1657 break;
1658 }
1659 }
1660 else
1661 {
1662 /* If we didn't find the guest process anymore, just assume it terminated normally. */
1663 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
1664 }
1665
1666 /* Make sure to set stopped state before we let the host know. */
1667 ASMAtomicWriteBool(&pThread->fStopped, true);
1668
1669 /* Report final status, regardless if we failed to wait above, so that the host knows what's going on. */
1670 VGSvcVerbose(3, "Reporting final status %RU32 of session ID=%RU32\n", uSessionStatus, idSession);
1671 Assert(uSessionStatus != GUEST_SESSION_NOTIFYTYPE_UNDEFINED);
1672
1673 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
1674 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
1675 rc2 = VbglR3GuestCtrlSessionNotify(&ctx, uSessionStatus, uSessionRc);
1676 if (RT_FAILURE(rc2))
1677 VGSvcError("Reporting final status of session ID=%RU32 failed with rc=%Rrc\n", idSession, rc2);
1678
1679 VGSvcVerbose(3, "Thread for session ID=%RU32 ended with sessionStatus=%RU32, sessionRc=%Rrc\n",
1680 idSession, uSessionStatus, uSessionRc);
1681
1682 return VINF_SUCCESS;
1683}
1684
1685/**
1686 * Reads the secret key the parent VBoxService instance passed us and pass it
1687 * along as a authentication token to the host service.
1688 *
1689 * For older hosts, this sets up the message filtering.
1690 *
1691 * @returns VBox status code.
1692 * @param idClient The HGCM client ID.
1693 * @param idSession The session ID.
1694 */
1695static int vgsvcGstCtrlSessionReadKeyAndAccept(uint32_t idClient, uint32_t idSession)
1696{
1697 /*
1698 * Read it.
1699 */
1700 RTHANDLE Handle;
1701 int rc = RTHandleGetStandard(RTHANDLESTD_INPUT, &Handle);
1702 if (RT_SUCCESS(rc))
1703 {
1704 if (Handle.enmType == RTHANDLETYPE_PIPE)
1705 {
1706 uint8_t abSecretKey[RT_SIZEOFMEMB(VBOXSERVICECTRLSESSIONTHREAD, abKey)];
1707 rc = RTPipeReadBlocking(Handle.u.hPipe, abSecretKey, sizeof(abSecretKey), NULL);
1708 if (RT_SUCCESS(rc))
1709 {
1710 VGSvcVerbose(3, "Got secret key from standard input.\n");
1711
1712 /*
1713 * Do the accepting, if appropriate.
1714 */
1715 if (g_fControlSupportsOptimizations)
1716 {
1717 rc = VbglR3GuestCtrlSessionAccept(idClient, idSession, abSecretKey, sizeof(abSecretKey));
1718 if (RT_SUCCESS(rc))
1719 VGSvcVerbose(3, "Session %u accepted (client ID %u)\n", idClient, idSession);
1720 else
1721 VGSvcError("Failed to accept session %u (client ID %u): %Rrc\n", idClient, idSession, rc);
1722 }
1723 else
1724 {
1725 /* For legacy hosts, we do the filtering thingy. */
1726 rc = VbglR3GuestCtrlMsgFilterSet(idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
1727 VBOX_GUESTCTRL_FILTER_BY_SESSION(idSession), 0);
1728 if (RT_SUCCESS(rc))
1729 VGSvcVerbose(3, "Session %u filtering successfully enabled\n", idSession);
1730 else
1731 VGSvcError("Failed to set session filter: %Rrc\n", rc);
1732 }
1733 }
1734 else
1735 VGSvcError("Error reading secret key from standard input: %Rrc\n", rc);
1736 }
1737 else
1738 {
1739 VGSvcError("Standard input is not a pipe!\n");
1740 rc = VERR_INVALID_HANDLE;
1741 }
1742 RTHandleClose(&Handle);
1743 }
1744 else
1745 VGSvcError("RTHandleGetStandard failed on standard input: %Rrc\n", rc);
1746 return rc;
1747}
1748
1749/**
1750 * Invalidates a guest session by updating all it's internal parameters like host features and stuff.
1751 *
1752 * @param pSession Session to invalidate.
1753 * @param idClient Client ID to use.
1754 */
1755static void vgsvcGstCtrlSessionInvalidate(PVBOXSERVICECTRLSESSION pSession, uint32_t idClient)
1756{
1757 RT_NOREF(pSession);
1758
1759 VGSvcVerbose(1, "Invalidating session %RU32 (client ID=%RU32)\n", idClient, pSession->StartupInfo.uSessionID);
1760
1761 int rc2 = VbglR3GuestCtrlQueryFeatures(idClient, &g_fControlHostFeatures0);
1762 if (RT_SUCCESS(rc2)) /* Querying host features is not fatal -- do not use rc here. */
1763 {
1764 VGSvcVerbose(1, "g_fControlHostFeatures0=%#x\n", g_fControlHostFeatures0);
1765 }
1766 else
1767 VGSvcVerbose(1, "Querying host features failed with %Rrc\n", rc2);
1768}
1769
1770/**
1771 * Main message handler for the guest control session process.
1772 *
1773 * @returns exit code.
1774 * @param pSession Pointer to g_Session.
1775 * @thread main.
1776 */
1777static RTEXITCODE vgsvcGstCtrlSessionSpawnWorker(PVBOXSERVICECTRLSESSION pSession)
1778{
1779 AssertPtrReturn(pSession, RTEXITCODE_FAILURE);
1780 VGSvcVerbose(0, "Hi, this is guest session ID=%RU32\n", pSession->StartupInfo.uSessionID);
1781
1782 /*
1783 * Connect to the host service.
1784 */
1785 uint32_t idClient;
1786 int rc = VbglR3GuestCtrlConnect(&idClient);
1787 if (RT_FAILURE(rc))
1788 return VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
1789 g_fControlSupportsOptimizations = VbglR3GuestCtrlSupportsOptimizations(idClient);
1790 g_idControlSvcClient = idClient;
1791
1792 VGSvcVerbose(1, "Using client ID=%RU32\n", idClient);
1793
1794 vgsvcGstCtrlSessionInvalidate(pSession, idClient);
1795
1796 rc = vgsvcGstCtrlSessionReadKeyAndAccept(idClient, pSession->StartupInfo.uSessionID);
1797 if (RT_SUCCESS(rc))
1798 {
1799 /*
1800 * Report started status.
1801 * If session status cannot be posted to the host for some reason, bail out.
1802 */
1803 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID),
1804 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
1805 rc = VbglR3GuestCtrlSessionNotify(&ctx, GUEST_SESSION_NOTIFYTYPE_STARTED, VINF_SUCCESS);
1806 if (RT_SUCCESS(rc))
1807 {
1808 /*
1809 * Allocate a scratch buffer for messages which also send payload data with them.
1810 * This buffer may grow if the host sends us larger chunks of data.
1811 */
1812 uint32_t cbScratchBuf = _64K;
1813 void *pvScratchBuf = RTMemAlloc(cbScratchBuf);
1814 if (pvScratchBuf)
1815 {
1816 int cFailedMsgPeeks = 0;
1817
1818 /*
1819 * Message processing loop.
1820 */
1821 VBGLR3GUESTCTRLCMDCTX CtxHost = { idClient, 0 /* Context ID */, pSession->StartupInfo.uProtocol, 0 };
1822 for (;;)
1823 {
1824 VGSvcVerbose(3, "Waiting for host msg ...\n");
1825 uint32_t uMsg = 0;
1826 rc = VbglR3GuestCtrlMsgPeekWait(idClient, &uMsg, &CtxHost.uNumParms, NULL);
1827 if (RT_SUCCESS(rc))
1828 {
1829 VGSvcVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved (%Rrc)\n", uMsg, CtxHost.uNumParms, rc);
1830
1831 /*
1832 * Pass it on to the session handler.
1833 * Note! Only when handling HOST_SESSION_CLOSE is the rc used.
1834 */
1835 bool fShutdown = false;
1836 rc = VGSvcGstCtrlSessionHandler(pSession, uMsg, &CtxHost, &pvScratchBuf, &cbScratchBuf, &fShutdown);
1837 if (fShutdown)
1838 break;
1839
1840 cFailedMsgPeeks = 0;
1841
1842 /* Let others run (guests are often single CPU) ... */
1843 RTThreadYield();
1844 }
1845 /*
1846 * Handle restore notification from host. All the context IDs (sessions,
1847 * files, proceses, etc) are invalidated by a VM restore and must be closed.
1848 */
1849 else if (rc == VERR_VM_RESTORED)
1850 {
1851 VGSvcVerbose(1, "The VM session ID changed (i.e. restored)\n");
1852 int rc2 = VGSvcGstCtrlSessionClose(&g_Session);
1853 AssertRC(rc2);
1854
1855 rc2 = VbglR3GuestCtrlSessionHasChanged(g_idControlSvcClient, g_idControlSvcClient);
1856 AssertRC(rc2);
1857
1858 /* Invalidate the internal state to match the current host we got restored from. */
1859 vgsvcGstCtrlSessionInvalidate(pSession, g_idControlSvcClient);
1860 }
1861 else
1862 {
1863 VGSvcVerbose(1, "Getting host message failed with %Rrc\n", rc);
1864
1865 if (cFailedMsgPeeks++ == 3)
1866 break;
1867
1868 RTThreadSleep(3 * RT_MS_1SEC);
1869
1870 /** @todo Shouldn't we have a plan for handling connection loss and such? */
1871 }
1872 }
1873
1874 /*
1875 * Shutdown.
1876 */
1877 RTMemFree(pvScratchBuf);
1878 }
1879 else
1880 rc = VERR_NO_MEMORY;
1881
1882 VGSvcVerbose(0, "Session %RU32 ended\n", pSession->StartupInfo.uSessionID);
1883 }
1884 else
1885 VGSvcError("Reporting session ID=%RU32 started status failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
1886 }
1887 else
1888 VGSvcError("Setting message filterAdd=0x%x failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
1889
1890 VGSvcVerbose(3, "Disconnecting client ID=%RU32 ...\n", idClient);
1891 VbglR3GuestCtrlDisconnect(idClient);
1892 g_idControlSvcClient = 0;
1893
1894 VGSvcVerbose(3, "Session worker returned with rc=%Rrc\n", rc);
1895 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1896}
1897
1898
1899/**
1900 * Finds a (formerly) started guest process given by its PID and increases its
1901 * reference count.
1902 *
1903 * Must be decreased by the caller with VGSvcGstCtrlProcessRelease().
1904 *
1905 * @returns Guest process if found, otherwise NULL.
1906 * @param pSession Pointer to guest session where to search process in.
1907 * @param uPID PID to search for.
1908 *
1909 * @note This does *not lock the process!
1910 */
1911PVBOXSERVICECTRLPROCESS VGSvcGstCtrlSessionRetainProcess(PVBOXSERVICECTRLSESSION pSession, uint32_t uPID)
1912{
1913 AssertPtrReturn(pSession, NULL);
1914
1915 PVBOXSERVICECTRLPROCESS pProcess = NULL;
1916 int rc = RTCritSectEnter(&pSession->CritSect);
1917 if (RT_SUCCESS(rc))
1918 {
1919 PVBOXSERVICECTRLPROCESS pCurProcess;
1920 RTListForEach(&pSession->lstProcesses, pCurProcess, VBOXSERVICECTRLPROCESS, Node)
1921 {
1922 if (pCurProcess->uPID == uPID)
1923 {
1924 rc = RTCritSectEnter(&pCurProcess->CritSect);
1925 if (RT_SUCCESS(rc))
1926 {
1927 pCurProcess->cRefs++;
1928 rc = RTCritSectLeave(&pCurProcess->CritSect);
1929 AssertRC(rc);
1930 }
1931
1932 if (RT_SUCCESS(rc))
1933 pProcess = pCurProcess;
1934 break;
1935 }
1936 }
1937
1938 rc = RTCritSectLeave(&pSession->CritSect);
1939 AssertRC(rc);
1940 }
1941
1942 return pProcess;
1943}
1944
1945
1946int VGSvcGstCtrlSessionClose(PVBOXSERVICECTRLSESSION pSession)
1947{
1948 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1949
1950 VGSvcVerbose(0, "Session %RU32 is about to close ...\n", pSession->StartupInfo.uSessionID);
1951
1952 int rc = RTCritSectEnter(&pSession->CritSect);
1953 if (RT_SUCCESS(rc))
1954 {
1955 /*
1956 * Close all guest processes.
1957 */
1958 VGSvcVerbose(0, "Stopping all guest processes ...\n");
1959
1960 /* Signal all guest processes in the active list that we want to shutdown. */
1961 PVBOXSERVICECTRLPROCESS pProcess;
1962 RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
1963 VGSvcGstCtrlProcessStop(pProcess);
1964
1965 VGSvcVerbose(1, "%RU32 guest processes were signalled to stop\n", pSession->cProcesses);
1966
1967 /* Wait for all active threads to shutdown and destroy the active thread list. */
1968 PVBOXSERVICECTRLPROCESS pProcessNext;
1969 RTListForEachSafe(&pSession->lstProcesses, pProcess, pProcessNext, VBOXSERVICECTRLPROCESS, Node)
1970 {
1971 int rc3 = RTCritSectLeave(&pSession->CritSect);
1972 AssertRC(rc3);
1973
1974 int rc2 = VGSvcGstCtrlProcessWait(pProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
1975
1976 rc3 = RTCritSectEnter(&pSession->CritSect);
1977 AssertRC(rc3);
1978
1979 if (RT_SUCCESS(rc2))
1980 {
1981 rc2 = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
1982 if (RT_SUCCESS(rc2))
1983 {
1984 VGSvcGstCtrlProcessFree(pProcess);
1985 pProcess = NULL;
1986 }
1987 }
1988 }
1989
1990 AssertMsg(pSession->cProcesses == 0,
1991 ("Session process list still contains %RU32 when it should not\n", pSession->cProcesses));
1992 AssertMsg(RTListIsEmpty(&pSession->lstProcesses),
1993 ("Session process list is not empty when it should\n"));
1994
1995 /*
1996 * Close all left guest files.
1997 */
1998 VGSvcVerbose(0, "Closing all guest files ...\n");
1999
2000 PVBOXSERVICECTRLFILE pFile, pFileNext;
2001 RTListForEachSafe(&pSession->lstFiles, pFile, pFileNext, VBOXSERVICECTRLFILE, Node)
2002 {
2003 int rc2 = vgsvcGstCtrlSessionFileFree(pFile);
2004 if (RT_FAILURE(rc2))
2005 {
2006 VGSvcError("Unable to close file '%s'; rc=%Rrc\n", pFile->pszName, rc2);
2007 if (RT_SUCCESS(rc))
2008 rc = rc2;
2009 /* Keep going. */
2010 }
2011
2012 pFile = NULL; /* To make it obvious. */
2013 }
2014
2015 AssertMsg(pSession->cFiles == 0,
2016 ("Session file list still contains %RU32 when it should not\n", pSession->cFiles));
2017 AssertMsg(RTListIsEmpty(&pSession->lstFiles),
2018 ("Session file list is not empty when it should\n"));
2019
2020 int rc2 = RTCritSectLeave(&pSession->CritSect);
2021 if (RT_SUCCESS(rc))
2022 rc = rc2;
2023 }
2024
2025 return rc;
2026}
2027
2028
2029int VGSvcGstCtrlSessionDestroy(PVBOXSERVICECTRLSESSION pSession)
2030{
2031 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2032
2033 int rc = VGSvcGstCtrlSessionClose(pSession);
2034
2035 /* Destroy critical section. */
2036 RTCritSectDelete(&pSession->CritSect);
2037
2038 return rc;
2039}
2040
2041
2042int VGSvcGstCtrlSessionInit(PVBOXSERVICECTRLSESSION pSession, uint32_t fFlags)
2043{
2044 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2045
2046 RTListInit(&pSession->lstProcesses);
2047 RTListInit(&pSession->lstFiles);
2048
2049 pSession->cProcesses = 0;
2050 pSession->cFiles = 0;
2051
2052 pSession->fFlags = fFlags;
2053
2054 /* Init critical section for protecting the thread lists. */
2055 int rc = RTCritSectInit(&pSession->CritSect);
2056 AssertRC(rc);
2057
2058 return rc;
2059}
2060
2061
2062/**
2063 * Adds a guest process to a session's process list.
2064 *
2065 * @return VBox status code.
2066 * @param pSession Guest session to add process to.
2067 * @param pProcess Guest process to add.
2068 */
2069int VGSvcGstCtrlSessionProcessAdd(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
2070{
2071 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2072 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2073
2074 int rc = RTCritSectEnter(&pSession->CritSect);
2075 if (RT_SUCCESS(rc))
2076 {
2077 VGSvcVerbose(3, "Adding process (PID %RU32) to session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
2078
2079 /* Add process to session list. */
2080 RTListAppend(&pSession->lstProcesses, &pProcess->Node);
2081
2082 pSession->cProcesses++;
2083 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
2084 pSession->StartupInfo.uSessionID, pSession->cProcesses);
2085
2086 int rc2 = RTCritSectLeave(&pSession->CritSect);
2087 if (RT_SUCCESS(rc))
2088 rc = rc2;
2089 }
2090
2091 return VINF_SUCCESS;
2092}
2093
2094/**
2095 * Removes a guest process from a session's process list.
2096 * Internal version, does not do locking.
2097 *
2098 * @return VBox status code.
2099 * @param pSession Guest session to remove process from.
2100 * @param pProcess Guest process to remove.
2101 */
2102static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
2103{
2104 VGSvcVerbose(3, "Removing process (PID %RU32) from session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
2105 AssertReturn(pProcess->cRefs == 0, VERR_WRONG_ORDER);
2106
2107 RTListNodeRemove(&pProcess->Node);
2108
2109 AssertReturn(pSession->cProcesses, VERR_WRONG_ORDER);
2110 pSession->cProcesses--;
2111 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
2112 pSession->StartupInfo.uSessionID, pSession->cProcesses);
2113
2114 return VINF_SUCCESS;
2115}
2116
2117/**
2118 * Removes a guest process from a session's process list.
2119 *
2120 * @return VBox status code.
2121 * @param pSession Guest session to remove process from.
2122 * @param pProcess Guest process to remove.
2123 */
2124int VGSvcGstCtrlSessionProcessRemove(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
2125{
2126 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2127 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2128
2129 int rc = RTCritSectEnter(&pSession->CritSect);
2130 if (RT_SUCCESS(rc))
2131 {
2132 rc = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
2133
2134 int rc2 = RTCritSectLeave(&pSession->CritSect);
2135 if (RT_SUCCESS(rc))
2136 rc = rc2;
2137 }
2138
2139 return rc;
2140}
2141
2142
2143/**
2144 * Determines whether starting a new guest process according to the
2145 * maximum number of concurrent guest processes defined is allowed or not.
2146 *
2147 * @return VBox status code.
2148 * @param pSession The guest session.
2149 * @param pfAllowed \c True if starting (another) guest process
2150 * is allowed, \c false if not.
2151 */
2152int VGSvcGstCtrlSessionProcessStartAllowed(const PVBOXSERVICECTRLSESSION pSession, bool *pfAllowed)
2153{
2154 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2155 AssertPtrReturn(pfAllowed, VERR_INVALID_POINTER);
2156
2157 int rc = RTCritSectEnter(&pSession->CritSect);
2158 if (RT_SUCCESS(rc))
2159 {
2160 /*
2161 * Check if we're respecting our memory policy by checking
2162 * how many guest processes are started and served already.
2163 */
2164 bool fLimitReached = false;
2165 if (pSession->uProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
2166 {
2167 VGSvcVerbose(3, "Maximum kept guest processes set to %RU32, acurrent=%RU32\n",
2168 pSession->uProcsMaxKept, pSession->cProcesses);
2169
2170 int32_t iProcsLeft = (pSession->uProcsMaxKept - pSession->cProcesses - 1);
2171 if (iProcsLeft < 0)
2172 {
2173 VGSvcVerbose(3, "Maximum running guest processes reached (%RU32)\n", pSession->uProcsMaxKept);
2174 fLimitReached = true;
2175 }
2176 }
2177
2178 *pfAllowed = !fLimitReached;
2179
2180 int rc2 = RTCritSectLeave(&pSession->CritSect);
2181 if (RT_SUCCESS(rc))
2182 rc = rc2;
2183 }
2184
2185 return rc;
2186}
2187
2188
2189/**
2190 * Cleans up stopped and no longer used processes.
2191 *
2192 * This will free and remove processes from the session's process list.
2193 *
2194 * @returns VBox status code.
2195 * @param pSession Session to clean up processes for.
2196 */
2197static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession)
2198{
2199 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2200
2201 VGSvcVerbose(3, "Cleaning up stopped processes for session %RU32 ...\n", pSession->StartupInfo.uSessionID);
2202
2203 int rc2 = RTCritSectEnter(&pSession->CritSect);
2204 AssertRC(rc2);
2205
2206 int rc = VINF_SUCCESS;
2207
2208 PVBOXSERVICECTRLPROCESS pCurProcess, pNextProcess;
2209 RTListForEachSafe(&pSession->lstProcesses, pCurProcess, pNextProcess, VBOXSERVICECTRLPROCESS, Node)
2210 {
2211 if (ASMAtomicReadBool(&pCurProcess->fStopped))
2212 {
2213 rc2 = RTCritSectLeave(&pSession->CritSect);
2214 AssertRC(rc2);
2215
2216 rc = VGSvcGstCtrlProcessWait(pCurProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
2217 if (RT_SUCCESS(rc))
2218 {
2219 VGSvcGstCtrlSessionProcessRemove(pSession, pCurProcess);
2220 VGSvcGstCtrlProcessFree(pCurProcess);
2221 }
2222
2223 rc2 = RTCritSectEnter(&pSession->CritSect);
2224 AssertRC(rc2);
2225
2226 /* If failed, try next time we're being called. */
2227 }
2228 }
2229
2230 rc2 = RTCritSectLeave(&pSession->CritSect);
2231 AssertRC(rc2);
2232
2233 if (RT_FAILURE(rc))
2234 VGSvcError("Cleaning up stopped processes for session %RU32 failed with %Rrc\n", pSession->StartupInfo.uSessionID, rc);
2235
2236 return rc;
2237}
2238
2239
2240/**
2241 * Creates the process for a guest session.
2242 *
2243 * @return VBox status code.
2244 * @param pSessionStartupInfo Session startup info.
2245 * @param pSessionThread The session thread under construction.
2246 * @param uCtrlSessionThread The session thread debug ordinal.
2247 */
2248static int vgsvcVGSvcGstCtrlSessionThreadCreateProcess(const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
2249 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread, uint32_t uCtrlSessionThread)
2250{
2251 RT_NOREF(uCtrlSessionThread);
2252
2253 /*
2254 * Is this an anonymous session? Anonymous sessions run with the same
2255 * privileges as the main VBoxService executable.
2256 */
2257 bool const fAnonymous = pSessionThread->pStartupInfo->pszUser
2258 && pSessionThread->pStartupInfo->pszUser[0] == '\0';
2259 if (fAnonymous)
2260 {
2261 Assert(!strlen(pSessionThread->pStartupInfo->pszPassword));
2262 Assert(!strlen(pSessionThread->pStartupInfo->pszDomain));
2263
2264 VGSvcVerbose(3, "New anonymous guest session ID=%RU32 created, fFlags=%x, using protocol %RU32\n",
2265 pSessionStartupInfo->uSessionID,
2266 pSessionStartupInfo->fFlags,
2267 pSessionStartupInfo->uProtocol);
2268 }
2269 else
2270 {
2271 VGSvcVerbose(3, "Spawning new guest session ID=%RU32, szUser=%s, szPassword=%s, szDomain=%s, fFlags=%x, using protocol %RU32\n",
2272 pSessionStartupInfo->uSessionID,
2273 pSessionStartupInfo->pszUser,
2274#ifdef DEBUG
2275 pSessionStartupInfo->pszPassword,
2276#else
2277 "XXX", /* Never show passwords in release mode. */
2278#endif
2279 pSessionStartupInfo->pszDomain,
2280 pSessionStartupInfo->fFlags,
2281 pSessionStartupInfo->uProtocol);
2282 }
2283
2284 /*
2285 * Spawn a child process for doing the actual session handling.
2286 * Start by assembling the argument list.
2287 */
2288 char szExeName[RTPATH_MAX];
2289 char *pszExeName = RTProcGetExecutablePath(szExeName, sizeof(szExeName));
2290 AssertReturn(pszExeName, VERR_FILENAME_TOO_LONG);
2291
2292 char szParmSessionID[32];
2293 RTStrPrintf(szParmSessionID, sizeof(szParmSessionID), "--session-id=%RU32", pSessionThread->pStartupInfo->uSessionID);
2294
2295 char szParmSessionProto[32];
2296 RTStrPrintf(szParmSessionProto, sizeof(szParmSessionProto), "--session-proto=%RU32",
2297 pSessionThread->pStartupInfo->uProtocol);
2298#ifdef DEBUG
2299 char szParmThreadId[32];
2300 RTStrPrintf(szParmThreadId, sizeof(szParmThreadId), "--thread-id=%RU32", uCtrlSessionThread);
2301#endif
2302 unsigned idxArg = 0; /* Next index in argument vector. */
2303 char const *apszArgs[24];
2304
2305 apszArgs[idxArg++] = pszExeName;
2306 apszArgs[idxArg++] = "guestsession";
2307 apszArgs[idxArg++] = szParmSessionID;
2308 apszArgs[idxArg++] = szParmSessionProto;
2309#ifdef DEBUG
2310 apszArgs[idxArg++] = szParmThreadId;
2311#endif
2312 if (!fAnonymous) /* Do we need to pass a user name? */
2313 {
2314 apszArgs[idxArg++] = "--user";
2315 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszUser;
2316
2317 if (strlen(pSessionThread->pStartupInfo->pszDomain))
2318 {
2319 apszArgs[idxArg++] = "--domain";
2320 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszDomain;
2321 }
2322 }
2323
2324 /* Add same verbose flags as parent process. */
2325 char szParmVerbose[32];
2326 if (g_cVerbosity > 0)
2327 {
2328 unsigned cVs = RT_MIN(g_cVerbosity, RT_ELEMENTS(szParmVerbose) - 2);
2329 szParmVerbose[0] = '-';
2330 memset(&szParmVerbose[1], 'v', cVs);
2331 szParmVerbose[1 + cVs] = '\0';
2332 apszArgs[idxArg++] = szParmVerbose;
2333 }
2334
2335 /* Add log file handling. Each session will have an own
2336 * log file, naming based on the parent log file. */
2337 char szParmLogFile[sizeof(g_szLogFile) + 128];
2338 if (g_szLogFile[0])
2339 {
2340 const char *pszSuffix = RTPathSuffix(g_szLogFile);
2341 if (!pszSuffix)
2342 pszSuffix = strchr(g_szLogFile, '\0');
2343 size_t cchBase = pszSuffix - g_szLogFile;
2344
2345 RTTIMESPEC Now;
2346 RTTimeNow(&Now);
2347 char szTime[64];
2348 RTTimeSpecToString(&Now, szTime, sizeof(szTime));
2349
2350 /* Replace out characters not allowed on Windows platforms, put in by RTTimeSpecToString(). */
2351 static const RTUNICP s_uszValidRangePairs[] =
2352 {
2353 ' ', ' ',
2354 '(', ')',
2355 '-', '.',
2356 '0', '9',
2357 'A', 'Z',
2358 'a', 'z',
2359 '_', '_',
2360 0xa0, 0xd7af,
2361 '\0'
2362 };
2363 ssize_t cReplaced = RTStrPurgeComplementSet(szTime, s_uszValidRangePairs, '_' /* chReplacement */);
2364 AssertReturn(cReplaced, VERR_INVALID_UTF8_ENCODING);
2365
2366#ifndef DEBUG
2367 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%s-%s%s",
2368 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, pSessionStartupInfo->pszUser, szTime, pszSuffix);
2369#else
2370 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%RU32-%s-%s%s",
2371 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, uCtrlSessionThread,
2372 pSessionStartupInfo->pszUser, szTime, pszSuffix);
2373#endif
2374 apszArgs[idxArg++] = "--logfile";
2375 apszArgs[idxArg++] = szParmLogFile;
2376 }
2377
2378#ifdef DEBUG
2379 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT)
2380 apszArgs[idxArg++] = "--dump-stdout";
2381 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR)
2382 apszArgs[idxArg++] = "--dump-stderr";
2383#endif
2384 apszArgs[idxArg] = NULL;
2385 Assert(idxArg < RT_ELEMENTS(apszArgs));
2386
2387 if (g_cVerbosity > 3)
2388 {
2389 VGSvcVerbose(4, "Spawning parameters:\n");
2390 for (idxArg = 0; apszArgs[idxArg]; idxArg++)
2391 VGSvcVerbose(4, " %s\n", apszArgs[idxArg]);
2392 }
2393
2394 /*
2395 * Flags.
2396 */
2397 uint32_t const fProcCreate = RTPROC_FLAGS_PROFILE
2398#ifdef RT_OS_WINDOWS
2399 | RTPROC_FLAGS_SERVICE
2400 | RTPROC_FLAGS_HIDDEN
2401#endif
2402 ;
2403
2404 /*
2405 * Configure standard handles.
2406 */
2407 RTHANDLE hStdIn;
2408 int rc = RTPipeCreate(&hStdIn.u.hPipe, &pSessionThread->hKeyPipe, RTPIPE_C_INHERIT_READ);
2409 if (RT_SUCCESS(rc))
2410 {
2411 hStdIn.enmType = RTHANDLETYPE_PIPE;
2412
2413 RTHANDLE hStdOutAndErr;
2414 rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
2415 if (RT_SUCCESS(rc))
2416 {
2417 hStdOutAndErr.enmType = RTHANDLETYPE_FILE;
2418
2419 /*
2420 * Windows: If a domain name is given, construct an UPN (User Principle Name)
2421 * with the domain name built-in, e.g. "[email protected]".
2422 */
2423 const char *pszUser = pSessionThread->pStartupInfo->pszUser;
2424#ifdef RT_OS_WINDOWS
2425 char *pszUserUPN = NULL;
2426 if (pSessionThread->pStartupInfo->pszDomain[0])
2427 {
2428 int cchbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s",
2429 pSessionThread->pStartupInfo->pszUser,
2430 pSessionThread->pStartupInfo->pszDomain);
2431 if (cchbUserUPN > 0)
2432 {
2433 pszUser = pszUserUPN;
2434 VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
2435 }
2436 else
2437 rc = VERR_NO_STR_MEMORY;
2438 }
2439 if (RT_SUCCESS(rc))
2440#endif
2441 {
2442 /*
2443 * Finally, create the process.
2444 */
2445 rc = RTProcCreateEx(pszExeName, apszArgs, RTENV_DEFAULT, fProcCreate,
2446 &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
2447 !fAnonymous ? pszUser : NULL,
2448 !fAnonymous ? pSessionThread->pStartupInfo->pszPassword : NULL,
2449 NULL /*pvExtraData*/,
2450 &pSessionThread->hProcess);
2451 }
2452#ifdef RT_OS_WINDOWS
2453 RTStrFree(pszUserUPN);
2454#endif
2455 RTFileClose(hStdOutAndErr.u.hFile);
2456 }
2457
2458 RTPipeClose(hStdIn.u.hPipe);
2459 }
2460 return rc;
2461}
2462
2463
2464/**
2465 * Creates a guest session.
2466 *
2467 * This will spawn a new VBoxService.exe instance under behalf of the given user
2468 * which then will act as a session host. On successful open, the session will
2469 * be added to the given session thread list.
2470 *
2471 * @return VBox status code.
2472 * @param pList Which list to use to store the session thread in.
2473 * @param pSessionStartupInfo Session startup info.
2474 * @param ppSessionThread Returns newly created session thread on success.
2475 * Optional.
2476 */
2477int VGSvcGstCtrlSessionThreadCreate(PRTLISTANCHOR pList, const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
2478 PVBOXSERVICECTRLSESSIONTHREAD *ppSessionThread)
2479{
2480 AssertPtrReturn(pList, VERR_INVALID_POINTER);
2481 AssertPtrReturn(pSessionStartupInfo, VERR_INVALID_POINTER);
2482 /* ppSessionThread is optional. */
2483
2484#ifdef VBOX_STRICT
2485 /* Check for existing session in debug mode. Should never happen because of
2486 * Main consistency. */
2487 PVBOXSERVICECTRLSESSIONTHREAD pSessionCur;
2488 RTListForEach(pList, pSessionCur, VBOXSERVICECTRLSESSIONTHREAD, Node)
2489 {
2490 AssertMsgReturn( pSessionCur->fStopped == true
2491 || pSessionCur->pStartupInfo->uSessionID != pSessionStartupInfo->uSessionID,
2492 ("Guest session thread ID=%RU32 already exists (fStopped=%RTbool)\n",
2493 pSessionCur->pStartupInfo->uSessionID, pSessionCur->fStopped), VERR_ALREADY_EXISTS);
2494 }
2495#endif
2496
2497 /* Static counter to help tracking session thread <-> process relations. */
2498 static uint32_t s_uCtrlSessionThread = 0;
2499
2500 /*
2501 * Allocate and initialize the session thread structure.
2502 */
2503 int rc;
2504 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread = (PVBOXSERVICECTRLSESSIONTHREAD)RTMemAllocZ(sizeof(*pSessionThread));
2505 if (pSessionThread)
2506 {
2507 //pSessionThread->fShutdown = false;
2508 //pSessionThread->fStarted = false;
2509 //pSessionThread->fStopped = false;
2510 pSessionThread->hKeyPipe = NIL_RTPIPE;
2511 pSessionThread->Thread = NIL_RTTHREAD;
2512 pSessionThread->hProcess = NIL_RTPROCESS;
2513
2514 /* Duplicate startup info. */
2515 pSessionThread->pStartupInfo = VbglR3GuestCtrlSessionStartupInfoDup(pSessionStartupInfo);
2516 AssertPtrReturn(pSessionThread->pStartupInfo, VERR_NO_MEMORY);
2517
2518 /* Generate the secret key. */
2519 RTRandBytes(pSessionThread->abKey, sizeof(pSessionThread->abKey));
2520
2521 rc = RTCritSectInit(&pSessionThread->CritSect);
2522 AssertRC(rc);
2523 if (RT_SUCCESS(rc))
2524 {
2525 /*
2526 * Give the session key to the host so it can validate the client.
2527 */
2528 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
2529 {
2530 for (uint32_t i = 0; i < 10; i++)
2531 {
2532 rc = VbglR3GuestCtrlSessionPrepare(g_idControlSvcClient, pSessionStartupInfo->uSessionID,
2533 pSessionThread->abKey, sizeof(pSessionThread->abKey));
2534 if (rc != VERR_OUT_OF_RESOURCES)
2535 break;
2536 RTThreadSleep(100);
2537 }
2538 }
2539 if (RT_SUCCESS(rc))
2540 {
2541 s_uCtrlSessionThread++;
2542
2543 /*
2544 * Start the session child process.
2545 */
2546 rc = vgsvcVGSvcGstCtrlSessionThreadCreateProcess(pSessionStartupInfo, pSessionThread, s_uCtrlSessionThread);
2547 if (RT_SUCCESS(rc))
2548 {
2549 /*
2550 * Start the session thread.
2551 */
2552 rc = RTThreadCreateF(&pSessionThread->Thread, vgsvcGstCtrlSessionThread, pSessionThread /*pvUser*/, 0 /*cbStack*/,
2553 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctls%RU32", s_uCtrlSessionThread);
2554 if (RT_SUCCESS(rc))
2555 {
2556 /* Wait for the thread to initialize. */
2557 rc = RTThreadUserWait(pSessionThread->Thread, RT_MS_1MIN);
2558 if ( RT_SUCCESS(rc)
2559 && !ASMAtomicReadBool(&pSessionThread->fShutdown))
2560 {
2561 VGSvcVerbose(2, "Thread for session ID=%RU32 started\n", pSessionThread->pStartupInfo->uSessionID);
2562
2563 ASMAtomicXchgBool(&pSessionThread->fStarted, true);
2564
2565 /* Add session to list. */
2566 RTListAppend(pList, &pSessionThread->Node);
2567 if (ppSessionThread) /* Return session if wanted. */
2568 *ppSessionThread = pSessionThread;
2569 return VINF_SUCCESS;
2570 }
2571
2572 /*
2573 * Bail out.
2574 */
2575 VGSvcError("Thread for session ID=%RU32 failed to start, rc=%Rrc\n",
2576 pSessionThread->pStartupInfo->uSessionID, rc);
2577 if (RT_SUCCESS_NP(rc))
2578 rc = VERR_CANT_CREATE; /** @todo Find a better rc. */
2579 }
2580 else
2581 VGSvcError("Creating session thread failed, rc=%Rrc\n", rc);
2582
2583 RTProcTerminate(pSessionThread->hProcess);
2584 uint32_t cMsWait = 1;
2585 while ( RTProcWait(pSessionThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, NULL) == VERR_PROCESS_RUNNING
2586 && cMsWait <= 9) /* 1023 ms */
2587 {
2588 RTThreadSleep(cMsWait);
2589 cMsWait <<= 1;
2590 }
2591 }
2592
2593 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
2594 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, pSessionStartupInfo->uSessionID);
2595 }
2596 else
2597 VGSvcVerbose(3, "VbglR3GuestCtrlSessionPrepare failed: %Rrc\n", rc);
2598 RTPipeClose(pSessionThread->hKeyPipe);
2599 pSessionThread->hKeyPipe = NIL_RTPIPE;
2600 RTCritSectDelete(&pSessionThread->CritSect);
2601 }
2602 RTMemFree(pSessionThread);
2603 }
2604 else
2605 rc = VERR_NO_MEMORY;
2606
2607 VGSvcVerbose(3, "Spawning session thread returned returned rc=%Rrc\n", rc);
2608 return rc;
2609}
2610
2611
2612/**
2613 * Waits for a formerly opened guest session process to close.
2614 *
2615 * @return VBox status code.
2616 * @param pThread Guest session thread to wait for.
2617 * @param uTimeoutMS Waiting timeout (in ms).
2618 * @param fFlags Closing flags.
2619 */
2620int VGSvcGstCtrlSessionThreadWait(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t uTimeoutMS, uint32_t fFlags)
2621{
2622 RT_NOREF(fFlags);
2623 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2624 /** @todo Validate closing flags. */
2625
2626 AssertMsgReturn(pThread->Thread != NIL_RTTHREAD,
2627 ("Guest session thread of session %p does not exist when it should\n", pThread),
2628 VERR_NOT_FOUND);
2629
2630 int rc = VINF_SUCCESS;
2631
2632 /*
2633 * The spawned session process should have received the same closing request,
2634 * so just wait for the process to close.
2635 */
2636 if (ASMAtomicReadBool(&pThread->fStarted))
2637 {
2638 /* Ask the thread to shutdown. */
2639 ASMAtomicXchgBool(&pThread->fShutdown, true);
2640
2641 VGSvcVerbose(3, "Waiting for session thread ID=%RU32 to close (%RU32ms) ...\n",
2642 pThread->pStartupInfo->uSessionID, uTimeoutMS);
2643
2644 int rcThread;
2645 rc = RTThreadWait(pThread->Thread, uTimeoutMS, &rcThread);
2646 if (RT_SUCCESS(rc))
2647 {
2648 AssertMsg(pThread->fStopped, ("Thread of session ID=%RU32 not in stopped state when it should\n",
2649 pThread->pStartupInfo->uSessionID));
2650
2651 VGSvcVerbose(3, "Session thread ID=%RU32 ended with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rcThread);
2652 }
2653 else
2654 VGSvcError("Waiting for session thread ID=%RU32 to close failed with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rc);
2655 }
2656 else
2657 VGSvcVerbose(3, "Thread for session ID=%RU32 not in started state, skipping wait\n", pThread->pStartupInfo->uSessionID);
2658
2659 LogFlowFuncLeaveRC(rc);
2660 return rc;
2661}
2662
2663/**
2664 * Waits for the specified session thread to end and remove
2665 * it from the session thread list.
2666 *
2667 * @return VBox status code.
2668 * @param pThread Session thread to destroy.
2669 * @param fFlags Closing flags.
2670 */
2671int VGSvcGstCtrlSessionThreadDestroy(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t fFlags)
2672{
2673 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2674 AssertPtrReturn(pThread->pStartupInfo, VERR_WRONG_ORDER);
2675
2676 const uint32_t uSessionID = pThread->pStartupInfo->uSessionID;
2677
2678 VGSvcVerbose(3, "Destroying session ID=%RU32 ...\n", uSessionID);
2679
2680 int rc = VGSvcGstCtrlSessionThreadWait(pThread, 5 * 60 * 1000 /* 5 minutes timeout */, fFlags);
2681 if (RT_SUCCESS(rc))
2682 {
2683 VbglR3GuestCtrlSessionStartupInfoFree(pThread->pStartupInfo);
2684 pThread->pStartupInfo = NULL;
2685
2686 /* Remove session from list and destroy object. */
2687 RTListNodeRemove(&pThread->Node);
2688
2689 RTMemFree(pThread);
2690 pThread = NULL;
2691 }
2692
2693 VGSvcVerbose(3, "Destroyed session ID=%RU32 with %Rrc\n", uSessionID, rc);
2694 return rc;
2695}
2696
2697/**
2698 * Close all open guest session threads.
2699 *
2700 * @note Caller is responsible for locking!
2701 *
2702 * @return VBox status code.
2703 * @param pList Which list to close the session threads for.
2704 * @param fFlags Closing flags.
2705 */
2706int VGSvcGstCtrlSessionThreadDestroyAll(PRTLISTANCHOR pList, uint32_t fFlags)
2707{
2708 AssertPtrReturn(pList, VERR_INVALID_POINTER);
2709
2710 int rc = VINF_SUCCESS;
2711
2712 /*int rc = VbglR3GuestCtrlClose
2713 if (RT_FAILURE(rc))
2714 VGSvcError("Cancelling pending waits failed; rc=%Rrc\n", rc);*/
2715
2716 PVBOXSERVICECTRLSESSIONTHREAD pSessIt;
2717 PVBOXSERVICECTRLSESSIONTHREAD pSessItNext;
2718 RTListForEachSafe(pList, pSessIt, pSessItNext, VBOXSERVICECTRLSESSIONTHREAD, Node)
2719 {
2720 int rc2 = VGSvcGstCtrlSessionThreadDestroy(pSessIt, fFlags);
2721 if (RT_FAILURE(rc2))
2722 {
2723 VGSvcError("Closing session thread '%s' failed with rc=%Rrc\n", RTThreadGetName(pSessIt->Thread), rc2);
2724 if (RT_SUCCESS(rc))
2725 rc = rc2;
2726 /* Keep going. */
2727 }
2728 }
2729
2730 VGSvcVerbose(4, "Destroying guest session threads ended with %Rrc\n", rc);
2731 return rc;
2732}
2733
2734
2735/**
2736 * Main function for the session process.
2737 *
2738 * @returns exit code.
2739 * @param argc Argument count.
2740 * @param argv Argument vector (UTF-8).
2741 */
2742RTEXITCODE VGSvcGstCtrlSessionSpawnInit(int argc, char **argv)
2743{
2744 static const RTGETOPTDEF s_aOptions[] =
2745 {
2746 { "--domain", VBOXSERVICESESSIONOPT_DOMAIN, RTGETOPT_REQ_STRING },
2747#ifdef DEBUG
2748 { "--dump-stdout", VBOXSERVICESESSIONOPT_DUMP_STDOUT, RTGETOPT_REQ_NOTHING },
2749 { "--dump-stderr", VBOXSERVICESESSIONOPT_DUMP_STDERR, RTGETOPT_REQ_NOTHING },
2750#endif
2751 { "--logfile", VBOXSERVICESESSIONOPT_LOG_FILE, RTGETOPT_REQ_STRING },
2752 { "--user", VBOXSERVICESESSIONOPT_USERNAME, RTGETOPT_REQ_STRING },
2753 { "--session-id", VBOXSERVICESESSIONOPT_SESSION_ID, RTGETOPT_REQ_UINT32 },
2754 { "--session-proto", VBOXSERVICESESSIONOPT_SESSION_PROTO, RTGETOPT_REQ_UINT32 },
2755#ifdef DEBUG
2756 { "--thread-id", VBOXSERVICESESSIONOPT_THREAD_ID, RTGETOPT_REQ_UINT32 },
2757#endif /* DEBUG */
2758 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2759 };
2760
2761 RTGETOPTSTATE GetState;
2762 RTGetOptInit(&GetState, argc, argv,
2763 s_aOptions, RT_ELEMENTS(s_aOptions),
2764 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2765
2766 uint32_t fSession = VBOXSERVICECTRLSESSION_FLAG_SPAWN;
2767
2768 /* Protocol and session ID must be specified explicitly. */
2769 g_Session.StartupInfo.uProtocol = UINT32_MAX;
2770 g_Session.StartupInfo.uSessionID = UINT32_MAX;
2771
2772 int ch;
2773 RTGETOPTUNION ValueUnion;
2774 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2775 {
2776 /* For options that require an argument, ValueUnion has received the value. */
2777 switch (ch)
2778 {
2779 case VBOXSERVICESESSIONOPT_DOMAIN:
2780 /* Information not needed right now, skip. */
2781 break;
2782#ifdef DEBUG
2783 case VBOXSERVICESESSIONOPT_DUMP_STDOUT:
2784 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
2785 break;
2786
2787 case VBOXSERVICESESSIONOPT_DUMP_STDERR:
2788 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
2789 break;
2790#endif
2791 case VBOXSERVICESESSIONOPT_SESSION_ID:
2792 g_Session.StartupInfo.uSessionID = ValueUnion.u32;
2793 break;
2794
2795 case VBOXSERVICESESSIONOPT_SESSION_PROTO:
2796 g_Session.StartupInfo.uProtocol = ValueUnion.u32;
2797 break;
2798#ifdef DEBUG
2799 case VBOXSERVICESESSIONOPT_THREAD_ID:
2800 /* Not handled. Mainly for processs listing. */
2801 break;
2802#endif
2803 case VBOXSERVICESESSIONOPT_LOG_FILE:
2804 {
2805 int rc = RTStrCopy(g_szLogFile, sizeof(g_szLogFile), ValueUnion.psz);
2806 if (RT_FAILURE(rc))
2807 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error copying log file name: %Rrc", rc);
2808 break;
2809 }
2810
2811 case VBOXSERVICESESSIONOPT_USERNAME:
2812 /* Information not needed right now, skip. */
2813 break;
2814
2815 /** @todo Implement help? */
2816
2817 case 'v':
2818 g_cVerbosity++;
2819 break;
2820
2821 case VINF_GETOPT_NOT_OPTION:
2822 {
2823 if (!RTStrICmp(ValueUnion.psz, VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
2824 break;
2825 /* else fall through and bail out. */
2826 RT_FALL_THROUGH();
2827 }
2828 default:
2829 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'", ValueUnion.psz);
2830 }
2831 }
2832
2833 /* Check that we've got all the required options. */
2834 if (g_Session.StartupInfo.uProtocol == UINT32_MAX)
2835 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No protocol version specified");
2836
2837 if (g_Session.StartupInfo.uSessionID == UINT32_MAX)
2838 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No session ID specified");
2839
2840 /* Init the session object. */
2841 int rc = VGSvcGstCtrlSessionInit(&g_Session, fSession);
2842 if (RT_FAILURE(rc))
2843 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to initialize session object, rc=%Rrc\n", rc);
2844
2845 rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
2846 if (RT_FAILURE(rc))
2847 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to create log file '%s', rc=%Rrc\n",
2848 g_szLogFile[0] ? g_szLogFile : "<None>", rc);
2849
2850 RTEXITCODE rcExit = vgsvcGstCtrlSessionSpawnWorker(&g_Session);
2851
2852 VGSvcLogDestroy();
2853 return rcExit;
2854}
2855
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