VirtualBox

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

Last change on this file since 103415 was 103415, checked in by vboxsync, 3 months ago

Additions,Main,VMM,Runtime: Fix some unused expression warnings, bugref:3409

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 142.6 KB
Line 
1/* $Id: VBoxServiceControlSession.cpp 103415 2024-02-19 07:52:27Z 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 char *pszNew;
1741 int rc2 = RTStrRealloc(&pszNew, pCtx->cbAlloc + RT_MAX(_4K, cch));
1742 AssertRCReturn(rc2, rc2);
1743 pCtx->psz = pszNew;
1744 }
1745
1746 memcpy(&pCtx->psz[pCtx->cb], pszMountpoint, cch);
1747 pCtx->cb += cch;
1748 AssertReturn(pCtx->cb <= pCtx->cbAlloc, VERR_BUFFER_OVERFLOW); /* Paranoia. */
1749
1750 return VINF_SUCCESS;
1751}
1752
1753/**
1754 * Handles getting the current mount points.
1755 *
1756 * @returns VBox status code.
1757 * @param pSession Guest session.
1758 * @param pHostCtx Host context.
1759 */
1760static int vgsvcGstCtrlSessionHandleMountPoints(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1761{
1762 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1763 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1764
1765 /*
1766 * Retrieve the request.
1767 */
1768 uint32_t fFlags;
1769 int rc = VbglR3GuestCtrlGetMountPoints(pHostCtx, &fFlags);
1770 if (RT_SUCCESS(rc))
1771 {
1772 /* Note: fFlags is currently unused, so we simply ignore this here. */
1773
1774 VGSVCMOUNTPOINTENUMCTX Ctx;
1775 Ctx.cb = 0;
1776 Ctx.cbAlloc = _4K; /* Start with something sensible. */
1777 Ctx.psz = RTStrAlloc(Ctx.cbAlloc);
1778 if (!Ctx.psz)
1779 rc = VERR_NO_MEMORY;
1780
1781 if (RT_SUCCESS(rc))
1782 rc = RTFsMountpointsEnum(vgsvcGstCtrlSessionHandleMountPointsEnumCallback, &Ctx);
1783
1784 /* Report back in any case. */
1785 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */, Ctx.psz,
1786 RT_SUCCESS(rc) ? (uint32_t)Ctx.cb : 0);
1787 if (RT_FAILURE(rc2))
1788 {
1789 VGSvcError("Failed to report mount points, rc=%Rrc\n", rc2);
1790 if (RT_SUCCESS(rc))
1791 rc = rc2;
1792 }
1793
1794 RTStrFree(Ctx.psz);
1795 Ctx.psz = NULL;
1796 }
1797 else
1798 {
1799 VGSvcError("Error fetching parameters for getting mount points request: %Rrc\n", rc);
1800 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1801 }
1802 return rc;
1803}
1804
1805
1806/**
1807 * Handles starting a guest processes.
1808 *
1809 * @returns VBox status code.
1810 * @param pSession Guest session.
1811 * @param pHostCtx Host context.
1812 */
1813static int vgsvcGstCtrlSessionHandleProcExec(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1814{
1815 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1816 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1817
1818 /* Initialize maximum environment block size -- needed as input
1819 * parameter to retrieve the stuff from the host. On output this then
1820 * will contain the actual block size. */
1821 PVBGLR3GUESTCTRLPROCSTARTUPINFO pStartupInfo;
1822 int rc = VbglR3GuestCtrlProcGetStart(pHostCtx, &pStartupInfo);
1823 if (RT_SUCCESS(rc))
1824 {
1825 VGSvcVerbose(3, "Request to start process szCmd=%s, fFlags=0x%x, szArgs=%s, szEnv=%s, szCwd=%s, uTimeout=%RU32\n",
1826 pStartupInfo->pszCmd, pStartupInfo->fFlags,
1827 pStartupInfo->cArgs ? pStartupInfo->pszArgs : "<None>",
1828 pStartupInfo->cEnvVars ? pStartupInfo->pszEnv : "<None>",
1829 pStartupInfo->cbCwd ? pStartupInfo->pszCwd : "<None>",
1830 pStartupInfo->uTimeLimitMS);
1831
1832 bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
1833 rc = VGSvcGstCtrlSessionProcessStartAllowed(pSession, &fStartAllowed);
1834 if (RT_SUCCESS(rc))
1835 {
1836 vgsvcGstCtrlSessionCleanupProcesses(pSession);
1837
1838 if (fStartAllowed)
1839 rc = VGSvcGstCtrlProcessStart(pSession, pStartupInfo, pHostCtx->uContextID);
1840 else
1841 rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
1842 }
1843
1844 /* We're responsible for signaling errors to the host (it will wait for ever otherwise). */
1845 if (RT_FAILURE(rc))
1846 {
1847 VGSvcError("Starting process failed with rc=%Rrc, protocol=%RU32, parameters=%RU32\n",
1848 rc, pHostCtx->uProtocol, pHostCtx->uNumParms);
1849 int rc2 = VbglR3GuestCtrlProcCbStatus(pHostCtx, 0 /*nil-PID*/, PROC_STS_ERROR, rc, NULL /*pvData*/, 0 /*cbData*/);
1850 if (RT_FAILURE(rc2))
1851 VGSvcError("Error sending start process status to host, rc=%Rrc\n", rc2);
1852 }
1853
1854 VbglR3GuestCtrlProcStartupInfoFree(pStartupInfo);
1855 pStartupInfo = NULL;
1856 }
1857 else
1858 {
1859 VGSvcError("Failed to retrieve parameters for process start: %Rrc (cParms=%u)\n", rc, pHostCtx->uNumParms);
1860 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1861 }
1862
1863 return rc;
1864}
1865
1866
1867/**
1868 * Sends stdin input to a specific guest process.
1869 *
1870 * @returns VBox status code.
1871 * @param pSession The session which is in charge.
1872 * @param pHostCtx The host context to use.
1873 * @param ppvScratchBuf The scratch buffer, we may grow it.
1874 * @param pcbScratchBuf The scratch buffer size for retrieving the input
1875 * data.
1876 */
1877static int vgsvcGstCtrlSessionHandleProcInput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
1878 void **ppvScratchBuf, uint32_t *pcbScratchBuf)
1879{
1880 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1881 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1882
1883 /*
1884 * Retrieve the data from the host.
1885 */
1886 uint32_t uPID;
1887 uint32_t fFlags;
1888 uint32_t cbInput;
1889 int rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1890 if ( rc == VERR_BUFFER_OVERFLOW
1891 && vgsvcGstCtrlSessionGrowScratchBuf(ppvScratchBuf, pcbScratchBuf, cbInput))
1892 rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags, *ppvScratchBuf, *pcbScratchBuf, &cbInput);
1893 if (RT_SUCCESS(rc))
1894 {
1895 if (fFlags & GUEST_PROC_IN_FLAG_EOF)
1896 VGSvcVerbose(4, "Got last process input block for PID=%RU32 (%RU32 bytes) ...\n", uPID, cbInput);
1897
1898 /*
1899 * Locate the process and feed it.
1900 */
1901 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1902 if (pProcess)
1903 {
1904 rc = VGSvcGstCtrlProcessHandleInput(pProcess, pHostCtx, RT_BOOL(fFlags & GUEST_PROC_IN_FLAG_EOF),
1905 *ppvScratchBuf, RT_MIN(cbInput, *pcbScratchBuf));
1906 if (RT_FAILURE(rc))
1907 VGSvcError("Error handling input message for PID=%RU32, rc=%Rrc\n", uPID, rc);
1908 VGSvcGstCtrlProcessRelease(pProcess);
1909 }
1910 else
1911 {
1912 VGSvcError("Could not find PID %u for feeding %u bytes to it.\n", uPID, cbInput);
1913 rc = VERR_PROCESS_NOT_FOUND;
1914 VbglR3GuestCtrlProcCbStatusInput(pHostCtx, uPID, INPUT_STS_ERROR, rc, 0);
1915 }
1916 }
1917 else
1918 {
1919 VGSvcError("Failed to retrieve parameters for process input: %Rrc (scratch %u bytes)\n", rc, *pcbScratchBuf);
1920 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1921 }
1922
1923 VGSvcVerbose(6, "Feeding input to PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1924 return rc;
1925}
1926
1927
1928/**
1929 * Gets stdout/stderr output of a specific guest process.
1930 *
1931 * @returns VBox status code.
1932 * @param pSession The session which is in charge.
1933 * @param pHostCtx The host context to use.
1934 */
1935static int vgsvcGstCtrlSessionHandleProcOutput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1936{
1937 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1938 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1939
1940 /*
1941 * Retrieve the request.
1942 */
1943 uint32_t uPID;
1944 uint32_t uHandleID;
1945 uint32_t fFlags;
1946 int rc = VbglR3GuestCtrlProcGetOutput(pHostCtx, &uPID, &uHandleID, &fFlags);
1947#ifdef DEBUG_andy
1948 VGSvcVerbose(4, "Getting output for PID=%RU32, CID=%RU32, uHandleID=%RU32, fFlags=%RU32\n",
1949 uPID, pHostCtx->uContextID, uHandleID, fFlags);
1950#endif
1951 if (RT_SUCCESS(rc))
1952 {
1953 /*
1954 * Locate the process and hand it the output request.
1955 */
1956 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
1957 if (pProcess)
1958 {
1959 rc = VGSvcGstCtrlProcessHandleOutput(pProcess, pHostCtx, uHandleID, _64K /* cbToRead */, fFlags);
1960 if (RT_FAILURE(rc))
1961 VGSvcError("Error getting output for PID=%RU32, rc=%Rrc\n", uPID, rc);
1962 VGSvcGstCtrlProcessRelease(pProcess);
1963 }
1964 else
1965 {
1966 VGSvcError("Could not find PID %u for draining handle %u (%#x).\n", uPID, uHandleID, uHandleID);
1967 rc = VERR_PROCESS_NOT_FOUND;
1968/** @todo r=bird:
1969 *
1970 * No way to report status status code for output requests?
1971 *
1972 */
1973 }
1974 }
1975 else
1976 {
1977 VGSvcError("Error fetching parameters for process output request: %Rrc\n", rc);
1978 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
1979 }
1980
1981#ifdef DEBUG_andy
1982 VGSvcVerbose(4, "Getting output for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
1983#endif
1984 return rc;
1985}
1986
1987
1988/**
1989 * Tells a guest process to terminate.
1990 *
1991 * @returns VBox status code.
1992 * @param pSession The session which is in charge.
1993 * @param pHostCtx The host context to use.
1994 */
1995static int vgsvcGstCtrlSessionHandleProcTerminate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
1996{
1997 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1998 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
1999
2000 /*
2001 * Retrieve the request.
2002 */
2003 uint32_t uPID;
2004 int rc = VbglR3GuestCtrlProcGetTerminate(pHostCtx, &uPID);
2005 if (RT_SUCCESS(rc))
2006 {
2007 /*
2008 * Locate the process and terminate it.
2009 */
2010 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
2011 if (pProcess)
2012 {
2013 rc = VGSvcGstCtrlProcessHandleTerm(pProcess);
2014 if (RT_FAILURE(rc))
2015 VGSvcError("Error terminating PID=%RU32, rc=%Rrc\n", uPID, rc);
2016
2017 VGSvcGstCtrlProcessRelease(pProcess);
2018 }
2019 else
2020 {
2021 VGSvcError("Could not find PID %u for termination.\n", uPID);
2022 rc = VERR_PROCESS_NOT_FOUND;
2023 }
2024 }
2025 else
2026 {
2027 VGSvcError("Error fetching parameters for process termination request: %Rrc\n", rc);
2028 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2029 }
2030#ifdef DEBUG_andy
2031 VGSvcVerbose(4, "Terminating PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
2032#endif
2033 return rc;
2034}
2035
2036
2037static int vgsvcGstCtrlSessionHandleProcWaitFor(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2038{
2039 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2040 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2041
2042 /*
2043 * Retrieve the request.
2044 */
2045 uint32_t uPID;
2046 uint32_t uWaitFlags;
2047 uint32_t uTimeoutMS;
2048 int rc = VbglR3GuestCtrlProcGetWaitFor(pHostCtx, &uPID, &uWaitFlags, &uTimeoutMS);
2049 if (RT_SUCCESS(rc))
2050 {
2051 /*
2052 * Locate the process and the realize that this call makes no sense
2053 * since we'll notify the host when a process terminates anyway and
2054 * hopefully don't need any additional encouragement.
2055 */
2056 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
2057 if (pProcess)
2058 {
2059 rc = VERR_NOT_IMPLEMENTED; /** @todo */
2060 VGSvcGstCtrlProcessRelease(pProcess);
2061 }
2062 else
2063 rc = VERR_NOT_FOUND;
2064 }
2065 else
2066 {
2067 VGSvcError("Error fetching parameters for process wait request: %Rrc\n", rc);
2068 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2069 }
2070 return rc;
2071}
2072
2073
2074#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2075static int vgsvcGstCtrlSessionHandleFsQueryInfo(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2076{
2077 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2078 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2079
2080 /*
2081 * Retrieve the request.
2082 */
2083 char szPath[RTPATH_MAX];
2084 int rc = VbglR3GuestCtrlFsGetQueryInfo(pHostCtx, szPath, sizeof(szPath));
2085 if (RT_SUCCESS(rc))
2086 {
2087 GSTCTLFSINFO fsInfo;
2088 RT_ZERO(fsInfo);
2089
2090 /* Query as much as we can; ignore any errors and continue. */
2091 int rc2 = RTFsQuerySizes(szPath, (RTFOFF *)&fsInfo.cbTotalSize, (RTFOFF *)&fsInfo.cbFree,
2092 &fsInfo.cbBlockSize, &fsInfo.cbSectorSize);
2093 if (RT_FAILURE(rc2))
2094 VGSvcError("Error calling RTFsQuerySizes() for fsqueryinfo operation: %Rrc\n", rc2);
2095
2096 RTFSPROPERTIES fsProps;
2097 rc2 = RTFsQueryProperties(szPath, &fsProps);
2098 if (RT_SUCCESS(rc2))
2099 {
2100 /* Regular (status) flags. */
2101 fsInfo.cMaxComponent = fsProps.cbMaxComponent;
2102 if (fsProps.fRemote)
2103 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_REMOTE;
2104 if (fsProps.fCaseSensitive)
2105 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_CASE_SENSITIVE;
2106 if (fsProps.fReadOnly)
2107 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_READ_ONLY;
2108 if (fsProps.fCompressed)
2109 fsInfo.fFlags |= GSTCTLFSINFO_F_IS_COMPRESSED;
2110
2111 /* Feature flags. */
2112 if (fsProps.fSupportsUnicode)
2113 fsInfo.fFeatures |= GSTCTLFSINFO_FEATURE_F_UNICODE;
2114 if (fsProps.fFileCompression)
2115 fsInfo.fFeatures |= GSTCTLFSINFO_FEATURE_F_FILE_COMPRESSION;
2116 }
2117 else
2118 VGSvcError("Error calling RTFsQueryProperties() for fsqueryinfo operation: %Rrc\n", rc2);
2119
2120 rc2 = RTFsQuerySerial(szPath, &fsInfo.uSerialNumber);
2121 if (RT_FAILURE(rc2))
2122 VGSvcError("Error calling RTFsQuerySerial() for fsqueryinfo operation: %Rrc\n", rc2);
2123
2124#if 0 /** @todo Enable as soon as RTFsQueryLabel() is implemented. */
2125 rc2 = RTFsQueryLabel(szPath, fsInfo.szLabel, sizeof(fsInfo.szLabel));
2126 if (RT_FAILURE(rc2))
2127 VGSvcError("Error calling RTFsQueryLabel() for fsqueryinfo operation: %Rrc\n", rc2);
2128#endif
2129
2130 RTFSTYPE enmFsType;
2131 rc2 = RTFsQueryType(szPath, &enmFsType);
2132 if (RT_SUCCESS(rc2))
2133 {
2134 if (RTStrPrintf2(fsInfo.szName, sizeof(fsInfo.szName), "%s", RTFsTypeName(enmFsType)) <= 0)
2135 VGSvcError("Error printing type returned by RTFsQueryType()\n");
2136 }
2137 else
2138 VGSvcError("Error calling RTFsQueryType() for fsqueryinfo operation: %Rrc\n", rc2);
2139
2140#if 0 /** @todo Enable as soon as RTFsQueryMountpoint() is implemented. */
2141 char szMountpoint[RTPATH_MAX];
2142 rc2 = RTFsQueryMountpoint(szPath, szMountpoint, sizeof(szMountpoint));
2143 if (RT_SUCCESS(rc2))
2144 {
2145 #error "Implement me"
2146 }
2147 else
2148 VGSvcError("Error calling RTFsQueryMountpoint() for fsqueryinfo operation: %Rrc\n", rc2);
2149#endif
2150
2151 if (RT_SUCCESS(rc))
2152 {
2153 VGSvcVerbose(3, "cbTotalSize=%RU64, cbFree=%RU64, cbBlockSize=%RU32, cbSectorSize=%RU32, fFlags=%#x, fFeatures=%#x\n",
2154 fsInfo.cbTotalSize, fsInfo.cbFree, fsInfo.cbBlockSize, fsInfo.cbSectorSize,
2155 fsInfo.fFlags, fsInfo.fFeatures);
2156 VGSvcVerbose(3, "szName=%s, szLabel=%s\n", fsInfo.szName, fsInfo.szLabel);
2157 }
2158
2159 uint32_t const cbFsInfo = sizeof(GSTCTLFSINFO); /** @todo Needs tweaking as soon as we resolve the mountpoint above. */
2160
2161 rc2 = VbglR3GuestCtrlFsCbQueryInfo(pHostCtx, rc, &fsInfo, cbFsInfo);
2162 if (RT_FAILURE(rc2))
2163 {
2164 VGSvcError("Failed to reply to fsobjquerinfo request %Rrc, rc=%Rrc\n", rc, rc2);
2165 if (RT_SUCCESS(rc))
2166 rc = rc2;
2167 }
2168 }
2169 else
2170 {
2171 VGSvcError("Error fetching parameters for fsqueryinfo operation: %Rrc\n", rc);
2172 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2173 }
2174 return rc;
2175}
2176
2177static int vgsvcGstCtrlSessionHandleFsObjQueryInfo(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2178{
2179 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2180 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2181
2182 /*
2183 * Retrieve the request.
2184 */
2185 char szPath[RTPATH_MAX];
2186 GSTCTLFSOBJATTRADD enmAttrAdd;
2187 uint32_t fFlags;
2188 RTFSOBJINFO objInfoRuntime;
2189
2190 int rc = VbglR3GuestCtrlFsObjGetQueryInfo(pHostCtx, szPath, sizeof(szPath), &enmAttrAdd, &fFlags);
2191 if (RT_SUCCESS(rc))
2192 {
2193 uint32_t fFlagsRuntime = 0;
2194
2195 if (!(fFlags & ~GSTCTL_PATH_F_VALID_MASK))
2196 {
2197 if (fFlags & GSTCTL_PATH_F_ON_LINK)
2198 fFlagsRuntime |= RTPATH_F_ON_LINK;
2199 if (fFlags & GSTCTL_PATH_F_FOLLOW_LINK)
2200 fFlagsRuntime |= RTPATH_F_FOLLOW_LINK;
2201 if (fFlags & GSTCTL_PATH_F_NO_SYMLINKS)
2202 fFlagsRuntime |= RTPATH_F_NO_SYMLINKS;
2203
2204 if (!RTPATH_F_IS_VALID(fFlagsRuntime, 0))
2205 rc = VERR_INVALID_PARAMETER;
2206 }
2207 else
2208 rc = VERR_INVALID_PARAMETER;
2209
2210 if (RT_FAILURE(rc))
2211 VGSvcError("Invalid fsobjqueryinfo flags: %#x (%#x)\n", fFlags, fFlagsRuntime);
2212
2213 if (RT_SUCCESS(rc))
2214 {
2215#define CASE_ATTR_ADD_VAL(a_Val) \
2216 case GSTCTL##a_Val: enmAttrRuntime = RT##a_Val; break;
2217
2218 RTFSOBJATTRADD enmAttrRuntime;
2219 switch (enmAttrAdd)
2220 {
2221 CASE_ATTR_ADD_VAL(FSOBJATTRADD_NOTHING);
2222 CASE_ATTR_ADD_VAL(FSOBJATTRADD_UNIX);
2223 CASE_ATTR_ADD_VAL(FSOBJATTRADD_UNIX_OWNER);
2224 CASE_ATTR_ADD_VAL(FSOBJATTRADD_UNIX_GROUP);
2225 CASE_ATTR_ADD_VAL(FSOBJATTRADD_EASIZE);
2226 default:
2227 enmAttrRuntime = RTFSOBJATTRADD_NOTHING;
2228 break;
2229 }
2230
2231#undef CASE_ATTR_ADD_VAL
2232
2233 /*
2234 * For now we ASSUME that RTFSOBJINFO == GSTCTLFSOBJINFO, which implies that we simply can cast RTFSOBJINFO
2235 * to GSTCTLFSOBJINFO. This might change in the future, however, so be extra cautious here.
2236 *
2237 * Ditto for RTFSOBJATTR == GSTCTLFSOBJATTR.
2238 */
2239 AssertCompileSize(objInfoRuntime, sizeof(GSTCTLFSOBJINFO));
2240 AssertCompile (RT_OFFSETOF(GSTCTLFSOBJINFO, cbObject) == RT_OFFSETOF(GSTCTLFSOBJINFO, cbObject));
2241 AssertCompile (RT_OFFSETOF(GSTCTLFSOBJINFO, Attr) == RT_OFFSETOF(GSTCTLFSOBJINFO, Attr));
2242 AssertCompileSize(RTFSOBJATTR, sizeof(GSTCTLFSOBJATTR));
2243
2244 rc = RTPathQueryInfoEx(szPath, &objInfoRuntime, enmAttrRuntime, fFlagsRuntime);
2245 }
2246
2247 PGSTCTLFSOBJINFO pObjInfo = (PGSTCTLFSOBJINFO)&objInfoRuntime;
2248
2249 const char *pszUser = VGSvcIdCacheGetUidName(&pSession->UidCache, pObjInfo->Attr.u.Unix.uid, szPath, NULL /* pszRelativeTo */);
2250 const char *pszGroup = VGSvcIdCacheGetGidName(&pSession->GidCache, pObjInfo->Attr.u.Unix.gid, szPath, NULL /* pszRelativeTo */);
2251
2252 int rc2 = VbglR3GuestCtrlFsObjCbQueryInfoEx(pHostCtx, rc, pObjInfo, pszUser, pszGroup);
2253 if (RT_FAILURE(rc2))
2254 {
2255 VGSvcError("Failed to reply to fsobjquerinfo request %Rrc, rc=%Rrc\n", rc, rc2);
2256 if (RT_SUCCESS(rc))
2257 rc = rc2;
2258 }
2259 }
2260 else
2261 {
2262 VGSvcError("Error fetching parameters for fsobjqueryinfo operation: %Rrc\n", rc);
2263 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2264 }
2265 return rc;
2266}
2267
2268
2269static int vgsvcGstCtrlSessionHandleFsCreateTemp(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
2270{
2271 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2272 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2273
2274 /*
2275 * Retrieve the request.
2276 */
2277 char szTemplate[RTPATH_MAX];
2278 char szPath[RTPATH_MAX];
2279 uint32_t fFlags = GSTCTL_CREATETEMP_F_NONE;
2280 RTFMODE fMode = 0700;
2281 int rc = VbglR3GuestCtrlFsGetCreateTemp(pHostCtx, szTemplate, sizeof(szTemplate), szPath, sizeof(szPath), &fFlags, &fMode);
2282 if (RT_SUCCESS(rc))
2283 {
2284 if (!(fFlags & ~GSTCTL_CREATETEMP_F_VALID_MASK))
2285 {
2286 const char *pszWhat = fFlags & GSTCTL_CREATETEMP_F_DIRECTORY ? "directory" : "file";
2287
2288 /* Validate that the template is as IPRT requires (asserted by IPRT). */
2289 if ( RTPathHasPath(szTemplate)
2290 || ( !strstr(szTemplate, "XXX")
2291 && szTemplate[strlen(szTemplate) - 1] != 'X'))
2292 {
2293 VGSvcError("createtemp: Template '%s' should contain a file name with no path and at least three consecutive 'X' characters or ending in 'X'\n",
2294 szTemplate);
2295 rc = VERR_INVALID_PARAMETER;
2296 }
2297
2298 if ( RT_SUCCESS(rc)
2299 && szPath[0] != '\0' && !RTPathStartsWithRoot(szPath))
2300 {
2301 VGSvcError("createtemp: Path '%s' must be absolute\n", szPath);
2302 rc = VERR_INVALID_PARAMETER;
2303 }
2304
2305 if (RT_SUCCESS(rc))
2306 {
2307 char szTemplateWithPath[RTPATH_MAX] = "";
2308 if (szPath[0] != '\0')
2309 {
2310 rc = RTStrCopy(szTemplateWithPath, sizeof(szTemplateWithPath), szPath);
2311 if (RT_FAILURE(rc))
2312 {
2313 VGSvcError("createtemp: Path '%s' too long\n", szPath);
2314 rc = VERR_INVALID_PARAMETER;
2315 }
2316 }
2317 else
2318 {
2319 rc = RTPathTemp(szTemplateWithPath, sizeof(szTemplateWithPath));
2320 if (RT_FAILURE(rc))
2321 {
2322 VGSvcError("createtemp: Failed to get the temporary directory (%Rrc)", rc);
2323 rc = VERR_INVALID_PARAMETER;
2324 }
2325 }
2326
2327 if (RT_SUCCESS(rc))
2328 {
2329 rc = RTPathAppend(szTemplateWithPath, sizeof(szTemplateWithPath), szTemplate);
2330 if (RT_FAILURE(rc))
2331 {
2332 VGSvcError("createtemp: Template '%s' too long for path\n", szTemplate);
2333 rc = VERR_INVALID_PARAMETER;
2334 }
2335 else
2336 {
2337 bool const fSecure = RT_BOOL(fFlags & GSTCTL_CREATETEMP_F_SECURE);
2338 if (fFlags & GSTCTL_CREATETEMP_F_DIRECTORY)
2339 {
2340 if (fSecure)
2341 rc = RTDirCreateTempSecure(szTemplateWithPath); /* File mode is fixed to 0700. */
2342 else
2343 rc = RTDirCreateTemp(szTemplate, fMode);
2344 }
2345 else /* File */
2346 {
2347 if (fSecure)
2348 rc = RTFileCreateTempSecure(szTemplateWithPath); /* File mode is fixed to 0700. */
2349 else
2350 rc = RTFileCreateTemp(szTemplate, fMode);
2351 }
2352
2353 VGSvcVerbose(3, "Creating temporary %s (szTemplate='%s', fFlags=%#x, fMode=%#x) -> rc=%Rrc\n",
2354 pszWhat, szTemplate, fFlags, fMode, rc);
2355 }
2356 }
2357 }
2358 }
2359 else
2360 {
2361 VGSvcError("Invalid temporary directory/file creation flags: %#x\n", fFlags);
2362 rc = VERR_NOT_SUPPORTED;
2363 }
2364
2365 /*
2366 * Report result back to host.
2367 */
2368 int rc2 = VbglR3GuestCtrlFsCbCreateTemp(pHostCtx, rc, szTemplate);
2369 if (RT_FAILURE(rc2))
2370 {
2371 VGSvcError("Failed to report temporary file/directory creation status, rc=%Rrc\n", rc2);
2372 if (RT_SUCCESS(rc))
2373 rc = rc2;
2374 }
2375 }
2376 else
2377 {
2378 VGSvcError("Error fetching parameters for file/directory creation operation: %Rrc\n", rc);
2379 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, rc, UINT32_MAX);
2380 }
2381 VGSvcVerbose(3, "Creating temporary file/directory returned rc=%Rrc\n", rc);
2382 return rc;
2383}
2384#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
2385
2386
2387int VGSvcGstCtrlSessionHandler(PVBOXSERVICECTRLSESSION pSession, uint32_t uMsg, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
2388 void **ppvScratchBuf, uint32_t *pcbScratchBuf, volatile bool *pfShutdown)
2389{
2390 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
2391 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
2392 AssertPtrReturn(*ppvScratchBuf, VERR_INVALID_POINTER);
2393 AssertPtrReturn(pfShutdown, VERR_INVALID_POINTER);
2394
2395
2396 /*
2397 * Only anonymous sessions (that is, sessions which run with local
2398 * service privileges) or spawned session processes can do certain
2399 * operations.
2400 */
2401 bool const fImpersonated = RT_BOOL(pSession->fFlags & ( VBOXSERVICECTRLSESSION_FLAG_SPAWN
2402 | VBOXSERVICECTRLSESSION_FLAG_ANONYMOUS));
2403 int rc = VERR_NOT_SUPPORTED; /* Play safe by default. */
2404
2405 switch (uMsg)
2406 {
2407 case HOST_MSG_SESSION_CLOSE:
2408 /* Shutdown (this spawn). */
2409 rc = VGSvcGstCtrlSessionClose(pSession);
2410 *pfShutdown = true; /* Shutdown in any case. */
2411 break;
2412
2413 case HOST_MSG_EXEC_CMD:
2414 rc = vgsvcGstCtrlSessionHandleProcExec(pSession, pHostCtx);
2415 break;
2416
2417 case HOST_MSG_EXEC_SET_INPUT:
2418 rc = vgsvcGstCtrlSessionHandleProcInput(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2419 break;
2420
2421 case HOST_MSG_EXEC_GET_OUTPUT:
2422 rc = vgsvcGstCtrlSessionHandleProcOutput(pSession, pHostCtx);
2423 break;
2424
2425 case HOST_MSG_EXEC_TERMINATE:
2426 rc = vgsvcGstCtrlSessionHandleProcTerminate(pSession, pHostCtx);
2427 break;
2428
2429 case HOST_MSG_EXEC_WAIT_FOR:
2430 rc = vgsvcGstCtrlSessionHandleProcWaitFor(pSession, pHostCtx);
2431 break;
2432
2433#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2434 case HOST_MSG_FS_OBJ_QUERY_INFO:
2435 if (fImpersonated)
2436 rc = vgsvcGstCtrlSessionHandleFsObjQueryInfo(pSession, pHostCtx);
2437 break;
2438
2439 case HOST_MSG_FS_CREATE_TEMP:
2440 if (fImpersonated)
2441 rc = vgsvcGstCtrlSessionHandleFsCreateTemp(pSession, pHostCtx);
2442 break;
2443
2444 case HOST_MSG_FS_QUERY_INFO:
2445 if (fImpersonated)
2446 rc = vgsvcGstCtrlSessionHandleFsQueryInfo(pSession, pHostCtx);
2447 break;
2448#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
2449
2450 case HOST_MSG_FILE_OPEN:
2451 if (fImpersonated)
2452 rc = vgsvcGstCtrlSessionHandleFileOpen(pSession, pHostCtx);
2453 break;
2454
2455 case HOST_MSG_FILE_CLOSE:
2456 if (fImpersonated)
2457 rc = vgsvcGstCtrlSessionHandleFileClose(pSession, pHostCtx);
2458 break;
2459
2460 case HOST_MSG_FILE_READ:
2461 if (fImpersonated)
2462 rc = vgsvcGstCtrlSessionHandleFileRead(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2463 break;
2464
2465 case HOST_MSG_FILE_READ_AT:
2466 if (fImpersonated)
2467 rc = vgsvcGstCtrlSessionHandleFileReadAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2468 break;
2469
2470 case HOST_MSG_FILE_WRITE:
2471 if (fImpersonated)
2472 rc = vgsvcGstCtrlSessionHandleFileWrite(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2473 break;
2474
2475 case HOST_MSG_FILE_WRITE_AT:
2476 if (fImpersonated)
2477 rc = vgsvcGstCtrlSessionHandleFileWriteAt(pSession, pHostCtx, ppvScratchBuf, pcbScratchBuf);
2478 break;
2479
2480 case HOST_MSG_FILE_SEEK:
2481 if (fImpersonated)
2482 rc = vgsvcGstCtrlSessionHandleFileSeek(pSession, pHostCtx);
2483 break;
2484
2485 case HOST_MSG_FILE_TELL:
2486 if (fImpersonated)
2487 rc = vgsvcGstCtrlSessionHandleFileTell(pSession, pHostCtx);
2488 break;
2489
2490 case HOST_MSG_FILE_SET_SIZE:
2491 if (fImpersonated)
2492 rc = vgsvcGstCtrlSessionHandleFileSetSize(pSession, pHostCtx);
2493 break;
2494
2495#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2496 case HOST_MSG_FILE_REMOVE:
2497 if (fImpersonated)
2498 rc = vgsvcGstCtrlSessionHandleFileRemove(pSession, pHostCtx);
2499 break;
2500
2501 case HOST_MSG_DIR_OPEN:
2502 if (fImpersonated)
2503 rc = vgsvcGstCtrlSessionHandleDirOpen(pSession, pHostCtx);
2504 break;
2505
2506 case HOST_MSG_DIR_CLOSE:
2507 if (fImpersonated)
2508 rc = vgsvcGstCtrlSessionHandleDirClose(pSession, pHostCtx);
2509 break;
2510
2511 case HOST_MSG_DIR_READ:
2512 if (fImpersonated)
2513 rc = vgsvcGstCtrlSessionHandleDirRead(pSession, pHostCtx);
2514 break;
2515
2516 case HOST_MSG_DIR_REWIND:
2517 if (fImpersonated)
2518 rc = vgsvcGstCtrlSessionHandleDirRewind(pSession, pHostCtx);
2519 break;
2520
2521 case HOST_MSG_DIR_CREATE:
2522 if (fImpersonated)
2523 rc = vgsvcGstCtrlSessionHandleDirCreate(pSession, pHostCtx);
2524 break;
2525
2526 case HOST_MSG_DIR_LIST:
2527 if (fImpersonated)
2528 rc = vgsvcGstCtrlSessionHandleDirList(pSession, pHostCtx);
2529 break;
2530#endif /* VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS */
2531
2532 case HOST_MSG_DIR_REMOVE:
2533 if (fImpersonated)
2534 rc = vgsvcGstCtrlSessionHandleDirRemove(pSession, pHostCtx);
2535 break;
2536
2537 case HOST_MSG_PATH_RENAME:
2538 if (fImpersonated)
2539 rc = vgsvcGstCtrlSessionHandlePathRename(pSession, pHostCtx);
2540 break;
2541
2542 case HOST_MSG_PATH_USER_DOCUMENTS:
2543 if (fImpersonated)
2544 rc = vgsvcGstCtrlSessionHandlePathUserDocuments(pSession, pHostCtx);
2545 break;
2546
2547 case HOST_MSG_PATH_USER_HOME:
2548 if (fImpersonated)
2549 rc = vgsvcGstCtrlSessionHandlePathUserHome(pSession, pHostCtx);
2550 break;
2551
2552 case HOST_MSG_MOUNT_POINTS:
2553 if (fImpersonated)
2554 rc = vgsvcGstCtrlSessionHandleMountPoints(pSession, pHostCtx);
2555 break;
2556
2557 case HOST_MSG_SHUTDOWN:
2558 rc = vgsvcGstCtrlSessionHandleShutdown(pSession, pHostCtx);
2559 break;
2560
2561 default: /* Not supported, see next code block. */
2562 break;
2563 }
2564 if (RT_SUCCESS(rc))
2565 { /* likely */ }
2566 else if (rc != VERR_NOT_SUPPORTED) /* Note: Reply to host must must be sent by above handler. */
2567 VGSvcError("Error while handling message %s (%#x, cParms=%RU32), rc=%Rrc\n",
2568 GstCtrlHostMsgtoStr((eHostMsg)uMsg), uMsg, pHostCtx->uNumParms, rc);
2569 else
2570 {
2571 /* We must skip and notify host here as best we can... */
2572 VGSvcVerbose(1, "Unsupported message (uMsg=%RU32, cParms=%RU32) from host, skipping\n", uMsg, pHostCtx->uNumParms);
2573 if (VbglR3GuestCtrlSupportsOptimizations(pHostCtx->uClientID))
2574 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID, VERR_NOT_SUPPORTED, uMsg);
2575 else
2576 VbglR3GuestCtrlMsgSkipOld(pHostCtx->uClientID);
2577 rc = VINF_SUCCESS;
2578 }
2579
2580 return rc;
2581}
2582
2583
2584/**
2585 * Thread main routine for a spawned guest session process.
2586 *
2587 * This thread runs in the main executable to control the spawned session process.
2588 *
2589 * @returns VBox status code.
2590 * @param hThreadSelf Thread handle.
2591 * @param pvUser Pointer to a VBOXSERVICECTRLSESSIONTHREAD structure.
2592 *
2593 */
2594static DECLCALLBACK(int) vgsvcGstCtrlSessionThread(RTTHREAD hThreadSelf, void *pvUser)
2595{
2596 PVBOXSERVICECTRLSESSIONTHREAD pThread = (PVBOXSERVICECTRLSESSIONTHREAD)pvUser;
2597 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2598
2599 uint32_t const idSession = pThread->pStartupInfo->uSessionID;
2600 uint32_t const idClient = g_idControlSvcClient;
2601 VGSvcVerbose(3, "Session ID=%RU32 thread running\n", idSession);
2602
2603 /* Let caller know that we're done initializing, regardless of the result. */
2604 int rc2 = RTThreadUserSignal(hThreadSelf);
2605 AssertRC(rc2);
2606
2607 /*
2608 * Wait for the child process to stop or the shutdown flag to be signalled.
2609 */
2610 RTPROCSTATUS ProcessStatus = { 0, RTPROCEXITREASON_NORMAL };
2611 bool fProcessAlive = true;
2612 bool fSessionCancelled = VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient);
2613 uint32_t cMsShutdownTimeout = 30 * 1000; /** @todo Make this configurable. Later. */
2614 uint64_t msShutdownStart = 0;
2615 uint64_t const msStart = RTTimeMilliTS();
2616 size_t offSecretKey = 0;
2617 int rcWait;
2618 for (;;)
2619 {
2620 /* Secret key feeding. */
2621 if (offSecretKey < sizeof(pThread->abKey))
2622 {
2623 size_t cbWritten = 0;
2624 rc2 = RTPipeWrite(pThread->hKeyPipe, &pThread->abKey[offSecretKey], sizeof(pThread->abKey) - offSecretKey, &cbWritten);
2625 if (RT_SUCCESS(rc2))
2626 offSecretKey += cbWritten;
2627 }
2628
2629 /* Poll child process status. */
2630 rcWait = RTProcWaitNoResume(pThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
2631 if ( rcWait == VINF_SUCCESS
2632 || rcWait == VERR_PROCESS_NOT_FOUND)
2633 {
2634 fProcessAlive = false;
2635 break;
2636 }
2637 AssertMsgBreak(rcWait == VERR_PROCESS_RUNNING || rcWait == VERR_INTERRUPTED,
2638 ("Got unexpected rc=%Rrc while waiting for session process termination\n", rcWait));
2639
2640 /* Shutting down? */
2641 if (ASMAtomicReadBool(&pThread->fShutdown))
2642 {
2643 if (!msShutdownStart)
2644 {
2645 VGSvcVerbose(3, "Notifying guest session process (PID=%RU32, session ID=%RU32) ...\n",
2646 pThread->hProcess, idSession);
2647
2648 VBGLR3GUESTCTRLCMDCTX hostCtx =
2649 {
2650 /* .idClient = */ idClient,
2651 /* .idContext = */ VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
2652 /* .uProtocol = */ pThread->pStartupInfo->uProtocol,
2653 /* .cParams = */ 2
2654 };
2655 rc2 = VbglR3GuestCtrlSessionClose(&hostCtx, 0 /* fFlags */);
2656 if (RT_FAILURE(rc2))
2657 {
2658 VGSvcError("Unable to notify guest session process (PID=%RU32, session ID=%RU32), rc=%Rrc\n",
2659 pThread->hProcess, idSession, rc2);
2660
2661 if (rc2 == VERR_NOT_SUPPORTED)
2662 {
2663 /* Terminate guest session process in case it's not supported by a too old host. */
2664 rc2 = RTProcTerminate(pThread->hProcess);
2665 VGSvcVerbose(3, "Terminating guest session process (PID=%RU32) ended with rc=%Rrc\n",
2666 pThread->hProcess, rc2);
2667 }
2668 break;
2669 }
2670
2671 VGSvcVerbose(3, "Guest session ID=%RU32 thread was asked to terminate, waiting for session process to exit (%RU32 ms timeout) ...\n",
2672 idSession, cMsShutdownTimeout);
2673 msShutdownStart = RTTimeMilliTS();
2674 continue; /* Don't waste time on waiting. */
2675 }
2676 if (RTTimeMilliTS() - msShutdownStart > cMsShutdownTimeout)
2677 {
2678 VGSvcVerbose(3, "Guest session ID=%RU32 process did not shut down within time\n", idSession);
2679 break;
2680 }
2681 }
2682
2683 /* Cancel the prepared session stuff after 30 seconds. */
2684 if ( !fSessionCancelled
2685 && RTTimeMilliTS() - msStart >= 30000)
2686 {
2687 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
2688 fSessionCancelled = true;
2689 }
2690
2691/** @todo r=bird: This 100ms sleep is _extremely_ sucky! */
2692 RTThreadSleep(100); /* Wait a bit. */
2693 }
2694
2695 if (!fSessionCancelled)
2696 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, idSession);
2697
2698 if (!fProcessAlive)
2699 {
2700 VGSvcVerbose(2, "Guest session process (ID=%RU32) terminated with rc=%Rrc, reason=%d, status=%d\n",
2701 idSession, rcWait, ProcessStatus.enmReason, ProcessStatus.iStatus);
2702 if (ProcessStatus.iStatus == RTEXITCODE_INIT)
2703 {
2704 VGSvcError("Guest session process (ID=%RU32) failed to initialize. Here some hints:\n", idSession);
2705 VGSvcError("- Is logging enabled and the output directory is read-only by the guest session user?\n");
2706 /** @todo Add more here. */
2707 }
2708 }
2709
2710 uint32_t uSessionStatus = GUEST_SESSION_NOTIFYTYPE_UNDEFINED;
2711 int32_t iSessionResult = VINF_SUCCESS;
2712
2713 if (fProcessAlive)
2714 {
2715 for (int i = 0; i < 3; i++)
2716 {
2717 if (i)
2718 RTThreadSleep(3000);
2719
2720 VGSvcVerbose(2, "Guest session ID=%RU32 process still alive, killing attempt %d/3\n", idSession, i + 1);
2721
2722 rc2 = RTProcTerminate(pThread->hProcess);
2723 if (RT_SUCCESS(rc2))
2724 break;
2725 }
2726
2727 VGSvcVerbose(2, "Guest session ID=%RU32 process termination resulted in rc=%Rrc\n", idSession, rc2);
2728 uSessionStatus = RT_SUCCESS(rc2) ? GUEST_SESSION_NOTIFYTYPE_TOK : GUEST_SESSION_NOTIFYTYPE_TOA;
2729 }
2730 else if (RT_SUCCESS(rcWait))
2731 {
2732 switch (ProcessStatus.enmReason)
2733 {
2734 case RTPROCEXITREASON_NORMAL:
2735 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
2736 iSessionResult = ProcessStatus.iStatus; /* Report back the session's exit code. */
2737 break;
2738
2739 case RTPROCEXITREASON_ABEND:
2740 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
2741 /* iSessionResult is undefined (0). */
2742 break;
2743
2744 case RTPROCEXITREASON_SIGNAL:
2745 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TES;
2746 iSessionResult = ProcessStatus.iStatus; /* Report back the signal number. */
2747 break;
2748
2749 default:
2750 AssertMsgFailed(("Unhandled process termination reason (%d)\n", ProcessStatus.enmReason));
2751 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
2752 break;
2753 }
2754 }
2755 else
2756 {
2757 /* If we didn't find the guest process anymore, just assume it terminated normally. */
2758 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
2759 }
2760
2761 /* Make sure to set stopped state before we let the host know. */
2762 ASMAtomicWriteBool(&pThread->fStopped, true);
2763
2764 /* Report final status, regardless if we failed to wait above, so that the host knows what's going on. */
2765 VGSvcVerbose(3, "Reporting final status %RU32 of session ID=%RU32\n", uSessionStatus, idSession);
2766 Assert(uSessionStatus != GUEST_SESSION_NOTIFYTYPE_UNDEFINED);
2767
2768 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
2769 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
2770 rc2 = VbglR3GuestCtrlSessionNotify(&ctx, uSessionStatus, iSessionResult);
2771 if (RT_FAILURE(rc2))
2772 VGSvcError("Reporting final status of session ID=%RU32 failed with rc=%Rrc\n", idSession, rc2);
2773
2774 VGSvcVerbose(3, "Thread for session ID=%RU32 ended with sessionStatus=%#x (%RU32), sessionRc=%#x (%Rrc)\n",
2775 idSession, uSessionStatus, uSessionStatus, iSessionResult, iSessionResult);
2776
2777 return VINF_SUCCESS;
2778}
2779
2780/**
2781 * Reads the secret key the parent VBoxService instance passed us and pass it
2782 * along as a authentication token to the host service.
2783 *
2784 * For older hosts, this sets up the message filtering.
2785 *
2786 * @returns VBox status code.
2787 * @param idClient The HGCM client ID.
2788 * @param idSession The session ID.
2789 */
2790static int vgsvcGstCtrlSessionReadKeyAndAccept(uint32_t idClient, uint32_t idSession)
2791{
2792 /*
2793 * Read it.
2794 */
2795 RTHANDLE Handle;
2796 int rc = RTHandleGetStandard(RTHANDLESTD_INPUT, true /*fLeaveOpen*/, &Handle);
2797 if (RT_SUCCESS(rc))
2798 {
2799 if (Handle.enmType == RTHANDLETYPE_PIPE)
2800 {
2801 uint8_t abSecretKey[RT_SIZEOFMEMB(VBOXSERVICECTRLSESSIONTHREAD, abKey)];
2802 rc = RTPipeReadBlocking(Handle.u.hPipe, abSecretKey, sizeof(abSecretKey), NULL);
2803 if (RT_SUCCESS(rc))
2804 {
2805 VGSvcVerbose(3, "Got secret key from standard input.\n");
2806
2807 /*
2808 * Do the accepting, if appropriate.
2809 */
2810 if (g_fControlSupportsOptimizations)
2811 {
2812 rc = VbglR3GuestCtrlSessionAccept(idClient, idSession, abSecretKey, sizeof(abSecretKey));
2813 if (RT_SUCCESS(rc))
2814 VGSvcVerbose(3, "Session %u accepted (client ID %u)\n", idClient, idSession);
2815 else
2816 VGSvcError("Failed to accept session %u (client ID %u): %Rrc\n", idClient, idSession, rc);
2817 }
2818 else
2819 {
2820 /* For legacy hosts, we do the filtering thingy. */
2821 rc = VbglR3GuestCtrlMsgFilterSet(idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(idSession),
2822 VBOX_GUESTCTRL_FILTER_BY_SESSION(idSession), 0);
2823 if (RT_SUCCESS(rc))
2824 VGSvcVerbose(3, "Session %u filtering successfully enabled\n", idSession);
2825 else
2826 VGSvcError("Failed to set session filter: %Rrc\n", rc);
2827 }
2828 }
2829 else
2830 VGSvcError("Error reading secret key from standard input: %Rrc\n", rc);
2831 }
2832 else
2833 {
2834 VGSvcError("Standard input is not a pipe!\n");
2835 rc = VERR_INVALID_HANDLE;
2836 }
2837 RTHandleClose(&Handle);
2838 }
2839 else
2840 VGSvcError("RTHandleGetStandard failed on standard input: %Rrc\n", rc);
2841 return rc;
2842}
2843
2844/**
2845 * Invalidates a guest session by updating all it's internal parameters like host features and stuff.
2846 *
2847 * @param pSession Session to invalidate.
2848 * @param idClient Client ID to use.
2849 */
2850static void vgsvcGstCtrlSessionInvalidate(PVBOXSERVICECTRLSESSION pSession, uint32_t idClient)
2851{
2852 RT_NOREF(pSession);
2853
2854 VGSvcVerbose(1, "Invalidating session %RU32 (client ID=%RU32)\n", idClient, pSession->StartupInfo.uSessionID);
2855
2856 int rc2 = VbglR3GuestCtrlQueryFeatures(idClient, &g_fControlHostFeatures0);
2857 if (RT_SUCCESS(rc2)) /* Querying host features is not fatal -- do not use rc here. */
2858 {
2859 VGSvcVerbose(1, "g_fControlHostFeatures0=%#x\n", g_fControlHostFeatures0);
2860 }
2861 else
2862 VGSvcVerbose(1, "Querying host features failed with %Rrc\n", rc2);
2863}
2864
2865/**
2866 * Main message handler for the guest control session process.
2867 *
2868 * @returns exit code.
2869 * @param pSession Pointer to g_Session.
2870 * @thread main.
2871 */
2872static RTEXITCODE vgsvcGstCtrlSessionSpawnWorker(PVBOXSERVICECTRLSESSION pSession)
2873{
2874 AssertPtrReturn(pSession, RTEXITCODE_FAILURE);
2875 VGSvcVerbose(0, "Hi, this is guest session ID=%RU32\n", pSession->StartupInfo.uSessionID);
2876
2877 /*
2878 * Connect to the host service.
2879 */
2880 uint32_t idClient;
2881 int rc = VbglR3GuestCtrlConnect(&idClient);
2882 if (RT_FAILURE(rc))
2883 return VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
2884 g_fControlSupportsOptimizations = VbglR3GuestCtrlSupportsOptimizations(idClient);
2885 g_idControlSvcClient = idClient;
2886
2887 VGSvcVerbose(1, "Using client ID=%RU32\n", idClient);
2888
2889 vgsvcGstCtrlSessionInvalidate(pSession, idClient);
2890
2891 rc = vgsvcGstCtrlSessionReadKeyAndAccept(idClient, pSession->StartupInfo.uSessionID);
2892 if (RT_SUCCESS(rc))
2893 {
2894 /*
2895 * Report started status.
2896 * If session status cannot be posted to the host for some reason, bail out.
2897 */
2898 VBGLR3GUESTCTRLCMDCTX ctx = { idClient, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID),
2899 0 /* uProtocol, unused */, 0 /* uNumParms, unused */ };
2900 rc = VbglR3GuestCtrlSessionNotify(&ctx, GUEST_SESSION_NOTIFYTYPE_STARTED, VINF_SUCCESS);
2901 if (RT_SUCCESS(rc))
2902 {
2903 /*
2904 * Allocate a scratch buffer for messages which also send payload data with them.
2905 * This buffer may grow if the host sends us larger chunks of data.
2906 */
2907 uint32_t cbScratchBuf = _64K;
2908 void *pvScratchBuf = RTMemAlloc(cbScratchBuf);
2909 if (pvScratchBuf)
2910 {
2911 int cFailedMsgPeeks = 0;
2912
2913 /*
2914 * Message processing loop.
2915 */
2916 VBGLR3GUESTCTRLCMDCTX CtxHost = { idClient, 0 /* Context ID */, pSession->StartupInfo.uProtocol, 0 };
2917 for (;;)
2918 {
2919 VGSvcVerbose(3, "Waiting for host msg ...\n");
2920 uint32_t uMsg = 0;
2921 rc = VbglR3GuestCtrlMsgPeekWait(idClient, &uMsg, &CtxHost.uNumParms, NULL);
2922 if (RT_SUCCESS(rc))
2923 {
2924 VGSvcVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved (%Rrc)\n", uMsg, CtxHost.uNumParms, rc);
2925
2926 /*
2927 * Pass it on to the session handler.
2928 * Note! Only when handling HOST_SESSION_CLOSE is the rc used.
2929 */
2930 bool fShutdown = false;
2931 rc = VGSvcGstCtrlSessionHandler(pSession, uMsg, &CtxHost, &pvScratchBuf, &cbScratchBuf, &fShutdown);
2932 if (fShutdown)
2933 break;
2934
2935 cFailedMsgPeeks = 0;
2936
2937 /* Let others run (guests are often single CPU) ... */
2938 RTThreadYield();
2939 }
2940 /*
2941 * Handle restore notification from host. All the context IDs (sessions,
2942 * files, proceses, etc) are invalidated by a VM restore and must be closed.
2943 */
2944 else if (rc == VERR_VM_RESTORED)
2945 {
2946 VGSvcVerbose(1, "The VM session ID changed (i.e. restored), closing stale session %RU32\n",
2947 pSession->StartupInfo.uSessionID);
2948
2949 /* We currently don't serialize guest sessions, guest processes and other guest control objects
2950 * within saved states. So just close this session and report success to the parent process.
2951 *
2952 * Note: Not notifying the host here is intentional, as it wouldn't have any information
2953 * about what to do with it.
2954 */
2955 rc = VINF_SUCCESS; /* Report success as exit code. */
2956 break;
2957 }
2958 else
2959 {
2960 VGSvcVerbose(1, "Getting host message failed with %Rrc\n", rc);
2961
2962 if (cFailedMsgPeeks++ == 3)
2963 break;
2964
2965 RTThreadSleep(3 * RT_MS_1SEC);
2966
2967 /** @todo Shouldn't we have a plan for handling connection loss and such? */
2968 }
2969 }
2970
2971 /*
2972 * Shutdown.
2973 */
2974 RTMemFree(pvScratchBuf);
2975 }
2976 else
2977 rc = VERR_NO_MEMORY;
2978
2979 VGSvcVerbose(0, "Session %RU32 ended\n", pSession->StartupInfo.uSessionID);
2980 }
2981 else
2982 VGSvcError("Reporting session ID=%RU32 started status failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
2983 }
2984 else
2985 VGSvcError("Setting message filterAdd=0x%x failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc);
2986
2987 VGSvcVerbose(3, "Disconnecting client ID=%RU32 ...\n", idClient);
2988 VbglR3GuestCtrlDisconnect(idClient);
2989 g_idControlSvcClient = 0;
2990
2991 VGSvcVerbose(3, "Session worker returned with rc=%Rrc\n", rc);
2992 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2993}
2994
2995
2996/**
2997 * Finds a (formerly) started guest process given by its PID and increases its
2998 * reference count.
2999 *
3000 * Must be decreased by the caller with VGSvcGstCtrlProcessRelease().
3001 *
3002 * @returns Guest process if found, otherwise NULL.
3003 * @param pSession Pointer to guest session where to search process in.
3004 * @param uPID PID to search for.
3005 *
3006 * @note This does *not lock the process!
3007 */
3008PVBOXSERVICECTRLPROCESS VGSvcGstCtrlSessionRetainProcess(PVBOXSERVICECTRLSESSION pSession, uint32_t uPID)
3009{
3010 AssertPtrReturn(pSession, NULL);
3011
3012 PVBOXSERVICECTRLPROCESS pProcess = NULL;
3013 int rc = RTCritSectEnter(&pSession->CritSect);
3014 if (RT_SUCCESS(rc))
3015 {
3016 PVBOXSERVICECTRLPROCESS pCurProcess;
3017 RTListForEach(&pSession->lstProcesses, pCurProcess, VBOXSERVICECTRLPROCESS, Node)
3018 {
3019 if (pCurProcess->uPID == uPID)
3020 {
3021 rc = RTCritSectEnter(&pCurProcess->CritSect);
3022 if (RT_SUCCESS(rc))
3023 {
3024 pCurProcess->cRefs++;
3025 rc = RTCritSectLeave(&pCurProcess->CritSect);
3026 AssertRC(rc);
3027 }
3028
3029 if (RT_SUCCESS(rc))
3030 pProcess = pCurProcess;
3031 break;
3032 }
3033 }
3034
3035 rc = RTCritSectLeave(&pSession->CritSect);
3036 AssertRC(rc);
3037 }
3038
3039 return pProcess;
3040}
3041
3042
3043int VGSvcGstCtrlSessionClose(PVBOXSERVICECTRLSESSION pSession)
3044{
3045 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3046
3047 VGSvcVerbose(0, "Session %RU32 is about to close ...\n", pSession->StartupInfo.uSessionID);
3048
3049 int rc = RTCritSectEnter(&pSession->CritSect);
3050 if (RT_SUCCESS(rc))
3051 {
3052 /*
3053 * Close all guest processes.
3054 */
3055 VGSvcVerbose(0, "Stopping all guest processes ...\n");
3056
3057 /* Signal all guest processes in the active list that we want to shutdown. */
3058 PVBOXSERVICECTRLPROCESS pProcess;
3059 RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
3060 VGSvcGstCtrlProcessStop(pProcess);
3061
3062 VGSvcVerbose(1, "%RU32 guest processes were signalled to stop\n", pSession->cProcesses);
3063
3064 /* Wait for all active threads to shutdown and destroy the active thread list. */
3065 PVBOXSERVICECTRLPROCESS pProcessNext;
3066 RTListForEachSafe(&pSession->lstProcesses, pProcess, pProcessNext, VBOXSERVICECTRLPROCESS, Node)
3067 {
3068 int rc3 = RTCritSectLeave(&pSession->CritSect);
3069 AssertRC(rc3);
3070
3071 int rc2 = VGSvcGstCtrlProcessWait(pProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
3072
3073 rc3 = RTCritSectEnter(&pSession->CritSect);
3074 AssertRC(rc3);
3075
3076 if (RT_SUCCESS(rc2))
3077 {
3078 rc2 = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
3079 if (RT_SUCCESS(rc2))
3080 {
3081 VGSvcGstCtrlProcessFree(pProcess);
3082 pProcess = NULL;
3083 }
3084 }
3085 }
3086
3087 AssertMsg(pSession->cProcesses == 0,
3088 ("Session process list still contains %RU32 when it should not\n", pSession->cProcesses));
3089 AssertMsg(RTListIsEmpty(&pSession->lstProcesses),
3090 ("Session process list is not empty when it should\n"));
3091
3092 /*
3093 * Close all left guest files.
3094 */
3095 VGSvcVerbose(0, "Closing all guest files ...\n");
3096
3097 PVBOXSERVICECTRLFILE pFile, pFileNext;
3098 RTListForEachSafe(&pSession->lstFiles, pFile, pFileNext, VBOXSERVICECTRLFILE, Node)
3099 {
3100 int rc2 = vgsvcGstCtrlSessionFileFree(pFile);
3101 if (RT_FAILURE(rc2))
3102 {
3103 VGSvcError("Unable to close file '%s'; rc=%Rrc\n", pFile->pszName, rc2);
3104 if (RT_SUCCESS(rc))
3105 rc = rc2;
3106 /* Keep going. */
3107 }
3108
3109 pFile = NULL; /* To make it obvious. */
3110 }
3111
3112#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
3113 AssertMsg(pSession->cDirs == 0,
3114 ("Session directory list still contains %RU32 when it should not\n", pSession->cDirs));
3115 AssertMsg(RTListIsEmpty(&pSession->lstDirs),
3116 ("Session directory list is not empty when it should\n"));
3117#endif
3118 AssertMsg(pSession->cFiles == 0,
3119 ("Session file list still contains %RU32 when it should not\n", pSession->cFiles));
3120 AssertMsg(RTListIsEmpty(&pSession->lstFiles),
3121 ("Session file list is not empty when it should\n"));
3122
3123 int rc2 = RTCritSectLeave(&pSession->CritSect);
3124 if (RT_SUCCESS(rc))
3125 rc = rc2;
3126 }
3127
3128 return rc;
3129}
3130
3131
3132int VGSvcGstCtrlSessionDestroy(PVBOXSERVICECTRLSESSION pSession)
3133{
3134 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3135
3136 int rc = VGSvcGstCtrlSessionClose(pSession);
3137
3138 /* Destroy critical section. */
3139 RTCritSectDelete(&pSession->CritSect);
3140
3141 return rc;
3142}
3143
3144
3145int VGSvcGstCtrlSessionInit(PVBOXSERVICECTRLSESSION pSession, uint32_t fFlags)
3146{
3147 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3148
3149 RTListInit(&pSession->lstProcesses);
3150#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
3151 RTListInit(&pSession->lstDirs);
3152#endif
3153 RTListInit(&pSession->lstFiles);
3154
3155 pSession->cProcesses = 0;
3156 pSession->cFiles = 0;
3157
3158 pSession->fFlags = fFlags;
3159
3160#ifdef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
3161 RT_ZERO(pSession->UidCache);
3162 RT_ZERO(pSession->GidCache);
3163#endif
3164
3165 /* Init critical section for protecting the thread lists. */
3166 int rc = RTCritSectInit(&pSession->CritSect);
3167 AssertRC(rc);
3168
3169 return rc;
3170}
3171
3172
3173/**
3174 * Adds a guest process to a session's process list.
3175 *
3176 * @return VBox status code.
3177 * @param pSession Guest session to add process to.
3178 * @param pProcess Guest process to add.
3179 */
3180int VGSvcGstCtrlSessionProcessAdd(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
3181{
3182 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3183 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
3184
3185 int rc = RTCritSectEnter(&pSession->CritSect);
3186 if (RT_SUCCESS(rc))
3187 {
3188 VGSvcVerbose(3, "Adding process (PID %RU32) to session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
3189
3190 /* Add process to session list. */
3191 RTListAppend(&pSession->lstProcesses, &pProcess->Node);
3192
3193 pSession->cProcesses++;
3194 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
3195 pSession->StartupInfo.uSessionID, pSession->cProcesses);
3196
3197 int rc2 = RTCritSectLeave(&pSession->CritSect);
3198 if (RT_SUCCESS(rc))
3199 rc = rc2;
3200 }
3201
3202 return VINF_SUCCESS;
3203}
3204
3205/**
3206 * Removes a guest process from a session's process list.
3207 * Internal version, does not do locking.
3208 *
3209 * @return VBox status code.
3210 * @param pSession Guest session to remove process from.
3211 * @param pProcess Guest process to remove.
3212 */
3213static int vgsvcGstCtrlSessionProcessRemoveInternal(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
3214{
3215 VGSvcVerbose(3, "Removing process (PID %RU32) from session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
3216 AssertReturn(pProcess->cRefs == 0, VERR_WRONG_ORDER);
3217
3218 RTListNodeRemove(&pProcess->Node);
3219
3220 AssertReturn(pSession->cProcesses, VERR_WRONG_ORDER);
3221 pSession->cProcesses--;
3222 VGSvcVerbose(3, "Now session ID=%RU32 has %RU32 processes total\n",
3223 pSession->StartupInfo.uSessionID, pSession->cProcesses);
3224
3225 return VINF_SUCCESS;
3226}
3227
3228/**
3229 * Removes a guest process from a session's process list.
3230 *
3231 * @return VBox status code.
3232 * @param pSession Guest session to remove process from.
3233 * @param pProcess Guest process to remove.
3234 */
3235int VGSvcGstCtrlSessionProcessRemove(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
3236{
3237 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3238 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
3239
3240 int rc = RTCritSectEnter(&pSession->CritSect);
3241 if (RT_SUCCESS(rc))
3242 {
3243 rc = vgsvcGstCtrlSessionProcessRemoveInternal(pSession, pProcess);
3244
3245 int rc2 = RTCritSectLeave(&pSession->CritSect);
3246 if (RT_SUCCESS(rc))
3247 rc = rc2;
3248 }
3249
3250 return rc;
3251}
3252
3253
3254/**
3255 * Determines whether starting a new guest process according to the
3256 * maximum number of concurrent guest processes defined is allowed or not.
3257 *
3258 * @return VBox status code.
3259 * @param pSession The guest session.
3260 * @param pfAllowed \c True if starting (another) guest process
3261 * is allowed, \c false if not.
3262 */
3263int VGSvcGstCtrlSessionProcessStartAllowed(const PVBOXSERVICECTRLSESSION pSession, bool *pfAllowed)
3264{
3265 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3266 AssertPtrReturn(pfAllowed, VERR_INVALID_POINTER);
3267
3268 int rc = RTCritSectEnter(&pSession->CritSect);
3269 if (RT_SUCCESS(rc))
3270 {
3271 /*
3272 * Check if we're respecting our memory policy by checking
3273 * how many guest processes are started and served already.
3274 */
3275 bool fLimitReached = false;
3276 if (pSession->uProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
3277 {
3278 VGSvcVerbose(3, "Maximum kept guest processes set to %RU32, acurrent=%RU32\n",
3279 pSession->uProcsMaxKept, pSession->cProcesses);
3280
3281 int32_t iProcsLeft = (pSession->uProcsMaxKept - pSession->cProcesses - 1);
3282 if (iProcsLeft < 0)
3283 {
3284 VGSvcVerbose(3, "Maximum running guest processes reached (%RU32)\n", pSession->uProcsMaxKept);
3285 fLimitReached = true;
3286 }
3287 }
3288
3289 *pfAllowed = !fLimitReached;
3290
3291 int rc2 = RTCritSectLeave(&pSession->CritSect);
3292 if (RT_SUCCESS(rc))
3293 rc = rc2;
3294 }
3295
3296 return rc;
3297}
3298
3299
3300/**
3301 * Cleans up stopped and no longer used processes.
3302 *
3303 * This will free and remove processes from the session's process list.
3304 *
3305 * @returns VBox status code.
3306 * @param pSession Session to clean up processes for.
3307 */
3308static int vgsvcGstCtrlSessionCleanupProcesses(const PVBOXSERVICECTRLSESSION pSession)
3309{
3310 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
3311
3312 VGSvcVerbose(3, "Cleaning up stopped processes for session %RU32 ...\n", pSession->StartupInfo.uSessionID);
3313
3314 int rc2 = RTCritSectEnter(&pSession->CritSect);
3315 AssertRC(rc2);
3316
3317 int rc = VINF_SUCCESS;
3318
3319 PVBOXSERVICECTRLPROCESS pCurProcess, pNextProcess;
3320 RTListForEachSafe(&pSession->lstProcesses, pCurProcess, pNextProcess, VBOXSERVICECTRLPROCESS, Node)
3321 {
3322 if (ASMAtomicReadBool(&pCurProcess->fStopped))
3323 {
3324 rc2 = RTCritSectLeave(&pSession->CritSect);
3325 AssertRC(rc2);
3326
3327 rc = VGSvcGstCtrlProcessWait(pCurProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
3328 if (RT_SUCCESS(rc))
3329 {
3330 VGSvcGstCtrlSessionProcessRemove(pSession, pCurProcess);
3331 VGSvcGstCtrlProcessFree(pCurProcess);
3332 }
3333
3334 rc2 = RTCritSectEnter(&pSession->CritSect);
3335 AssertRC(rc2);
3336
3337 /* If failed, try next time we're being called. */
3338 }
3339 }
3340
3341 rc2 = RTCritSectLeave(&pSession->CritSect);
3342 AssertRC(rc2);
3343
3344 if (RT_FAILURE(rc))
3345 VGSvcError("Cleaning up stopped processes for session %RU32 failed with %Rrc\n", pSession->StartupInfo.uSessionID, rc);
3346
3347 return rc;
3348}
3349
3350
3351/**
3352 * Creates the process for a guest session.
3353 *
3354 * @return VBox status code.
3355 * @param pSessionStartupInfo Session startup info.
3356 * @param pSessionThread The session thread under construction.
3357 * @param uCtrlSessionThread The session thread debug ordinal.
3358 */
3359static int vgsvcVGSvcGstCtrlSessionThreadCreateProcess(const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
3360 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread, uint32_t uCtrlSessionThread)
3361{
3362 RT_NOREF(uCtrlSessionThread);
3363
3364 /*
3365 * Is this an anonymous session? Anonymous sessions run with the same
3366 * privileges as the main VBoxService executable.
3367 */
3368 bool const fAnonymous = pSessionThread->pStartupInfo->pszUser
3369 && pSessionThread->pStartupInfo->pszUser[0] == '\0';
3370 if (fAnonymous)
3371 {
3372 Assert(!strlen(pSessionThread->pStartupInfo->pszPassword));
3373 Assert(!strlen(pSessionThread->pStartupInfo->pszDomain));
3374
3375 VGSvcVerbose(3, "New anonymous guest session ID=%RU32 created, fFlags=%x, using protocol %RU32\n",
3376 pSessionStartupInfo->uSessionID,
3377 pSessionStartupInfo->fFlags,
3378 pSessionStartupInfo->uProtocol);
3379 }
3380 else
3381 {
3382 VGSvcVerbose(3, "Spawning new guest session ID=%RU32, szUser=%s, szPassword=%s, szDomain=%s, fFlags=%x, using protocol %RU32\n",
3383 pSessionStartupInfo->uSessionID,
3384 pSessionStartupInfo->pszUser,
3385#ifdef DEBUG
3386 pSessionStartupInfo->pszPassword,
3387#else
3388 "XXX", /* Never show passwords in release mode. */
3389#endif
3390 pSessionStartupInfo->pszDomain,
3391 pSessionStartupInfo->fFlags,
3392 pSessionStartupInfo->uProtocol);
3393 }
3394
3395 /*
3396 * Spawn a child process for doing the actual session handling.
3397 * Start by assembling the argument list.
3398 */
3399 char szExeName[RTPATH_MAX];
3400 char *pszExeName = RTProcGetExecutablePath(szExeName, sizeof(szExeName));
3401 AssertPtrReturn(pszExeName, VERR_FILENAME_TOO_LONG);
3402
3403 char szParmSessionID[32];
3404 RTStrPrintf(szParmSessionID, sizeof(szParmSessionID), "--session-id=%RU32", pSessionThread->pStartupInfo->uSessionID);
3405
3406 char szParmSessionProto[32];
3407 RTStrPrintf(szParmSessionProto, sizeof(szParmSessionProto), "--session-proto=%RU32",
3408 pSessionThread->pStartupInfo->uProtocol);
3409#ifdef DEBUG
3410 char szParmThreadId[32];
3411 RTStrPrintf(szParmThreadId, sizeof(szParmThreadId), "--thread-id=%RU32", uCtrlSessionThread);
3412#endif
3413 unsigned idxArg = 0; /* Next index in argument vector. */
3414 char const *apszArgs[24];
3415
3416 apszArgs[idxArg++] = pszExeName;
3417#ifdef VBOXSERVICE_ARG1_UTF8_ARGV
3418 apszArgs[idxArg++] = VBOXSERVICE_ARG1_UTF8_ARGV; Assert(idxArg == 2);
3419#endif
3420 apszArgs[idxArg++] = "guestsession";
3421 apszArgs[idxArg++] = szParmSessionID;
3422 apszArgs[idxArg++] = szParmSessionProto;
3423#ifdef DEBUG
3424 apszArgs[idxArg++] = szParmThreadId;
3425#endif
3426 if (!fAnonymous) /* Do we need to pass a user name? */
3427 {
3428 apszArgs[idxArg++] = "--user";
3429 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszUser;
3430
3431 if (strlen(pSessionThread->pStartupInfo->pszDomain))
3432 {
3433 apszArgs[idxArg++] = "--domain";
3434 apszArgs[idxArg++] = pSessionThread->pStartupInfo->pszDomain;
3435 }
3436 }
3437
3438 /* Add same verbose flags as parent process. */
3439 char szParmVerbose[32];
3440 if (g_cVerbosity > 0)
3441 {
3442 unsigned cVs = RT_MIN(g_cVerbosity, RT_ELEMENTS(szParmVerbose) - 2);
3443 szParmVerbose[0] = '-';
3444 memset(&szParmVerbose[1], 'v', cVs);
3445 szParmVerbose[1 + cVs] = '\0';
3446 apszArgs[idxArg++] = szParmVerbose;
3447 }
3448
3449 /* Add log file handling. Each session will have an own
3450 * log file, naming based on the parent log file. */
3451 char szParmLogFile[sizeof(g_szLogFile) + 128];
3452 if (g_szLogFile[0])
3453 {
3454 const char *pszSuffix = RTPathSuffix(g_szLogFile);
3455 if (!pszSuffix)
3456 pszSuffix = strchr(g_szLogFile, '\0');
3457 size_t cchBase = pszSuffix - g_szLogFile;
3458
3459 RTTIMESPEC Now;
3460 RTTimeNow(&Now);
3461 char szTime[64];
3462 RTTimeSpecToString(&Now, szTime, sizeof(szTime));
3463
3464 /* Replace out characters not allowed on Windows platforms, put in by RTTimeSpecToString(). */
3465 static const RTUNICP s_uszValidRangePairs[] =
3466 {
3467 ' ', ' ',
3468 '(', ')',
3469 '-', '.',
3470 '0', '9',
3471 'A', 'Z',
3472 'a', 'z',
3473 '_', '_',
3474 0xa0, 0xd7af,
3475 '\0'
3476 };
3477 ssize_t cReplaced = RTStrPurgeComplementSet(szTime, s_uszValidRangePairs, '_' /* chReplacement */);
3478 AssertReturn(cReplaced, VERR_INVALID_UTF8_ENCODING);
3479
3480#ifndef DEBUG
3481 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%s-%s%s",
3482 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, pSessionStartupInfo->pszUser, szTime, pszSuffix);
3483#else
3484 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%RU32-%s-%s%s",
3485 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, uCtrlSessionThread,
3486 pSessionStartupInfo->pszUser, szTime, pszSuffix);
3487#endif
3488 apszArgs[idxArg++] = "--logfile";
3489 apszArgs[idxArg++] = szParmLogFile;
3490 }
3491
3492#ifdef DEBUG
3493 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT)
3494 apszArgs[idxArg++] = "--dump-stdout";
3495 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR)
3496 apszArgs[idxArg++] = "--dump-stderr";
3497#endif
3498 apszArgs[idxArg] = NULL;
3499 Assert(idxArg < RT_ELEMENTS(apszArgs));
3500
3501 if (g_cVerbosity > 3)
3502 {
3503 VGSvcVerbose(4, "Spawning parameters:\n");
3504 for (idxArg = 0; apszArgs[idxArg]; idxArg++)
3505 VGSvcVerbose(4, " %s\n", apszArgs[idxArg]);
3506 }
3507
3508 /*
3509 * Flags.
3510 */
3511 uint32_t const fProcCreate = RTPROC_FLAGS_PROFILE
3512#ifdef RT_OS_WINDOWS
3513 | RTPROC_FLAGS_SERVICE
3514 | RTPROC_FLAGS_HIDDEN
3515#endif
3516 | VBOXSERVICE_PROC_F_UTF8_ARGV;
3517
3518 /*
3519 * Configure standard handles.
3520 */
3521 RTHANDLE hStdIn;
3522 int rc = RTPipeCreate(&hStdIn.u.hPipe, &pSessionThread->hKeyPipe, RTPIPE_C_INHERIT_READ);
3523 if (RT_SUCCESS(rc))
3524 {
3525 hStdIn.enmType = RTHANDLETYPE_PIPE;
3526
3527 RTHANDLE hStdOutAndErr;
3528 rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
3529 if (RT_SUCCESS(rc))
3530 {
3531 hStdOutAndErr.enmType = RTHANDLETYPE_FILE;
3532
3533 /*
3534 * Windows: If a domain name is given, construct an UPN (User Principle Name)
3535 * with the domain name built-in, e.g. "joedoe@example.com".
3536 */
3537 const char *pszUser = pSessionThread->pStartupInfo->pszUser;
3538#ifdef RT_OS_WINDOWS
3539 char *pszUserUPN = NULL;
3540 if (pSessionThread->pStartupInfo->pszDomain[0])
3541 {
3542 int cchbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s",
3543 pSessionThread->pStartupInfo->pszUser,
3544 pSessionThread->pStartupInfo->pszDomain);
3545 if (cchbUserUPN > 0)
3546 {
3547 pszUser = pszUserUPN;
3548 VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
3549 }
3550 else
3551 rc = VERR_NO_STR_MEMORY;
3552 }
3553 if (RT_SUCCESS(rc))
3554#endif
3555 {
3556 /*
3557 * Finally, create the process.
3558 */
3559 rc = RTProcCreateEx(pszExeName, apszArgs, RTENV_DEFAULT, fProcCreate,
3560 &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
3561 !fAnonymous ? pszUser : NULL,
3562 !fAnonymous ? pSessionThread->pStartupInfo->pszPassword : NULL,
3563 NULL /*pvExtraData*/,
3564 &pSessionThread->hProcess);
3565 }
3566#ifdef RT_OS_WINDOWS
3567 RTStrFree(pszUserUPN);
3568#endif
3569 RTFileClose(hStdOutAndErr.u.hFile);
3570 }
3571
3572 RTPipeClose(hStdIn.u.hPipe);
3573 }
3574 return rc;
3575}
3576
3577
3578/**
3579 * Creates a guest session.
3580 *
3581 * This will spawn a new VBoxService.exe instance under behalf of the given user
3582 * which then will act as a session host. On successful open, the session will
3583 * be added to the given session thread list.
3584 *
3585 * @return VBox status code.
3586 * @param pList Which list to use to store the session thread in.
3587 * @param pSessionStartupInfo Session startup info.
3588 * @param ppSessionThread Returns newly created session thread on success.
3589 * Optional.
3590 */
3591int VGSvcGstCtrlSessionThreadCreate(PRTLISTANCHOR pList, const PVBGLR3GUESTCTRLSESSIONSTARTUPINFO pSessionStartupInfo,
3592 PVBOXSERVICECTRLSESSIONTHREAD *ppSessionThread)
3593{
3594 AssertPtrReturn(pList, VERR_INVALID_POINTER);
3595 AssertPtrReturn(pSessionStartupInfo, VERR_INVALID_POINTER);
3596 /* ppSessionThread is optional. */
3597
3598#ifdef VBOX_STRICT
3599 /* Check for existing session in debug mode. Should never happen because of
3600 * Main consistency. */
3601 PVBOXSERVICECTRLSESSIONTHREAD pSessionCur;
3602 RTListForEach(pList, pSessionCur, VBOXSERVICECTRLSESSIONTHREAD, Node)
3603 {
3604 AssertMsgReturn( pSessionCur->fStopped == true
3605 || pSessionCur->pStartupInfo->uSessionID != pSessionStartupInfo->uSessionID,
3606 ("Guest session thread ID=%RU32 already exists (fStopped=%RTbool)\n",
3607 pSessionCur->pStartupInfo->uSessionID, pSessionCur->fStopped), VERR_ALREADY_EXISTS);
3608 }
3609#endif
3610
3611 /* Static counter to help tracking session thread <-> process relations. */
3612 static uint32_t s_uCtrlSessionThread = 0;
3613
3614 /*
3615 * Allocate and initialize the session thread structure.
3616 */
3617 int rc;
3618 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread = (PVBOXSERVICECTRLSESSIONTHREAD)RTMemAllocZ(sizeof(*pSessionThread));
3619 if (pSessionThread)
3620 {
3621 //pSessionThread->fShutdown = false;
3622 //pSessionThread->fStarted = false;
3623 //pSessionThread->fStopped = false;
3624 pSessionThread->hKeyPipe = NIL_RTPIPE;
3625 pSessionThread->Thread = NIL_RTTHREAD;
3626 pSessionThread->hProcess = NIL_RTPROCESS;
3627
3628 /* Duplicate startup info. */
3629 pSessionThread->pStartupInfo = VbglR3GuestCtrlSessionStartupInfoDup(pSessionStartupInfo);
3630 AssertPtrReturn(pSessionThread->pStartupInfo, VERR_NO_MEMORY);
3631
3632 /* Generate the secret key. */
3633 RTRandBytes(pSessionThread->abKey, sizeof(pSessionThread->abKey));
3634
3635 rc = RTCritSectInit(&pSessionThread->CritSect);
3636 AssertRC(rc);
3637 if (RT_SUCCESS(rc))
3638 {
3639 /*
3640 * Give the session key to the host so it can validate the client.
3641 */
3642 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
3643 {
3644 for (uint32_t i = 0; i < 10; i++)
3645 {
3646 rc = VbglR3GuestCtrlSessionPrepare(g_idControlSvcClient, pSessionStartupInfo->uSessionID,
3647 pSessionThread->abKey, sizeof(pSessionThread->abKey));
3648 if (rc != VERR_OUT_OF_RESOURCES)
3649 break;
3650 RTThreadSleep(100);
3651 }
3652 }
3653 if (RT_SUCCESS(rc))
3654 {
3655 s_uCtrlSessionThread++;
3656
3657 /*
3658 * Start the session child process.
3659 */
3660 rc = vgsvcVGSvcGstCtrlSessionThreadCreateProcess(pSessionStartupInfo, pSessionThread, s_uCtrlSessionThread);
3661 if (RT_SUCCESS(rc))
3662 {
3663 /*
3664 * Start the session thread.
3665 */
3666 rc = RTThreadCreateF(&pSessionThread->Thread, vgsvcGstCtrlSessionThread, pSessionThread /*pvUser*/, 0 /*cbStack*/,
3667 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "gctls%RU32", s_uCtrlSessionThread);
3668 if (RT_SUCCESS(rc))
3669 {
3670 /* Wait for the thread to initialize. */
3671 rc = RTThreadUserWait(pSessionThread->Thread, RT_MS_1MIN);
3672 if ( RT_SUCCESS(rc)
3673 && !ASMAtomicReadBool(&pSessionThread->fShutdown))
3674 {
3675 VGSvcVerbose(2, "Thread for session ID=%RU32 started\n", pSessionThread->pStartupInfo->uSessionID);
3676
3677 ASMAtomicXchgBool(&pSessionThread->fStarted, true);
3678
3679 /* Add session to list. */
3680 RTListAppend(pList, &pSessionThread->Node);
3681 if (ppSessionThread) /* Return session if wanted. */
3682 *ppSessionThread = pSessionThread;
3683 return VINF_SUCCESS;
3684 }
3685
3686 /*
3687 * Bail out.
3688 */
3689 VGSvcError("Thread for session ID=%RU32 failed to start, rc=%Rrc\n",
3690 pSessionThread->pStartupInfo->uSessionID, rc);
3691 if (RT_SUCCESS_NP(rc))
3692 rc = VERR_CANT_CREATE; /** @todo Find a better rc. */
3693 }
3694 else
3695 VGSvcError("Creating session thread failed, rc=%Rrc\n", rc);
3696
3697 RTProcTerminate(pSessionThread->hProcess);
3698 uint32_t cMsWait = 1;
3699 while ( RTProcWait(pSessionThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, NULL) == VERR_PROCESS_RUNNING
3700 && cMsWait <= 9) /* 1023 ms */
3701 {
3702 RTThreadSleep(cMsWait);
3703 cMsWait <<= 1;
3704 }
3705 }
3706
3707 if (VbglR3GuestCtrlSupportsOptimizations(g_idControlSvcClient))
3708 VbglR3GuestCtrlSessionCancelPrepared(g_idControlSvcClient, pSessionStartupInfo->uSessionID);
3709 }
3710 else
3711 VGSvcVerbose(3, "VbglR3GuestCtrlSessionPrepare failed: %Rrc\n", rc);
3712 RTPipeClose(pSessionThread->hKeyPipe);
3713 pSessionThread->hKeyPipe = NIL_RTPIPE;
3714 RTCritSectDelete(&pSessionThread->CritSect);
3715 }
3716 RTMemFree(pSessionThread);
3717 }
3718 else
3719 rc = VERR_NO_MEMORY;
3720
3721 VGSvcVerbose(3, "Spawning session thread returned returned rc=%Rrc\n", rc);
3722 return rc;
3723}
3724
3725
3726/**
3727 * Waits for a formerly opened guest session process to close.
3728 *
3729 * @return VBox status code.
3730 * @param pThread Guest session thread to wait for.
3731 * @param uTimeoutMS Waiting timeout (in ms).
3732 * @param fFlags Closing flags.
3733 */
3734static int VGSvcGstCtrlSessionThreadWait(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t uTimeoutMS, uint32_t fFlags)
3735{
3736 RT_NOREF(fFlags);
3737 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
3738 /** @todo Validate closing flags. */
3739
3740 AssertMsgReturn(pThread->Thread != NIL_RTTHREAD,
3741 ("Guest session thread of session %p does not exist when it should\n", pThread),
3742 VERR_NOT_FOUND);
3743
3744 int rc = VINF_SUCCESS;
3745
3746 /*
3747 * The spawned session process should have received the same closing request,
3748 * so just wait for the process to close.
3749 */
3750 if (ASMAtomicReadBool(&pThread->fStarted))
3751 {
3752 /* Ask the thread to shutdown. */
3753 ASMAtomicXchgBool(&pThread->fShutdown, true);
3754
3755 VGSvcVerbose(3, "Waiting for session thread ID=%RU32 to close (%RU32ms) ...\n",
3756 pThread->pStartupInfo->uSessionID, uTimeoutMS);
3757
3758 int rcThread;
3759 rc = RTThreadWait(pThread->Thread, uTimeoutMS, &rcThread);
3760 if (RT_SUCCESS(rc))
3761 {
3762 AssertMsg(pThread->fStopped, ("Thread of session ID=%RU32 not in stopped state when it should\n",
3763 pThread->pStartupInfo->uSessionID));
3764
3765 VGSvcVerbose(3, "Session thread ID=%RU32 ended with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rcThread);
3766 }
3767 else
3768 VGSvcError("Waiting for session thread ID=%RU32 to close failed with rc=%Rrc\n", pThread->pStartupInfo->uSessionID, rc);
3769 }
3770 else
3771 VGSvcVerbose(3, "Thread for session ID=%RU32 not in started state, skipping wait\n", pThread->pStartupInfo->uSessionID);
3772
3773 LogFlowFuncLeaveRC(rc);
3774 return rc;
3775}
3776
3777/**
3778 * Waits for the specified session thread to end and remove
3779 * it from the session thread list.
3780 *
3781 * @return VBox status code.
3782 * @param pThread Session thread to destroy.
3783 * @param fFlags Closing flags.
3784 */
3785int VGSvcGstCtrlSessionThreadDestroy(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t fFlags)
3786{
3787 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
3788 AssertPtrReturn(pThread->pStartupInfo, VERR_WRONG_ORDER);
3789
3790 const uint32_t uSessionID = pThread->pStartupInfo->uSessionID;
3791
3792 VGSvcVerbose(3, "Destroying session ID=%RU32 ...\n", uSessionID);
3793
3794 int rc = VGSvcGstCtrlSessionThreadWait(pThread, 5 * 60 * 1000 /* 5 minutes timeout */, fFlags);
3795 if (RT_SUCCESS(rc))
3796 {
3797 VbglR3GuestCtrlSessionStartupInfoFree(pThread->pStartupInfo);
3798 pThread->pStartupInfo = NULL;
3799
3800 RTPipeClose(pThread->hKeyPipe);
3801 pThread->hKeyPipe = NIL_RTPIPE;
3802
3803 RTCritSectDelete(&pThread->CritSect);
3804
3805 /* Remove session from list and destroy object. */
3806 RTListNodeRemove(&pThread->Node);
3807
3808 RTMemFree(pThread);
3809 pThread = NULL;
3810 }
3811
3812 VGSvcVerbose(3, "Destroyed session ID=%RU32 with %Rrc\n", uSessionID, rc);
3813 return rc;
3814}
3815
3816/**
3817 * Close all open guest session threads.
3818 *
3819 * @note Caller is responsible for locking!
3820 *
3821 * @return VBox status code.
3822 * @param pList Which list to close the session threads for.
3823 * @param fFlags Closing flags.
3824 */
3825int VGSvcGstCtrlSessionThreadDestroyAll(PRTLISTANCHOR pList, uint32_t fFlags)
3826{
3827 AssertPtrReturn(pList, VERR_INVALID_POINTER);
3828
3829 int rc = VINF_SUCCESS;
3830
3831 /*int rc = VbglR3GuestCtrlClose
3832 if (RT_FAILURE(rc))
3833 VGSvcError("Cancelling pending waits failed; rc=%Rrc\n", rc);*/
3834
3835 PVBOXSERVICECTRLSESSIONTHREAD pSessIt;
3836 PVBOXSERVICECTRLSESSIONTHREAD pSessItNext;
3837 RTListForEachSafe(pList, pSessIt, pSessItNext, VBOXSERVICECTRLSESSIONTHREAD, Node)
3838 {
3839 int rc2 = VGSvcGstCtrlSessionThreadDestroy(pSessIt, fFlags);
3840 if (RT_FAILURE(rc2))
3841 {
3842 VGSvcError("Closing session thread '%s' failed with rc=%Rrc\n", RTThreadGetName(pSessIt->Thread), rc2);
3843 if (RT_SUCCESS(rc))
3844 rc = rc2;
3845 /* Keep going. */
3846 }
3847 }
3848
3849 VGSvcVerbose(4, "Destroying guest session threads ended with %Rrc\n", rc);
3850 return rc;
3851}
3852
3853
3854/**
3855 * Main function for the session process.
3856 *
3857 * @returns exit code.
3858 * @param argc Argument count.
3859 * @param argv Argument vector (UTF-8).
3860 */
3861RTEXITCODE VGSvcGstCtrlSessionSpawnInit(int argc, char **argv)
3862{
3863 static const RTGETOPTDEF s_aOptions[] =
3864 {
3865 { "--domain", VBOXSERVICESESSIONOPT_DOMAIN, RTGETOPT_REQ_STRING },
3866#ifdef DEBUG
3867 { "--dump-stdout", VBOXSERVICESESSIONOPT_DUMP_STDOUT, RTGETOPT_REQ_NOTHING },
3868 { "--dump-stderr", VBOXSERVICESESSIONOPT_DUMP_STDERR, RTGETOPT_REQ_NOTHING },
3869#endif
3870 { "--logfile", VBOXSERVICESESSIONOPT_LOG_FILE, RTGETOPT_REQ_STRING },
3871 { "--user", VBOXSERVICESESSIONOPT_USERNAME, RTGETOPT_REQ_STRING },
3872 { "--session-id", VBOXSERVICESESSIONOPT_SESSION_ID, RTGETOPT_REQ_UINT32 },
3873 { "--session-proto", VBOXSERVICESESSIONOPT_SESSION_PROTO, RTGETOPT_REQ_UINT32 },
3874#ifdef DEBUG
3875 { "--thread-id", VBOXSERVICESESSIONOPT_THREAD_ID, RTGETOPT_REQ_UINT32 },
3876#endif /* DEBUG */
3877 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
3878 };
3879
3880 RTGETOPTSTATE GetState;
3881 RTGetOptInit(&GetState, argc, argv,
3882 s_aOptions, RT_ELEMENTS(s_aOptions),
3883 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3884
3885 uint32_t fSession = VBOXSERVICECTRLSESSION_FLAG_SPAWN;
3886
3887 /* Protocol and session ID must be specified explicitly. */
3888 g_Session.StartupInfo.uProtocol = UINT32_MAX;
3889 g_Session.StartupInfo.uSessionID = UINT32_MAX;
3890
3891 int ch;
3892 RTGETOPTUNION ValueUnion;
3893 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3894 {
3895 /* For options that require an argument, ValueUnion has received the value. */
3896 switch (ch)
3897 {
3898 case VBOXSERVICESESSIONOPT_DOMAIN:
3899 /* Information not needed right now, skip. */
3900 break;
3901#ifdef DEBUG
3902 case VBOXSERVICESESSIONOPT_DUMP_STDOUT:
3903 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
3904 break;
3905
3906 case VBOXSERVICESESSIONOPT_DUMP_STDERR:
3907 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
3908 break;
3909#endif
3910 case VBOXSERVICESESSIONOPT_SESSION_ID:
3911 g_Session.StartupInfo.uSessionID = ValueUnion.u32;
3912 break;
3913
3914 case VBOXSERVICESESSIONOPT_SESSION_PROTO:
3915 g_Session.StartupInfo.uProtocol = ValueUnion.u32;
3916 break;
3917#ifdef DEBUG
3918 case VBOXSERVICESESSIONOPT_THREAD_ID:
3919 /* Not handled. Mainly for processs listing. */
3920 break;
3921#endif
3922 case VBOXSERVICESESSIONOPT_LOG_FILE:
3923 {
3924 int rc = RTStrCopy(g_szLogFile, sizeof(g_szLogFile), ValueUnion.psz);
3925 if (RT_FAILURE(rc))
3926 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error copying log file name: %Rrc", rc);
3927 break;
3928 }
3929
3930 case VBOXSERVICESESSIONOPT_USERNAME:
3931 /* Information not needed right now, skip. */
3932 break;
3933
3934 /** @todo Implement help? */
3935
3936 case 'v':
3937 g_cVerbosity++;
3938 break;
3939
3940 case VINF_GETOPT_NOT_OPTION:
3941 {
3942 if (!RTStrICmp(ValueUnion.psz, VBOXSERVICECTRLSESSION_GETOPT_PREFIX))
3943 break;
3944 /* else fall through and bail out. */
3945 RT_FALL_THROUGH();
3946 }
3947 default:
3948 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown argument '%s'", ValueUnion.psz);
3949 }
3950 }
3951
3952 /* Check that we've got all the required options. */
3953 if (g_Session.StartupInfo.uProtocol == UINT32_MAX)
3954 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No protocol version specified");
3955
3956 if (g_Session.StartupInfo.uSessionID == UINT32_MAX)
3957 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No session ID specified");
3958
3959 /* Init the session object. */
3960 int rc = VGSvcGstCtrlSessionInit(&g_Session, fSession);
3961 if (RT_FAILURE(rc))
3962 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to initialize session object, rc=%Rrc\n", rc);
3963
3964 rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
3965 if (RT_FAILURE(rc))
3966 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to create log file '%s', rc=%Rrc\n",
3967 g_szLogFile[0] ? g_szLogFile : "<None>", rc);
3968
3969 RTEXITCODE rcExit = vgsvcGstCtrlSessionSpawnWorker(&g_Session);
3970
3971 VGSvcLogDestroy();
3972 return rcExit;
3973}
3974
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use