VirtualBox

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

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

Guest Control/VBoxService: Assertion nit. 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 84731 2020-06-09 07:12:44Z 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",
1026 (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "Rebooting" : "Shutting down", rc);
1027 }
1028 }
1029 else
1030 {
1031 VGSvcError("Error fetching parameters for shutdown / reboot request: %Rrc\n", rc);
1032 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1033 }
1034
1035 return rc;
1036}
1037
1038
1039/**
1040 * Handles getting the user's home directory.
1041 *
1042 * @returns VBox status code.
1043 * @param pSession Guest session.
1044 * @param pHostCtx Host context.
1045 */
1046static int vgsvcGstCtrlSessionHandlePathUserHome(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1047{
1048 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1049 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1050
1051 /*
1052 * Retrieve the request.
1053 */
1054 int rc = VbglR3GuestCtrlPathGetUserHome(pHostCtx);
1055 if (RT_SUCCESS(rc))
1056 {
1057 /*
1058 * Get the path and pass it back to the host..
1059 */
1060 char szPath[RTPATH_MAX];
1061 rc = RTPathUserHome(szPath, sizeof(szPath));
1062
1063#ifdef DEBUG
1064 VGSvcVerbose(2, "User home is '%s', rc=%Rrc\n", szPath, rc);
1065#endif
1066 /* Report back in any case. */
1067 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
1068 RT_SUCCESS(rc) ?(uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
1069 if (RT_FAILURE(rc2))
1070 {
1071 VGSvcError("Failed to report user home, rc=%Rrc\n", rc2);
1072 if (RT_SUCCESS(rc))
1073 rc = rc2;
1074 }
1075 }
1076 else
1077 {
1078 VGSvcError("Error fetching parameters for user home directory path request: %Rrc\n", rc);
1079 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1080 }
1081 return rc;
1082}
1083
1084/**
1085 * Handles starting a guest processes.
1086 *
1087 * @returns VBox status code.
1088 * @param pSession Guest session.
1089 * @param pHostCtx Host context.
1090 */
1091static int vgsvcGstCtrlSessionHandleProcExec(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1092{
1093 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1094 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1095
1096 /* Initialize maximum environment block size -- needed as input
1097 * parameter to retrieve the stuff from the host. On output this then
1098 * will contain the actual block size. */
1099 PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo;
1100 int rc = VbglR3GuestCtrlProcGetStart(pHostCtx, &pStartupInfo);
1101 if (RT_SUCCESS(rc))
1102 {
1103 VGSvcVerbose(3, "Request to start process szCmd=%s, fFlags=0x%x, szArgs=%s, szEnv=%s, uTimeout=%RU32\n",
1104 pStartupInfo->pszCmd, pStartupInfo->fFlags,
1105 pStartupInfo->cArgs ? pStartupInfo->pszArgs : "<None>",
1106 pStartupInfo->cEnvVars ? pStartupInfo->pszEnv : "<None>",
1107 pStartupInfo->uTimeLimitMS);
1108
1109 bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
1110 rc = VGSvcGstCtrlSessionProcessStartAllowed(pSession, &fStartAllowed);
1111 if (RT_SUCCESS(rc))
1112 {
1113 vgsvcGstCtrlSessionCleanupProcesses(pSession);
1114
1115 if (fStartAllowed)
1116 rc = VGSvcGstCtrlProcessStart(pSession, pStartupInfo, pHostCtx->uContextID);
1117 else
1118 rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
1119 }
1120
1121 /* We're responsible for signaling errors to the host (it will wait for ever otherwise). */
1122 if (RT_FAILURE(rc))
1123 {
1124 VGSvcError("Starting process failed with rc=%Rrc, protocol=%RU32, parameters=%RU32\n",
1125 rc, pHostCtx->uProtocol, pHostCtx->uNumParms);
1126 int rc2 = VbglR3GuestCtrlProcCbStatus(pHostCtx, 0 /*nil-PID*/, PROC_STS_ERROR, rc, NULL /*pvData*/, 0 /*cbData*/);
1127 if (RT_FAILURE(rc2))
1128 VGSvcError("Error sending start process status to host, rc=%Rrc\n", rc2);
1129 }
1130
1131 VbglR3GuestCtrlProcStartupInfoFree(pStartupInfo);
1132 pStartupInfo = NULL;
1133 }
1134 else
1135 {
1136 VGSvcError("Failed to retrieve parameters for process start: %Rrc (cParms=%u)\n", rc, pHostCtx->uNumParms);
1137 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1138 }
1139
1140 return rc;
1141}
1142
1143
1144/**
1145 * Sends stdin input to a specific guest process.
1146 *
1147 * @returns VBox status code.
1148 * @param pSession The session which is in charge.
1149 * @param pHostCtx The host context to use.
1150 * @param ppvScratchBuf The scratch buffer, we may grow it.
1151 * @param pcbScratchBuf The scratch buffer size for retrieving the input
1152 * data.
1153 */
1154static int vgsvcGstCtrlSessionHandleProcInput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1155 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
1156{
1157 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1158 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1159
1160 /*
1161 * Retrieve the data from the host.
1162 */
1163 uint32_t uPID;
1164 uint32_t fFlags;
1165 uint32_t cbInput;
1166 int rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1167 if ( rc == VERR_BUFFER_OVERFLOW
1168 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbInput))
1169 rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1170 if (RT_SUCCESS(rc))
1171 {
1172 if (fFlags & INPUT_FLAG_EOF)
1173 VGSvcVerbose(4, "Got last process input block for PID=%RU32 (%RU32 bytes) ...\n", uPID, cbInput);
1174
1175 /*
1176 * Locate the process and feed it.
1177 */
1178 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1179 if (pProcess)
1180 {
1181 rc = VGSvcGstCtrlProcessHandleInput(pProcess, pHostCtx, RT_BOOL(fFlags & INPUT_FLAG_EOF),
1182 *ppvScratchBuf, RT_MIN(cbInput, *pcbScratchBuf));
1183 if (RT_FAILURE(rc))
1184 VGSvcError("Error handling input message for PID=%RU32, rc=%Rrc\n", uPID, rc);
1185 VGSvcGstCtrlProcessRelease(pProcess);
1186 }
1187 else
1188 {
1189 VGSvcError("Could not find PID %u for feeding %u bytes to it.\n", uPID, cbInput);
1190 rc = VERR_PROCESS_NOT_FOUND;
1191 VbglR3GuestCtrlProcCbStatusInput(pHostCtx, uPID, INPUT_STS_ERROR, rc, 0);
1192 }
1193 }
1194 else
1195 {
1196 VGSvcError("Failed to retrieve parameters for process input: %Rrc (scratch %u bytes)\n", rc, *pcbScratchBuf);
1197 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1198 }
1199
1200 VGSvcVerbose(6, "Feeding input to PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1201 return rc;
1202}
1203
1204
1205/**
1206 * Gets stdout/stderr output of a specific guest process.
1207 *
1208 * @returns VBox status code.
1209 * @param pSession The session which is in charge.
1210 * @param pHostCtx The host context to use.
1211 */
1212static int vgsvcGstCtrlSessionHandleProcOutput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1213{
1214 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1215 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1216
1217 /*
1218 * Retrieve the request.
1219 */
1220 uint32_t uPID;
1221 uint32_t uHandleID;
1222 uint32_t fFlags;
1223 int rc = VbglR3GuestCtrlProcGetOutput(pHostCtx, &uPID, &uHandleID, &fFlags);
1224#ifdef DEBUG_andy
1225 VGSvcVerbose(4, "Getting output for PID=%RU32, CID=%RU32, uHandleID=%RU32, fFlags=%RU32\n",
1226 uPID, pHostCtx->uContextID, uHandleID, fFlags);
1227#endif
1228 if (RT_SUCCESS(rc))
1229 {
1230 /*
1231 * Locate the process and hand it the output request.
1232 */
1233 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1234 if (pProcess)
1235 {
1236 rc = VGSvcGstCtrlProcessHandleOutput(pProcess, pHostCtx, uHandleID, _64K /* cbToRead */, fFlags);
1237 if (RT_FAILURE(rc))
1238 VGSvcError("Error getting output for PID=%RU32, rc=%Rrc\n", uPID, rc);
1239 VGSvcGstCtrlProcessRelease(pProcess);
1240 }
1241 else
1242 {
1243 VGSvcError("Could not find PID %u for draining handle %u (%#x).\n", uPID, uHandleID, uHandleID);
1244 rc = VERR_PROCESS_NOT_FOUND;
1245/** @todo r=bird:
1246 *
1247 * No way to report status status code for output requests?
1248 *
1249 */
1250 }
1251 }
1252 else
1253 {
1254 VGSvcError("Error fetching parameters for process output request: %Rrc\n", rc);
1255 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1256 }
1257
1258#ifdef DEBUG_andy
1259 VGSvcVerbose(4, "Getting output for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1260#endif
1261 return rc;
1262}
1263
1264
1265/**
1266 * Tells a guest process to terminate.
1267 *
1268 * @returns VBox status code.
1269 * @param pSession The session which is in charge.
1270 * @param pHostCtx The host context to use.
1271 */
1272static int vgsvcGstCtrlSessionHandleProcTerminate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1273{
1274 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1275 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1276
1277 /*
1278 * Retrieve the request.
1279 */
1280 uint32_t uPID;
1281 int rc = VbglR3GuestCtrlProcGetTerminate(pHostCtx, &uPID);
1282 if (RT_SUCCESS(rc))
1283 {
1284 /*
1285 * Locate the process and terminate it.
1286 */
1287 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1288 if (pProcess)
1289 {
1290 rc = VGSvcGstCtrlProcessHandleTerm(pProcess);
1291 if (RT_FAILURE(rc))
1292 VGSvcError("Error terminating PID=%RU32, rc=%Rrc\n", uPID, rc);
1293
1294 VGSvcGstCtrlProcessRelease(pProcess);
1295 }
1296 else
1297 {
1298 VGSvcError("Could not find PID %u for termination.\n", uPID);
1299 rc = VERR_PROCESS_NOT_FOUND;
1300 }
1301 }
1302 else
1303 {
1304 VGSvcError("Error fetching parameters for process termination request: %Rrc\n", rc);
1305 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1306 }
1307#ifdef DEBUG_andy
1308 VGSvcVerbose(4, "Terminating PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1309#endif
1310 return rc;
1311}
1312
1313
1314static int vgsvcGstCtrlSessionHandleProcWaitFor(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1315{
1316 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1317 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1318
1319 /*
1320 * Retrieve the request.
1321 */
1322 uint32_t uPID;
1323 uint32_t uWaitFlags;
1324 uint32_t uTimeoutMS;
1325 int rc = VbglR3GuestCtrlProcGetWaitFor(pHostCtx, &uPID, &uWaitFlags, &uTimeoutMS);
1326 if (RT_SUCCESS(rc))
1327 {
1328 /*
1329 * Locate the process and the realize that this call makes no sense
1330 * since we'll notify the host when a process terminates anyway and
1331 * hopefully don't need any additional encouragement.
1332 */
1333 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1334 if (pProcess)
1335 {
1336 rc = VERR_NOT_IMPLEMENTED; /** @todo */
1337 VGSvcGstCtrlProcessRelease(pProcess);
1338 }
1339 else
1340 rc = VERR_NOT_FOUND;
1341 }
1342 else
1343 {
1344 VGSvcError("Error fetching parameters for process wait request: %Rrc\n", rc);
1345 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1346 }
1347 return rc;
1348}
1349
1350
1351int VGSvcGstCtrlSessionHandler(PVBOXSERVICECTRLSESSION pSession, uint32_t uMsg, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1352 void **ppvScratchBuf, uint32_t *pcbScratchBuf, volatile bool *pfShutdown)
1353{
1354 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1355 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1356 AssertPtrReturn(*ppvScratchBuf, VERR_INVALID_POINTER);
1357 AssertPtrReturn(pfShutdown, VERR_INVALID_POINTER);
1358
1359
1360 /*
1361 * Only anonymous sessions (that is, sessions which run with local
1362 * service privileges) or spawned session processes can do certain
1363 * operations.
1364 */
1365 bool const fImpersonated = RT_BOOL(pSession->fFlags & ( VBOXSERVICECTRLSESSION_FLAG_SPAWN
1366 | VBOXSERVICECTRLSESSION_FLAG_ANONYMOUS));
1367 int rc = VERR_NOT_SUPPORTED; /* Play safe by default. */
1368
1369 switch (uMsg)
1370 {
1371 case HOST_MSG_SESSION_CLOSE:
1372 /* Shutdown (this spawn). */
1373 rc = VGSvcGstCtrlSessionClose(pSession);
1374 *pfShutdown = true; /* Shutdown in any case. */
1375 break;
1376
1377 case HOST_MSG_DIR_REMOVE:
1378 if (fImpersonated)
1379 rc = vgsvcGstCtrlSessionHandleDirRemove(pSession, pHostCtx);
1380 break;
1381
1382 case HOST_MSG_EXEC_CMD:
1383 rc = vgsvcGstCtrlSessionHandleProcExec(pSession, pHostCtx);
1384 break;
1385
1386 case HOST_MSG_EXEC_SET_INPUT:
1387 rc = vgsvcGstCtrlSessionHandleProcInput(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1388 break;
1389
1390 case HOST_MSG_EXEC_GET_OUTPUT:
1391 rc = vgsvcGstCtrlSessionHandleProcOutput(pSession, pHostCtx);
1392 break;
1393
1394 case HOST_MSG_EXEC_TERMINATE:
1395 rc = vgsvcGstCtrlSessionHandleProcTerminate(pSession, pHostCtx);
1396 break;
1397
1398 case HOST_MSG_EXEC_WAIT_FOR:
1399 rc = vgsvcGstCtrlSessionHandleProcWaitFor(pSession, pHostCtx);
1400 break;
1401
1402 case HOST_MSG_FILE_OPEN:
1403 if (fImpersonated)
1404 rc = vgsvcGstCtrlSessionHandleFileOpen(pSession, pHostCtx);
1405 break;
1406
1407 case HOST_MSG_FILE_CLOSE:
1408 if (fImpersonated)
1409 rc = vgsvcGstCtrlSessionHandleFileClose(pSession, pHostCtx);
1410 break;
1411
1412 case HOST_MSG_FILE_READ:
1413 if (fImpersonated)
1414 rc = vgsvcGstCtrlSessionHandleFileRead(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1415 break;
1416
1417 case HOST_MSG_FILE_READ_AT:
1418 if (fImpersonated)
1419 rc = vgsvcGstCtrlSessionHandleFileReadAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1420 break;
1421
1422 case HOST_MSG_FILE_WRITE:
1423 if (fImpersonated)
1424 rc = vgsvcGstCtrlSessionHandleFileWrite(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1425 break;
1426
1427 case HOST_MSG_FILE_WRITE_AT:
1428 if (fImpersonated)
1429 rc = vgsvcGstCtrlSessionHandleFileWriteAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
1430 break;
1431
1432 case HOST_MSG_FILE_SEEK:
1433 if (fImpersonated)
1434 rc = vgsvcGstCtrlSessionHandleFileSeek(pSession, pHostCtx);
1435 break;
1436
1437 case HOST_MSG_FILE_TELL:
1438 if (fImpersonated)
1439 rc = vgsvcGstCtrlSessionHandleFileTell(pSession, pHostCtx);
1440 break;
1441
1442 case HOST_MSG_FILE_SET_SIZE:
1443 if (fImpersonated)
1444 rc = vgsvcGstCtrlSessionHandleFileSetSize(pSession, pHostCtx);
1445 break;
1446
1447 case HOST_MSG_PATH_RENAME:
1448 if (fImpersonated)
1449 rc = vgsvcGstCtrlSessionHandlePathRename(pSession, pHostCtx);
1450 break;
1451
1452 case HOST_MSG_PATH_USER_DOCUMENTS:
1453 if (fImpersonated)
1454 rc = vgsvcGstCtrlSessionHandlePathUserDocuments(pSession, pHostCtx);
1455 break;
1456
1457 case HOST_MSG_PATH_USER_HOME:
1458 if (fImpersonated)
1459 rc = vgsvcGstCtrlSessionHandlePathUserHome(pSession, pHostCtx);
1460 break;
1461
1462 case HOST_MSG_SHUTDOWN:
1463 rc = vgsvcGstCtrlSessionHandleShutdown(pSession, pHostCtx);
1464 break;
1465
1466 default: /* Not supported, see next code block. */
1467 break;
1468 }
1469 if (RT_SUCCESS(rc))
1470 { /* likely */ }
1471 else if (rc != VERR_NOT_SUPPORTED) /* Note: Reply to host must must be sent by above handler. */
1472 VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);
1473 else
1474 {
1475 /* We must skip and notify host here as best we can... */
1476 VGSvcVerbose(1, "Unsupported message (uMsg=%RU32, cParms=%RU32) from host, skipping\n", uMsg, pHostCtx->uNumParms);
1477 if (VbglR3GuestCtrlSupportsOptimizations(pHostCtx->uClientID))
1478 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, VERR_NOT_SUPPORTED, uMsg);
1479 else
1480 VbglR3GuestCtrlMsgSkipOld(pHostCtx->uClientID);
1481 rc = VINF_SUCCESS;
1482 }
1483
1484 if (RT_FAILURE(rc))
1485 VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);
1486
1487 return rc;
1488}
1489
1490
1491/**
1492 * Thread main routine for a spawned guest session process.
1493 *
1494 * This thread runs in the main executable to control the spawned session process.
1495 *
1496 * @returns VBox status code.
1497 * @param hThreadSelf Thread handle.
1498 * @param pvUser Pointer to a VBOXSERVICECTRLSESSIONTHREAD structure.
1499 *
1500 */
1501static DECLCALLBACK(int) vgsvcGstCtrlSessionThread(RTTHREAD hThreadSelf, void *pvUser)
1502{
1503 PVBOXSERVICECTRLSESSIONTHREAD pThread = (PVBOXSERVICECTRLSESSIONTHREAD)pvUser;
1504 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
1505
1506 uint32_t const idSession = pThread->pStartupInfo->uSessionID;
1507 uint32_t const idClient = g_idControlSvcClient;
1508 VGSvcVerbose(3, "Session ID=%RU32 thread running\n", idSession);
1509
1510 /* Let caller know that we're done initializing, regardless of the result. */
1511 int rc2 = RTThreadUserSignal(hThreadSelf);
1512 AssertRC(rc2);
1513
1514 /*
1515 * Wait for the child process to stop or the shutdown flag to be signalled.
1516 */
1517 RTPROCSTATUS ProcessStatus = { 0, RTPROCEXITREASON_NORMAL };
1518 bool fProcessAlive = true;
1519 bool fSessionCancelled = VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient);
1520 uint32_t cMsShutdownTimeout = 30 * 1000; /** @todo Make this configurable. Later. */
1521 uint64_t msShutdownStart = 0;
1522 uint64_t const msStart = RTTimeMilliTS();
1523 size_t offSecretKey = 0;
1524 int rcWait;
1525 for (;;)
1526 {
1527 /* Secret key feeding. */
1528 if (offSecretKey < sizeof(pThread->abKey))
1529 {
1530 size_t cbWritten = 0;
1531 rc2 = RTPipeWrite(pThread->hKeyPipe, &pThread->abKey[offSecretKey], sizeof(pThread->abKey) - offSecretKey, &cbWritten);
1532 if (RT_SUCCESS(rc2))
1533 offSecretKey += cbWritten;
1534 }
1535
1536 /* Poll child process status. */
1537 rcWait = RTProcWaitNoResume(pThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
1538 if ( rcWait == VINF_SUCCESS
1539 || rcWait == VERR_PROCESS_NOT_FOUND)
1540 {
1541 fProcessAlive = false;
1542 break;
1543 }
1544 AssertMsgBreak(rcWait == VERR_PROCESS_RUNNING || rcWait == VERR_INTERRUPTED,
1545 ("Got unexpected rc=%Rrc while waiting for session process termination\n", rcWait));
1546
1547 /* Shutting down? */
1548 if (ASMAtomicReadBool(&pThread->fShutdown))
1549 {
1550 if (!msShutdownStart)
1551 {
1552 VGSvcVerbose(3, "Notifying guest session process (PID=%RU32, session ID=%RU32) ...\n",
1553 pThread->hProcess, idSession);
1554
1555 VBGLR3GUESTCTRLCMDCTX hostCtx =
1556 {
1557 /* .idClient = */ idClient,
1558 /* .idContext = */ VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
1559 /* .uProtocol = */ pThread->pStartupInfo->uProtocol,
1560 /* .cParams = */ 2
1561 };
1562 rc2 = VbglR3GuestCtrlSessionClose(&hostCtx, 0 /* fFlags */);
1563 if (RT_FAILURE(rc2))
1564 {
1565 VGSvcError("Unable to notify guest session process (PID=%RU32, session ID=%RU32), rc=%Rrc\n",
1566 pThread->hProcess, idSession, rc2);
1567
1568 if (rc2 == VERR_NOT_SUPPORTED)
1569 {
1570 /* Terminate guest session process in case it's not supported by a too old host. */
1571 rc2 = RTProcTerminate(pThread->hProcess);
1572 VGSvcVerbose(3, "Terminating guest session process (PID=%RU32) ended with rc=%Rrc\n",
1573 pThread->hProcess, rc2);
1574 }
1575 break;
1576 }
1577
1578 VGSvcVerbose(3, "Guest session ID=%RU32 thread was asked to terminate, waiting for session process to exit (%RU32 ms timeout) ...\n",
1579 idSession, cMsShutdownTimeout);
1580 msShutdownStart = RTTimeMilliTS();
1581 continue; /* Don't waste time on waiting. */
1582 }
1583 if (RTTimeMilliTS() - msShutdownStart > cMsShutdownTimeout)
1584 {
1585 VGSvcVerbose(3, "Guest session ID=%RU32 process did not shut down within time\n", idSession);
1586 break;
1587 }
1588 }
1589
1590 /* Cancel the prepared session stuff after 30 seconds. */
1591 if ( !fSessionCancelled
1592 && RTTimeMilliTS() - msStart >= 30000)
1593 {
1594 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
1595 fSessionCancelled = true;
1596 }
1597
1598/** @todo r=bird: This 100ms sleep is _extremely_ sucky! */
1599 RTThreadSleep(100); /* Wait a bit. */
1600 }
1601
1602 if (!fSessionCancelled)
1603 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
1604
1605 if (!fProcessAlive)
1606 {
1607 VGSvcVerbose(2, "Guest session process (ID=%RU32) terminated with rc=%Rrc, reason=%d, status=%d\n",
1608 idSession, rcWait, ProcessStatus.enmReason, ProcessStatus.iStatus);
1609 if (ProcessStatus.iStatus == RTEXITCODE_INIT)
1610 {
1611 VGSvcError("Guest session process (ID=%RU32) failed to initialize. Here some hints:\n", idSession);
1612 VGSvcError("- Is logging enabled and the output directory is read-only by the guest session user?\n");
1613 /** @todo Add more here. */
1614 }
1615 }
1616
1617 uint32_t uSessionStatus = GUEST_SESSION_NOTIFYTYPE_UNDEFINED;
1618 uint32_t uSessionRc = VINF_SUCCESS; /** uint32_t vs. int. */
1619
1620 if (fProcessAlive)
1621 {
1622 for (int i = 0; i < 3; i++)
1623 {
1624 if (i)
1625 RTThreadSleep(3000);
1626
1627 VGSvcVerbose(2, "Guest session ID=%RU32 process still alive, killing attempt %d/3\n", idSession, i + 1);
1628
1629 rc2 = RTProcTerminate(pThread->hProcess);
1630 if (RT_SUCCESS(rc2))
1631 break;
1632 }
1633
1634 VGSvcVerbose(2, "Guest session ID=%RU32 process termination resulted in rc=%Rrc\n", idSession, rc2);
1635 uSessionStatus = RT_SUCCESS(rc2) ? GUEST_SESSION_NOTIFYTYPE_TOK : GUEST_SESSION_NOTIFYTYPE_TOA;
1636 }
1637 else if (RT_SUCCESS(rcWait))
1638 {
1639 switch (ProcessStatus.enmReason)
1640 {
1641 case RTPROCEXITREASON_NORMAL:
1642 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
1643 break;
1644
1645 case RTPROCEXITREASON_ABEND:
1646 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
1647 break;
1648
1649 case RTPROCEXITREASON_SIGNAL:
1650 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TES;
1651 break;
1652
1653 default:
1654 AssertMsgFailed(("Unhandled process termination reason (%d)\n", ProcessStatus.enmReason));
1655 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
1656 break;
1657 }
1658 }
1659 else
1660 {
1661 /* If we didn't find the guest process anymore, just assume it terminated normally. */
1662 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
1663 }
1664
1665 /* Make sure to set stopped state before we let the host know. */
1666 ASMAtomicWriteBool(&pThread->fStopped, true);
1667
1668 /* Report final status, regardless if we failed to wait above, so that the host knows what's going on. */
1669 VGSvcVerbose(3, "Reporting final status %RU32 of session ID=%RU32\n", uSessionStatus, idSession);
1670 Assert(uSessionStatus != GUEST_SESSION_NOTIFYTYPE_UNDEFINED);
1671
1672 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
1673 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
1674 rc2 = VbglR3GuestCtrlSessionNotify(&ctx, uSessionStatus, uSessionRc);
1675 if (RT_FAILURE(rc2))
1676 VGSvcError("Reporting final status of session ID=%RU32 failed with rc=%Rrc\n", idSession, rc2);
1677
1678 VGSvcVerbose(3, "Thread for session ID=%RU32 ended with sessionStatus=%RU32, sessionRc=%Rrc\n",
1679 idSession, uSessionStatus, uSessionRc);
1680
1681 return VINF_SUCCESS;
1682}
1683
1684/**
1685 * Reads the secret key the parent VBoxService instance passed us and pass it
1686 * along as a authentication token to the host service.
1687 *
1688 * For older hosts, this sets up the message filtering.
1689 *
1690 * @returns VBox status code.
1691 * @param idClient The HGCM client ID.
1692 * @param idSession The session ID.
1693 */
1694static int vgsvcGstCtrlSessionReadKeyAndAccept(uint32_t idClient, uint32_t idSession)
1695{
1696 /*
1697 * Read it.
1698 */
1699 RTHANDLE Handle;
1700 int rc = RTHandleGetStandard(RTHANDLESTD_INPUT, &Handle);
1701 if (RT_SUCCESS(rc))
1702 {
1703 if (Handle.enmType == RTHANDLETYPE_PIPE)
1704 {
1705 uint8_t abSecretKey[RT_SIZEOFMEMB(VBOXSERVICECTRLSESSIONTHREAD, abKey)];
1706 rc = RTPipeReadBlocking(Handle.u.hPipe, abSecretKey, sizeof(abSecretKey), NULL);
1707 if (RT_SUCCESS(rc))
1708 {
1709 VGSvcVerbose(3, "Got secret key from standard input.\n");
1710
1711 /*
1712 * Do the accepting, if appropriate.
1713 */
1714 if (g_fControlSupportsOptimizations)
1715 {
1716 rc = VbglR3GuestCtrlSessionAccept(idClient, idSession, abSecretKey, sizeof(abSecretKey));
1717 if (RT_SUCCESS(rc))
1718 VGSvcVerbose(3, "Session %u accepted (client ID %u)\n", idClient, idSession);
1719 else
1720 VGSvcError("Failed to accept session %u (client ID %u): %Rrc\n", idClient, idSession, rc);
1721 }
1722 else
1723 {
1724 /* For legacy hosts, we do the filtering thingy. */
1725 rc = VbglR3GuestCtrlMsgFilterSet(idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
1726 VBOX_GUESTCTRL_FILTER_BY_SESSION(idSession), 0);
1727 if (RT_SUCCESS(rc))
1728 VGSvcVerbose(3, "Session %u filtering successfully enabled\n", idSession);
1729 else
1730 VGSvcError("Failed to set session filter: %Rrc\n", rc);
1731 }
1732 }
1733 else
1734 VGSvcError("Error reading secret key from standard input: %Rrc\n", rc);
1735 }
1736 else
1737 {
1738 VGSvcError("Standard input is not a pipe!\n");
1739 rc = VERR_INVALID_HANDLE;
1740 }
1741 RTHandleClose(&Handle);
1742 }
1743 else
1744 VGSvcError("RTHandleGetStandard failed on standard input: %Rrc\n", rc);
1745 return rc;
1746}
1747
1748/**
1749 * Invalidates a guest session by updating all it's internal parameters like host features and stuff.
1750 *
1751 * @param pSession Session to invalidate.
1752 * @param idClient Client ID to use.
1753 */
1754static void vgsvcGstCtrlSessionInvalidate(PVBOXSERVICECTRLSESSION pSession, uint32_t idClient)
1755{
1756 RT_NOREF(pSession);
1757
1758 VGSvcVerbose(1, "Invalidating session %RU32 (client ID=%RU32)\n", idClient, pSession->StartupInfo.uSessionID);
1759
1760 int rc2 = VbglR3GuestCtrlQueryFeatures(idClient, &g_fControlHostFeatures0);
1761 if (RT_SUCCESS(rc2)) /* Querying host features is not fatal -- do not use rc here. */
1762 {
1763 VGSvcVerbose(1, "g_fControlHostFeatures0=%#x\n", g_fControlHostFeatures0);
1764 }
1765 else
1766 VGSvcVerbose(1, "Querying host features failed with %Rrc\n", rc2);
1767}
1768
1769/**
1770 * Main message handler for the guest control session process.
1771 *
1772 * @returns exit code.
1773 * @param pSession Pointer to g_Session.
1774 * @thread main.
1775 */
1776static RTEXITCODE vgsvcGstCtrlSessionSpawnWorker(PVBOXSERVICECTRLSESSION pSession)
1777{
1778 AssertPtrReturn(pSession, RTEXITCODE_FAILURE);
1779 VGSvcVerbose(0, "Hi, this is guest session ID=%RU32\n", pSession->StartupInfo.uSessionID);
1780
1781 /*
1782 * Connect to the host service.
1783 */
1784 uint32_t idClient;
1785 int rc = VbglR3GuestCtrlConnect(&idClient);
1786 if (RT_FAILURE(rc))
1787 return VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
1788 g_fControlSupportsOptimizations = VbglR3GuestCtrlSupportsOptimizations(idClient);
1789 g_idControlSvcClient = idClient;
1790
1791 VGSvcVerbose(1, "Using client ID=%RU32\n", idClient);
1792
1793 vgsvcGstCtrlSessionInvalidate(pSession, idClient);
1794
1795 rc = vgsvcGstCtrlSessionReadKeyAndAccept(idClient, pSession->StartupInfo.uSessionID);
1796 if (RT_SUCCESS(rc))
1797 {
1798 /*
1799 * Report started status.
1800 * If session status cannot be posted to the host for some reason, bail out.
1801 */
1802 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID),
1803 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
1804 rc = VbglR3GuestCtrlSessionNotify(&ctx, GUEST_SESSION_NOTIFYTYPE_STARTED, VINF_SUCCESS);
1805 if (RT_SUCCESS(rc))
1806 {
1807 /*
1808 * Allocate a scratch buffer for messages which also send payload data with them.
1809 * This buffer may grow if the host sends us larger chunks of data.
1810 */
1811 uint32_t cbScratchBuf = _64K;
1812 void *pvScratchBuf = RTMemAlloc(cbScratchBuf);
1813 if (pvScratchBuf)
1814 {
1815 int cFailedMsgPeeks = 0;
1816
1817 /*
1818 * Message processing loop.
1819 */
1820 VBGLR3GUESTCTRLCMDCTX CtxHost = { idClient, 0 /* Context ID */, pSession->StartupInfo.uProtocol, 0 };
1821 for (;;)
1822 {
1823 VGSvcVerbose(3, "Waiting for host msg ...\n");
1824 uint32_t uMsg = 0;
1825 rc = VbglR3GuestCtrlMsgPeekWait(idClient, &uMsg, &CtxHost.uNumParms, NULL);
1826 if (RT_SUCCESS(rc))
1827 {
1828 VGSvcVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved (%Rrc)\n", uMsg, CtxHost.uNumParms, rc);
1829
1830 /*
1831 * Pass it on to the session handler.
1832 * Note! Only when handling HOST_SESSION_CLOSE is the rc used.
1833 */
1834 bool fShutdown = false;
1835 rc = VGSvcGstCtrlSessionHandler(pSession, uMsg, &CtxHost, &pvScratchBuf, &cbScratchBuf, &fShutdown);
1836 if (fShutdown)
1837 break;
1838
1839 cFailedMsgPeeks = 0;
1840
1841 /* Let others run (guests are often single CPU) ... */
1842 RTThreadYield();
1843 }
1844 /*
1845 * Handle restore notification from host. All the context IDs (sessions,
1846 * files, proceses, etc) are invalidated by a VM restore and must be closed.
1847 */
1848 else if (rc == VERR_VM_RESTORED)
1849 {
1850 VGSvcVerbose(1, "The VM session ID changed (i.e. restored)\n");
1851 int rc2 = VGSvcGstCtrlSessionClose(&g_Session);
1852 AssertRC(rc2);
1853
1854 rc2 = VbglR3GuestCtrlSessionHasChanged(g_idControlSvcClient, g_idControlSvcClient);
1855 AssertRC(rc2);
1856
1857 /* Invalidate the internal state to match the current host we got restored from. */
1858 vgsvcGstCtrlSessionInvalidate(pSession, g_idControlSvcClient);
1859 }
1860 else
1861 {
1862 VGSvcVerbose(1, "Getting host message failed with %Rrc\n", rc);
1863
1864 if (cFailedMsgPeeks++ == 3)
1865 break;
1866
1867 RTThreadSleep(3 * RT_MS_1SEC);
1868
1869 /** @todo Shouldn't we have a plan for handling connection loss and such? */
1870 }
1871 }
1872
1873 /*
1874 * Shutdown.
1875 */
1876 RTMemFree(pvScratchBuf);
1877 }
1878 else
1879 rc = VERR_NO_MEMORY;
1880
1881 VGSvcVerbose(0, "Session %RU32 ended\n", pSession->StartupInfo.uSessionID);
1882 }
1883 else
1884 VGSvcError("Reporting session ID=%RU32 started status failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
1885 }
1886 else
1887 VGSvcError("Setting message filterAdd=0x%x failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
1888
1889 VGSvcVerbose(3, "Disconnecting client ID=%RU32 ...\n", idClient);
1890 VbglR3GuestCtrlDisconnect(idClient);
1891 g_idControlSvcClient = 0;
1892
1893 VGSvcVerbose(3, "Session worker returned with rc=%Rrc\n", rc);
1894 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1895}
1896
1897
1898/**
1899 * Finds a (formerly) started guest process given by its PID and increases its
1900 * reference count.
1901 *
1902 * Must be decreased by the caller with VGSvcGstCtrlProcessRelease().
1903 *
1904 * @returns Guest process if found, otherwise NULL.
1905 * @param pSession Pointer to guest session where to search process in.
1906 * @param uPID PID to search for.
1907 *
1908 * @note This does *not lock the process!
1909 */
1910PVBOXSERVICECTRLPROCESS VGSvcGstCtrlSessionRetainProcess(PVBOXSERVICECTRLSESSION pSession, uint32_t uPID)
1911{
1912 AssertPtrReturn(pSession, NULL);
1913
1914 PVBOXSERVICECTRLPROCESS pProcess = NULL;
1915 int rc = RTCritSectEnter(&pSession->CritSect);
1916 if (RT_SUCCESS(rc))
1917 {
1918 PVBOXSERVICECTRLPROCESS pCurProcess;
1919 RTListForEach(&pSession->lstProcesses, pCurProcess, VBOXSERVICECTRLPROCESS, Node)
1920 {
1921 if (pCurProcess->uPID == uPID)
1922 {
1923 rc = RTCritSectEnter(&pCurProcess->CritSect);
1924 if (RT_SUCCESS(rc))
1925 {
1926 pCurProcess->cRefs++;
1927 rc = RTCritSectLeave(&pCurProcess->CritSect);
1928 AssertRC(rc);
1929 }
1930
1931 if (RT_SUCCESS(rc))
1932 pProcess = pCurProcess;
1933 break;
1934 }
1935 }
1936
1937 rc = RTCritSectLeave(&pSession->CritSect);
1938 AssertRC(rc);
1939 }
1940
1941 return pProcess;
1942}
1943
1944
1945int VGSvcGstCtrlSessionClose(PVBOXSERVICECTRLSESSION pSession)
1946{
1947 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1948
1949 VGSvcVerbose(0, "Session %RU32 is about to close ...\n", pSession->StartupInfo.uSessionID);
1950
1951 int rc = RTCritSectEnter(&pSession->CritSect);
1952 if (RT_SUCCESS(rc))
1953 {
1954 /*
1955 * Close all guest processes.
1956 */
1957 VGSvcVerbose(0, "Stopping all guest processes ...\n");
1958
1959 /* Signal all guest processes in the active list that we want to shutdown. */
1960 PVBOXSERVICECTRLPROCESS pProcess;
1961 RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
1962 VGSvcGstCtrlProcessStop(pProcess);
1963
1964 VGSvcVerbose(1, "%RU32 guest processes were signalled to stop\n", pSession->cProcesses);
1965
1966 /* Wait for all active threads to shutdown and destroy the active thread list. */
1967 PVBOXSERVICECTRLPROCESS pProcessNext;
1968 RTListForEachSafe(&pSession->lstProcesses, pProcess, pProcessNext, VBOXSERVICECTRLPROCESS, Node)
1969 {
1970 int rc3 = RTCritSectLeave(&pSession->CritSect);
1971 AssertRC(rc3);
1972
1973 int rc2 = VGSvcGstCtrlProcessWait(pProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
1974
1975 rc3 = RTCritSectEnter(&pSession->CritSect);
1976 AssertRC(rc3);
1977
1978 if (RT_SUCCESS(rc2))
1979 {
1980 rc2 = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
1981 if (RT_SUCCESS(rc2))
1982 {
1983 VGSvcGstCtrlProcessFree(pProcess);
1984 pProcess = NULL;
1985 }
1986 }
1987 }
1988
1989 AssertMsg(pSession->cProcesses == 0,
1990 ("Session process list still contains %RU32 when it should not\n", pSession->cProcesses));
1991 AssertMsg(RTListIsEmpty(&pSession->lstProcesses),
1992 ("Session process list is not empty when it should\n"));
1993
1994 /*
1995 * Close all left guest files.
1996 */
1997 VGSvcVerbose(0, "Closing all guest files ...\n");
1998
1999 PVBOXSERVICECTRLFILE pFile, pFileNext;
2000 RTListForEachSafe(&pSession->lstFiles, pFile, pFileNext, VBOXSERVICECTRLFILE, Node)
2001 {
2002 int rc2 = vgsvcGstCtrlSessionFileFree(pFile);
2003 if (RT_FAILURE(rc2))
2004 {
2005 VGSvcError("Unable to close file '%s'; rc=%Rrc\n", pFile->pszName, rc2);
2006 if (RT_SUCCESS(rc))
2007 rc = rc2;
2008 /* Keep going. */
2009 }
2010
2011 pFile = NULL; /* To make it obvious. */
2012 }
2013
2014 AssertMsg(pSession->cFiles == 0,
2015 ("Session file list still contains %RU32 when it should not\n", pSession->cFiles));
2016 AssertMsg(RTListIsEmpty(&pSession->lstFiles),
2017 ("Session file list is not empty when it should\n"));
2018
2019 int rc2 = RTCritSectLeave(&pSession->CritSect);
2020 if (RT_SUCCESS(rc))
2021 rc = rc2;
2022 }
2023
2024 return rc;
2025}
2026
2027
2028int VGSvcGstCtrlSessionDestroy(PVBOXSERVICECTRLSESSION pSession)
2029{
2030 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2031
2032 int rc = VGSvcGstCtrlSessionClose(pSession);
2033
2034 /* Destroy critical section. */
2035 RTCritSectDelete(&pSession->CritSect);
2036
2037 return rc;
2038}
2039
2040
2041int VGSvcGstCtrlSessionInit(PVBOXSERVICECTRLSESSION pSession, uint32_t fFlags)
2042{
2043 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2044
2045 RTListInit(&pSession->lstProcesses);
2046 RTListInit(&pSession->lstFiles);
2047
2048 pSession->cProcesses = 0;
2049 pSession->cFiles = 0;
2050
2051 pSession->fFlags = fFlags;
2052
2053 /* Init critical section for protecting the thread lists. */
2054 int rc = RTCritSectInit(&pSession->CritSect);
2055 AssertRC(rc);
2056
2057 return rc;
2058}
2059
2060
2061/**
2062 * Adds a guest process to a session's process list.
2063 *
2064 * @return VBox status code.
2065 * @param pSession Guest session to add process to.
2066 * @param pProcess Guest process to add.
2067 */
2068int VGSvcGstCtrlSessionProcessAdd(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
2069{
2070 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2071 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2072
2073 int rc = RTCritSectEnter(&pSession->CritSect);
2074 if (RT_SUCCESS(rc))
2075 {
2076 VGSvcVerbose(3, "Adding process (PID %RU32) to session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
2077
2078 /* Add process to session list. */
2079 RTListAppend(&pSession->lstProcesses, &pProcess->Node);
2080
2081 pSession->cProcesses++;
2082 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
2083 pSession->StartupInfo.uSessionID, pSession->cProcesses);
2084
2085 int rc2 = RTCritSectLeave(&pSession->CritSect);
2086 if (RT_SUCCESS(rc))
2087 rc = rc2;
2088 }
2089
2090 return VINF_SUCCESS;
2091}
2092
2093/**
2094 * Removes a guest process from a session's process list.
2095 * Internal version, does not do locking.
2096 *
2097 * @return VBox status code.
2098 * @param pSession Guest session to remove process from.
2099 * @param pProcess Guest process to remove.
2100 */
2101static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
2102{
2103 VGSvcVerbose(3, "Removing process (PID %RU32) from session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
2104 AssertReturn(pProcess->cRefs == 0, VERR_WRONG_ORDER);
2105
2106 RTListNodeRemove(&pProcess->Node);
2107
2108 AssertReturn(pSession->cProcesses, VERR_WRONG_ORDER);
2109 pSession->cProcesses--;
2110 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
2111 pSession->StartupInfo.uSessionID, pSession->cProcesses);
2112
2113 return VINF_SUCCESS;
2114}
2115
2116/**
2117 * Removes a guest process from a session's process list.
2118 *
2119 * @return VBox status code.
2120 * @param pSession Guest session to remove process from.
2121 * @param pProcess Guest process to remove.
2122 */
2123int VGSvcGstCtrlSessionProcessRemove(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
2124{
2125 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2126 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
2127
2128 int rc = RTCritSectEnter(&pSession->CritSect);
2129 if (RT_SUCCESS(rc))
2130 {
2131 rc = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
2132
2133 int rc2 = RTCritSectLeave(&pSession->CritSect);
2134 if (RT_SUCCESS(rc))
2135 rc = rc2;
2136 }
2137
2138 return rc;
2139}
2140
2141
2142/**
2143 * Determines whether starting a new guest process according to the
2144 * maximum number of concurrent guest processes defined is allowed or not.
2145 *
2146 * @return VBox status code.
2147 * @param pSession The guest session.
2148 * @param pfAllowed \c True if starting (another) guest process
2149 * is allowed, \c false if not.
2150 */
2151int VGSvcGstCtrlSessionProcessStartAllowed(const PVBOXSERVICECTRLSESSION pSession, bool *pfAllowed)
2152{
2153 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2154 AssertPtrReturn(pfAllowed, VERR_INVALID_POINTER);
2155
2156 int rc = RTCritSectEnter(&pSession->CritSect);
2157 if (RT_SUCCESS(rc))
2158 {
2159 /*
2160 * Check if we're respecting our memory policy by checking
2161 * how many guest processes are started and served already.
2162 */
2163 bool fLimitReached = false;
2164 if (pSession->uProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
2165 {
2166 VGSvcVerbose(3, "Maximum kept guest processes set to %RU32, acurrent=%RU32\n",
2167 pSession->uProcsMaxKept, pSession->cProcesses);
2168
2169 int32_t iProcsLeft = (pSession->uProcsMaxKept - pSession->cProcesses - 1);
2170 if (iProcsLeft < 0)
2171 {
2172 VGSvcVerbose(3, "Maximum running guest processes reached (%RU32)\n", pSession->uProcsMaxKept);
2173 fLimitReached = true;
2174 }
2175 }
2176
2177 *pfAllowed = !fLimitReached;
2178
2179 int rc2 = RTCritSectLeave(&pSession->CritSect);
2180 if (RT_SUCCESS(rc))
2181 rc = rc2;
2182 }
2183
2184 return rc;
2185}
2186
2187
2188/**
2189 * Cleans up stopped and no longer used processes.
2190 *
2191 * This will free and remove processes from the session's process list.
2192 *
2193 * @returns VBox status code.
2194 * @param pSession Session to clean up processes for.
2195 */
2196static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession)
2197{
2198 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2199
2200 VGSvcVerbose(3, "Cleaning up stopped processes for session %RU32 ...\n", pSession->StartupInfo.uSessionID);
2201
2202 int rc2 = RTCritSectEnter(&pSession->CritSect);
2203 AssertRC(rc2);
2204
2205 int rc = VINF_SUCCESS;
2206
2207 PVBOXSERVICECTRLPROCESS pCurProcess, pNextProcess;
2208 RTListForEachSafe(&pSession->lstProcesses, pCurProcess, pNextProcess, VBOXSERVICECTRLPROCESS, Node)
2209 {
2210 if (ASMAtomicReadBool(&pCurProcess->fStopped))
2211 {
2212 rc2 = RTCritSectLeave(&pSession->CritSect);
2213 AssertRC(rc2);
2214
2215 rc = VGSvcGstCtrlProcessWait(pCurProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
2216 if (RT_SUCCESS(rc))
2217 {
2218 VGSvcGstCtrlSessionProcessRemove(pSession, pCurProcess);
2219 VGSvcGstCtrlProcessFree(pCurProcess);
2220 }
2221
2222 rc2 = RTCritSectEnter(&pSession->CritSect);
2223 AssertRC(rc2);
2224
2225 /* If failed, try next time we're being called. */
2226 }
2227 }
2228
2229 rc2 = RTCritSectLeave(&pSession->CritSect);
2230 AssertRC(rc2);
2231
2232 if (RT_FAILURE(rc))
2233 VGSvcError("Cleaning up stopped processes for session %RU32 failed with %Rrc\n", pSession->StartupInfo.uSessionID, rc);
2234
2235 return rc;
2236}
2237
2238
2239/**
2240 * Creates the process for a guest session.
2241 *
2242 * @return VBox status code.
2243 * @param pSessionStartupInfo Session startup info.
2244 * @param pSessionThread The session thread under construction.
2245 * @param uCtrlSessionThread The session thread debug ordinal.
2246 */
2247static int vgsvcVGSvcGstCtrlSessionThreadCreateProcess(const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
2248 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread, uint32_t uCtrlSessionThread)
2249{
2250 RT_NOREF(uCtrlSessionThread);
2251
2252 /*
2253 * Is this an anonymous session? Anonymous sessions run with the same
2254 * privileges as the main VBoxService executable.
2255 */
2256 bool const fAnonymous = pSessionThread->pStartupInfo->pszUser
2257 && pSessionThread->pStartupInfo->pszUser[0] == '\0';
2258 if (fAnonymous)
2259 {
2260 Assert(!strlen(pSessionThread->pStartupInfo->pszPassword));
2261 Assert(!strlen(pSessionThread->pStartupInfo->pszDomain));
2262
2263 VGSvcVerbose(3, "New anonymous guest session ID=%RU32 created, fFlags=%x, using protocol %RU32\n",
2264 pSessionStartupInfo->uSessionID,
2265 pSessionStartupInfo->fFlags,
2266 pSessionStartupInfo->uProtocol);
2267 }
2268 else
2269 {
2270 VGSvcVerbose(3, "Spawning new guest session ID=%RU32, szUser=%s, szPassword=%s, szDomain=%s, fFlags=%x, using protocol %RU32\n",
2271 pSessionStartupInfo->uSessionID,
2272 pSessionStartupInfo->pszUser,
2273#ifdef DEBUG
2274 pSessionStartupInfo->pszPassword,
2275#else
2276 "XXX", /* Never show passwords in release mode. */
2277#endif
2278 pSessionStartupInfo->pszDomain,
2279 pSessionStartupInfo->fFlags,
2280 pSessionStartupInfo->uProtocol);
2281 }
2282
2283 /*
2284 * Spawn a child process for doing the actual session handling.
2285 * Start by assembling the argument list.
2286 */
2287 char szExeName[RTPATH_MAX];
2288 char *pszExeName = RTProcGetExecutablePath(szExeName, sizeof(szExeName));
2289 AssertPtrReturn(pszExeName, VERR_FILENAME_TOO_LONG);
2290
2291 char szParmSessionID[32];
2292 RTStrPrintf(szParmSessionID, sizeof(szParmSessionID), "--session-id=%RU32", pSessionThread->pStartupInfo->uSessionID);
2293
2294 char szParmSessionProto[32];
2295 RTStrPrintf(szParmSessionProto, sizeof(szParmSessionProto), "--session-proto=%RU32",
2296 pSessionThread->pStartupInfo->uProtocol);
2297#ifdef DEBUG
2298 char szParmThreadId[32];
2299 RTStrPrintf(szParmThreadId, sizeof(szParmThreadId), "--thread-id=%RU32", uCtrlSessionThread);
2300#endif
2301 unsigned idxArg = 0; /* Next index in argument vector. */
2302 char const *apszArgs[24];
2303
2304 apszArgs[idxArg++] = pszExeName;
2305 apszArgs[idxArg++] = "guestsession";
2306 apszArgs[idxArg++] = szParmSessionID;
2307 apszArgs[idxArg++] = szParmSessionProto;
2308#ifdef DEBUG
2309 apszArgs[idxArg++] = szParmThreadId;
2310#endif
2311 if (!fAnonymous) /* Do we need to pass a user name? */
2312 {
2313 apszArgs[idxArg++] = "--user";
2314 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszUser;
2315
2316 if (strlen(pSessionThread->pStartupInfo->pszDomain))
2317 {
2318 apszArgs[idxArg++] = "--domain";
2319 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszDomain;
2320 }
2321 }
2322
2323 /* Add same verbose flags as parent process. */
2324 char szParmVerbose[32];
2325 if (g_cVerbosity > 0)
2326 {
2327 unsigned cVs = RT_MIN(g_cVerbosity, RT_ELEMENTS(szParmVerbose) - 2);
2328 szParmVerbose[0] = '-';
2329 memset(&szParmVerbose[1], 'v', cVs);
2330 szParmVerbose[1 + cVs] = '\0';
2331 apszArgs[idxArg++] = szParmVerbose;
2332 }
2333
2334 /* Add log file handling. Each session will have an own
2335 * log file, naming based on the parent log file. */
2336 char szParmLogFile[sizeof(g_szLogFile) + 128];
2337 if (g_szLogFile[0])
2338 {
2339 const char *pszSuffix = RTPathSuffix(g_szLogFile);
2340 if (!pszSuffix)
2341 pszSuffix = strchr(g_szLogFile, '\0');
2342 size_t cchBase = pszSuffix - g_szLogFile;
2343
2344 RTTIMESPEC Now;
2345 RTTimeNow(&Now);
2346 char szTime[64];
2347 RTTimeSpecToString(&Now, szTime, sizeof(szTime));
2348
2349 /* Replace out characters not allowed on Windows platforms, put in by RTTimeSpecToString(). */
2350 static const RTUNICP s_uszValidRangePairs[] =
2351 {
2352 ' ', ' ',
2353 '(', ')',
2354 '-', '.',
2355 '0', '9',
2356 'A', 'Z',
2357 'a', 'z',
2358 '_', '_',
2359 0xa0, 0xd7af,
2360 '\0'
2361 };
2362 ssize_t cReplaced = RTStrPurgeComplementSet(szTime, s_uszValidRangePairs, '_' /* chReplacement */);
2363 AssertReturn(cReplaced, VERR_INVALID_UTF8_ENCODING);
2364
2365#ifndef DEBUG
2366 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%s-%s%s",
2367 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, pSessionStartupInfo->pszUser, szTime, pszSuffix);
2368#else
2369 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%RU32-%s-%s%s",
2370 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, uCtrlSessionThread,
2371 pSessionStartupInfo->pszUser, szTime, pszSuffix);
2372#endif
2373 apszArgs[idxArg++] = "--logfile";
2374 apszArgs[idxArg++] = szParmLogFile;
2375 }
2376
2377#ifdef DEBUG
2378 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT)
2379 apszArgs[idxArg++] = "--dump-stdout";
2380 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR)
2381 apszArgs[idxArg++] = "--dump-stderr";
2382#endif
2383 apszArgs[idxArg] = NULL;
2384 Assert(idxArg < RT_ELEMENTS(apszArgs));
2385
2386 if (g_cVerbosity > 3)
2387 {
2388 VGSvcVerbose(4, "Spawning parameters:\n");
2389 for (idxArg = 0; apszArgs[idxArg]; idxArg++)
2390 VGSvcVerbose(4, " %s\n", apszArgs[idxArg]);
2391 }
2392
2393 /*
2394 * Flags.
2395 */
2396 uint32_t const fProcCreate = RTPROC_FLAGS_PROFILE
2397#ifdef RT_OS_WINDOWS
2398 | RTPROC_FLAGS_SERVICE
2399 | RTPROC_FLAGS_HIDDEN
2400#endif
2401 ;
2402
2403 /*
2404 * Configure standard handles.
2405 */
2406 RTHANDLE hStdIn;
2407 int rc = RTPipeCreate(&hStdIn.u.hPipe, &pSessionThread->hKeyPipe, RTPIPE_C_INHERIT_READ);
2408 if (RT_SUCCESS(rc))
2409 {
2410 hStdIn.enmType = RTHANDLETYPE_PIPE;
2411
2412 RTHANDLE hStdOutAndErr;
2413 rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
2414 if (RT_SUCCESS(rc))
2415 {
2416 hStdOutAndErr.enmType = RTHANDLETYPE_FILE;
2417
2418 /*
2419 * Windows: If a domain name is given, construct an UPN (User Principle Name)
2420 * with the domain name built-in, e.g. "[email protected]".
2421 */
2422 const char *pszUser = pSessionThread->pStartupInfo->pszUser;
2423#ifdef RT_OS_WINDOWS
2424 char *pszUserUPN = NULL;
2425 if (pSessionThread->pStartupInfo->pszDomain[0])
2426 {
2427 int cchbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s",
2428 pSessionThread->pStartupInfo->pszUser,
2429 pSessionThread->pStartupInfo->pszDomain);
2430 if (cchbUserUPN > 0)
2431 {
2432 pszUser = pszUserUPN;
2433 VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
2434 }
2435 else
2436 rc = VERR_NO_STR_MEMORY;
2437 }
2438 if (RT_SUCCESS(rc))
2439#endif
2440 {
2441 /*
2442 * Finally, create the process.
2443 */
2444 rc = RTProcCreateEx(pszExeName, apszArgs, RTENV_DEFAULT, fProcCreate,
2445 &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
2446 !fAnonymous ? pszUser : NULL,
2447 !fAnonymous ? pSessionThread->pStartupInfo->pszPassword : NULL,
2448 NULL /*pvExtraData*/,
2449 &pSessionThread->hProcess);
2450 }
2451#ifdef RT_OS_WINDOWS
2452 RTStrFree(pszUserUPN);
2453#endif
2454 RTFileClose(hStdOutAndErr.u.hFile);
2455 }
2456
2457 RTPipeClose(hStdIn.u.hPipe);
2458 }
2459 return rc;
2460}
2461
2462
2463/**
2464 * Creates a guest session.
2465 *
2466 * This will spawn a new VBoxService.exe instance under behalf of the given user
2467 * which then will act as a session host. On successful open, the session will
2468 * be added to the given session thread list.
2469 *
2470 * @return VBox status code.
2471 * @param pList Which list to use to store the session thread in.
2472 * @param pSessionStartupInfo Session startup info.
2473 * @param ppSessionThread Returns newly created session thread on success.
2474 * Optional.
2475 */
2476int VGSvcGstCtrlSessionThreadCreate(PRTLISTANCHOR pList, const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
2477 PVBOXSERVICECTRLSESSIONTHREAD *ppSessionThread)
2478{
2479 AssertPtrReturn(pList, VERR_INVALID_POINTER);
2480 AssertPtrReturn(pSessionStartupInfo, VERR_INVALID_POINTER);
2481 /* ppSessionThread is optional. */
2482
2483#ifdef VBOX_STRICT
2484 /* Check for existing session in debug mode. Should never happen because of
2485 * Main consistency. */
2486 PVBOXSERVICECTRLSESSIONTHREAD pSessionCur;
2487 RTListForEach(pList, pSessionCur, VBOXSERVICECTRLSESSIONTHREAD, Node)
2488 {
2489 AssertMsgReturn( pSessionCur->fStopped == true
2490 || pSessionCur->pStartupInfo->uSessionID != pSessionStartupInfo->uSessionID,
2491 ("Guest session thread ID=%RU32 already exists (fStopped=%RTbool)\n",
2492 pSessionCur->pStartupInfo->uSessionID, pSessionCur->fStopped), VERR_ALREADY_EXISTS);
2493 }
2494#endif
2495
2496 /* Static counter to help tracking session thread <-> process relations. */
2497 static uint32_t s_uCtrlSessionThread = 0;
2498
2499 /*
2500 * Allocate and initialize the session thread structure.
2501 */
2502 int rc;
2503 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread = (PVBOXSERVICECTRLSESSIONTHREAD)RTMemAllocZ(sizeof(*pSessionThread));
2504 if (pSessionThread)
2505 {
2506 //pSessionThread->fShutdown = false;
2507 //pSessionThread->fStarted = false;
2508 //pSessionThread->fStopped = false;
2509 pSessionThread->hKeyPipe = NIL_RTPIPE;
2510 pSessionThread->Thread = NIL_RTTHREAD;
2511 pSessionThread->hProcess = NIL_RTPROCESS;
2512
2513 /* Duplicate startup info. */
2514 pSessionThread->pStartupInfo = VbglR3GuestCtrlSessionStartupInfoDup(pSessionStartupInfo);
2515 AssertPtrReturn(pSessionThread->pStartupInfo, VERR_NO_MEMORY);
2516
2517 /* Generate the secret key. */
2518 RTRandBytes(pSessionThread->abKey, sizeof(pSessionThread->abKey));
2519
2520 rc = RTCritSectInit(&pSessionThread->CritSect);
2521 AssertRC(rc);
2522 if (RT_SUCCESS(rc))
2523 {
2524 /*
2525 * Give the session key to the host so it can validate the client.
2526 */
2527 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
2528 {
2529 for (uint32_t i = 0; i < 10; i++)
2530 {
2531 rc = VbglR3GuestCtrlSessionPrepare(g_idControlSvcClient, pSessionStartupInfo->uSessionID,
2532 pSessionThread->abKey, sizeof(pSessionThread->abKey));
2533 if (rc != VERR_OUT_OF_RESOURCES)
2534 break;
2535 RTThreadSleep(100);
2536 }
2537 }
2538 if (RT_SUCCESS(rc))
2539 {
2540 s_uCtrlSessionThread++;
2541
2542 /*
2543 * Start the session child process.
2544 */
2545 rc = vgsvcVGSvcGstCtrlSessionThreadCreateProcess(pSessionStartupInfo, pSessionThread, s_uCtrlSessionThread);
2546 if (RT_SUCCESS(rc))
2547 {
2548 /*
2549 * Start the session thread.
2550 */
2551 rc = RTThreadCreateF(&pSessionThread->Thread, vgsvcGstCtrlSessionThread, pSessionThread /*pvUser*/, 0 /*cbStack*/,
2552 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctls%RU32", s_uCtrlSessionThread);
2553 if (RT_SUCCESS(rc))
2554 {
2555 /* Wait for the thread to initialize. */
2556 rc = RTThreadUserWait(pSessionThread->Thread, RT_MS_1MIN);
2557 if ( RT_SUCCESS(rc)
2558 && !ASMAtomicReadBool(&pSessionThread->fShutdown))
2559 {
2560 VGSvcVerbose(2, "Thread for session ID=%RU32 started\n", pSessionThread->pStartupInfo->uSessionID);
2561
2562 ASMAtomicXchgBool(&pSessionThread->fStarted, true);
2563
2564 /* Add session to list. */
2565 RTListAppend(pList, &pSessionThread->Node);
2566 if (ppSessionThread) /* Return session if wanted. */
2567 *ppSessionThread = pSessionThread;
2568 return VINF_SUCCESS;
2569 }
2570
2571 /*
2572 * Bail out.
2573 */
2574 VGSvcError("Thread for session ID=%RU32 failed to start, rc=%Rrc\n",
2575 pSessionThread->pStartupInfo->uSessionID, rc);
2576 if (RT_SUCCESS_NP(rc))
2577 rc = VERR_CANT_CREATE; /** @todo Find a better rc. */
2578 }
2579 else
2580 VGSvcError("Creating session thread failed, rc=%Rrc\n", rc);
2581
2582 RTProcTerminate(pSessionThread->hProcess);
2583 uint32_t cMsWait = 1;
2584 while ( RTProcWait(pSessionThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, NULL) == VERR_PROCESS_RUNNING
2585 && cMsWait <= 9) /* 1023 ms */
2586 {
2587 RTThreadSleep(cMsWait);
2588 cMsWait <<= 1;
2589 }
2590 }
2591
2592 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
2593 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, pSessionStartupInfo->uSessionID);
2594 }
2595 else
2596 VGSvcVerbose(3, "VbglR3GuestCtrlSessionPrepare failed: %Rrc\n", rc);
2597 RTPipeClose(pSessionThread->hKeyPipe);
2598 pSessionThread->hKeyPipe = NIL_RTPIPE;
2599 RTCritSectDelete(&pSessionThread->CritSect);
2600 }
2601 RTMemFree(pSessionThread);
2602 }
2603 else
2604 rc = VERR_NO_MEMORY;
2605
2606 VGSvcVerbose(3, "Spawning session thread returned returned rc=%Rrc\n", rc);
2607 return rc;
2608}
2609
2610
2611/**
2612 * Waits for a formerly opened guest session process to close.
2613 *
2614 * @return VBox status code.
2615 * @param pThread Guest session thread to wait for.
2616 * @param uTimeoutMS Waiting timeout (in ms).
2617 * @param fFlags Closing flags.
2618 */
2619int VGSvcGstCtrlSessionThreadWait(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t uTimeoutMS, uint32_t fFlags)
2620{
2621 RT_NOREF(fFlags);
2622 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2623 /** @todo Validate closing flags. */
2624
2625 AssertMsgReturn(pThread->Thread != NIL_RTTHREAD,
2626 ("Guest session thread of session %p does not exist when it should\n", pThread),
2627 VERR_NOT_FOUND);
2628
2629 int rc = VINF_SUCCESS;
2630
2631 /*
2632 * The spawned session process should have received the same closing request,
2633 * so just wait for the process to close.
2634 */
2635 if (ASMAtomicReadBool(&pThread->fStarted))
2636 {
2637 /* Ask the thread to shutdown. */
2638 ASMAtomicXchgBool(&pThread->fShutdown, true);
2639
2640 VGSvcVerbose(3, "Waiting for session thread ID=%RU32 to close (%RU32ms) ...\n",
2641 pThread->pStartupInfo->uSessionID, uTimeoutMS);
2642
2643 int rcThread;
2644 rc = RTThreadWait(pThread->Thread, uTimeoutMS, &rcThread);
2645 if (RT_SUCCESS(rc))
2646 {
2647 AssertMsg(pThread->fStopped, ("Thread of session ID=%RU32 not in stopped state when it should\n",
2648 pThread->pStartupInfo->uSessionID));
2649
2650 VGSvcVerbose(3, "Session thread ID=%RU32 ended with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rcThread);
2651 }
2652 else
2653 VGSvcError("Waiting for session thread ID=%RU32 to close failed with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rc);
2654 }
2655 else
2656 VGSvcVerbose(3, "Thread for session ID=%RU32 not in started state, skipping wait\n", pThread->pStartupInfo->uSessionID);
2657
2658 LogFlowFuncLeaveRC(rc);
2659 return rc;
2660}
2661
2662/**
2663 * Waits for the specified session thread to end and remove
2664 * it from the session thread list.
2665 *
2666 * @return VBox status code.
2667 * @param pThread Session thread to destroy.
2668 * @param fFlags Closing flags.
2669 */
2670int VGSvcGstCtrlSessionThreadDestroy(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t fFlags)
2671{
2672 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2673 AssertPtrReturn(pThread->pStartupInfo, VERR_WRONG_ORDER);
2674
2675 const uint32_t uSessionID = pThread->pStartupInfo->uSessionID;
2676
2677 VGSvcVerbose(3, "Destroying session ID=%RU32 ...\n", uSessionID);
2678
2679 int rc = VGSvcGstCtrlSessionThreadWait(pThread, 5 * 60 * 1000 /* 5 minutes timeout */, fFlags);
2680 if (RT_SUCCESS(rc))
2681 {
2682 VbglR3GuestCtrlSessionStartupInfoFree(pThread->pStartupInfo);
2683 pThread->pStartupInfo = NULL;
2684
2685 /* Remove session from list and destroy object. */
2686 RTListNodeRemove(&pThread->Node);
2687
2688 RTMemFree(pThread);
2689 pThread = NULL;
2690 }
2691
2692 VGSvcVerbose(3, "Destroyed session ID=%RU32 with %Rrc\n", uSessionID, rc);
2693 return rc;
2694}
2695
2696/**
2697 * Close all open guest session threads.
2698 *
2699 * @note Caller is responsible for locking!
2700 *
2701 * @return VBox status code.
2702 * @param pList Which list to close the session threads for.
2703 * @param fFlags Closing flags.
2704 */
2705int VGSvcGstCtrlSessionThreadDestroyAll(PRTLISTANCHOR pList, uint32_t fFlags)
2706{
2707 AssertPtrReturn(pList, VERR_INVALID_POINTER);
2708
2709 int rc = VINF_SUCCESS;
2710
2711 /*int rc = VbglR3GuestCtrlClose
2712 if (RT_FAILURE(rc))
2713 VGSvcError("Cancelling pending waits failed; rc=%Rrc\n", rc);*/
2714
2715 PVBOXSERVICECTRLSESSIONTHREAD pSessIt;
2716 PVBOXSERVICECTRLSESSIONTHREAD pSessItNext;
2717 RTListForEachSafe(pList, pSessIt, pSessItNext, VBOXSERVICECTRLSESSIONTHREAD, Node)
2718 {
2719 int rc2 = VGSvcGstCtrlSessionThreadDestroy(pSessIt, fFlags);
2720 if (RT_FAILURE(rc2))
2721 {
2722 VGSvcError("Closing session thread '%s' failed with rc=%Rrc\n", RTThreadGetName(pSessIt->Thread), rc2);
2723 if (RT_SUCCESS(rc))
2724 rc = rc2;
2725 /* Keep going. */
2726 }
2727 }
2728
2729 VGSvcVerbose(4, "Destroying guest session threads ended with %Rrc\n", rc);
2730 return rc;
2731}
2732
2733
2734/**
2735 * Main function for the session process.
2736 *
2737 * @returns exit code.
2738 * @param argc Argument count.
2739 * @param argv Argument vector (UTF-8).
2740 */
2741RTEXITCODE VGSvcGstCtrlSessionSpawnInit(int argc, char **argv)
2742{
2743 static const RTGETOPTDEF s_aOptions[] =
2744 {
2745 { "--domain", VBOXSERVICESESSIONOPT_DOMAIN, RTGETOPT_REQ_STRING },
2746#ifdef DEBUG
2747 { "--dump-stdout", VBOXSERVICESESSIONOPT_DUMP_STDOUT, RTGETOPT_REQ_NOTHING },
2748 { "--dump-stderr", VBOXSERVICESESSIONOPT_DUMP_STDERR, RTGETOPT_REQ_NOTHING },
2749#endif
2750 { "--logfile", VBOXSERVICESESSIONOPT_LOG_FILE, RTGETOPT_REQ_STRING },
2751 { "--user", VBOXSERVICESESSIONOPT_USERNAME, RTGETOPT_REQ_STRING },
2752 { "--session-id", VBOXSERVICESESSIONOPT_SESSION_ID, RTGETOPT_REQ_UINT32 },
2753 { "--session-proto", VBOXSERVICESESSIONOPT_SESSION_PROTO, RTGETOPT_REQ_UINT32 },
2754#ifdef DEBUG
2755 { "--thread-id", VBOXSERVICESESSIONOPT_THREAD_ID, RTGETOPT_REQ_UINT32 },
2756#endif /* DEBUG */
2757 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2758 };
2759
2760 RTGETOPTSTATE GetState;
2761 RTGetOptInit(&GetState, argc, argv,
2762 s_aOptions, RT_ELEMENTS(s_aOptions),
2763 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2764
2765 uint32_t fSession = VBOXSERVICECTRLSESSION_FLAG_SPAWN;
2766
2767 /* Protocol and session ID must be specified explicitly. */
2768 g_Session.StartupInfo.uProtocol = UINT32_MAX;
2769 g_Session.StartupInfo.uSessionID = UINT32_MAX;
2770
2771 int ch;
2772 RTGETOPTUNION ValueUnion;
2773 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2774 {
2775 /* For options that require an argument, ValueUnion has received the value. */
2776 switch (ch)
2777 {
2778 case VBOXSERVICESESSIONOPT_DOMAIN:
2779 /* Information not needed right now, skip. */
2780 break;
2781#ifdef DEBUG
2782 case VBOXSERVICESESSIONOPT_DUMP_STDOUT:
2783 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
2784 break;
2785
2786 case VBOXSERVICESESSIONOPT_DUMP_STDERR:
2787 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
2788 break;
2789#endif
2790 case VBOXSERVICESESSIONOPT_SESSION_ID:
2791 g_Session.StartupInfo.uSessionID = ValueUnion.u32;
2792 break;
2793
2794 case VBOXSERVICESESSIONOPT_SESSION_PROTO:
2795 g_Session.StartupInfo.uProtocol = ValueUnion.u32;
2796 break;
2797#ifdef DEBUG
2798 case VBOXSERVICESESSIONOPT_THREAD_ID:
2799 /* Not handled. Mainly for processs listing. */
2800 break;
2801#endif
2802 case VBOXSERVICESESSIONOPT_LOG_FILE:
2803 {
2804 int rc = RTStrCopy(g_szLogFile, sizeof(g_szLogFile), ValueUnion.psz);
2805 if (RT_FAILURE(rc))
2806 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error copying log file name: %Rrc", rc);
2807 break;
2808 }
2809
2810 case VBOXSERVICESESSIONOPT_USERNAME:
2811 /* Information not needed right now, skip. */
2812 break;
2813
2814 /** @todo Implement help? */
2815
2816 case 'v':
2817 g_cVerbosity++;
2818 break;
2819
2820 case VINF_GETOPT_NOT_OPTION:
2821 {
2822 if (!RTStrICmp(ValueUnion.psz, VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
2823 break;
2824 /* else fall through and bail out. */
2825 RT_FALL_THROUGH();
2826 }
2827 default:
2828 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'", ValueUnion.psz);
2829 }
2830 }
2831
2832 /* Check that we've got all the required options. */
2833 if (g_Session.StartupInfo.uProtocol == UINT32_MAX)
2834 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No protocol version specified");
2835
2836 if (g_Session.StartupInfo.uSessionID == UINT32_MAX)
2837 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No session ID specified");
2838
2839 /* Init the session object. */
2840 int rc = VGSvcGstCtrlSessionInit(&g_Session, fSession);
2841 if (RT_FAILURE(rc))
2842 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to initialize session object, rc=%Rrc\n", rc);
2843
2844 rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
2845 if (RT_FAILURE(rc))
2846 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to create log file '%s', rc=%Rrc\n",
2847 g_szLogFile[0] ? g_szLogFile : "<None>", rc);
2848
2849 RTEXITCODE rcExit = vgsvcGstCtrlSessionSpawnWorker(&g_Session);
2850
2851 VGSvcLogDestroy();
2852 return rcExit;
2853}
2854
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