VirtualBox

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

Last change on this file since 98613 was 98526, checked in by vboxsync, 22 months ago

Guest Control: Initial commit (work in progress, disabled by default). bugref:9783

IGuestDirectory:

Added new attributes id + status + an own event source. Also added for rewind support via rewind().

New event types for guest directory [un]registration, state changes and entry reads.

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

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