VirtualBox

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

Last change on this file was 103471, checked in by vboxsync, 2 months ago

Guest Control/VBoxService: Fixed reallocation in vgsvcGstCtrlSessionHandleMountPointsEnumCallback(). bugref:10415

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 142.5 KB
Line 
1/* $Id: VBoxServiceControlSession.cpp 103471 2024-02-20 09:06:22Z vboxsync $ */
2/** @file
3 * VBoxServiceControlSession - Guest session handling. Also handles the spawned session processes.
4 */
5
6/*
7 * Copyright (C) 2013-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#include <iprt/asm.h>
33#include <iprt/assert.h>
34#include <iprt/dir.h>
35#include <iprt/env.h>
36#include <iprt/file.h>
37#include <iprt/getopt.h>
38#include <iprt/handle.h>
39#include <iprt/mem.h>
40#include <iprt/message.h>
41#include <iprt/path.h>
42#include <iprt/pipe.h>
43#include <iprt/poll.h>
44#include <iprt/process.h>
45#include <iprt/rand.h>
46#include <iprt/system.h> /* For RTShutdown. */
47
48#include "VBoxServiceInternal.h"
49#include "VBoxServiceUtils.h"
50#include "VBoxServiceControl.h"
51
52using namespace guestControl;
53
54
55/*********************************************************************************************************************************
56* Structures and Typedefs *
57*********************************************************************************************************************************/
58/** Generic option indices for session spawn arguments. */
59enum
60{
61 VBOXSERVICESESSIONOPT_FIRST = 1000, /* For initialization. */
62 VBOXSERVICESESSIONOPT_DOMAIN,
63#ifdef DEBUG
64 VBOXSERVICESESSIONOPT_DUMP_STDOUT,
65 VBOXSERVICESESSIONOPT_DUMP_STDERR,
66#endif
67 VBOXSERVICESESSIONOPT_LOG_FILE,
68 VBOXSERVICESESSIONOPT_USERNAME,
69 VBOXSERVICESESSIONOPT_SESSION_ID,
70 VBOXSERVICESESSIONOPT_SESSION_PROTO,
71 VBOXSERVICESESSIONOPT_THREAD_ID
72};
73
74
75static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession);
76static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess);
77
78
79/**
80 * Helper that grows the scratch buffer.
81 * @returns Success indicator.
82 */
83static bool vgsvcGstCtrlSessionGrowScratchBuf(void **ppvScratchBuf, uint32_t *pcbScratchBuf, uint32_t cbMinBuf)
84{
85 uint32_t cbNew = *pcbScratchBuf * 2;
86 if ( cbNew <= VMMDEV_MAX_HGCM_DATA_SIZE
87 && cbMinBuf <= VMMDEV_MAX_HGCM_DATA_SIZE)
88 {
89 while (cbMinBuf > cbNew)
90 cbNew *= 2;
91 void *pvNew = RTMemRealloc(*ppvScratchBuf, cbNew);
92 if (pvNew)
93 {
94 *ppvScratchBuf = pvNew;
95 *pcbScratchBuf = cbNew;
96 return true;
97 }
98 }
99 return false;
100}
101
102
103#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
104/**
105 * Free's a guest directory entry.
106 *
107 * @returns VBox status code.
108 * @param pDir Directory entry to free.
109 * The pointer will be invalid on success.
110 */
111static int vgsvcGstCtrlSessionDirFree(PVBOXSERVICECTRLDIR pDir)
112{
113 if (!pDir)
114 return VINF_SUCCESS;
115
116 RTMemFree(pDir->pDirEntryEx);
117
118 int rc;
119 if (pDir->hDir != NIL_RTDIR)
120 {
121 rc = RTDirClose(pDir->hDir);
122 pDir->hDir = NIL_RTDIR;
123 }
124 else
125 rc = VINF_SUCCESS;
126
127 if (RT_SUCCESS(rc))
128 {
129 RTStrFree(pDir->pszPathAbs);
130 RTListNodeRemove(&pDir->Node);
131 RTMemFree(pDir);
132 }
133
134 return rc;
135}
136
137
138/**
139 * Acquires an internal guest directory.
140 *
141 * Must be released via vgsvcGstCtrlSessionDirRelease().
142 *
143 * @returns Guest directory entry on success, or NULL if not found.
144 * @param pSession Guest control session to acquire guest directory for.
145 * @param uHandle Handle of directory to acquire.
146 *
147 * @note No locking done yet.
148 */
149static PVBOXSERVICECTRLDIR vgsvcGstCtrlSessionDirAcquire(const PVBOXSERVICECTRLSESSION pSession, uint32_t uHandle)
150{
151 AssertPtrReturn(pSession, NULL);
152
153 /** @todo Use a map later! */
154 PVBOXSERVICECTRLDIR pDirCur;
155 RTListForEach(&pSession->lstDirs, pDirCur, VBOXSERVICECTRLDIR, Node)
156 {
157 if (pDirCur->uHandle == uHandle)
158 return pDirCur;
159 }
160
161 return NULL;
162}
163
164
165/**
166 * Releases a formerly acquired guest directory.
167 *
168 * @param pDir Directory to release.
169 */
170static void vgsvcGstCtrlSessionDirRelease(PVBOXSERVICECTRLDIR pDir)
171{
172 RT_NOREF(pDir);
173}
174#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
175
176
177/**
178 * Free's a guest file entry.
179 *
180 * @returns VBox status code.
181 * @param pFile Guest file entry to free.
182 * The pointer wil be invalid on success.
183 */
184static int vgsvcGstCtrlSessionFileFree(PVBOXSERVICECTRLFILE pFile)
185{
186 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
187
188 int rc = RTFileClose(pFile->hFile);
189 if (RT_SUCCESS(rc))
190 {
191 RTStrFree(pFile->pszName);
192
193 /* Remove file entry in any case. */
194 RTListNodeRemove(&pFile->Node);
195 /* Destroy this object. */
196 RTMemFree(pFile);
197 }
198
199 return rc;
200}
201
202
203/**
204 * Acquires an internal guest file entry.
205 *
206 * Must be released via vgsvcGstCtrlSessionFileRelease().
207 *
208 * @returns Guest file entry on success, or NULL if not found.
209 * @param pSession Guest session to use.
210 * @param uHandle Handle of guest file entry to acquire.
211 *
212 * @note No locking done yet.
213 */
214static PVBOXSERVICECTRLFILE vgsvcGstCtrlSessionFileAcquire(const PVBOXSERVICECTRLSESSION pSession, uint32_t uHandle)
215{
216 AssertPtrReturn(pSession, NULL);
217
218 /** @todo Use a map later! */
219 PVBOXSERVICECTRLFILE pFileCur;
220 RTListForEach(&pSession->lstFiles, pFileCur, VBOXSERVICECTRLFILE, Node)
221 {
222 if (pFileCur->uHandle == uHandle)
223 return pFileCur;
224 }
225
226 return NULL;
227}
228
229
230/**
231 * Releases a formerly acquired guest file.
232 *
233 * @param pFile File to release.
234 */
235static void vgsvcGstCtrlSessionFileRelease(PVBOXSERVICECTRLFILE pFile)
236{
237 RT_NOREF(pFile);
238}
239
240
241/**
242 * Recursion worker for vgsvcGstCtrlSessionHandleDirRemove.
243 * Only (recursively) removes directory structures which are not empty. Will fail if not empty.
244 *
245 * @returns IPRT status code.
246 * @param pszDir The directory buffer, RTPATH_MAX in length.
247 * Contains the abs path to the directory to
248 * recurse into. Trailing slash.
249 * @param cchDir The length of the directory we're recursing into,
250 * including the trailing slash.
251 * @param pDirEntry The dir entry buffer. (Shared to save stack.)
252 */
253static int vgsvcGstCtrlSessionHandleDirRemoveSub(char *pszDir, size_t cchDir, PRTDIRENTRY pDirEntry)
254{
255 RTDIR hDir;
256 int rc = RTDirOpen(&hDir, pszDir);
257 if (RT_FAILURE(rc))
258 {
259 /* Ignore non-existing directories like RTDirRemoveRecursive does: */
260 if (rc == VERR_FILE_NOT_FOUND || rc == VERR_PATH_NOT_FOUND)
261 return VINF_SUCCESS;
262 return rc;
263 }
264
265 for (;;)
266 {
267 rc = RTDirRead(hDir, pDirEntry, NULL);
268 if (RT_FAILURE(rc))
269 {
270 if (rc == VERR_NO_MORE_FILES)
271 rc = VINF_SUCCESS;
272 break;
273 }
274
275 if (!RTDirEntryIsStdDotLink(pDirEntry))
276 {
277 /* Construct the full name of the entry. */
278 if (cchDir + pDirEntry->cbName + 1 /* dir slash */ < RTPATH_MAX)
279 memcpy(&pszDir[cchDir], pDirEntry->szName, pDirEntry->cbName + 1);
280 else
281 {
282 rc = VERR_FILENAME_TOO_LONG;
283 break;
284 }
285
286 /* Make sure we've got the entry type. */
287 if (pDirEntry->enmType == RTDIRENTRYTYPE_UNKNOWN)
288 RTDirQueryUnknownType(pszDir, false /*fFollowSymlinks*/, &pDirEntry->enmType);
289
290 /* Recurse into subdirs and remove them: */
291 if (pDirEntry->enmType == RTDIRENTRYTYPE_DIRECTORY)
292 {
293 size_t cchSubDir = cchDir + pDirEntry->cbName;
294 pszDir[cchSubDir++] = RTPATH_SLASH;
295 pszDir[cchSubDir] = '\0';
296 rc = vgsvcGstCtrlSessionHandleDirRemoveSub(pszDir, cchSubDir, pDirEntry);
297 if (RT_SUCCESS(rc))
298 {
299 pszDir[cchSubDir] = '\0';
300 rc = RTDirRemove(pszDir);
301 if (RT_FAILURE(rc))
302 break;
303 }
304 else
305 break;
306 }
307 /* Not a subdirectory - fail: */
308 else
309 {
310 rc = VERR_DIR_NOT_EMPTY;
311 break;
312 }
313 }
314 }
315
316 RTDirClose(hDir);
317 return rc;
318}
319
320
321static int vgsvcGstCtrlSessionHandleDirRemove(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
322{
323 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
324 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
325
326 /*
327 * Retrieve the message.
328 */
329 char szDir[RTPATH_MAX];
330 uint32_t fFlags; /* DIRREMOVE_FLAG_XXX */
331 int rc = VbglR3GuestCtrlDirGetRemove(pHostCtx, szDir, sizeof(szDir), &fFlags);
332 if (RT_SUCCESS(rc))
333 {
334 /*
335 * Do some validating before executing the job.
336 */
337 if (!(fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK))
338 {
339 if (fFlags & DIRREMOVEREC_FLAG_RECURSIVE)
340 {
341 if (fFlags & (DIRREMOVEREC_FLAG_CONTENT_AND_DIR | DIRREMOVEREC_FLAG_CONTENT_ONLY))
342 {
343 uint32_t fFlagsRemRec = fFlags & DIRREMOVEREC_FLAG_CONTENT_AND_DIR
344 ? RTDIRRMREC_F_CONTENT_AND_DIR : RTDIRRMREC_F_CONTENT_ONLY;
345 rc = RTDirRemoveRecursive(szDir, fFlagsRemRec);
346 }
347 else /* Only remove empty directory structures. Will fail if non-empty. */
348 {
349 RTDIRENTRY DirEntry;
350 RTPathEnsureTrailingSeparator(szDir, sizeof(szDir));
351 rc = vgsvcGstCtrlSessionHandleDirRemoveSub(szDir, strlen(szDir), &DirEntry);
352 }
353 VGSvcVerbose(4, "[Dir %s]: rmdir /s (%#x) -> rc=%Rrc\n", szDir, fFlags, rc);
354 }
355 else
356 {
357 /* Only delete directory if not empty. */
358 rc = RTDirRemove(szDir);
359 VGSvcVerbose(4, "[Dir %s]: rmdir (%#x), rc=%Rrc\n", szDir, fFlags, rc);
360 }
361 }
362 else
363 {
364 VGSvcError("[Dir %s]: Unsupported flags: %#x (all %#x)\n", szDir, (fFlags & ~DIRREMOVEREC_FLAG_VALID_MASK), fFlags);
365 rc = VERR_NOT_SUPPORTED;
366 }
367
368 /*
369 * Report result back to host.
370 */
371 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
372 if (RT_FAILURE(rc2))
373 {
374 VGSvcError("[Dir %s]: Failed to report removing status, rc=%Rrc\n", szDir, rc2);
375 if (RT_SUCCESS(rc))
376 rc = rc2;
377 }
378 }
379 else
380 {
381 VGSvcError("Error fetching parameters for rmdir operation: %Rrc\n", rc);
382 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
383 }
384
385 VGSvcVerbose(6, "Removing directory '%s' returned rc=%Rrc\n", szDir, rc);
386 return rc;
387}
388
389
390static int vgsvcGstCtrlSessionHandleFileOpen(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
391{
392 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
393 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
394
395 /*
396 * Retrieve the message.
397 */
398 char szFile[RTPATH_MAX];
399 char szAccess[64];
400 char szDisposition[64];
401 char szSharing[64];
402 uint32_t uCreationMode = 0;
403 uint64_t offOpen = 0;
404 uint32_t uHandle = 0;
405 int rc = VbglR3GuestCtrlFileGetOpen(pHostCtx,
406 /* File to open. */
407 szFile, sizeof(szFile),
408 /* Open mode. */
409 szAccess, sizeof(szAccess),
410 /* Disposition. */
411 szDisposition, sizeof(szDisposition),
412 /* Sharing. */
413 szSharing, sizeof(szSharing),
414 /* Creation mode. */
415 &uCreationMode,
416 /* Offset. */
417 &offOpen);
418 VGSvcVerbose(4, "[File %s]: szAccess=%s, szDisposition=%s, szSharing=%s, offOpen=%RU64, rc=%Rrc\n",
419 szFile, szAccess, szDisposition, szSharing, offOpen, rc);
420 if (RT_SUCCESS(rc))
421 {
422 PVBOXSERVICECTRLFILE pFile = (PVBOXSERVICECTRLFILE)RTMemAllocZ(sizeof(VBOXSERVICECTRLFILE));
423 if (pFile)
424 {
425 pFile->hFile = NIL_RTFILE; /* Not zero or NULL! */
426 if (szFile[0])
427 {
428 pFile->pszName = RTStrDup(szFile);
429 if (!pFile->pszName)
430 rc = VERR_NO_MEMORY;
431/** @todo
432 * Implement szSharing!
433 */
434 uint64_t fFlags;
435 if (RT_SUCCESS(rc))
436 {
437 rc = RTFileModeToFlagsEx(szAccess, szDisposition, NULL /* pszSharing, not used yet */, &fFlags);
438 VGSvcVerbose(4, "[File %s] Opening with fFlags=%#RX64 -> rc=%Rrc\n", pFile->pszName, fFlags, rc);
439 }
440
441 if (RT_SUCCESS(rc))
442 {
443 fFlags |= (uCreationMode << RTFILE_O_CREATE_MODE_SHIFT) & RTFILE_O_CREATE_MODE_MASK;
444 /* If we're opening a file in read-only mode, strip truncation mode.
445 * rtFileRecalcAndValidateFlags() will validate it anyway, but avoid asserting in debug builds. */
446 if (fFlags & RTFILE_O_READ)
447 fFlags &= ~RTFILE_O_TRUNCATE;
448 rc = RTFileOpen(&pFile->hFile, pFile->pszName, fFlags);
449 if (RT_SUCCESS(rc))
450 {
451 RTFSOBJINFO objInfo;
452 rc = RTFileQueryInfo(pFile->hFile, &objInfo, RTFSOBJATTRADD_NOTHING);
453 if (RT_SUCCESS(rc))
454 {
455 /* Make sure that we only open stuff we really support.
456 * Only POSIX / UNIX we could open stuff like directories and sockets as well. */
457 if ( RT_LIKELY(RTFS_IS_FILE(objInfo.Attr.fMode))
458 || RTFS_IS_SYMLINK(objInfo.Attr.fMode))
459 {
460 /* Seeking is optional. However, the whole operation
461 * will fail if we don't succeed seeking to the wanted position. */
462 if (offOpen)
463 rc = RTFileSeek(pFile->hFile, (int64_t)offOpen, RTFILE_SEEK_BEGIN, NULL /* Current offset */);
464 if (RT_SUCCESS(rc))
465 {
466 /*
467 * Succeeded!
468 */
469 uHandle = VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pHostCtx->uContextID);
470 pFile->uHandle = uHandle;
471 pFile->fOpen = fFlags;
472 RTListAppend(&pSession->lstFiles, &pFile->Node);
473 VGSvcVerbose(2, "[File %s] Opened (ID=%RU32)\n", pFile->pszName, pFile->uHandle);
474 }
475 else
476 VGSvcError("[File %s] Seeking to offset %RU64 failed: rc=%Rrc\n", pFile->pszName, offOpen, rc);
477 }
478 else
479 {
480 VGSvcError("[File %s] Unsupported mode %#x\n", pFile->pszName, objInfo.Attr.fMode);
481 rc = VERR_NOT_SUPPORTED;
482 }
483 }
484 else
485 VGSvcError("[File %s] Getting mode failed with rc=%Rrc\n", pFile->pszName, rc);
486 }
487 else
488 VGSvcError("[File %s] Opening failed with rc=%Rrc\n", pFile->pszName, rc);
489 }
490 }
491 else
492 {
493 VGSvcError("Opening file failed: Empty filename!\n");
494 rc = VERR_INVALID_NAME;
495 }
496
497 /* clean up if we failed. */
498 if (RT_FAILURE(rc))
499 {
500 RTStrFree(pFile->pszName);
501 if (pFile->hFile != NIL_RTFILE)
502 RTFileClose(pFile->hFile);
503 RTMemFree(pFile);
504 }
505 }
506 else
507 rc = VERR_NO_MEMORY;
508
509 /*
510 * Report result back to host.
511 */
512 int rc2 = VbglR3GuestCtrlFileCbOpen(pHostCtx, rc, uHandle);
513 if (RT_FAILURE(rc2))
514 {
515 VGSvcError("[File %s]: Failed to report file open status, rc=%Rrc\n", szFile, rc2);
516 if (RT_SUCCESS(rc))
517 rc = rc2;
518 }
519 }
520 else
521 {
522 VGSvcError("Error fetching parameters for open file operation: %Rrc\n", rc);
523 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
524 }
525
526 VGSvcVerbose(4, "[File %s] Opening (open mode='%s', disposition='%s', creation mode=0x%x) returned rc=%Rrc\n",
527 szFile, szAccess, szDisposition, uCreationMode, rc);
528 return rc;
529}
530
531
532static int vgsvcGstCtrlSessionHandleFileClose(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
533{
534 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
535 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
536
537 /*
538 * Retrieve the message.
539 */
540 uint32_t uHandle = 0;
541 int rc = VbglR3GuestCtrlFileGetClose(pHostCtx, &uHandle /* File handle to close */);
542 if (RT_SUCCESS(rc))
543 {
544 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
545 if (pFile)
546 {
547 VGSvcVerbose(2, "[File %s] Closing (handle=%RU32)\n", pFile ? pFile->pszName : "<Not found>", uHandle);
548 rc = vgsvcGstCtrlSessionFileFree(pFile);
549 }
550 else
551 {
552 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
553 rc = VERR_NOT_FOUND;
554 }
555
556 /*
557 * Report result back to host.
558 */
559 int rc2 = VbglR3GuestCtrlFileCbClose(pHostCtx, rc);
560 if (RT_FAILURE(rc2))
561 {
562 VGSvcError("Failed to report file close status, rc=%Rrc\n", rc2);
563 if (RT_SUCCESS(rc))
564 rc = rc2;
565 }
566 }
567 else
568 {
569 VGSvcError("Error fetching parameters for close file operation: %Rrc\n", rc);
570 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
571 }
572 return rc;
573}
574
575
576static int vgsvcGstCtrlSessionHandleFileRead(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
577 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
578{
579 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
580 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
581
582 /*
583 * Retrieve the request.
584 */
585 uint32_t uHandle = 0;
586 uint32_t cbToRead;
587 int rc = VbglR3GuestCtrlFileGetRead(pHostCtx, &uHandle, &cbToRead);
588 if (RT_SUCCESS(rc))
589 {
590 /*
591 * Locate the file and do the reading.
592 *
593 * If the request is larger than our scratch buffer, try grow it - just
594 * ignore failure as the host better respect our buffer limits.
595 */
596 uint32_t offNew = 0;
597 size_t cbRead = 0;
598 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
599 if (pFile)
600 {
601 if (*pcbScratchBuf < cbToRead)
602 vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToRead);
603
604 rc = RTFileRead(pFile->hFile, *ppvScratchBuf, RT_MIN(cbToRead, *pcbScratchBuf), &cbRead);
605 offNew = (int64_t)RTFileTell(pFile->hFile);
606 VGSvcVerbose(5, "[File %s] Read %zu/%RU32 bytes, rc=%Rrc, offNew=%RI64\n", pFile->pszName, cbRead, cbToRead, rc, offNew);
607 vgsvcGstCtrlSessionFileRelease(pFile);
608 }
609 else
610 {
611 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
612 rc = VERR_NOT_FOUND;
613 }
614
615 /*
616 * Report result and data back to the host.
617 */
618 int rc2;
619 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
620 rc2 = VbglR3GuestCtrlFileCbReadOffset(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead, offNew);
621 else
622 rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead);
623 if (RT_FAILURE(rc2))
624 {
625 VGSvcError("Failed to report file read status, rc=%Rrc\n", rc2);
626 if (RT_SUCCESS(rc))
627 rc = rc2;
628 }
629 }
630 else
631 {
632 VGSvcError("Error fetching parameters for file read operation: %Rrc\n", rc);
633 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
634 }
635 return rc;
636}
637
638
639static int vgsvcGstCtrlSessionHandleFileReadAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
640 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
641{
642 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
643 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
644
645 /*
646 * Retrieve the request.
647 */
648 uint32_t uHandle = 0;
649 uint32_t cbToRead;
650 uint64_t offReadAt;
651 int rc = VbglR3GuestCtrlFileGetReadAt(pHostCtx, &uHandle, &cbToRead, &offReadAt);
652 if (RT_SUCCESS(rc))
653 {
654 /*
655 * Locate the file and do the reading.
656 *
657 * If the request is larger than our scratch buffer, try grow it - just
658 * ignore failure as the host better respect our buffer limits.
659 */
660 int64_t offNew = 0;
661 size_t cbRead = 0;
662 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
663 if (pFile)
664 {
665 if (*pcbScratchBuf < cbToRead)
666 vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToRead);
667
668 rc = RTFileReadAt(pFile->hFile, (RTFOFF)offReadAt, *ppvScratchBuf, RT_MIN(cbToRead, *pcbScratchBuf), &cbRead);
669 if (RT_SUCCESS(rc))
670 {
671 offNew = offReadAt + cbRead;
672 RTFileSeek(pFile->hFile, offNew, RTFILE_SEEK_BEGIN, NULL); /* RTFileReadAt does not always change position. */
673 }
674 else
675 offNew = (int64_t)RTFileTell(pFile->hFile);
676 VGSvcVerbose(5, "[File %s] Read %zu bytes @ %RU64, rc=%Rrc, offNew=%RI64\n", pFile->pszName, cbRead, offReadAt, rc, offNew);
677 vgsvcGstCtrlSessionFileRelease(pFile);
678 }
679 else
680 {
681 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
682 rc = VERR_NOT_FOUND;
683 }
684
685 /*
686 * Report result and data back to the host.
687 */
688 int rc2;
689 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
690 rc2 = VbglR3GuestCtrlFileCbReadOffset(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead, offNew);
691 else
692 rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, *ppvScratchBuf, (uint32_t)cbRead);
693 if (RT_FAILURE(rc2))
694 {
695 VGSvcError("Failed to report file read at status, rc=%Rrc\n", rc2);
696 if (RT_SUCCESS(rc))
697 rc = rc2;
698 }
699 }
700 else
701 {
702 VGSvcError("Error fetching parameters for file read at operation: %Rrc\n", rc);
703 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
704 }
705 return rc;
706}
707
708
709static int vgsvcGstCtrlSessionHandleFileWrite(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
710 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
711{
712 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
713 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
714
715 /*
716 * Retrieve the request and data to write.
717 */
718 uint32_t uHandle = 0;
719 uint32_t cbToWrite;
720 int rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite);
721 if ( rc == VERR_BUFFER_OVERFLOW
722 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToWrite))
723 rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite);
724 if (RT_SUCCESS(rc))
725 {
726 /*
727 * Locate the file and do the writing.
728 */
729 int64_t offNew = 0;
730 size_t cbWritten = 0;
731 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
732 if (pFile)
733 {
734 rc = RTFileWrite(pFile->hFile, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), &cbWritten);
735 offNew = (int64_t)RTFileTell(pFile->hFile);
736 VGSvcVerbose(5, "[File %s] Writing %p LB %RU32 => %Rrc, cbWritten=%zu, offNew=%RI64\n",
737 pFile->pszName, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), rc, cbWritten, offNew);
738 vgsvcGstCtrlSessionFileRelease(pFile);
739 }
740 else
741 {
742 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
743 rc = VERR_NOT_FOUND;
744 }
745
746 /*
747 * Report result back to host.
748 */
749 int rc2;
750 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
751 rc2 = VbglR3GuestCtrlFileCbWriteOffset(pHostCtx, rc, (uint32_t)cbWritten, offNew);
752 else
753 rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
754 if (RT_FAILURE(rc2))
755 {
756 VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
757 if (RT_SUCCESS(rc))
758 rc = rc2;
759 }
760 }
761 else
762 {
763 VGSvcError("Error fetching parameters for file write operation: %Rrc\n", rc);
764 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
765 }
766 return rc;
767}
768
769
770static int vgsvcGstCtrlSessionHandleFileWriteAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
771 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
772{
773 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
774 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
775
776 /*
777 * Retrieve the request and data to write.
778 */
779 uint32_t uHandle = 0;
780 uint32_t cbToWrite;
781 uint64_t offWriteAt;
782 int rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite, &offWriteAt);
783 if ( rc == VERR_BUFFER_OVERFLOW
784 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbToWrite))
785 rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, *ppvScratchBuf, *pcbScratchBuf, &cbToWrite, &offWriteAt);
786 if (RT_SUCCESS(rc))
787 {
788 /*
789 * Locate the file and do the writing.
790 */
791 int64_t offNew = 0;
792 size_t cbWritten = 0;
793 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
794 if (pFile)
795 {
796 rc = RTFileWriteAt(pFile->hFile, (RTFOFF)offWriteAt, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), &cbWritten);
797 if (RT_SUCCESS(rc))
798 {
799 offNew = offWriteAt + cbWritten;
800
801 /* RTFileWriteAt does not always change position: */
802 if (!(pFile->fOpen & RTFILE_O_APPEND))
803 RTFileSeek(pFile->hFile, offNew, RTFILE_SEEK_BEGIN, NULL);
804 else
805 RTFileSeek(pFile->hFile, 0, RTFILE_SEEK_END, (uint64_t *)&offNew);
806 }
807 else
808 offNew = (int64_t)RTFileTell(pFile->hFile);
809 VGSvcVerbose(5, "[File %s] Writing %p LB %RU32 @ %RU64 => %Rrc, cbWritten=%zu, offNew=%RI64\n",
810 pFile->pszName, *ppvScratchBuf, RT_MIN(cbToWrite, *pcbScratchBuf), offWriteAt, rc, cbWritten, offNew);
811 vgsvcGstCtrlSessionFileRelease(pFile);
812 }
813 else
814 {
815 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
816 rc = VERR_NOT_FOUND;
817 }
818
819 /*
820 * Report result back to host.
821 */
822 int rc2;
823 if (g_fControlHostFeatures0 & VBOX_GUESTCTRL_HF_0_NOTIFY_RDWR_OFFSET)
824 rc2 = VbglR3GuestCtrlFileCbWriteOffset(pHostCtx, rc, (uint32_t)cbWritten, offNew);
825 else
826 rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
827 if (RT_FAILURE(rc2))
828 {
829 VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
830 if (RT_SUCCESS(rc))
831 rc = rc2;
832 }
833 }
834 else
835 {
836 VGSvcError("Error fetching parameters for file write at operation: %Rrc\n", rc);
837 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
838 }
839 return rc;
840}
841
842
843static int vgsvcGstCtrlSessionHandleFileSeek(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
844{
845 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
846 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
847
848 /*
849 * Retrieve the request.
850 */
851 uint32_t uHandle = 0;
852 uint32_t uSeekMethod;
853 uint64_t offSeek; /* Will be converted to int64_t. */
854 int rc = VbglR3GuestCtrlFileGetSeek(pHostCtx, &uHandle, &uSeekMethod, &offSeek);
855 if (RT_SUCCESS(rc))
856 {
857 uint64_t offActual = 0;
858
859 /*
860 * Validate and convert the seek method to IPRT speak.
861 */
862 static const uint8_t s_abMethods[GUEST_FILE_SEEKTYPE_END + 1] =
863 {
864 UINT8_MAX, RTFILE_SEEK_BEGIN, UINT8_MAX, UINT8_MAX, RTFILE_SEEK_CURRENT,
865 UINT8_MAX, UINT8_MAX, UINT8_MAX, RTFILE_SEEK_END
866 };
867 if ( uSeekMethod < RT_ELEMENTS(s_abMethods)
868 && s_abMethods[uSeekMethod] != UINT8_MAX)
869 {
870 /*
871 * Locate the file and do the seek.
872 */
873 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
874 if (pFile)
875 {
876 rc = RTFileSeek(pFile->hFile, (int64_t)offSeek, s_abMethods[uSeekMethod], &offActual);
877 VGSvcVerbose(5, "[File %s]: Seeking to offSeek=%RI64, uSeekMethodIPRT=%u, rc=%Rrc\n",
878 pFile->pszName, offSeek, s_abMethods[uSeekMethod], rc);
879 vgsvcGstCtrlSessionFileRelease(pFile);
880 }
881 else
882 {
883 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
884 rc = VERR_NOT_FOUND;
885 }
886 }
887 else
888 {
889 VGSvcError("Invalid seek method: %#x\n", uSeekMethod);
890 rc = VERR_NOT_SUPPORTED;
891 }
892
893 /*
894 * Report result back to host.
895 */
896 int rc2 = VbglR3GuestCtrlFileCbSeek(pHostCtx, rc, offActual);
897 if (RT_FAILURE(rc2))
898 {
899 VGSvcError("Failed to report file seek status, rc=%Rrc\n", rc2);
900 if (RT_SUCCESS(rc))
901 rc = rc2;
902 }
903 }
904 else
905 {
906 VGSvcError("Error fetching parameters for file seek operation: %Rrc\n", rc);
907 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
908 }
909 return rc;
910}
911
912
913static int vgsvcGstCtrlSessionHandleFileTell(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
914{
915 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
916 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
917
918 /*
919 * Retrieve the request.
920 */
921 uint32_t uHandle = 0;
922 int rc = VbglR3GuestCtrlFileGetTell(pHostCtx, &uHandle);
923 if (RT_SUCCESS(rc))
924 {
925 /*
926 * Locate the file and ask for the current position.
927 */
928 uint64_t offCurrent = 0;
929 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
930 if (pFile)
931 {
932 offCurrent = RTFileTell(pFile->hFile);
933 VGSvcVerbose(5, "[File %s]: Telling offCurrent=%RU64\n", pFile->pszName, offCurrent);
934 vgsvcGstCtrlSessionFileRelease(pFile);
935 }
936 else
937 {
938 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
939 rc = VERR_NOT_FOUND;
940 }
941
942 /*
943 * Report result back to host.
944 */
945 int rc2 = VbglR3GuestCtrlFileCbTell(pHostCtx, rc, offCurrent);
946 if (RT_FAILURE(rc2))
947 {
948 VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
949 if (RT_SUCCESS(rc))
950 rc = rc2;
951 }
952 }
953 else
954 {
955 VGSvcError("Error fetching parameters for file tell operation: %Rrc\n", rc);
956 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
957 }
958 return rc;
959}
960
961
962static int vgsvcGstCtrlSessionHandleFileSetSize(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
963{
964 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
965 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
966
967 /*
968 * Retrieve the request.
969 */
970 uint32_t uHandle = 0;
971 uint64_t cbNew = 0;
972 int rc = VbglR3GuestCtrlFileGetSetSize(pHostCtx, &uHandle, &cbNew);
973 if (RT_SUCCESS(rc))
974 {
975 /*
976 * Locate the file and ask for the current position.
977 */
978 PVBOXSERVICECTRLFILE pFile = vgsvcGstCtrlSessionFileAcquire(pSession, uHandle);
979 if (pFile)
980 {
981 rc = RTFileSetSize(pFile->hFile, cbNew);
982 VGSvcVerbose(5, "[File %s]: Changing size to %RU64 (%#RX64), rc=%Rrc\n", pFile->pszName, cbNew, cbNew, rc);
983 vgsvcGstCtrlSessionFileRelease(pFile);
984 }
985 else
986 {
987 VGSvcError("File %u (%#x) not found!\n", uHandle, uHandle);
988 cbNew = UINT64_MAX;
989 rc = VERR_NOT_FOUND;
990 }
991
992 /*
993 * Report result back to host.
994 */
995 int rc2 = VbglR3GuestCtrlFileCbSetSize(pHostCtx, rc, cbNew);
996 if (RT_FAILURE(rc2))
997 {
998 VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
999 if (RT_SUCCESS(rc))
1000 rc = rc2;
1001 }
1002 }
1003 else
1004 {
1005 VGSvcError("Error fetching parameters for file tell operation: %Rrc\n", rc);
1006 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1007 }
1008 return rc;
1009}
1010
1011
1012#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
1013static int vgsvcGstCtrlSessionHandleFileRemove(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1014{
1015 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1016 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1017
1018 /*
1019 * Retrieve the request.
1020 */
1021 char szPath[RTPATH_MAX];
1022 int rc = VbglR3GuestCtrlFileGetRemove(pHostCtx, szPath, sizeof(szPath));
1023 if (RT_SUCCESS(rc))
1024 {
1025 VGSvcVerbose(4, "Deleting file szPath=%s\n", szPath);
1026 rc = RTFileDelete(szPath);
1027
1028 /*
1029 * Report result back to host.
1030 */
1031 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
1032 if (RT_FAILURE(rc2))
1033 {
1034 VGSvcError("Failed to report file deletion status, rc=%Rrc\n", rc2);
1035 if (RT_SUCCESS(rc))
1036 rc = rc2;
1037 }
1038 }
1039 else
1040 {
1041 VGSvcError("Error fetching parameters for file deletion operation: %Rrc\n", rc);
1042 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1043 }
1044 VGSvcVerbose(5, "Deleting file returned rc=%Rrc\n", rc);
1045 return rc;
1046}
1047
1048
1049static int vgsvcGstCtrlSessionHandleDirOpen(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1050{
1051 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1052 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1053
1054 char szPath[RTPATH_MAX];
1055 uint32_t fFlags;
1056 GSTCTLDIRFILTER enmFilter;
1057 uint32_t uHandle = 0;
1058 uint32_t fReadFlags;
1059 GSTCTLFSOBJATTRADD enmAttrAdd;
1060 int rc = VbglR3GuestCtrlDirGetOpen(pHostCtx, szPath, sizeof(szPath), &fFlags, &enmFilter, &enmAttrAdd, &fReadFlags);
1061 VGSvcVerbose(4, "[Dir %s]: fFlags=%#x, enmFilter=%#x, rc=%Rrc\n", szPath, fFlags, enmFilter, rc);
1062 if (RT_SUCCESS(rc))
1063 {
1064 PVBOXSERVICECTRLDIR pDir = (PVBOXSERVICECTRLDIR)RTMemAllocZ(sizeof(VBOXSERVICECTRLDIR));
1065 AssertPtrReturn(pDir, VERR_NO_MEMORY);
1066 pDir->hDir = NIL_RTDIR; /* Not zero or NULL! */
1067 if (szPath[0])
1068 {
1069 pDir->pszPathAbs = RTStrDup(szPath);
1070 if (!pDir->pszPathAbs)
1071 rc = VERR_NO_MEMORY;
1072
1073 /* Save reading parameters for subsequent directory entry read calls later. */
1074 pDir->fRead = fReadFlags;
1075 pDir->enmReadAttrAdd = enmAttrAdd;
1076
1077 pDir->cbDirEntryEx = GSTCTL_DIRENTRY_MAX_SIZE;
1078 pDir->pDirEntryEx = (PRTDIRENTRYEX)RTMemAlloc(pDir->cbDirEntryEx);
1079 AssertPtrReturn(pDir->pDirEntryEx, VERR_NO_MEMORY);
1080
1081 if (RT_SUCCESS(rc))
1082 {
1083 rc = RTDirOpenFiltered(&pDir->hDir, pDir->pszPathAbs, (RTDIRFILTER)enmFilter, fFlags);
1084 if (RT_SUCCESS(rc))
1085 {
1086 uHandle = VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pHostCtx->uContextID);
1087 pDir->uHandle = uHandle;
1088 RTListAppend(&pSession->lstDirs, &pDir->Node);
1089 VGSvcVerbose(2, "[Dir %s] Opened (ID=%RU32)\n", pDir->pszPathAbs, pDir->uHandle);
1090 }
1091 }
1092 }
1093 else
1094 {
1095 VGSvcError("Opening directory failed: Empty path!\n");
1096 rc = VERR_INVALID_NAME;
1097 }
1098
1099 /* Clean up if we failed. */
1100 if (RT_FAILURE(rc))
1101 {
1102 RTStrFree(pDir->pszPathAbs);
1103 if (pDir->hDir != NIL_RTDIR)
1104 RTDirClose(pDir->hDir);
1105 RTMemFree(pDir);
1106 }
1107
1108 /*
1109 * Report result back to host.
1110 */
1111 int rc2 = VbglR3GuestCtrlDirCbOpen(pHostCtx, rc, uHandle);
1112 if (RT_FAILURE(rc2))
1113 {
1114 VGSvcError("[Dir %s]: Failed to report directory open status, rc=%Rrc\n", szPath, rc2);
1115 if (RT_SUCCESS(rc))
1116 rc = rc2;
1117 }
1118 }
1119 else
1120 {
1121 VGSvcError("Error fetching parameters for directory open operation: %Rrc\n", rc);
1122 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1123 }
1124
1125 VGSvcVerbose(4, "[Dir %s] Opening (flags=%#x, filter flags=%#x) returned rc=%Rrc\n",
1126 szPath, fFlags, enmFilter, rc);
1127 return rc;
1128}
1129
1130
1131static int vgsvcGstCtrlSessionHandleDirClose(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1132{
1133 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1134 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1135
1136 /*
1137 * Retrieve the message.
1138 */
1139 uint32_t uHandle = 0;
1140 int rc = VbglR3GuestCtrlDirGetClose(pHostCtx, &uHandle /* Dir handle to close */);
1141 if (RT_SUCCESS(rc))
1142 {
1143 PVBOXSERVICECTRLDIR pDir = vgsvcGstCtrlSessionDirAcquire(pSession, uHandle);
1144 if (pDir)
1145 {
1146 VGSvcVerbose(2, "[Dir %s] Closing (handle=%RU32)\n", pDir ? pDir->pszPathAbs : "<Not found>", uHandle);
1147 rc = vgsvcGstCtrlSessionDirFree(pDir);
1148 }
1149 else
1150 {
1151 VGSvcError("Directory %u (%#x) not found!\n", uHandle, uHandle);
1152 rc = VERR_NOT_FOUND;
1153 }
1154
1155 /*
1156 * Report result back to host.
1157 */
1158 int rc2 = VbglR3GuestCtrlDirCbClose(pHostCtx, rc);
1159 if (RT_FAILURE(rc2))
1160 {
1161 VGSvcError("Failed to report directory close status, rc=%Rrc\n", rc2);
1162 if (RT_SUCCESS(rc))
1163 rc = rc2;
1164 }
1165 }
1166 else
1167 {
1168 VGSvcError("Error fetching parameters for directory close operation: %Rrc\n", rc);
1169 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1170 }
1171 return rc;
1172}
1173
1174
1175/**
1176 * Worker function for reading a next guest directory entry.
1177 *
1178 * @returns VBox status code.
1179 * @param pSession Guest Control session to use.
1180 * @param pDir Guest directory to read the next entry for.
1181 * @param ppDirEntryEx Where to store the pointer to the next guest directory entry on success.
1182 * @param pcbDirEntryEx Where to return the size (in bytes) of \a ppGstCtlDirEntryEx on success.
1183 * @param ppszUser Where to return the resolved user name string.
1184 * @param ppszGroups Where to return the resolved groups string.
1185 */
1186static int vgsvcGstCtrlSessionDirReadNext(const PVBOXSERVICECTRLSESSION pSession,
1187 PVBOXSERVICECTRLDIR pDir,
1188 PGSTCTLDIRENTRYEX *ppDirEntryEx, size_t *pcbDirEntryEx,
1189 const char **ppszUser, const char **ppszGroups)
1190{
1191 PRTDIRENTRYEX pDirEntryEx = pDir->pDirEntryEx;
1192
1193 size_t cbDirEntryEx = pDir->cbDirEntryEx;
1194 int rc = RTDirReadEx(pDir->hDir, pDir->pDirEntryEx, &cbDirEntryEx, (RTFSOBJATTRADD)pDir->enmReadAttrAdd, pDir->fRead);
1195
1196 VGSvcVerbose(2, "[Dir %s] Read next entry '%s' -> %Rrc (%zu bytes)\n",
1197 pDir->pszPathAbs, RT_SUCCESS(rc) ? pDirEntryEx->szName : "<None>", rc, cbDirEntryEx);
1198
1199 if (RT_FAILURE(rc))
1200 return rc;
1201
1202 /* Paranoia. */
1203 AssertReturn(cbDirEntryEx <= pDir->cbDirEntryEx, VERR_BUFFER_OVERFLOW);
1204
1205 *ppszUser = VGSvcIdCacheGetUidName(&pSession->UidCache,
1206 pDirEntryEx->Info.Attr.u.Unix.uid, pDirEntryEx->szName, pDir->pszPathAbs);
1207 *ppszGroups = VGSvcIdCacheGetGidName(&pSession->GidCache,
1208 pDirEntryEx->Info.Attr.u.Unix.gid, pDirEntryEx->szName, pDir->pszPathAbs);
1209
1210 VGSvcVerbose(2, "[Dir %s] Entry '%s': %zu bytes, uid=%s (%d), gid=%s (%d)\n",
1211 pDir->pszPathAbs, pDirEntryEx->szName, pDirEntryEx->Info.cbObject,
1212 *ppszUser, pDirEntryEx->Info.Attr.u.UnixOwner.uid,
1213 *ppszGroups, pDirEntryEx->Info.Attr.u.UnixGroup.gid);
1214
1215 /*
1216 * For now we ASSUME that RTDIRENTRYEX == GSTCTLDIRENTRYEX, which implies that we simply can cast RTDIRENTRYEX
1217 * to GSTCTLDIRENTRYEX. This might change in the future, however, so be extra cautious here.
1218 *
1219 * Ditto for RTFSOBJATTRADD == GSTCTLFSOBJATTRADD.
1220 */
1221 AssertCompile(sizeof(GSTCTLDIRENTRYEX) == sizeof(RTDIRENTRYEX));
1222 AssertCompile(RT_OFFSETOF(GSTCTLDIRENTRYEX, Info) == RT_OFFSETOF(RTDIRENTRYEX, Info));
1223 AssertCompile(RT_OFFSETOF(GSTCTLDIRENTRYEX, cbName) == RT_OFFSETOF(RTDIRENTRYEX, cbName));
1224 AssertCompile(RT_OFFSETOF(GSTCTLDIRENTRYEX, szName) == RT_OFFSETOF(RTDIRENTRYEX, szName));
1225 AssertCompile(RT_OFFSETOF(GSTCTLFSOBJINFO, Attr) == RT_OFFSETOF(RTFSOBJINFO, Attr));
1226
1227 if (RT_SUCCESS(rc))
1228 {
1229 *ppDirEntryEx = (PGSTCTLDIRENTRYEX)pDirEntryEx;
1230 *pcbDirEntryEx = cbDirEntryEx;
1231 }
1232
1233 return rc;
1234}
1235
1236
1237static int vgsvcGstCtrlSessionHandleDirRead(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1238{
1239 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1240 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1241
1242 /*
1243 * Retrieve the message.
1244 */
1245 uint32_t uHandle;
1246 int rc = VbglR3GuestCtrlDirGetRead(pHostCtx, &uHandle);
1247 if (RT_SUCCESS(rc))
1248 {
1249 PVBOXSERVICECTRLDIR pDir = vgsvcGstCtrlSessionDirAcquire(pSession, uHandle);
1250 if (pDir)
1251 {
1252 PGSTCTLDIRENTRYEX pDirEntryEx;
1253 size_t cbDirEntryEx;
1254 const char *pszUser = NULL;
1255 const char *pszGroups = NULL;
1256 rc = vgsvcGstCtrlSessionDirReadNext(pSession, pDir,
1257 &pDirEntryEx, &cbDirEntryEx, &pszUser, &pszGroups);
1258
1259 VGSvcVerbose(2, "[Dir %s] %Rrc\n", pDir->pszPathAbs, rc);
1260
1261 int rc2;
1262 if (RT_SUCCESS(rc))
1263 rc2 = VbglR3GuestCtrlDirCbReadEx(pHostCtx, rc, pDirEntryEx, (uint32_t)cbDirEntryEx, pszUser, pszGroups);
1264 else
1265 rc2 = VbglR3GuestCtrlDirCbRead(pHostCtx, rc, NULL /* pEntry */, 0 /* cbSize */);
1266 if (RT_FAILURE(rc2))
1267 VGSvcError("Failed to report directory read status (%Rrc), rc=%Rrc\n", rc, rc2);
1268
1269 VGSvcVerbose(2, "[Dir %s] 2 %Rrc\n", pDir->pszPathAbs, rc);
1270
1271 if (rc == VERR_NO_MORE_FILES) /* Directory reading done. */
1272 rc = VINF_SUCCESS;
1273
1274 vgsvcGstCtrlSessionDirRelease(pDir);
1275 }
1276 else
1277 {
1278 VGSvcError("Directory %u (%#x) not found!\n", uHandle, uHandle);
1279 rc = VERR_NOT_FOUND;
1280 }
1281 }
1282 else
1283 {
1284 VGSvcError("Error fetching parameters for directory read operation: %Rrc\n", rc);
1285 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1286 }
1287 return rc;
1288}
1289
1290
1291static int vgsvcGstCtrlSessionHandleDirRewind(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1292{
1293 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1294 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1295
1296 /*
1297 * Retrieve the message.
1298 */
1299 uint32_t uHandle = 0;
1300 int rc = VbglR3GuestCtrlDirGetRewind(pHostCtx, &uHandle);
1301 if (RT_SUCCESS(rc))
1302 {
1303 PVBOXSERVICECTRLDIR pDir = vgsvcGstCtrlSessionDirAcquire(pSession, uHandle);
1304 if (pDir)
1305 {
1306 VGSvcVerbose(2, "[Dir %s] Rewinding (handle=%RU32)\n", pDir ? pDir->pszPathAbs : "<Not found>", uHandle);
1307
1308 rc = RTDirRewind(pDir->hDir);
1309
1310 vgsvcGstCtrlSessionDirRelease(pDir);
1311 }
1312 else
1313 {
1314 VGSvcError("Directory %u (%#x) not found!\n", uHandle, uHandle);
1315 rc = VERR_NOT_FOUND;
1316 }
1317
1318 /*
1319 * Report result back to host.
1320 */
1321 int rc2 = VbglR3GuestCtrlDirCbRewind(pHostCtx, rc);
1322 if (RT_FAILURE(rc2))
1323 {
1324 VGSvcError("Failed to report directory rewind status, rc=%Rrc\n", rc2);
1325 if (RT_SUCCESS(rc))
1326 rc = rc2;
1327 }
1328 }
1329 else
1330 {
1331 VGSvcError("Error fetching parameters for directory rewind operation: %Rrc\n", rc);
1332 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1333 }
1334 return rc;
1335}
1336
1337
1338static int vgsvcGstCtrlSessionHandleDirCreate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1339{
1340 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1341 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1342
1343 /*
1344 * Retrieve the request.
1345 */
1346 char szPath[RTPATH_MAX];
1347 RTFMODE fMode;
1348 uint32_t fCreate;
1349 int rc = VbglR3GuestCtrlDirGetCreate(pHostCtx, szPath, sizeof(szPath), &fMode, &fCreate);
1350 if (RT_SUCCESS(rc))
1351 {
1352 if (!(fCreate & ~GSTCTL_CREATEDIRECTORY_F_VALID_MASK))
1353 {
1354 /* Translate flags. */
1355 int fCreateRuntime = 0; /* RTDIRCREATE_FLAGS_XXX */
1356 if (fCreate & GSTCTL_CREATEDIRECTORY_F_NO_SYMLINKS)
1357 fCreateRuntime |= RTDIRCREATE_FLAGS_NO_SYMLINKS;
1358 if (fCreate & GSTCTL_CREATEDIRECTORY_F_IGNORE_UMASK)
1359 fCreateRuntime |= RTDIRCREATE_FLAGS_IGNORE_UMASK;
1360
1361 if (fCreate & GSTCTL_CREATEDIRECTORY_F_PARENTS)
1362 rc = RTDirCreateFullPath(szPath, fMode);
1363 else
1364 rc = RTDirCreate(szPath, fMode, fCreateRuntime);
1365
1366 VGSvcVerbose(4, "Creating directory (szPath='%s', fMode=%#x, fCreate=%#x) -> rc=%Rrc\n", szPath, fMode, fCreate, rc);
1367 }
1368 else
1369 {
1370 VGSvcError("Invalid directory creation flags: %#x\n", fCreate);
1371 rc = VERR_NOT_SUPPORTED;
1372 }
1373
1374 /*
1375 * Report result back to host.
1376 */
1377 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
1378 if (RT_FAILURE(rc2))
1379 {
1380 VGSvcError("Failed to report directory creation status, rc=%Rrc\n", rc2);
1381 if (RT_SUCCESS(rc))
1382 rc = rc2;
1383 }
1384 }
1385 else
1386 {
1387 VGSvcError("Error fetching parameters for directory creation operation: %Rrc\n", rc);
1388 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1389 }
1390 VGSvcVerbose(5, "Creating directory returned rc=%Rrc\n", rc);
1391 return rc;
1392}
1393
1394static int vgsvcGstCtrlSessionHandleDirList(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1395{
1396 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1397 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1398
1399 /*
1400 * Retrieve the request.
1401 */
1402 uint32_t uHandle;
1403 uint32_t cEntries;
1404 uint32_t cEntriesRead = 0;
1405 uint32_t fFlags;
1406 int rc = VbglR3GuestCtrlDirGetList(pHostCtx, &uHandle, &cEntries, &fFlags);
1407 if (RT_SUCCESS(rc))
1408 {
1409 size_t cbGrowSize = _64K;
1410 void *pvBuf = RTMemAlloc(cbGrowSize);
1411 if (!pvBuf)
1412 rc = VERR_NO_MEMORY;
1413 size_t cbBufUsed = 0;
1414 if (RT_SUCCESS(rc))
1415 {
1416 if (!(fFlags & ~GSTCTL_DIRLIST_F_VALID_MASK))
1417 {
1418 size_t cbBufSize = cbGrowSize;
1419
1420 PVBOXSERVICECTRLDIR pDir = vgsvcGstCtrlSessionDirAcquire(pSession, uHandle);
1421 if (pDir)
1422 {
1423 PGSTCTLDIRENTRYEX pDirEntryEx;
1424 size_t cbDirEntryEx;
1425 const char *pszUser = NULL;
1426 const char *pszGroups = NULL;
1427
1428 while (cEntries--)
1429 {
1430 rc = vgsvcGstCtrlSessionDirReadNext(pSession, pDir,
1431 &pDirEntryEx, &cbDirEntryEx, &pszUser, &pszGroups);
1432 if (RT_FAILURE(rc)) /* Might be VERR_NO_MORE_FILES. */
1433 break;
1434
1435 size_t const cbHdr = sizeof(GSTCTLDIRENTRYLISTHDR);
1436 size_t const cbUser = strlen(pszUser) + 1; /* Include terminator. */
1437 size_t const cbGroups = strlen(pszGroups) + 1; /* Ditto. */
1438 size_t const cbTotal = cbHdr + cbDirEntryEx + cbUser + cbGroups;
1439
1440 if (cbBufSize - cbBufUsed < cbTotal) /* Grow buffer, if needed. */
1441 {
1442 AssertBreakStmt(cbTotal <= cbGrowSize, rc = VERR_BUFFER_OVERFLOW);
1443 pvBuf = RTMemRealloc(pvBuf, cbBufSize + cbGrowSize);
1444 AssertPtrBreakStmt(pvBuf, rc = VERR_NO_MEMORY);
1445 cbBufSize += cbGrowSize;
1446 }
1447
1448 GSTCTLDIRENTRYLISTHDR Hdr;
1449 Hdr.cbDirEntryEx = (uint32_t)cbDirEntryEx;
1450 Hdr.cbUser = (uint32_t)cbUser;
1451 Hdr.cbGroups = (uint32_t)cbGroups;
1452
1453 memcpy((uint8_t *)pvBuf + cbBufUsed, &Hdr, cbHdr);
1454 cbBufUsed += cbHdr;
1455 memcpy((uint8_t *)pvBuf + cbBufUsed, pDirEntryEx, cbDirEntryEx);
1456 cbBufUsed += cbDirEntryEx;
1457 memcpy((uint8_t *)pvBuf + cbBufUsed, pszUser, cbUser);
1458 cbBufUsed += cbUser;
1459 memcpy((uint8_t *)pvBuf + cbBufUsed, pszGroups, cbGroups);
1460 cbBufUsed += cbGroups;
1461
1462 Assert(cbBufUsed <= cbBufSize);
1463 cEntriesRead++;
1464 }
1465
1466 vgsvcGstCtrlSessionDirRelease(pDir);
1467 }
1468
1469 VGSvcVerbose(4, "Read %RU32 directory entries (requested %RU32 entries) -> %zu bytes, rc=%Rrc\n",
1470 cEntriesRead, cEntries, cbBufUsed, rc);
1471
1472 /* Directory reading done? */
1473 if ( cEntriesRead
1474 && rc == VERR_NO_MORE_FILES)
1475 rc = VINF_SUCCESS;
1476
1477 /* Note: Subsequent calls will return VERR_NO_MORE_FILES to the host. */
1478 }
1479 else
1480 {
1481 VGSvcError("Unsupported directory listing flags: %#x (all %#x)\n", (fFlags & ~GSTCTL_DIRLIST_F_VALID_MASK), fFlags);
1482 rc = VERR_NOT_SUPPORTED;
1483 }
1484 }
1485
1486 /*
1487 * Report result back to host.
1488 */
1489 int rc2 = VbglR3GuestCtrlDirCbList(pHostCtx, rc, cEntriesRead, pvBuf, (uint32_t)cbBufUsed);
1490 if (RT_FAILURE(rc2))
1491 VGSvcError("Failed to report directory listing (%Rrc), rc=%Rrc\n", rc, rc2);
1492
1493 if (rc == VERR_NO_MORE_FILES) /* Directory reading done? */
1494 rc = VINF_SUCCESS;
1495
1496 RTMemFree(pvBuf);
1497 }
1498 else
1499 {
1500 VGSvcError("Error fetching parameters for directory listing operation: %Rrc\n", rc);
1501 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1502 }
1503 VGSvcVerbose(5, "Listing directory returned rc=%Rrc\n", rc);
1504 return rc;
1505}
1506#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
1507
1508
1509static int vgsvcGstCtrlSessionHandlePathRename(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1510{
1511 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1512 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1513
1514 /*
1515 * Retrieve the request.
1516 */
1517 char szSource[RTPATH_MAX];
1518 char szDest[RTPATH_MAX];
1519 uint32_t fFlags = 0; /* PATHRENAME_FLAG_XXX */
1520 int rc = VbglR3GuestCtrlPathGetRename(pHostCtx, szSource, sizeof(szSource), szDest, sizeof(szDest), &fFlags);
1521 if (RT_SUCCESS(rc))
1522 {
1523 /*
1524 * Validate the flags (kudos for using the same as IPRT), then do the renaming.
1525 */
1526 AssertCompile(PATHRENAME_FLAG_NO_REPLACE == RTPATHRENAME_FLAGS_NO_REPLACE);
1527 AssertCompile(PATHRENAME_FLAG_REPLACE == RTPATHRENAME_FLAGS_REPLACE);
1528 AssertCompile(PATHRENAME_FLAG_NO_SYMLINKS == RTPATHRENAME_FLAGS_NO_SYMLINKS);
1529 AssertCompile(PATHRENAME_FLAG_VALID_MASK == (RTPATHRENAME_FLAGS_NO_REPLACE | RTPATHRENAME_FLAGS_REPLACE | RTPATHRENAME_FLAGS_NO_SYMLINKS));
1530 if (!(fFlags & ~PATHRENAME_FLAG_VALID_MASK))
1531 {
1532 VGSvcVerbose(4, "Renaming '%s' to '%s', fFlags=%#x, rc=%Rrc\n", szSource, szDest, fFlags, rc);
1533 rc = RTPathRename(szSource, szDest, fFlags);
1534 }
1535 else
1536 {
1537 VGSvcError("Invalid rename flags: %#x\n", fFlags);
1538 rc = VERR_NOT_SUPPORTED;
1539 }
1540
1541 /*
1542 * Report result back to host.
1543 */
1544 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
1545 if (RT_FAILURE(rc2))
1546 {
1547 VGSvcError("Failed to report renaming status, rc=%Rrc\n", rc2);
1548 if (RT_SUCCESS(rc))
1549 rc = rc2;
1550 }
1551 }
1552 else
1553 {
1554 VGSvcError("Error fetching parameters for rename operation: %Rrc\n", rc);
1555 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1556 }
1557 VGSvcVerbose(5, "Renaming '%s' to '%s' returned rc=%Rrc\n", szSource, szDest, rc);
1558 return rc;
1559}
1560
1561
1562/**
1563 * Handles getting the user's documents directory.
1564 *
1565 * @returns VBox status code.
1566 * @param pSession Guest session.
1567 * @param pHostCtx Host context.
1568 */
1569static int vgsvcGstCtrlSessionHandlePathUserDocuments(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1570{
1571 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1572 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1573
1574 /*
1575 * Retrieve the request.
1576 */
1577 int rc = VbglR3GuestCtrlPathGetUserDocuments(pHostCtx);
1578 if (RT_SUCCESS(rc))
1579 {
1580 /*
1581 * Get the path and pass it back to the host..
1582 */
1583 char szPath[RTPATH_MAX];
1584 rc = RTPathUserDocuments(szPath, sizeof(szPath));
1585#ifdef DEBUG
1586 VGSvcVerbose(2, "User documents is '%s', rc=%Rrc\n", szPath, rc);
1587#endif
1588
1589 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
1590 RT_SUCCESS(rc) ? (uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
1591 if (RT_FAILURE(rc2))
1592 {
1593 VGSvcError("Failed to report user documents, rc=%Rrc\n", rc2);
1594 if (RT_SUCCESS(rc))
1595 rc = rc2;
1596 }
1597 }
1598 else
1599 {
1600 VGSvcError("Error fetching parameters for user documents path request: %Rrc\n", rc);
1601 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1602 }
1603 return rc;
1604}
1605
1606
1607/**
1608 * Handles shutting down / rebooting the guest OS.
1609 *
1610 * @returns VBox status code.
1611 * @param pSession Guest session.
1612 * @param pHostCtx Host context.
1613 */
1614static int vgsvcGstCtrlSessionHandleShutdown(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1615{
1616 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1617 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1618
1619 /*
1620 * Retrieve the request.
1621 */
1622 uint32_t fAction;
1623 int rc = VbglR3GuestCtrlGetShutdown(pHostCtx, &fAction);
1624 if (RT_SUCCESS(rc))
1625 {
1626 VGSvcVerbose(1, "Host requested to %s system ...\n", (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "reboot" : "shutdown");
1627
1628 /* Reply first to the host, in order to avoid host hangs when issuing the guest shutdown. */
1629 rc = VbglR3GuestCtrlMsgReply(pHostCtx, VINF_SUCCESS);
1630 if (RT_FAILURE(rc))
1631 {
1632 VGSvcError("Failed to reply to shutdown / reboot request, rc=%Rrc\n", rc);
1633 }
1634 else
1635 {
1636 uint32_t fSystemShutdown = RTSYSTEM_SHUTDOWN_PLANNED;
1637
1638 /* Translate SHUTDOWN_FLAG_ into RTSYSTEM_SHUTDOWN_ flags. */
1639 if (fAction & GUEST_SHUTDOWN_FLAG_REBOOT)
1640 fSystemShutdown |= RTSYSTEM_SHUTDOWN_REBOOT;
1641 else /* SHUTDOWN_FLAG_POWER_OFF */
1642 fSystemShutdown |= RTSYSTEM_SHUTDOWN_POWER_OFF;
1643
1644 if (fAction & GUEST_SHUTDOWN_FLAG_FORCE)
1645 fSystemShutdown |= RTSYSTEM_SHUTDOWN_FORCE;
1646
1647 rc = RTSystemShutdown(0 /*cMsDelay*/, fSystemShutdown, "VBoxService");
1648 if (RT_FAILURE(rc))
1649 VGSvcError("%s system failed with %Rrc\n",
1650 (fAction & RTSYSTEM_SHUTDOWN_REBOOT) ? "Rebooting" : "Shutting down", rc);
1651 }
1652 }
1653 else
1654 {
1655 VGSvcError("Error fetching parameters for shutdown / reboot request: %Rrc\n", rc);
1656 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1657 }
1658
1659 return rc;
1660}
1661
1662
1663/**
1664 * Handles getting the user's home directory.
1665 *
1666 * @returns VBox status code.
1667 * @param pSession Guest session.
1668 * @param pHostCtx Host context.
1669 */
1670static int vgsvcGstCtrlSessionHandlePathUserHome(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1671{
1672 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1673 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1674
1675 /*
1676 * Retrieve the request.
1677 */
1678 int rc = VbglR3GuestCtrlPathGetUserHome(pHostCtx);
1679 if (RT_SUCCESS(rc))
1680 {
1681 /*
1682 * Get the path and pass it back to the host..
1683 */
1684 char szPath[RTPATH_MAX];
1685 rc = RTPathUserHome(szPath, sizeof(szPath));
1686
1687#ifdef DEBUG
1688 VGSvcVerbose(2, "User home is '%s', rc=%Rrc\n", szPath, rc);
1689#endif
1690 /* Report back in any case. */
1691 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, szPath,
1692 RT_SUCCESS(rc) ?(uint32_t)strlen(szPath) + 1 /* Include terminating zero */ : 0);
1693 if (RT_FAILURE(rc2))
1694 {
1695 VGSvcError("Failed to report user home, rc=%Rrc\n", rc2);
1696 if (RT_SUCCESS(rc))
1697 rc = rc2;
1698 }
1699 }
1700 else
1701 {
1702 VGSvcError("Error fetching parameters for user home directory path request: %Rrc\n", rc);
1703 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1704 }
1705 return rc;
1706}
1707
1708/**
1709 * Structure for keeping a mount point enumeration context.
1710 */
1711typedef struct VGSVCMOUNTPOINTENUMCTX
1712{
1713 /** Mount points as strings, delimited with a string terminator ('\0').
1714 * List ends with an additional string terminator. Might get re-allocated, so don't rely on this pointer! */
1715 char *psz;
1716 /** Current size of \a psz in bytes. Includes ending terminator. */
1717 size_t cb;
1718 /** Total allocation Size of \a psz in bytes. */
1719 size_t cbAlloc;
1720} VGSVCMOUNTPOINTENUMCTX;
1721/** Pointer to a structure for keeping a mount point enumeration context. */
1722typedef VGSVCMOUNTPOINTENUMCTX *PVGSVCMOUNTPOINTENUMCTX;
1723
1724/**
1725 * Enumeration callback for storing the mount points.
1726 *
1727 * @returns VBox status code.
1728 * @param pszMountpoint Mount point to handle.
1729 * @param pvUser Pointer of type PVGSVCMOUNTPOINTENUMCTX.
1730 */
1731static DECLCALLBACK(int) vgsvcGstCtrlSessionHandleMountPointsEnumCallback(const char *pszMountpoint, void *pvUser)
1732{
1733 PVGSVCMOUNTPOINTENUMCTX pCtx = (PVGSVCMOUNTPOINTENUMCTX)pvUser;
1734 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
1735
1736 size_t const cch = strlen(pszMountpoint) + 1 /* Entry terminator */;
1737 AssertReturn(cch < RTPATH_MAX, VERR_INVALID_PARAMETER); /* Paranoia. */
1738 if (cch > pCtx->cbAlloc - pCtx->cb - 1 /* Ending terminator */)
1739 {
1740 int rc2 = RTStrRealloc(&pCtx->psz, pCtx->cbAlloc + RT_MAX(_4K, cch));
1741 AssertRCReturn(rc2, rc2);
1742 }
1743
1744 memcpy(&pCtx->psz[pCtx->cb], pszMountpoint, cch);
1745 pCtx->cb += cch;
1746 AssertReturn(pCtx->cb <= pCtx->cbAlloc, VERR_BUFFER_OVERFLOW); /* Paranoia. */
1747
1748 return VINF_SUCCESS;
1749}
1750
1751/**
1752 * Handles getting the current mount points.
1753 *
1754 * @returns VBox status code.
1755 * @param pSession Guest session.
1756 * @param pHostCtx Host context.
1757 */
1758static int vgsvcGstCtrlSessionHandleMountPoints(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1759{
1760 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1761 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1762
1763 /*
1764 * Retrieve the request.
1765 */
1766 uint32_t fFlags;
1767 int rc = VbglR3GuestCtrlGetMountPoints(pHostCtx, &fFlags);
1768 if (RT_SUCCESS(rc))
1769 {
1770 /* Note: fFlags is currently unused, so we simply ignore this here. */
1771
1772 VGSVCMOUNTPOINTENUMCTX Ctx;
1773 Ctx.cb = 0;
1774 Ctx.cbAlloc = _4K; /* Start with something sensible. */
1775 Ctx.psz = RTStrAlloc(Ctx.cbAlloc);
1776 if (!Ctx.psz)
1777 rc = VERR_NO_MEMORY;
1778
1779 if (RT_SUCCESS(rc))
1780 rc = RTFsMountpointsEnum(vgsvcGstCtrlSessionHandleMountPointsEnumCallback, &Ctx);
1781
1782 /* Report back in any case. */
1783 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, Ctx.psz,
1784 RT_SUCCESS(rc) ? (uint32_t)Ctx.cb : 0);
1785 if (RT_FAILURE(rc2))
1786 {
1787 VGSvcError("Failed to report mount points, rc=%Rrc\n", rc2);
1788 if (RT_SUCCESS(rc))
1789 rc = rc2;
1790 }
1791
1792 RTStrFree(Ctx.psz);
1793 Ctx.psz = NULL;
1794 }
1795 else
1796 {
1797 VGSvcError("Error fetching parameters for getting mount points request: %Rrc\n", rc);
1798 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1799 }
1800 return rc;
1801}
1802
1803
1804/**
1805 * Handles starting a guest processes.
1806 *
1807 * @returns VBox status code.
1808 * @param pSession Guest session.
1809 * @param pHostCtx Host context.
1810 */
1811static int vgsvcGstCtrlSessionHandleProcExec(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1812{
1813 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1814 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1815
1816 /* Initialize maximum environment block size -- needed as input
1817 * parameter to retrieve the stuff from the host. On output this then
1818 * will contain the actual block size. */
1819 PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo;
1820 int rc = VbglR3GuestCtrlProcGetStart(pHostCtx, &pStartupInfo);
1821 if (RT_SUCCESS(rc))
1822 {
1823 VGSvcVerbose(3, "Request to start process szCmd=%s, fFlags=0x%x, szArgs=%s, szEnv=%s, szCwd=%s, uTimeout=%RU32\n",
1824 pStartupInfo->pszCmd, pStartupInfo->fFlags,
1825 pStartupInfo->cArgs ? pStartupInfo->pszArgs : "<None>",
1826 pStartupInfo->cEnvVars ? pStartupInfo->pszEnv : "<None>",
1827 pStartupInfo->cbCwd ? pStartupInfo->pszCwd : "<None>",
1828 pStartupInfo->uTimeLimitMS);
1829
1830 bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
1831 rc = VGSvcGstCtrlSessionProcessStartAllowed(pSession, &fStartAllowed);
1832 if (RT_SUCCESS(rc))
1833 {
1834 vgsvcGstCtrlSessionCleanupProcesses(pSession);
1835
1836 if (fStartAllowed)
1837 rc = VGSvcGstCtrlProcessStart(pSession, pStartupInfo, pHostCtx->uContextID);
1838 else
1839 rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
1840 }
1841
1842 /* We're responsible for signaling errors to the host (it will wait for ever otherwise). */
1843 if (RT_FAILURE(rc))
1844 {
1845 VGSvcError("Starting process failed with rc=%Rrc, protocol=%RU32, parameters=%RU32\n",
1846 rc, pHostCtx->uProtocol, pHostCtx->uNumParms);
1847 int rc2 = VbglR3GuestCtrlProcCbStatus(pHostCtx, 0 /*nil-PID*/, PROC_STS_ERROR, rc, NULL /*pvData*/, 0 /*cbData*/);
1848 if (RT_FAILURE(rc2))
1849 VGSvcError("Error sending start process status to host, rc=%Rrc\n", rc2);
1850 }
1851
1852 VbglR3GuestCtrlProcStartupInfoFree(pStartupInfo);
1853 pStartupInfo = NULL;
1854 }
1855 else
1856 {
1857 VGSvcError("Failed to retrieve parameters for process start: %Rrc (cParms=%u)\n", rc, pHostCtx->uNumParms);
1858 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1859 }
1860
1861 return rc;
1862}
1863
1864
1865/**
1866 * Sends stdin input to a specific guest process.
1867 *
1868 * @returns VBox status code.
1869 * @param pSession The session which is in charge.
1870 * @param pHostCtx The host context to use.
1871 * @param ppvScratchBuf The scratch buffer, we may grow it.
1872 * @param pcbScratchBuf The scratch buffer size for retrieving the input
1873 * data.
1874 */
1875static int vgsvcGstCtrlSessionHandleProcInput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1876 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
1877{
1878 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1879 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1880
1881 /*
1882 * Retrieve the data from the host.
1883 */
1884 uint32_t uPID;
1885 uint32_t fFlags;
1886 uint32_t cbInput;
1887 int rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1888 if ( rc == VERR_BUFFER_OVERFLOW
1889 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbInput))
1890 rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1891 if (RT_SUCCESS(rc))
1892 {
1893 if (fFlags & GUEST_PROC_IN_FLAG_EOF)
1894 VGSvcVerbose(4, "Got last process input block for PID=%RU32 (%RU32 bytes) ...\n", uPID, cbInput);
1895
1896 /*
1897 * Locate the process and feed it.
1898 */
1899 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1900 if (pProcess)
1901 {
1902 rc = VGSvcGstCtrlProcessHandleInput(pProcess, pHostCtx, RT_BOOL(fFlags & GUEST_PROC_IN_FLAG_EOF),
1903 *ppvScratchBuf, RT_MIN(cbInput, *pcbScratchBuf));
1904 if (RT_FAILURE(rc))
1905 VGSvcError("Error handling input message for PID=%RU32, rc=%Rrc\n", uPID, rc);
1906 VGSvcGstCtrlProcessRelease(pProcess);
1907 }
1908 else
1909 {
1910 VGSvcError("Could not find PID %u for feeding %u bytes to it.\n", uPID, cbInput);
1911 rc = VERR_PROCESS_NOT_FOUND;
1912 VbglR3GuestCtrlProcCbStatusInput(pHostCtx, uPID, INPUT_STS_ERROR, rc, 0);
1913 }
1914 }
1915 else
1916 {
1917 VGSvcError("Failed to retrieve parameters for process input: %Rrc (scratch %u bytes)\n", rc, *pcbScratchBuf);
1918 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1919 }
1920
1921 VGSvcVerbose(6, "Feeding input to PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1922 return rc;
1923}
1924
1925
1926/**
1927 * Gets stdout/stderr output of a specific guest process.
1928 *
1929 * @returns VBox status code.
1930 * @param pSession The session which is in charge.
1931 * @param pHostCtx The host context to use.
1932 */
1933static int vgsvcGstCtrlSessionHandleProcOutput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1934{
1935 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1936 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1937
1938 /*
1939 * Retrieve the request.
1940 */
1941 uint32_t uPID;
1942 uint32_t uHandleID;
1943 uint32_t fFlags;
1944 int rc = VbglR3GuestCtrlProcGetOutput(pHostCtx, &uPID, &uHandleID, &fFlags);
1945#ifdef DEBUG_andy
1946 VGSvcVerbose(4, "Getting output for PID=%RU32, CID=%RU32, uHandleID=%RU32, fFlags=%RU32\n",
1947 uPID, pHostCtx->uContextID, uHandleID, fFlags);
1948#endif
1949 if (RT_SUCCESS(rc))
1950 {
1951 /*
1952 * Locate the process and hand it the output request.
1953 */
1954 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1955 if (pProcess)
1956 {
1957 rc = VGSvcGstCtrlProcessHandleOutput(pProcess, pHostCtx, uHandleID, _64K /* cbToRead */, fFlags);
1958 if (RT_FAILURE(rc))
1959 VGSvcError("Error getting output for PID=%RU32, rc=%Rrc\n", uPID, rc);
1960 VGSvcGstCtrlProcessRelease(pProcess);
1961 }
1962 else
1963 {
1964 VGSvcError("Could not find PID %u for draining handle %u (%#x).\n", uPID, uHandleID, uHandleID);
1965 rc = VERR_PROCESS_NOT_FOUND;
1966/** @todo r=bird:
1967 *
1968 * No way to report status status code for output requests?
1969 *
1970 */
1971 }
1972 }
1973 else
1974 {
1975 VGSvcError("Error fetching parameters for process output request: %Rrc\n", rc);
1976 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1977 }
1978
1979#ifdef DEBUG_andy
1980 VGSvcVerbose(4, "Getting output for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1981#endif
1982 return rc;
1983}
1984
1985
1986/**
1987 * Tells a guest process to terminate.
1988 *
1989 * @returns VBox status code.
1990 * @param pSession The session which is in charge.
1991 * @param pHostCtx The host context to use.
1992 */
1993static int vgsvcGstCtrlSessionHandleProcTerminate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1994{
1995 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1996 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1997
1998 /*
1999 * Retrieve the request.
2000 */
2001 uint32_t uPID;
2002 int rc = VbglR3GuestCtrlProcGetTerminate(pHostCtx, &uPID);
2003 if (RT_SUCCESS(rc))
2004 {
2005 /*
2006 * Locate the process and terminate it.
2007 */
2008 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
2009 if (pProcess)
2010 {
2011 rc = VGSvcGstCtrlProcessHandleTerm(pProcess);
2012 if (RT_FAILURE(rc))
2013 VGSvcError("Error terminating PID=%RU32, rc=%Rrc\n", uPID, rc);
2014
2015 VGSvcGstCtrlProcessRelease(pProcess);
2016 }
2017 else
2018 {
2019 VGSvcError("Could not find PID %u for termination.\n", uPID);
2020 rc = VERR_PROCESS_NOT_FOUND;
2021 }
2022 }
2023 else
2024 {
2025 VGSvcError("Error fetching parameters for process termination request: %Rrc\n", rc);
2026 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2027 }
2028#ifdef DEBUG_andy
2029 VGSvcVerbose(4, "Terminating PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
2030#endif
2031 return rc;
2032}
2033
2034
2035static int vgsvcGstCtrlSessionHandleProcWaitFor(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2036{
2037 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2038 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2039
2040 /*
2041 * Retrieve the request.
2042 */
2043 uint32_t uPID;
2044 uint32_t uWaitFlags;
2045 uint32_t uTimeoutMS;
2046 int rc = VbglR3GuestCtrlProcGetWaitFor(pHostCtx, &uPID, &uWaitFlags, &uTimeoutMS);
2047 if (RT_SUCCESS(rc))
2048 {
2049 /*
2050 * Locate the process and the realize that this call makes no sense
2051 * since we'll notify the host when a process terminates anyway and
2052 * hopefully don't need any additional encouragement.
2053 */
2054 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
2055 if (pProcess)
2056 {
2057 rc = VERR_NOT_IMPLEMENTED; /** @todo */
2058 VGSvcGstCtrlProcessRelease(pProcess);
2059 }
2060 else
2061 rc = VERR_NOT_FOUND;
2062 }
2063 else
2064 {
2065 VGSvcError("Error fetching parameters for process wait request: %Rrc\n", rc);
2066 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2067 }
2068 return rc;
2069}
2070
2071
2072#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2073static int vgsvcGstCtrlSessionHandleFsQueryInfo(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2074{
2075 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2076 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2077
2078 /*
2079 * Retrieve the request.
2080 */
2081 char szPath[RTPATH_MAX];
2082 int rc = VbglR3GuestCtrlFsGetQueryInfo(pHostCtx, szPath, sizeof(szPath));
2083 if (RT_SUCCESS(rc))
2084 {
2085 GSTCTLFSINFO fsInfo;
2086 RT_ZERO(fsInfo);
2087
2088 /* Query as much as we can; ignore any errors and continue. */
2089 int rc2 = RTFsQuerySizes(szPath, (RTFOFF *)&fsInfo.cbTotalSize, (RTFOFF *)&fsInfo.cbFree,
2090 &fsInfo.cbBlockSize, &fsInfo.cbSectorSize);
2091 if (RT_FAILURE(rc2))
2092 VGSvcError("Error calling RTFsQuerySizes() for fsqueryinfo operation: %Rrc\n", rc2);
2093
2094 RTFSPROPERTIES fsProps;
2095 rc2 = RTFsQueryProperties(szPath, &fsProps);
2096 if (RT_SUCCESS(rc2))
2097 {
2098 /* Regular (status) flags. */
2099 fsInfo.cMaxComponent = fsProps.cbMaxComponent;
2100 if (fsProps.fRemote)
2101 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_REMOTE;
2102 if (fsProps.fCaseSensitive)
2103 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_CASE_SENSITIVE;
2104 if (fsProps.fReadOnly)
2105 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_READ_ONLY;
2106 if (fsProps.fCompressed)
2107 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_COMPRESSED;
2108
2109 /* Feature flags. */
2110 if (fsProps.fSupportsUnicode)
2111 fsInfo.fFeatures |= GSTCTLFSINFO_FEATURE_F_UNICODE;
2112 if (fsProps.fFileCompression)
2113 fsInfo.fFeatures |= GSTCTLFSINFO_FEATURE_F_FILE_COMPRESSION;
2114 }
2115 else
2116 VGSvcError("Error calling RTFsQueryProperties() for fsqueryinfo operation: %Rrc\n", rc2);
2117
2118 rc2 = RTFsQuerySerial(szPath, &fsInfo.uSerialNumber);
2119 if (RT_FAILURE(rc2))
2120 VGSvcError("Error calling RTFsQuerySerial() for fsqueryinfo operation: %Rrc\n", rc2);
2121
2122#if 0 /** @todo Enable as soon as RTFsQueryLabel() is implemented. */
2123 rc2 = RTFsQueryLabel(szPath, fsInfo.szLabel, sizeof(fsInfo.szLabel));
2124 if (RT_FAILURE(rc2))
2125 VGSvcError("Error calling RTFsQueryLabel() for fsqueryinfo operation: %Rrc\n", rc2);
2126#endif
2127
2128 RTFSTYPE enmFsType;
2129 rc2 = RTFsQueryType(szPath, &enmFsType);
2130 if (RT_SUCCESS(rc2))
2131 {
2132 if (RTStrPrintf2(fsInfo.szName, sizeof(fsInfo.szName), "%s", RTFsTypeName(enmFsType)) <= 0)
2133 VGSvcError("Error printing type returned by RTFsQueryType()\n");
2134 }
2135 else
2136 VGSvcError("Error calling RTFsQueryType() for fsqueryinfo operation: %Rrc\n", rc2);
2137
2138#if 0 /** @todo Enable as soon as RTFsQueryMountpoint() is implemented. */
2139 char szMountpoint[RTPATH_MAX];
2140 rc2 = RTFsQueryMountpoint(szPath, szMountpoint, sizeof(szMountpoint));
2141 if (RT_SUCCESS(rc2))
2142 {
2143 #error "Implement me"
2144 }
2145 else
2146 VGSvcError("Error calling RTFsQueryMountpoint() for fsqueryinfo operation: %Rrc\n", rc2);
2147#endif
2148
2149 if (RT_SUCCESS(rc))
2150 {
2151 VGSvcVerbose(3, "cbTotalSize=%RU64, cbFree=%RU64, cbBlockSize=%RU32, cbSectorSize=%RU32, fFlags=%#x, fFeatures=%#x\n",
2152 fsInfo.cbTotalSize, fsInfo.cbFree, fsInfo.cbBlockSize, fsInfo.cbSectorSize,
2153 fsInfo.fFlags, fsInfo.fFeatures);
2154 VGSvcVerbose(3, "szName=%s, szLabel=%s\n", fsInfo.szName, fsInfo.szLabel);
2155 }
2156
2157 uint32_t const cbFsInfo = sizeof(GSTCTLFSINFO); /** @todo Needs tweaking as soon as we resolve the mountpoint above. */
2158
2159 rc2 = VbglR3GuestCtrlFsCbQueryInfo(pHostCtx, rc, &fsInfo, cbFsInfo);
2160 if (RT_FAILURE(rc2))
2161 {
2162 VGSvcError("Failed to reply to fsobjquerinfo request %Rrc, rc=%Rrc\n", rc, rc2);
2163 if (RT_SUCCESS(rc))
2164 rc = rc2;
2165 }
2166 }
2167 else
2168 {
2169 VGSvcError("Error fetching parameters for fsqueryinfo operation: %Rrc\n", rc);
2170 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2171 }
2172 return rc;
2173}
2174
2175static int vgsvcGstCtrlSessionHandleFsObjQueryInfo(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2176{
2177 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2178 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2179
2180 /*
2181 * Retrieve the request.
2182 */
2183 char szPath[RTPATH_MAX];
2184 GSTCTLFSOBJATTRADD enmAttrAdd;
2185 uint32_t fFlags;
2186 RTFSOBJINFO objInfoRuntime;
2187
2188 int rc = VbglR3GuestCtrlFsObjGetQueryInfo(pHostCtx, szPath, sizeof(szPath), &enmAttrAdd, &fFlags);
2189 if (RT_SUCCESS(rc))
2190 {
2191 uint32_t fFlagsRuntime = 0;
2192
2193 if (!(fFlags & ~GSTCTL_PATH_F_VALID_MASK))
2194 {
2195 if (fFlags & GSTCTL_PATH_F_ON_LINK)
2196 fFlagsRuntime |= RTPATH_F_ON_LINK;
2197 if (fFlags & GSTCTL_PATH_F_FOLLOW_LINK)
2198 fFlagsRuntime |= RTPATH_F_FOLLOW_LINK;
2199 if (fFlags & GSTCTL_PATH_F_NO_SYMLINKS)
2200 fFlagsRuntime |= RTPATH_F_NO_SYMLINKS;
2201
2202 if (!RTPATH_F_IS_VALID(fFlagsRuntime, 0))
2203 rc = VERR_INVALID_PARAMETER;
2204 }
2205 else
2206 rc = VERR_INVALID_PARAMETER;
2207
2208 if (RT_FAILURE(rc))
2209 VGSvcError("Invalid fsobjqueryinfo flags: %#x (%#x)\n", fFlags, fFlagsRuntime);
2210
2211 if (RT_SUCCESS(rc))
2212 {
2213#define CASE_ATTR_ADD_VAL(a_Val) \
2214 case GSTCTL##a_Val: enmAttrRuntime = RT##a_Val; break;
2215
2216 RTFSOBJATTRADD enmAttrRuntime;
2217 switch (enmAttrAdd)
2218 {
2219 CASE_ATTR_ADD_VAL(FSOBJATTRADD_NOTHING);
2220 CASE_ATTR_ADD_VAL(FSOBJATTRADD_UNIX);
2221 CASE_ATTR_ADD_VAL(FSOBJATTRADD_UNIX_OWNER);
2222 CASE_ATTR_ADD_VAL(FSOBJATTRADD_UNIX_GROUP);
2223 CASE_ATTR_ADD_VAL(FSOBJATTRADD_EASIZE);
2224 default:
2225 enmAttrRuntime = RTFSOBJATTRADD_NOTHING;
2226 break;
2227 }
2228
2229#undef CASE_ATTR_ADD_VAL
2230
2231 /*
2232 * For now we ASSUME that RTFSOBJINFO == GSTCTLFSOBJINFO, which implies that we simply can cast RTFSOBJINFO
2233 * to GSTCTLFSOBJINFO. This might change in the future, however, so be extra cautious here.
2234 *
2235 * Ditto for RTFSOBJATTR == GSTCTLFSOBJATTR.
2236 */
2237 AssertCompileSize(objInfoRuntime, sizeof(GSTCTLFSOBJINFO));
2238 AssertCompile (RT_OFFSETOF(GSTCTLFSOBJINFO, cbObject) == RT_OFFSETOF(GSTCTLFSOBJINFO, cbObject));
2239 AssertCompile (RT_OFFSETOF(GSTCTLFSOBJINFO, Attr) == RT_OFFSETOF(GSTCTLFSOBJINFO, Attr));
2240 AssertCompileSize(RTFSOBJATTR, sizeof(GSTCTLFSOBJATTR));
2241
2242 rc = RTPathQueryInfoEx(szPath, &objInfoRuntime, enmAttrRuntime, fFlagsRuntime);
2243 }
2244
2245 PGSTCTLFSOBJINFO pObjInfo = (PGSTCTLFSOBJINFO)&objInfoRuntime;
2246
2247 const char *pszUser = VGSvcIdCacheGetUidName(&pSession->UidCache, pObjInfo->Attr.u.Unix.uid, szPath, NULL /* pszRelativeTo */);
2248 const char *pszGroup = VGSvcIdCacheGetGidName(&pSession->GidCache, pObjInfo->Attr.u.Unix.gid, szPath, NULL /* pszRelativeTo */);
2249
2250 int rc2 = VbglR3GuestCtrlFsObjCbQueryInfoEx(pHostCtx, rc, pObjInfo, pszUser, pszGroup);
2251 if (RT_FAILURE(rc2))
2252 {
2253 VGSvcError("Failed to reply to fsobjquerinfo request %Rrc, rc=%Rrc\n", rc, rc2);
2254 if (RT_SUCCESS(rc))
2255 rc = rc2;
2256 }
2257 }
2258 else
2259 {
2260 VGSvcError("Error fetching parameters for fsobjqueryinfo operation: %Rrc\n", rc);
2261 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2262 }
2263 return rc;
2264}
2265
2266
2267static int vgsvcGstCtrlSessionHandleFsCreateTemp(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2268{
2269 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2270 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2271
2272 /*
2273 * Retrieve the request.
2274 */
2275 char szTemplate[RTPATH_MAX];
2276 char szPath[RTPATH_MAX];
2277 uint32_t fFlags = GSTCTL_CREATETEMP_F_NONE;
2278 RTFMODE fMode = 0700;
2279 int rc = VbglR3GuestCtrlFsGetCreateTemp(pHostCtx, szTemplate, sizeof(szTemplate), szPath, sizeof(szPath), &fFlags, &fMode);
2280 if (RT_SUCCESS(rc))
2281 {
2282 if (!(fFlags & ~GSTCTL_CREATETEMP_F_VALID_MASK))
2283 {
2284 const char *pszWhat = fFlags & GSTCTL_CREATETEMP_F_DIRECTORY ? "directory" : "file";
2285
2286 /* Validate that the template is as IPRT requires (asserted by IPRT). */
2287 if ( RTPathHasPath(szTemplate)
2288 || ( !strstr(szTemplate, "XXX")
2289 && szTemplate[strlen(szTemplate) - 1] != 'X'))
2290 {
2291 VGSvcError("createtemp: Template '%s' should contain a file name with no path and at least three consecutive 'X' characters or ending in 'X'\n",
2292 szTemplate);
2293 rc = VERR_INVALID_PARAMETER;
2294 }
2295
2296 if ( RT_SUCCESS(rc)
2297 && szPath[0] != '\0' && !RTPathStartsWithRoot(szPath))
2298 {
2299 VGSvcError("createtemp: Path '%s' must be absolute\n", szPath);
2300 rc = VERR_INVALID_PARAMETER;
2301 }
2302
2303 if (RT_SUCCESS(rc))
2304 {
2305 char szTemplateWithPath[RTPATH_MAX] = "";
2306 if (szPath[0] != '\0')
2307 {
2308 rc = RTStrCopy(szTemplateWithPath, sizeof(szTemplateWithPath), szPath);
2309 if (RT_FAILURE(rc))
2310 {
2311 VGSvcError("createtemp: Path '%s' too long\n", szPath);
2312 rc = VERR_INVALID_PARAMETER;
2313 }
2314 }
2315 else
2316 {
2317 rc = RTPathTemp(szTemplateWithPath, sizeof(szTemplateWithPath));
2318 if (RT_FAILURE(rc))
2319 {
2320 VGSvcError("createtemp: Failed to get the temporary directory (%Rrc)", rc);
2321 rc = VERR_INVALID_PARAMETER;
2322 }
2323 }
2324
2325 if (RT_SUCCESS(rc))
2326 {
2327 rc = RTPathAppend(szTemplateWithPath, sizeof(szTemplateWithPath), szTemplate);
2328 if (RT_FAILURE(rc))
2329 {
2330 VGSvcError("createtemp: Template '%s' too long for path\n", szTemplate);
2331 rc = VERR_INVALID_PARAMETER;
2332 }
2333 else
2334 {
2335 bool const fSecure = RT_BOOL(fFlags & GSTCTL_CREATETEMP_F_SECURE);
2336 if (fFlags & GSTCTL_CREATETEMP_F_DIRECTORY)
2337 {
2338 if (fSecure)
2339 rc = RTDirCreateTempSecure(szTemplateWithPath); /* File mode is fixed to 0700. */
2340 else
2341 rc = RTDirCreateTemp(szTemplate, fMode);
2342 }
2343 else /* File */
2344 {
2345 if (fSecure)
2346 rc = RTFileCreateTempSecure(szTemplateWithPath); /* File mode is fixed to 0700. */
2347 else
2348 rc = RTFileCreateTemp(szTemplate, fMode);
2349 }
2350
2351 VGSvcVerbose(3, "Creating temporary %s (szTemplate='%s', fFlags=%#x, fMode=%#x) -> rc=%Rrc\n",
2352 pszWhat, szTemplate, fFlags, fMode, rc);
2353 }
2354 }
2355 }
2356 }
2357 else
2358 {
2359 VGSvcError("Invalid temporary directory/file creation flags: %#x\n", fFlags);
2360 rc = VERR_NOT_SUPPORTED;
2361 }
2362
2363 /*
2364 * Report result back to host.
2365 */
2366 int rc2 = VbglR3GuestCtrlFsCbCreateTemp(pHostCtx, rc, szTemplate);
2367 if (RT_FAILURE(rc2))
2368 {
2369 VGSvcError("Failed to report temporary file/directory creation status, rc=%Rrc\n", rc2);
2370 if (RT_SUCCESS(rc))
2371 rc = rc2;
2372 }
2373 }
2374 else
2375 {
2376 VGSvcError("Error fetching parameters for file/directory creation operation: %Rrc\n", rc);
2377 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2378 }
2379 VGSvcVerbose(3, "Creating temporary file/directory returned rc=%Rrc\n", rc);
2380 return rc;
2381}
2382#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
2383
2384
2385int VGSvcGstCtrlSessionHandler(PVBOXSERVICECTRLSESSION pSession, uint32_t uMsg, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2386 void **ppvScratchBuf, uint32_t *pcbScratchBuf, volatile bool *pfShutdown)
2387{
2388 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2389 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2390 AssertPtrReturn(*ppvScratchBuf, VERR_INVALID_POINTER);
2391 AssertPtrReturn(pfShutdown, VERR_INVALID_POINTER);
2392
2393
2394 /*
2395 * Only anonymous sessions (that is, sessions which run with local
2396 * service privileges) or spawned session processes can do certain
2397 * operations.
2398 */
2399 bool const fImpersonated = RT_BOOL(pSession->fFlags & ( VBOXSERVICECTRLSESSION_FLAG_SPAWN
2400 | VBOXSERVICECTRLSESSION_FLAG_ANONYMOUS));
2401 int rc = VERR_NOT_SUPPORTED; /* Play safe by default. */
2402
2403 switch (uMsg)
2404 {
2405 case HOST_MSG_SESSION_CLOSE:
2406 /* Shutdown (this spawn). */
2407 rc = VGSvcGstCtrlSessionClose(pSession);
2408 *pfShutdown = true; /* Shutdown in any case. */
2409 break;
2410
2411 case HOST_MSG_EXEC_CMD:
2412 rc = vgsvcGstCtrlSessionHandleProcExec(pSession, pHostCtx);
2413 break;
2414
2415 case HOST_MSG_EXEC_SET_INPUT:
2416 rc = vgsvcGstCtrlSessionHandleProcInput(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2417 break;
2418
2419 case HOST_MSG_EXEC_GET_OUTPUT:
2420 rc = vgsvcGstCtrlSessionHandleProcOutput(pSession, pHostCtx);
2421 break;
2422
2423 case HOST_MSG_EXEC_TERMINATE:
2424 rc = vgsvcGstCtrlSessionHandleProcTerminate(pSession, pHostCtx);
2425 break;
2426
2427 case HOST_MSG_EXEC_WAIT_FOR:
2428 rc = vgsvcGstCtrlSessionHandleProcWaitFor(pSession, pHostCtx);
2429 break;
2430
2431#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2432 case HOST_MSG_FS_OBJ_QUERY_INFO:
2433 if (fImpersonated)
2434 rc = vgsvcGstCtrlSessionHandleFsObjQueryInfo(pSession, pHostCtx);
2435 break;
2436
2437 case HOST_MSG_FS_CREATE_TEMP:
2438 if (fImpersonated)
2439 rc = vgsvcGstCtrlSessionHandleFsCreateTemp(pSession, pHostCtx);
2440 break;
2441
2442 case HOST_MSG_FS_QUERY_INFO:
2443 if (fImpersonated)
2444 rc = vgsvcGstCtrlSessionHandleFsQueryInfo(pSession, pHostCtx);
2445 break;
2446#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
2447
2448 case HOST_MSG_FILE_OPEN:
2449 if (fImpersonated)
2450 rc = vgsvcGstCtrlSessionHandleFileOpen(pSession, pHostCtx);
2451 break;
2452
2453 case HOST_MSG_FILE_CLOSE:
2454 if (fImpersonated)
2455 rc = vgsvcGstCtrlSessionHandleFileClose(pSession, pHostCtx);
2456 break;
2457
2458 case HOST_MSG_FILE_READ:
2459 if (fImpersonated)
2460 rc = vgsvcGstCtrlSessionHandleFileRead(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2461 break;
2462
2463 case HOST_MSG_FILE_READ_AT:
2464 if (fImpersonated)
2465 rc = vgsvcGstCtrlSessionHandleFileReadAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2466 break;
2467
2468 case HOST_MSG_FILE_WRITE:
2469 if (fImpersonated)
2470 rc = vgsvcGstCtrlSessionHandleFileWrite(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2471 break;
2472
2473 case HOST_MSG_FILE_WRITE_AT:
2474 if (fImpersonated)
2475 rc = vgsvcGstCtrlSessionHandleFileWriteAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2476 break;
2477
2478 case HOST_MSG_FILE_SEEK:
2479 if (fImpersonated)
2480 rc = vgsvcGstCtrlSessionHandleFileSeek(pSession, pHostCtx);
2481 break;
2482
2483 case HOST_MSG_FILE_TELL:
2484 if (fImpersonated)
2485 rc = vgsvcGstCtrlSessionHandleFileTell(pSession, pHostCtx);
2486 break;
2487
2488 case HOST_MSG_FILE_SET_SIZE:
2489 if (fImpersonated)
2490 rc = vgsvcGstCtrlSessionHandleFileSetSize(pSession, pHostCtx);
2491 break;
2492
2493#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2494 case HOST_MSG_FILE_REMOVE:
2495 if (fImpersonated)
2496 rc = vgsvcGstCtrlSessionHandleFileRemove(pSession, pHostCtx);
2497 break;
2498
2499 case HOST_MSG_DIR_OPEN:
2500 if (fImpersonated)
2501 rc = vgsvcGstCtrlSessionHandleDirOpen(pSession, pHostCtx);
2502 break;
2503
2504 case HOST_MSG_DIR_CLOSE:
2505 if (fImpersonated)
2506 rc = vgsvcGstCtrlSessionHandleDirClose(pSession, pHostCtx);
2507 break;
2508
2509 case HOST_MSG_DIR_READ:
2510 if (fImpersonated)
2511 rc = vgsvcGstCtrlSessionHandleDirRead(pSession, pHostCtx);
2512 break;
2513
2514 case HOST_MSG_DIR_REWIND:
2515 if (fImpersonated)
2516 rc = vgsvcGstCtrlSessionHandleDirRewind(pSession, pHostCtx);
2517 break;
2518
2519 case HOST_MSG_DIR_CREATE:
2520 if (fImpersonated)
2521 rc = vgsvcGstCtrlSessionHandleDirCreate(pSession, pHostCtx);
2522 break;
2523
2524 case HOST_MSG_DIR_LIST:
2525 if (fImpersonated)
2526 rc = vgsvcGstCtrlSessionHandleDirList(pSession, pHostCtx);
2527 break;
2528#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
2529
2530 case HOST_MSG_DIR_REMOVE:
2531 if (fImpersonated)
2532 rc = vgsvcGstCtrlSessionHandleDirRemove(pSession, pHostCtx);
2533 break;
2534
2535 case HOST_MSG_PATH_RENAME:
2536 if (fImpersonated)
2537 rc = vgsvcGstCtrlSessionHandlePathRename(pSession, pHostCtx);
2538 break;
2539
2540 case HOST_MSG_PATH_USER_DOCUMENTS:
2541 if (fImpersonated)
2542 rc = vgsvcGstCtrlSessionHandlePathUserDocuments(pSession, pHostCtx);
2543 break;
2544
2545 case HOST_MSG_PATH_USER_HOME:
2546 if (fImpersonated)
2547 rc = vgsvcGstCtrlSessionHandlePathUserHome(pSession, pHostCtx);
2548 break;
2549
2550 case HOST_MSG_MOUNT_POINTS:
2551 if (fImpersonated)
2552 rc = vgsvcGstCtrlSessionHandleMountPoints(pSession, pHostCtx);
2553 break;
2554
2555 case HOST_MSG_SHUTDOWN:
2556 rc = vgsvcGstCtrlSessionHandleShutdown(pSession, pHostCtx);
2557 break;
2558
2559 default: /* Not supported, see next code block. */
2560 break;
2561 }
2562 if (RT_SUCCESS(rc))
2563 { /* likely */ }
2564 else if (rc != VERR_NOT_SUPPORTED) /* Note: Reply to host must must be sent by above handler. */
2565 VGSvcError("Error while handling message %s (%#x, cParms=%RU32), rc=%Rrc\n",
2566 GstCtrlHostMsgtoStr((eHostMsg)uMsg), uMsg, pHostCtx->uNumParms, rc);
2567 else
2568 {
2569 /* We must skip and notify host here as best we can... */
2570 VGSvcVerbose(1, "Unsupported message (uMsg=%RU32, cParms=%RU32) from host, skipping\n", uMsg, pHostCtx->uNumParms);
2571 if (VbglR3GuestCtrlSupportsOptimizations(pHostCtx->uClientID))
2572 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, VERR_NOT_SUPPORTED, uMsg);
2573 else
2574 VbglR3GuestCtrlMsgSkipOld(pHostCtx->uClientID);
2575 rc = VINF_SUCCESS;
2576 }
2577
2578 return rc;
2579}
2580
2581
2582/**
2583 * Thread main routine for a spawned guest session process.
2584 *
2585 * This thread runs in the main executable to control the spawned session process.
2586 *
2587 * @returns VBox status code.
2588 * @param hThreadSelf Thread handle.
2589 * @param pvUser Pointer to a VBOXSERVICECTRLSESSIONTHREAD structure.
2590 *
2591 */
2592static DECLCALLBACK(int) vgsvcGstCtrlSessionThread(RTTHREAD hThreadSelf, void *pvUser)
2593{
2594 PVBOXSERVICECTRLSESSIONTHREAD pThread = (PVBOXSERVICECTRLSESSIONTHREAD)pvUser;
2595 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2596
2597 uint32_t const idSession = pThread->pStartupInfo->uSessionID;
2598 uint32_t const idClient = g_idControlSvcClient;
2599 VGSvcVerbose(3, "Session ID=%RU32 thread running\n", idSession);
2600
2601 /* Let caller know that we're done initializing, regardless of the result. */
2602 int rc2 = RTThreadUserSignal(hThreadSelf);
2603 AssertRC(rc2);
2604
2605 /*
2606 * Wait for the child process to stop or the shutdown flag to be signalled.
2607 */
2608 RTPROCSTATUS ProcessStatus = { 0, RTPROCEXITREASON_NORMAL };
2609 bool fProcessAlive = true;
2610 bool fSessionCancelled = VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient);
2611 uint32_t cMsShutdownTimeout = 30 * 1000; /** @todo Make this configurable. Later. */
2612 uint64_t msShutdownStart = 0;
2613 uint64_t const msStart = RTTimeMilliTS();
2614 size_t offSecretKey = 0;
2615 int rcWait;
2616 for (;;)
2617 {
2618 /* Secret key feeding. */
2619 if (offSecretKey < sizeof(pThread->abKey))
2620 {
2621 size_t cbWritten = 0;
2622 rc2 = RTPipeWrite(pThread->hKeyPipe, &pThread->abKey[offSecretKey], sizeof(pThread->abKey) - offSecretKey, &cbWritten);
2623 if (RT_SUCCESS(rc2))
2624 offSecretKey += cbWritten;
2625 }
2626
2627 /* Poll child process status. */
2628 rcWait = RTProcWaitNoResume(pThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
2629 if ( rcWait == VINF_SUCCESS
2630 || rcWait == VERR_PROCESS_NOT_FOUND)
2631 {
2632 fProcessAlive = false;
2633 break;
2634 }
2635 AssertMsgBreak(rcWait == VERR_PROCESS_RUNNING || rcWait == VERR_INTERRUPTED,
2636 ("Got unexpected rc=%Rrc while waiting for session process termination\n", rcWait));
2637
2638 /* Shutting down? */
2639 if (ASMAtomicReadBool(&pThread->fShutdown))
2640 {
2641 if (!msShutdownStart)
2642 {
2643 VGSvcVerbose(3, "Notifying guest session process (PID=%RU32, session ID=%RU32) ...\n",
2644 pThread->hProcess, idSession);
2645
2646 VBGLR3GUESTCTRLCMDCTX hostCtx =
2647 {
2648 /* .idClient = */ idClient,
2649 /* .idContext = */ VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
2650 /* .uProtocol = */ pThread->pStartupInfo->uProtocol,
2651 /* .cParams = */ 2
2652 };
2653 rc2 = VbglR3GuestCtrlSessionClose(&hostCtx, 0 /* fFlags */);
2654 if (RT_FAILURE(rc2))
2655 {
2656 VGSvcError("Unable to notify guest session process (PID=%RU32, session ID=%RU32), rc=%Rrc\n",
2657 pThread->hProcess, idSession, rc2);
2658
2659 if (rc2 == VERR_NOT_SUPPORTED)
2660 {
2661 /* Terminate guest session process in case it's not supported by a too old host. */
2662 rc2 = RTProcTerminate(pThread->hProcess);
2663 VGSvcVerbose(3, "Terminating guest session process (PID=%RU32) ended with rc=%Rrc\n",
2664 pThread->hProcess, rc2);
2665 }
2666 break;
2667 }
2668
2669 VGSvcVerbose(3, "Guest session ID=%RU32 thread was asked to terminate, waiting for session process to exit (%RU32 ms timeout) ...\n",
2670 idSession, cMsShutdownTimeout);
2671 msShutdownStart = RTTimeMilliTS();
2672 continue; /* Don't waste time on waiting. */
2673 }
2674 if (RTTimeMilliTS() - msShutdownStart > cMsShutdownTimeout)
2675 {
2676 VGSvcVerbose(3, "Guest session ID=%RU32 process did not shut down within time\n", idSession);
2677 break;
2678 }
2679 }
2680
2681 /* Cancel the prepared session stuff after 30 seconds. */
2682 if ( !fSessionCancelled
2683 && RTTimeMilliTS() - msStart >= 30000)
2684 {
2685 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
2686 fSessionCancelled = true;
2687 }
2688
2689/** @todo r=bird: This 100ms sleep is _extremely_ sucky! */
2690 RTThreadSleep(100); /* Wait a bit. */
2691 }
2692
2693 if (!fSessionCancelled)
2694 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
2695
2696 if (!fProcessAlive)
2697 {
2698 VGSvcVerbose(2, "Guest session process (ID=%RU32) terminated with rc=%Rrc, reason=%d, status=%d\n",
2699 idSession, rcWait, ProcessStatus.enmReason, ProcessStatus.iStatus);
2700 if (ProcessStatus.iStatus == RTEXITCODE_INIT)
2701 {
2702 VGSvcError("Guest session process (ID=%RU32) failed to initialize. Here some hints:\n", idSession);
2703 VGSvcError("- Is logging enabled and the output directory is read-only by the guest session user?\n");
2704 /** @todo Add more here. */
2705 }
2706 }
2707
2708 uint32_t uSessionStatus = GUEST_SESSION_NOTIFYTYPE_UNDEFINED;
2709 int32_t iSessionResult = VINF_SUCCESS;
2710
2711 if (fProcessAlive)
2712 {
2713 for (int i = 0; i < 3; i++)
2714 {
2715 if (i)
2716 RTThreadSleep(3000);
2717
2718 VGSvcVerbose(2, "Guest session ID=%RU32 process still alive, killing attempt %d/3\n", idSession, i + 1);
2719
2720 rc2 = RTProcTerminate(pThread->hProcess);
2721 if (RT_SUCCESS(rc2))
2722 break;
2723 }
2724
2725 VGSvcVerbose(2, "Guest session ID=%RU32 process termination resulted in rc=%Rrc\n", idSession, rc2);
2726 uSessionStatus = RT_SUCCESS(rc2) ? GUEST_SESSION_NOTIFYTYPE_TOK : GUEST_SESSION_NOTIFYTYPE_TOA;
2727 }
2728 else if (RT_SUCCESS(rcWait))
2729 {
2730 switch (ProcessStatus.enmReason)
2731 {
2732 case RTPROCEXITREASON_NORMAL:
2733 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
2734 iSessionResult = ProcessStatus.iStatus; /* Report back the session's exit code. */
2735 break;
2736
2737 case RTPROCEXITREASON_ABEND:
2738 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
2739 /* iSessionResult is undefined (0). */
2740 break;
2741
2742 case RTPROCEXITREASON_SIGNAL:
2743 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TES;
2744 iSessionResult = ProcessStatus.iStatus; /* Report back the signal number. */
2745 break;
2746
2747 default:
2748 AssertMsgFailed(("Unhandled process termination reason (%d)\n", ProcessStatus.enmReason));
2749 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
2750 break;
2751 }
2752 }
2753 else
2754 {
2755 /* If we didn't find the guest process anymore, just assume it terminated normally. */
2756 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
2757 }
2758
2759 /* Make sure to set stopped state before we let the host know. */
2760 ASMAtomicWriteBool(&pThread->fStopped, true);
2761
2762 /* Report final status, regardless if we failed to wait above, so that the host knows what's going on. */
2763 VGSvcVerbose(3, "Reporting final status %RU32 of session ID=%RU32\n", uSessionStatus, idSession);
2764 Assert(uSessionStatus != GUEST_SESSION_NOTIFYTYPE_UNDEFINED);
2765
2766 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
2767 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
2768 rc2 = VbglR3GuestCtrlSessionNotify(&ctx, uSessionStatus, iSessionResult);
2769 if (RT_FAILURE(rc2))
2770 VGSvcError("Reporting final status of session ID=%RU32 failed with rc=%Rrc\n", idSession, rc2);
2771
2772 VGSvcVerbose(3, "Thread for session ID=%RU32 ended with sessionStatus=%#x (%RU32), sessionRc=%#x (%Rrc)\n",
2773 idSession, uSessionStatus, uSessionStatus, iSessionResult, iSessionResult);
2774
2775 return VINF_SUCCESS;
2776}
2777
2778/**
2779 * Reads the secret key the parent VBoxService instance passed us and pass it
2780 * along as a authentication token to the host service.
2781 *
2782 * For older hosts, this sets up the message filtering.
2783 *
2784 * @returns VBox status code.
2785 * @param idClient The HGCM client ID.
2786 * @param idSession The session ID.
2787 */
2788static int vgsvcGstCtrlSessionReadKeyAndAccept(uint32_t idClient, uint32_t idSession)
2789{
2790 /*
2791 * Read it.
2792 */
2793 RTHANDLE Handle;
2794 int rc = RTHandleGetStandard(RTHANDLESTD_INPUT, true /*fLeaveOpen*/, &Handle);
2795 if (RT_SUCCESS(rc))
2796 {
2797 if (Handle.enmType == RTHANDLETYPE_PIPE)
2798 {
2799 uint8_t abSecretKey[RT_SIZEOFMEMB(VBOXSERVICECTRLSESSIONTHREAD, abKey)];
2800 rc = RTPipeReadBlocking(Handle.u.hPipe, abSecretKey, sizeof(abSecretKey), NULL);
2801 if (RT_SUCCESS(rc))
2802 {
2803 VGSvcVerbose(3, "Got secret key from standard input.\n");
2804
2805 /*
2806 * Do the accepting, if appropriate.
2807 */
2808 if (g_fControlSupportsOptimizations)
2809 {
2810 rc = VbglR3GuestCtrlSessionAccept(idClient, idSession, abSecretKey, sizeof(abSecretKey));
2811 if (RT_SUCCESS(rc))
2812 VGSvcVerbose(3, "Session %u accepted (client ID %u)\n", idClient, idSession);
2813 else
2814 VGSvcError("Failed to accept session %u (client ID %u): %Rrc\n", idClient, idSession, rc);
2815 }
2816 else
2817 {
2818 /* For legacy hosts, we do the filtering thingy. */
2819 rc = VbglR3GuestCtrlMsgFilterSet(idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
2820 VBOX_GUESTCTRL_FILTER_BY_SESSION(idSession), 0);
2821 if (RT_SUCCESS(rc))
2822 VGSvcVerbose(3, "Session %u filtering successfully enabled\n", idSession);
2823 else
2824 VGSvcError("Failed to set session filter: %Rrc\n", rc);
2825 }
2826 }
2827 else
2828 VGSvcError("Error reading secret key from standard input: %Rrc\n", rc);
2829 }
2830 else
2831 {
2832 VGSvcError("Standard input is not a pipe!\n");
2833 rc = VERR_INVALID_HANDLE;
2834 }
2835 RTHandleClose(&Handle);
2836 }
2837 else
2838 VGSvcError("RTHandleGetStandard failed on standard input: %Rrc\n", rc);
2839 return rc;
2840}
2841
2842/**
2843 * Invalidates a guest session by updating all it's internal parameters like host features and stuff.
2844 *
2845 * @param pSession Session to invalidate.
2846 * @param idClient Client ID to use.
2847 */
2848static void vgsvcGstCtrlSessionInvalidate(PVBOXSERVICECTRLSESSION pSession, uint32_t idClient)
2849{
2850 RT_NOREF(pSession);
2851
2852 VGSvcVerbose(1, "Invalidating session %RU32 (client ID=%RU32)\n", idClient, pSession->StartupInfo.uSessionID);
2853
2854 int rc2 = VbglR3GuestCtrlQueryFeatures(idClient, &g_fControlHostFeatures0);
2855 if (RT_SUCCESS(rc2)) /* Querying host features is not fatal -- do not use rc here. */
2856 {
2857 VGSvcVerbose(1, "g_fControlHostFeatures0=%#x\n", g_fControlHostFeatures0);
2858 }
2859 else
2860 VGSvcVerbose(1, "Querying host features failed with %Rrc\n", rc2);
2861}
2862
2863/**
2864 * Main message handler for the guest control session process.
2865 *
2866 * @returns exit code.
2867 * @param pSession Pointer to g_Session.
2868 * @thread main.
2869 */
2870static RTEXITCODE vgsvcGstCtrlSessionSpawnWorker(PVBOXSERVICECTRLSESSION pSession)
2871{
2872 AssertPtrReturn(pSession, RTEXITCODE_FAILURE);
2873 VGSvcVerbose(0, "Hi, this is guest session ID=%RU32\n", pSession->StartupInfo.uSessionID);
2874
2875 /*
2876 * Connect to the host service.
2877 */
2878 uint32_t idClient;
2879 int rc = VbglR3GuestCtrlConnect(&idClient);
2880 if (RT_FAILURE(rc))
2881 return VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
2882 g_fControlSupportsOptimizations = VbglR3GuestCtrlSupportsOptimizations(idClient);
2883 g_idControlSvcClient = idClient;
2884
2885 VGSvcVerbose(1, "Using client ID=%RU32\n", idClient);
2886
2887 vgsvcGstCtrlSessionInvalidate(pSession, idClient);
2888
2889 rc = vgsvcGstCtrlSessionReadKeyAndAccept(idClient, pSession->StartupInfo.uSessionID);
2890 if (RT_SUCCESS(rc))
2891 {
2892 /*
2893 * Report started status.
2894 * If session status cannot be posted to the host for some reason, bail out.
2895 */
2896 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID),
2897 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
2898 rc = VbglR3GuestCtrlSessionNotify(&ctx, GUEST_SESSION_NOTIFYTYPE_STARTED, VINF_SUCCESS);
2899 if (RT_SUCCESS(rc))
2900 {
2901 /*
2902 * Allocate a scratch buffer for messages which also send payload data with them.
2903 * This buffer may grow if the host sends us larger chunks of data.
2904 */
2905 uint32_t cbScratchBuf = _64K;
2906 void *pvScratchBuf = RTMemAlloc(cbScratchBuf);
2907 if (pvScratchBuf)
2908 {
2909 int cFailedMsgPeeks = 0;
2910
2911 /*
2912 * Message processing loop.
2913 */
2914 VBGLR3GUESTCTRLCMDCTX CtxHost = { idClient, 0 /* Context ID */, pSession->StartupInfo.uProtocol, 0 };
2915 for (;;)
2916 {
2917 VGSvcVerbose(3, "Waiting for host msg ...\n");
2918 uint32_t uMsg = 0;
2919 rc = VbglR3GuestCtrlMsgPeekWait(idClient, &uMsg, &CtxHost.uNumParms, NULL);
2920 if (RT_SUCCESS(rc))
2921 {
2922 VGSvcVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved (%Rrc)\n", uMsg, CtxHost.uNumParms, rc);
2923
2924 /*
2925 * Pass it on to the session handler.
2926 * Note! Only when handling HOST_SESSION_CLOSE is the rc used.
2927 */
2928 bool fShutdown = false;
2929 rc = VGSvcGstCtrlSessionHandler(pSession, uMsg, &CtxHost, &pvScratchBuf, &cbScratchBuf, &fShutdown);
2930 if (fShutdown)
2931 break;
2932
2933 cFailedMsgPeeks = 0;
2934
2935 /* Let others run (guests are often single CPU) ... */
2936 RTThreadYield();
2937 }
2938 /*
2939 * Handle restore notification from host. All the context IDs (sessions,
2940 * files, proceses, etc) are invalidated by a VM restore and must be closed.
2941 */
2942 else if (rc == VERR_VM_RESTORED)
2943 {
2944 VGSvcVerbose(1, "The VM session ID changed (i.e. restored), closing stale session %RU32\n",
2945 pSession->StartupInfo.uSessionID);
2946
2947 /* We currently don't serialize guest sessions, guest processes and other guest control objects
2948 * within saved states. So just close this session and report success to the parent process.
2949 *
2950 * Note: Not notifying the host here is intentional, as it wouldn't have any information
2951 * about what to do with it.
2952 */
2953 rc = VINF_SUCCESS; /* Report success as exit code. */
2954 break;
2955 }
2956 else
2957 {
2958 VGSvcVerbose(1, "Getting host message failed with %Rrc\n", rc);
2959
2960 if (cFailedMsgPeeks++ == 3)
2961 break;
2962
2963 RTThreadSleep(3 * RT_MS_1SEC);
2964
2965 /** @todo Shouldn't we have a plan for handling connection loss and such? */
2966 }
2967 }
2968
2969 /*
2970 * Shutdown.
2971 */
2972 RTMemFree(pvScratchBuf);
2973 }
2974 else
2975 rc = VERR_NO_MEMORY;
2976
2977 VGSvcVerbose(0, "Session %RU32 ended\n", pSession->StartupInfo.uSessionID);
2978 }
2979 else
2980 VGSvcError("Reporting session ID=%RU32 started status failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
2981 }
2982 else
2983 VGSvcError("Setting message filterAdd=0x%x failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
2984
2985 VGSvcVerbose(3, "Disconnecting client ID=%RU32 ...\n", idClient);
2986 VbglR3GuestCtrlDisconnect(idClient);
2987 g_idControlSvcClient = 0;
2988
2989 VGSvcVerbose(3, "Session worker returned with rc=%Rrc\n", rc);
2990 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2991}
2992
2993
2994/**
2995 * Finds a (formerly) started guest process given by its PID and increases its
2996 * reference count.
2997 *
2998 * Must be decreased by the caller with VGSvcGstCtrlProcessRelease().
2999 *
3000 * @returns Guest process if found, otherwise NULL.
3001 * @param pSession Pointer to guest session where to search process in.
3002 * @param uPID PID to search for.
3003 *
3004 * @note This does *not lock the process!
3005 */
3006PVBOXSERVICECTRLPROCESS VGSvcGstCtrlSessionRetainProcess(PVBOXSERVICECTRLSESSION pSession, uint32_t uPID)
3007{
3008 AssertPtrReturn(pSession, NULL);
3009
3010 PVBOXSERVICECTRLPROCESS pProcess = NULL;
3011 int rc = RTCritSectEnter(&pSession->CritSect);
3012 if (RT_SUCCESS(rc))
3013 {
3014 PVBOXSERVICECTRLPROCESS pCurProcess;
3015 RTListForEach(&pSession->lstProcesses, pCurProcess, VBOXSERVICECTRLPROCESS, Node)
3016 {
3017 if (pCurProcess->uPID == uPID)
3018 {
3019 rc = RTCritSectEnter(&pCurProcess->CritSect);
3020 if (RT_SUCCESS(rc))
3021 {
3022 pCurProcess->cRefs++;
3023 rc = RTCritSectLeave(&pCurProcess->CritSect);
3024 AssertRC(rc);
3025 }
3026
3027 if (RT_SUCCESS(rc))
3028 pProcess = pCurProcess;
3029 break;
3030 }
3031 }
3032
3033 rc = RTCritSectLeave(&pSession->CritSect);
3034 AssertRC(rc);
3035 }
3036
3037 return pProcess;
3038}
3039
3040
3041int VGSvcGstCtrlSessionClose(PVBOXSERVICECTRLSESSION pSession)
3042{
3043 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3044
3045 VGSvcVerbose(0, "Session %RU32 is about to close ...\n", pSession->StartupInfo.uSessionID);
3046
3047 int rc = RTCritSectEnter(&pSession->CritSect);
3048 if (RT_SUCCESS(rc))
3049 {
3050 /*
3051 * Close all guest processes.
3052 */
3053 VGSvcVerbose(0, "Stopping all guest processes ...\n");
3054
3055 /* Signal all guest processes in the active list that we want to shutdown. */
3056 PVBOXSERVICECTRLPROCESS pProcess;
3057 RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
3058 VGSvcGstCtrlProcessStop(pProcess);
3059
3060 VGSvcVerbose(1, "%RU32 guest processes were signalled to stop\n", pSession->cProcesses);
3061
3062 /* Wait for all active threads to shutdown and destroy the active thread list. */
3063 PVBOXSERVICECTRLPROCESS pProcessNext;
3064 RTListForEachSafe(&pSession->lstProcesses, pProcess, pProcessNext, VBOXSERVICECTRLPROCESS, Node)
3065 {
3066 int rc3 = RTCritSectLeave(&pSession->CritSect);
3067 AssertRC(rc3);
3068
3069 int rc2 = VGSvcGstCtrlProcessWait(pProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
3070
3071 rc3 = RTCritSectEnter(&pSession->CritSect);
3072 AssertRC(rc3);
3073
3074 if (RT_SUCCESS(rc2))
3075 {
3076 rc2 = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
3077 if (RT_SUCCESS(rc2))
3078 {
3079 VGSvcGstCtrlProcessFree(pProcess);
3080 pProcess = NULL;
3081 }
3082 }
3083 }
3084
3085 AssertMsg(pSession->cProcesses == 0,
3086 ("Session process list still contains %RU32 when it should not\n", pSession->cProcesses));
3087 AssertMsg(RTListIsEmpty(&pSession->lstProcesses),
3088 ("Session process list is not empty when it should\n"));
3089
3090 /*
3091 * Close all left guest files.
3092 */
3093 VGSvcVerbose(0, "Closing all guest files ...\n");
3094
3095 PVBOXSERVICECTRLFILE pFile, pFileNext;
3096 RTListForEachSafe(&pSession->lstFiles, pFile, pFileNext, VBOXSERVICECTRLFILE, Node)
3097 {
3098 int rc2 = vgsvcGstCtrlSessionFileFree(pFile);
3099 if (RT_FAILURE(rc2))
3100 {
3101 VGSvcError("Unable to close file '%s'; rc=%Rrc\n", pFile->pszName, rc2);
3102 if (RT_SUCCESS(rc))
3103 rc = rc2;
3104 /* Keep going. */
3105 }
3106
3107 pFile = NULL; /* To make it obvious. */
3108 }
3109
3110#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
3111 AssertMsg(pSession->cDirs == 0,
3112 ("Session directory list still contains %RU32 when it should not\n", pSession->cDirs));
3113 AssertMsg(RTListIsEmpty(&pSession->lstDirs),
3114 ("Session directory list is not empty when it should\n"));
3115#endif
3116 AssertMsg(pSession->cFiles == 0,
3117 ("Session file list still contains %RU32 when it should not\n", pSession->cFiles));
3118 AssertMsg(RTListIsEmpty(&pSession->lstFiles),
3119 ("Session file list is not empty when it should\n"));
3120
3121 int rc2 = RTCritSectLeave(&pSession->CritSect);
3122 if (RT_SUCCESS(rc))
3123 rc = rc2;
3124 }
3125
3126 return rc;
3127}
3128
3129
3130int VGSvcGstCtrlSessionDestroy(PVBOXSERVICECTRLSESSION pSession)
3131{
3132 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3133
3134 int rc = VGSvcGstCtrlSessionClose(pSession);
3135
3136 /* Destroy critical section. */
3137 RTCritSectDelete(&pSession->CritSect);
3138
3139 return rc;
3140}
3141
3142
3143int VGSvcGstCtrlSessionInit(PVBOXSERVICECTRLSESSION pSession, uint32_t fFlags)
3144{
3145 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3146
3147 RTListInit(&pSession->lstProcesses);
3148#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
3149 RTListInit(&pSession->lstDirs);
3150#endif
3151 RTListInit(&pSession->lstFiles);
3152
3153 pSession->cProcesses = 0;
3154 pSession->cFiles = 0;
3155
3156 pSession->fFlags = fFlags;
3157
3158#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
3159 RT_ZERO(pSession->UidCache);
3160 RT_ZERO(pSession->GidCache);
3161#endif
3162
3163 /* Init critical section for protecting the thread lists. */
3164 int rc = RTCritSectInit(&pSession->CritSect);
3165 AssertRC(rc);
3166
3167 return rc;
3168}
3169
3170
3171/**
3172 * Adds a guest process to a session's process list.
3173 *
3174 * @return VBox status code.
3175 * @param pSession Guest session to add process to.
3176 * @param pProcess Guest process to add.
3177 */
3178int VGSvcGstCtrlSessionProcessAdd(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
3179{
3180 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3181 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
3182
3183 int rc = RTCritSectEnter(&pSession->CritSect);
3184 if (RT_SUCCESS(rc))
3185 {
3186 VGSvcVerbose(3, "Adding process (PID %RU32) to session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
3187
3188 /* Add process to session list. */
3189 RTListAppend(&pSession->lstProcesses, &pProcess->Node);
3190
3191 pSession->cProcesses++;
3192 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
3193 pSession->StartupInfo.uSessionID, pSession->cProcesses);
3194
3195 int rc2 = RTCritSectLeave(&pSession->CritSect);
3196 if (RT_SUCCESS(rc))
3197 rc = rc2;
3198 }
3199
3200 return VINF_SUCCESS;
3201}
3202
3203/**
3204 * Removes a guest process from a session's process list.
3205 * Internal version, does not do locking.
3206 *
3207 * @return VBox status code.
3208 * @param pSession Guest session to remove process from.
3209 * @param pProcess Guest process to remove.
3210 */
3211static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
3212{
3213 VGSvcVerbose(3, "Removing process (PID %RU32) from session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
3214 AssertReturn(pProcess->cRefs == 0, VERR_WRONG_ORDER);
3215
3216 RTListNodeRemove(&pProcess->Node);
3217
3218 AssertReturn(pSession->cProcesses, VERR_WRONG_ORDER);
3219 pSession->cProcesses--;
3220 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
3221 pSession->StartupInfo.uSessionID, pSession->cProcesses);
3222
3223 return VINF_SUCCESS;
3224}
3225
3226/**
3227 * Removes a guest process from a session's process list.
3228 *
3229 * @return VBox status code.
3230 * @param pSession Guest session to remove process from.
3231 * @param pProcess Guest process to remove.
3232 */
3233int VGSvcGstCtrlSessionProcessRemove(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
3234{
3235 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3236 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
3237
3238 int rc = RTCritSectEnter(&pSession->CritSect);
3239 if (RT_SUCCESS(rc))
3240 {
3241 rc = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
3242
3243 int rc2 = RTCritSectLeave(&pSession->CritSect);
3244 if (RT_SUCCESS(rc))
3245 rc = rc2;
3246 }
3247
3248 return rc;
3249}
3250
3251
3252/**
3253 * Determines whether starting a new guest process according to the
3254 * maximum number of concurrent guest processes defined is allowed or not.
3255 *
3256 * @return VBox status code.
3257 * @param pSession The guest session.
3258 * @param pfAllowed \c True if starting (another) guest process
3259 * is allowed, \c false if not.
3260 */
3261int VGSvcGstCtrlSessionProcessStartAllowed(const PVBOXSERVICECTRLSESSION pSession, bool *pfAllowed)
3262{
3263 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3264 AssertPtrReturn(pfAllowed, VERR_INVALID_POINTER);
3265
3266 int rc = RTCritSectEnter(&pSession->CritSect);
3267 if (RT_SUCCESS(rc))
3268 {
3269 /*
3270 * Check if we're respecting our memory policy by checking
3271 * how many guest processes are started and served already.
3272 */
3273 bool fLimitReached = false;
3274 if (pSession->uProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
3275 {
3276 VGSvcVerbose(3, "Maximum kept guest processes set to %RU32, acurrent=%RU32\n",
3277 pSession->uProcsMaxKept, pSession->cProcesses);
3278
3279 int32_t iProcsLeft = (pSession->uProcsMaxKept - pSession->cProcesses - 1);
3280 if (iProcsLeft < 0)
3281 {
3282 VGSvcVerbose(3, "Maximum running guest processes reached (%RU32)\n", pSession->uProcsMaxKept);
3283 fLimitReached = true;
3284 }
3285 }
3286
3287 *pfAllowed = !fLimitReached;
3288
3289 int rc2 = RTCritSectLeave(&pSession->CritSect);
3290 if (RT_SUCCESS(rc))
3291 rc = rc2;
3292 }
3293
3294 return rc;
3295}
3296
3297
3298/**
3299 * Cleans up stopped and no longer used processes.
3300 *
3301 * This will free and remove processes from the session's process list.
3302 *
3303 * @returns VBox status code.
3304 * @param pSession Session to clean up processes for.
3305 */
3306static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession)
3307{
3308 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3309
3310 VGSvcVerbose(3, "Cleaning up stopped processes for session %RU32 ...\n", pSession->StartupInfo.uSessionID);
3311
3312 int rc2 = RTCritSectEnter(&pSession->CritSect);
3313 AssertRC(rc2);
3314
3315 int rc = VINF_SUCCESS;
3316
3317 PVBOXSERVICECTRLPROCESS pCurProcess, pNextProcess;
3318 RTListForEachSafe(&pSession->lstProcesses, pCurProcess, pNextProcess, VBOXSERVICECTRLPROCESS, Node)
3319 {
3320 if (ASMAtomicReadBool(&pCurProcess->fStopped))
3321 {
3322 rc2 = RTCritSectLeave(&pSession->CritSect);
3323 AssertRC(rc2);
3324
3325 rc = VGSvcGstCtrlProcessWait(pCurProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
3326 if (RT_SUCCESS(rc))
3327 {
3328 VGSvcGstCtrlSessionProcessRemove(pSession, pCurProcess);
3329 VGSvcGstCtrlProcessFree(pCurProcess);
3330 }
3331
3332 rc2 = RTCritSectEnter(&pSession->CritSect);
3333 AssertRC(rc2);
3334
3335 /* If failed, try next time we're being called. */
3336 }
3337 }
3338
3339 rc2 = RTCritSectLeave(&pSession->CritSect);
3340 AssertRC(rc2);
3341
3342 if (RT_FAILURE(rc))
3343 VGSvcError("Cleaning up stopped processes for session %RU32 failed with %Rrc\n", pSession->StartupInfo.uSessionID, rc);
3344
3345 return rc;
3346}
3347
3348
3349/**
3350 * Creates the process for a guest session.
3351 *
3352 * @return VBox status code.
3353 * @param pSessionStartupInfo Session startup info.
3354 * @param pSessionThread The session thread under construction.
3355 * @param uCtrlSessionThread The session thread debug ordinal.
3356 */
3357static int vgsvcVGSvcGstCtrlSessionThreadCreateProcess(const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
3358 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread, uint32_t uCtrlSessionThread)
3359{
3360 RT_NOREF(uCtrlSessionThread);
3361
3362 /*
3363 * Is this an anonymous session? Anonymous sessions run with the same
3364 * privileges as the main VBoxService executable.
3365 */
3366 bool const fAnonymous = pSessionThread->pStartupInfo->pszUser
3367 && pSessionThread->pStartupInfo->pszUser[0] == '\0';
3368 if (fAnonymous)
3369 {
3370 Assert(!strlen(pSessionThread->pStartupInfo->pszPassword));
3371 Assert(!strlen(pSessionThread->pStartupInfo->pszDomain));
3372
3373 VGSvcVerbose(3, "New anonymous guest session ID=%RU32 created, fFlags=%x, using protocol %RU32\n",
3374 pSessionStartupInfo->uSessionID,
3375 pSessionStartupInfo->fFlags,
3376 pSessionStartupInfo->uProtocol);
3377 }
3378 else
3379 {
3380 VGSvcVerbose(3, "Spawning new guest session ID=%RU32, szUser=%s, szPassword=%s, szDomain=%s, fFlags=%x, using protocol %RU32\n",
3381 pSessionStartupInfo->uSessionID,
3382 pSessionStartupInfo->pszUser,
3383#ifdef DEBUG
3384 pSessionStartupInfo->pszPassword,
3385#else
3386 "XXX", /* Never show passwords in release mode. */
3387#endif
3388 pSessionStartupInfo->pszDomain,
3389 pSessionStartupInfo->fFlags,
3390 pSessionStartupInfo->uProtocol);
3391 }
3392
3393 /*
3394 * Spawn a child process for doing the actual session handling.
3395 * Start by assembling the argument list.
3396 */
3397 char szExeName[RTPATH_MAX];
3398 char *pszExeName = RTProcGetExecutablePath(szExeName, sizeof(szExeName));
3399 AssertPtrReturn(pszExeName, VERR_FILENAME_TOO_LONG);
3400
3401 char szParmSessionID[32];
3402 RTStrPrintf(szParmSessionID, sizeof(szParmSessionID), "--session-id=%RU32", pSessionThread->pStartupInfo->uSessionID);
3403
3404 char szParmSessionProto[32];
3405 RTStrPrintf(szParmSessionProto, sizeof(szParmSessionProto), "--session-proto=%RU32",
3406 pSessionThread->pStartupInfo->uProtocol);
3407#ifdef DEBUG
3408 char szParmThreadId[32];
3409 RTStrPrintf(szParmThreadId, sizeof(szParmThreadId), "--thread-id=%RU32", uCtrlSessionThread);
3410#endif
3411 unsigned idxArg = 0; /* Next index in argument vector. */
3412 char const *apszArgs[24];
3413
3414 apszArgs[idxArg++] = pszExeName;
3415#ifdef VBOXSERVICE_ARG1_UTF8_ARGV
3416 apszArgs[idxArg++] = VBOXSERVICE_ARG1_UTF8_ARGV; Assert(idxArg == 2);
3417#endif
3418 apszArgs[idxArg++] = "guestsession";
3419 apszArgs[idxArg++] = szParmSessionID;
3420 apszArgs[idxArg++] = szParmSessionProto;
3421#ifdef DEBUG
3422 apszArgs[idxArg++] = szParmThreadId;
3423#endif
3424 if (!fAnonymous) /* Do we need to pass a user name? */
3425 {
3426 apszArgs[idxArg++] = "--user";
3427 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszUser;
3428
3429 if (strlen(pSessionThread->pStartupInfo->pszDomain))
3430 {
3431 apszArgs[idxArg++] = "--domain";
3432 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszDomain;
3433 }
3434 }
3435
3436 /* Add same verbose flags as parent process. */
3437 char szParmVerbose[32];
3438 if (g_cVerbosity > 0)
3439 {
3440 unsigned cVs = RT_MIN(g_cVerbosity, RT_ELEMENTS(szParmVerbose) - 2);
3441 szParmVerbose[0] = '-';
3442 memset(&szParmVerbose[1], 'v', cVs);
3443 szParmVerbose[1 + cVs] = '\0';
3444 apszArgs[idxArg++] = szParmVerbose;
3445 }
3446
3447 /* Add log file handling. Each session will have an own
3448 * log file, naming based on the parent log file. */
3449 char szParmLogFile[sizeof(g_szLogFile) + 128];
3450 if (g_szLogFile[0])
3451 {
3452 const char *pszSuffix = RTPathSuffix(g_szLogFile);
3453 if (!pszSuffix)
3454 pszSuffix = strchr(g_szLogFile, '\0');
3455 size_t cchBase = pszSuffix - g_szLogFile;
3456
3457 RTTIMESPEC Now;
3458 RTTimeNow(&Now);
3459 char szTime[64];
3460 RTTimeSpecToString(&Now, szTime, sizeof(szTime));
3461
3462 /* Replace out characters not allowed on Windows platforms, put in by RTTimeSpecToString(). */
3463 static const RTUNICP s_uszValidRangePairs[] =
3464 {
3465 ' ', ' ',
3466 '(', ')',
3467 '-', '.',
3468 '0', '9',
3469 'A', 'Z',
3470 'a', 'z',
3471 '_', '_',
3472 0xa0, 0xd7af,
3473 '\0'
3474 };
3475 ssize_t cReplaced = RTStrPurgeComplementSet(szTime, s_uszValidRangePairs, '_' /* chReplacement */);
3476 AssertReturn(cReplaced, VERR_INVALID_UTF8_ENCODING);
3477
3478#ifndef DEBUG
3479 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%s-%s%s",
3480 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, pSessionStartupInfo->pszUser, szTime, pszSuffix);
3481#else
3482 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%RU32-%s-%s%s",
3483 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, uCtrlSessionThread,
3484 pSessionStartupInfo->pszUser, szTime, pszSuffix);
3485#endif
3486 apszArgs[idxArg++] = "--logfile";
3487 apszArgs[idxArg++] = szParmLogFile;
3488 }
3489
3490#ifdef DEBUG
3491 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT)
3492 apszArgs[idxArg++] = "--dump-stdout";
3493 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR)
3494 apszArgs[idxArg++] = "--dump-stderr";
3495#endif
3496 apszArgs[idxArg] = NULL;
3497 Assert(idxArg < RT_ELEMENTS(apszArgs));
3498
3499 if (g_cVerbosity > 3)
3500 {
3501 VGSvcVerbose(4, "Spawning parameters:\n");
3502 for (idxArg = 0; apszArgs[idxArg]; idxArg++)
3503 VGSvcVerbose(4, " %s\n", apszArgs[idxArg]);
3504 }
3505
3506 /*
3507 * Flags.
3508 */
3509 uint32_t const fProcCreate = RTPROC_FLAGS_PROFILE
3510#ifdef RT_OS_WINDOWS
3511 | RTPROC_FLAGS_SERVICE
3512 | RTPROC_FLAGS_HIDDEN
3513#endif
3514 | VBOXSERVICE_PROC_F_UTF8_ARGV;
3515
3516 /*
3517 * Configure standard handles.
3518 */
3519 RTHANDLE hStdIn;
3520 int rc = RTPipeCreate(&hStdIn.u.hPipe, &pSessionThread->hKeyPipe, RTPIPE_C_INHERIT_READ);
3521 if (RT_SUCCESS(rc))
3522 {
3523 hStdIn.enmType = RTHANDLETYPE_PIPE;
3524
3525 RTHANDLE hStdOutAndErr;
3526 rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
3527 if (RT_SUCCESS(rc))
3528 {
3529 hStdOutAndErr.enmType = RTHANDLETYPE_FILE;
3530
3531 /*
3532 * Windows: If a domain name is given, construct an UPN (User Principle Name)
3533 * with the domain name built-in, e.g. "joedoe@example.com".
3534 */
3535 const char *pszUser = pSessionThread->pStartupInfo->pszUser;
3536#ifdef RT_OS_WINDOWS
3537 char *pszUserUPN = NULL;
3538 if (pSessionThread->pStartupInfo->pszDomain[0])
3539 {
3540 int cchbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s",
3541 pSessionThread->pStartupInfo->pszUser,
3542 pSessionThread->pStartupInfo->pszDomain);
3543 if (cchbUserUPN > 0)
3544 {
3545 pszUser = pszUserUPN;
3546 VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
3547 }
3548 else
3549 rc = VERR_NO_STR_MEMORY;
3550 }
3551 if (RT_SUCCESS(rc))
3552#endif
3553 {
3554 /*
3555 * Finally, create the process.
3556 */
3557 rc = RTProcCreateEx(pszExeName, apszArgs, RTENV_DEFAULT, fProcCreate,
3558 &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
3559 !fAnonymous ? pszUser : NULL,
3560 !fAnonymous ? pSessionThread->pStartupInfo->pszPassword : NULL,
3561 NULL /*pvExtraData*/,
3562 &pSessionThread->hProcess);
3563 }
3564#ifdef RT_OS_WINDOWS
3565 RTStrFree(pszUserUPN);
3566#endif
3567 RTFileClose(hStdOutAndErr.u.hFile);
3568 }
3569
3570 RTPipeClose(hStdIn.u.hPipe);
3571 }
3572 return rc;
3573}
3574
3575
3576/**
3577 * Creates a guest session.
3578 *
3579 * This will spawn a new VBoxService.exe instance under behalf of the given user
3580 * which then will act as a session host. On successful open, the session will
3581 * be added to the given session thread list.
3582 *
3583 * @return VBox status code.
3584 * @param pList Which list to use to store the session thread in.
3585 * @param pSessionStartupInfo Session startup info.
3586 * @param ppSessionThread Returns newly created session thread on success.
3587 * Optional.
3588 */
3589int VGSvcGstCtrlSessionThreadCreate(PRTLISTANCHOR pList, const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
3590 PVBOXSERVICECTRLSESSIONTHREAD *ppSessionThread)
3591{
3592 AssertPtrReturn(pList, VERR_INVALID_POINTER);
3593 AssertPtrReturn(pSessionStartupInfo, VERR_INVALID_POINTER);
3594 /* ppSessionThread is optional. */
3595
3596#ifdef VBOX_STRICT
3597 /* Check for existing session in debug mode. Should never happen because of
3598 * Main consistency. */
3599 PVBOXSERVICECTRLSESSIONTHREAD pSessionCur;
3600 RTListForEach(pList, pSessionCur, VBOXSERVICECTRLSESSIONTHREAD, Node)
3601 {
3602 AssertMsgReturn( pSessionCur->fStopped == true
3603 || pSessionCur->pStartupInfo->uSessionID != pSessionStartupInfo->uSessionID,
3604 ("Guest session thread ID=%RU32 already exists (fStopped=%RTbool)\n",
3605 pSessionCur->pStartupInfo->uSessionID, pSessionCur->fStopped), VERR_ALREADY_EXISTS);
3606 }
3607#endif
3608
3609 /* Static counter to help tracking session thread <-> process relations. */
3610 static uint32_t s_uCtrlSessionThread = 0;
3611
3612 /*
3613 * Allocate and initialize the session thread structure.
3614 */
3615 int rc;
3616 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread = (PVBOXSERVICECTRLSESSIONTHREAD)RTMemAllocZ(sizeof(*pSessionThread));
3617 if (pSessionThread)
3618 {
3619 //pSessionThread->fShutdown = false;
3620 //pSessionThread->fStarted = false;
3621 //pSessionThread->fStopped = false;
3622 pSessionThread->hKeyPipe = NIL_RTPIPE;
3623 pSessionThread->Thread = NIL_RTTHREAD;
3624 pSessionThread->hProcess = NIL_RTPROCESS;
3625
3626 /* Duplicate startup info. */
3627 pSessionThread->pStartupInfo = VbglR3GuestCtrlSessionStartupInfoDup(pSessionStartupInfo);
3628 AssertPtrReturn(pSessionThread->pStartupInfo, VERR_NO_MEMORY);
3629
3630 /* Generate the secret key. */
3631 RTRandBytes(pSessionThread->abKey, sizeof(pSessionThread->abKey));
3632
3633 rc = RTCritSectInit(&pSessionThread->CritSect);
3634 AssertRC(rc);
3635 if (RT_SUCCESS(rc))
3636 {
3637 /*
3638 * Give the session key to the host so it can validate the client.
3639 */
3640 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
3641 {
3642 for (uint32_t i = 0; i < 10; i++)
3643 {
3644 rc = VbglR3GuestCtrlSessionPrepare(g_idControlSvcClient, pSessionStartupInfo->uSessionID,
3645 pSessionThread->abKey, sizeof(pSessionThread->abKey));
3646 if (rc != VERR_OUT_OF_RESOURCES)
3647 break;
3648 RTThreadSleep(100);
3649 }
3650 }
3651 if (RT_SUCCESS(rc))
3652 {
3653 s_uCtrlSessionThread++;
3654
3655 /*
3656 * Start the session child process.
3657 */
3658 rc = vgsvcVGSvcGstCtrlSessionThreadCreateProcess(pSessionStartupInfo, pSessionThread, s_uCtrlSessionThread);
3659 if (RT_SUCCESS(rc))
3660 {
3661 /*
3662 * Start the session thread.
3663 */
3664 rc = RTThreadCreateF(&pSessionThread->Thread, vgsvcGstCtrlSessionThread, pSessionThread /*pvUser*/, 0 /*cbStack*/,
3665 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctls%RU32", s_uCtrlSessionThread);
3666 if (RT_SUCCESS(rc))
3667 {
3668 /* Wait for the thread to initialize. */
3669 rc = RTThreadUserWait(pSessionThread->Thread, RT_MS_1MIN);
3670 if ( RT_SUCCESS(rc)
3671 && !ASMAtomicReadBool(&pSessionThread->fShutdown))
3672 {
3673 VGSvcVerbose(2, "Thread for session ID=%RU32 started\n", pSessionThread->pStartupInfo->uSessionID);
3674
3675 ASMAtomicXchgBool(&pSessionThread->fStarted, true);
3676
3677 /* Add session to list. */
3678 RTListAppend(pList, &pSessionThread->Node);
3679 if (ppSessionThread) /* Return session if wanted. */
3680 *ppSessionThread = pSessionThread;
3681 return VINF_SUCCESS;
3682 }
3683
3684 /*
3685 * Bail out.
3686 */
3687 VGSvcError("Thread for session ID=%RU32 failed to start, rc=%Rrc\n",
3688 pSessionThread->pStartupInfo->uSessionID, rc);
3689 if (RT_SUCCESS_NP(rc))
3690 rc = VERR_CANT_CREATE; /** @todo Find a better rc. */
3691 }
3692 else
3693 VGSvcError("Creating session thread failed, rc=%Rrc\n", rc);
3694
3695 RTProcTerminate(pSessionThread->hProcess);
3696 uint32_t cMsWait = 1;
3697 while ( RTProcWait(pSessionThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, NULL) == VERR_PROCESS_RUNNING
3698 && cMsWait <= 9) /* 1023 ms */
3699 {
3700 RTThreadSleep(cMsWait);
3701 cMsWait <<= 1;
3702 }
3703 }
3704
3705 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
3706 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, pSessionStartupInfo->uSessionID);
3707 }
3708 else
3709 VGSvcVerbose(3, "VbglR3GuestCtrlSessionPrepare failed: %Rrc\n", rc);
3710 RTPipeClose(pSessionThread->hKeyPipe);
3711 pSessionThread->hKeyPipe = NIL_RTPIPE;
3712 RTCritSectDelete(&pSessionThread->CritSect);
3713 }
3714 RTMemFree(pSessionThread);
3715 }
3716 else
3717 rc = VERR_NO_MEMORY;
3718
3719 VGSvcVerbose(3, "Spawning session thread returned returned rc=%Rrc\n", rc);
3720 return rc;
3721}
3722
3723
3724/**
3725 * Waits for a formerly opened guest session process to close.
3726 *
3727 * @return VBox status code.
3728 * @param pThread Guest session thread to wait for.
3729 * @param uTimeoutMS Waiting timeout (in ms).
3730 * @param fFlags Closing flags.
3731 */
3732static int VGSvcGstCtrlSessionThreadWait(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t uTimeoutMS, uint32_t fFlags)
3733{
3734 RT_NOREF(fFlags);
3735 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
3736 /** @todo Validate closing flags. */
3737
3738 AssertMsgReturn(pThread->Thread != NIL_RTTHREAD,
3739 ("Guest session thread of session %p does not exist when it should\n", pThread),
3740 VERR_NOT_FOUND);
3741
3742 int rc = VINF_SUCCESS;
3743
3744 /*
3745 * The spawned session process should have received the same closing request,
3746 * so just wait for the process to close.
3747 */
3748 if (ASMAtomicReadBool(&pThread->fStarted))
3749 {
3750 /* Ask the thread to shutdown. */
3751 ASMAtomicXchgBool(&pThread->fShutdown, true);
3752
3753 VGSvcVerbose(3, "Waiting for session thread ID=%RU32 to close (%RU32ms) ...\n",
3754 pThread->pStartupInfo->uSessionID, uTimeoutMS);
3755
3756 int rcThread;
3757 rc = RTThreadWait(pThread->Thread, uTimeoutMS, &rcThread);
3758 if (RT_SUCCESS(rc))
3759 {
3760 AssertMsg(pThread->fStopped, ("Thread of session ID=%RU32 not in stopped state when it should\n",
3761 pThread->pStartupInfo->uSessionID));
3762
3763 VGSvcVerbose(3, "Session thread ID=%RU32 ended with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rcThread);
3764 }
3765 else
3766 VGSvcError("Waiting for session thread ID=%RU32 to close failed with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rc);
3767 }
3768 else
3769 VGSvcVerbose(3, "Thread for session ID=%RU32 not in started state, skipping wait\n", pThread->pStartupInfo->uSessionID);
3770
3771 LogFlowFuncLeaveRC(rc);
3772 return rc;
3773}
3774
3775/**
3776 * Waits for the specified session thread to end and remove
3777 * it from the session thread list.
3778 *
3779 * @return VBox status code.
3780 * @param pThread Session thread to destroy.
3781 * @param fFlags Closing flags.
3782 */
3783int VGSvcGstCtrlSessionThreadDestroy(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t fFlags)
3784{
3785 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
3786 AssertPtrReturn(pThread->pStartupInfo, VERR_WRONG_ORDER);
3787
3788 const uint32_t uSessionID = pThread->pStartupInfo->uSessionID;
3789
3790 VGSvcVerbose(3, "Destroying session ID=%RU32 ...\n", uSessionID);
3791
3792 int rc = VGSvcGstCtrlSessionThreadWait(pThread, 5 * 60 * 1000 /* 5 minutes timeout */, fFlags);
3793 if (RT_SUCCESS(rc))
3794 {
3795 VbglR3GuestCtrlSessionStartupInfoFree(pThread->pStartupInfo);
3796 pThread->pStartupInfo = NULL;
3797
3798 RTPipeClose(pThread->hKeyPipe);
3799 pThread->hKeyPipe = NIL_RTPIPE;
3800
3801 RTCritSectDelete(&pThread->CritSect);
3802
3803 /* Remove session from list and destroy object. */
3804 RTListNodeRemove(&pThread->Node);
3805
3806 RTMemFree(pThread);
3807 pThread = NULL;
3808 }
3809
3810 VGSvcVerbose(3, "Destroyed session ID=%RU32 with %Rrc\n", uSessionID, rc);
3811 return rc;
3812}
3813
3814/**
3815 * Close all open guest session threads.
3816 *
3817 * @note Caller is responsible for locking!
3818 *
3819 * @return VBox status code.
3820 * @param pList Which list to close the session threads for.
3821 * @param fFlags Closing flags.
3822 */
3823int VGSvcGstCtrlSessionThreadDestroyAll(PRTLISTANCHOR pList, uint32_t fFlags)
3824{
3825 AssertPtrReturn(pList, VERR_INVALID_POINTER);
3826
3827 int rc = VINF_SUCCESS;
3828
3829 /*int rc = VbglR3GuestCtrlClose
3830 if (RT_FAILURE(rc))
3831 VGSvcError("Cancelling pending waits failed; rc=%Rrc\n", rc);*/
3832
3833 PVBOXSERVICECTRLSESSIONTHREAD pSessIt;
3834 PVBOXSERVICECTRLSESSIONTHREAD pSessItNext;
3835 RTListForEachSafe(pList, pSessIt, pSessItNext, VBOXSERVICECTRLSESSIONTHREAD, Node)
3836 {
3837 int rc2 = VGSvcGstCtrlSessionThreadDestroy(pSessIt, fFlags);
3838 if (RT_FAILURE(rc2))
3839 {
3840 VGSvcError("Closing session thread '%s' failed with rc=%Rrc\n", RTThreadGetName(pSessIt->Thread), rc2);
3841 if (RT_SUCCESS(rc))
3842 rc = rc2;
3843 /* Keep going. */
3844 }
3845 }
3846
3847 VGSvcVerbose(4, "Destroying guest session threads ended with %Rrc\n", rc);
3848 return rc;
3849}
3850
3851
3852/**
3853 * Main function for the session process.
3854 *
3855 * @returns exit code.
3856 * @param argc Argument count.
3857 * @param argv Argument vector (UTF-8).
3858 */
3859RTEXITCODE VGSvcGstCtrlSessionSpawnInit(int argc, char **argv)
3860{
3861 static const RTGETOPTDEF s_aOptions[] =
3862 {
3863 { "--domain", VBOXSERVICESESSIONOPT_DOMAIN, RTGETOPT_REQ_STRING },
3864#ifdef DEBUG
3865 { "--dump-stdout", VBOXSERVICESESSIONOPT_DUMP_STDOUT, RTGETOPT_REQ_NOTHING },
3866 { "--dump-stderr", VBOXSERVICESESSIONOPT_DUMP_STDERR, RTGETOPT_REQ_NOTHING },
3867#endif
3868 { "--logfile", VBOXSERVICESESSIONOPT_LOG_FILE, RTGETOPT_REQ_STRING },
3869 { "--user", VBOXSERVICESESSIONOPT_USERNAME, RTGETOPT_REQ_STRING },
3870 { "--session-id", VBOXSERVICESESSIONOPT_SESSION_ID, RTGETOPT_REQ_UINT32 },
3871 { "--session-proto", VBOXSERVICESESSIONOPT_SESSION_PROTO, RTGETOPT_REQ_UINT32 },
3872#ifdef DEBUG
3873 { "--thread-id", VBOXSERVICESESSIONOPT_THREAD_ID, RTGETOPT_REQ_UINT32 },
3874#endif /* DEBUG */
3875 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
3876 };
3877
3878 RTGETOPTSTATE GetState;
3879 RTGetOptInit(&GetState, argc, argv,
3880 s_aOptions, RT_ELEMENTS(s_aOptions),
3881 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3882
3883 uint32_t fSession = VBOXSERVICECTRLSESSION_FLAG_SPAWN;
3884
3885 /* Protocol and session ID must be specified explicitly. */
3886 g_Session.StartupInfo.uProtocol = UINT32_MAX;
3887 g_Session.StartupInfo.uSessionID = UINT32_MAX;
3888
3889 int ch;
3890 RTGETOPTUNION ValueUnion;
3891 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3892 {
3893 /* For options that require an argument, ValueUnion has received the value. */
3894 switch (ch)
3895 {
3896 case VBOXSERVICESESSIONOPT_DOMAIN:
3897 /* Information not needed right now, skip. */
3898 break;
3899#ifdef DEBUG
3900 case VBOXSERVICESESSIONOPT_DUMP_STDOUT:
3901 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
3902 break;
3903
3904 case VBOXSERVICESESSIONOPT_DUMP_STDERR:
3905 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
3906 break;
3907#endif
3908 case VBOXSERVICESESSIONOPT_SESSION_ID:
3909 g_Session.StartupInfo.uSessionID = ValueUnion.u32;
3910 break;
3911
3912 case VBOXSERVICESESSIONOPT_SESSION_PROTO:
3913 g_Session.StartupInfo.uProtocol = ValueUnion.u32;
3914 break;
3915#ifdef DEBUG
3916 case VBOXSERVICESESSIONOPT_THREAD_ID:
3917 /* Not handled. Mainly for processs listing. */
3918 break;
3919#endif
3920 case VBOXSERVICESESSIONOPT_LOG_FILE:
3921 {
3922 int rc = RTStrCopy(g_szLogFile, sizeof(g_szLogFile), ValueUnion.psz);
3923 if (RT_FAILURE(rc))
3924 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error copying log file name: %Rrc", rc);
3925 break;
3926 }
3927
3928 case VBOXSERVICESESSIONOPT_USERNAME:
3929 /* Information not needed right now, skip. */
3930 break;
3931
3932 /** @todo Implement help? */
3933
3934 case 'v':
3935 g_cVerbosity++;
3936 break;
3937
3938 case VINF_GETOPT_NOT_OPTION:
3939 {
3940 if (!RTStrICmp(ValueUnion.psz, VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
3941 break;
3942 /* else fall through and bail out. */
3943 RT_FALL_THROUGH();
3944 }
3945 default:
3946 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'", ValueUnion.psz);
3947 }
3948 }
3949
3950 /* Check that we've got all the required options. */
3951 if (g_Session.StartupInfo.uProtocol == UINT32_MAX)
3952 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No protocol version specified");
3953
3954 if (g_Session.StartupInfo.uSessionID == UINT32_MAX)
3955 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No session ID specified");
3956
3957 /* Init the session object. */
3958 int rc = VGSvcGstCtrlSessionInit(&g_Session, fSession);
3959 if (RT_FAILURE(rc))
3960 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to initialize session object, rc=%Rrc\n", rc);
3961
3962 rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
3963 if (RT_FAILURE(rc))
3964 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to create log file '%s', rc=%Rrc\n",
3965 g_szLogFile[0] ? g_szLogFile : "<None>", rc);
3966
3967 RTEXITCODE rcExit = vgsvcGstCtrlSessionSpawnWorker(&g_Session);
3968
3969 VGSvcLogDestroy();
3970 return rcExit;
3971}
3972
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use