VirtualBox

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

Last change on this file since 71405 was 71405, checked in by vboxsync, 7 years ago

Guest Control/VBoxService: Cleaned up / shortened VGSvcGstCtrlSessionHandler().

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 81.3 KB
Line 
1/* $Id: VBoxServiceControlSession.cpp 71405 2018-03-20 14:20:36Z vboxsync $ */
2/** @file
3 * VBoxServiceControlSession - Guest session handling. Also handles the spawned session processes.
4 */
5
6/*
7 * Copyright (C) 2013-2018 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22#include <iprt/asm.h>
23#include <iprt/assert.h>
24#include <iprt/dir.h>
25#include <iprt/env.h>
26#include <iprt/file.h>
27#include <iprt/getopt.h>
28#include <iprt/handle.h>
29#include <iprt/mem.h>
30#include <iprt/message.h>
31#include <iprt/path.h>
32#include <iprt/pipe.h>
33#include <iprt/poll.h>
34#include <iprt/process.h>
35
36#include "VBoxServiceInternal.h"
37#include "VBoxServiceUtils.h"
38#include "VBoxServiceControl.h"
39
40using namespace guestControl;
41
42
43/*********************************************************************************************************************************
44* Structures and Typedefs *
45*********************************************************************************************************************************/
46/** Generic option indices for session spawn arguments. */
47enum
48{
49 VBOXSERVICESESSIONOPT_FIRST = 1000, /* For initialization. */
50 VBOXSERVICESESSIONOPT_DOMAIN,
51#ifdef DEBUG
52 VBOXSERVICESESSIONOPT_DUMP_STDOUT,
53 VBOXSERVICESESSIONOPT_DUMP_STDERR,
54#endif
55 VBOXSERVICESESSIONOPT_LOG_FILE,
56 VBOXSERVICESESSIONOPT_USERNAME,
57 VBOXSERVICESESSIONOPT_SESSION_ID,
58 VBOXSERVICESESSIONOPT_SESSION_PROTO,
59 VBOXSERVICESESSIONOPT_THREAD_ID
60};
61
62
63
64static int vgsvcGstCtrlSessionFileDestroy(PVBOXSERVICECTRLFILE pFile)
65{
66 AssertPtrReturn(pFile, VERR_INVALID_POINTER);
67
68 int rc = RTFileClose(pFile->hFile);
69 if (RT_SUCCESS(rc))
70 {
71 /* Remove file entry in any case. */
72 RTListNodeRemove(&pFile->Node);
73 /* Destroy this object. */
74 RTMemFree(pFile);
75 }
76
77 return rc;
78}
79
80
81/** @todo No locking done yet! */
82static PVBOXSERVICECTRLFILE vgsvcGstCtrlSessionFileGetLocked(const PVBOXSERVICECTRLSESSION pSession, uint32_t uHandle)
83{
84 AssertPtrReturn(pSession, NULL);
85
86 /** @todo Use a map later! */
87 PVBOXSERVICECTRLFILE pFileCur;
88 RTListForEach(&pSession->lstFiles, pFileCur, VBOXSERVICECTRLFILE, Node)
89 {
90 if (pFileCur->uHandle == uHandle)
91 return pFileCur;
92 }
93
94 return NULL;
95}
96
97
98static int vgsvcGstCtrlSessionHandleDirRemove(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
99{
100 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
101 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
102
103 char szDir[RTPATH_MAX];
104 uint32_t fFlags = 0;
105
106 int rc = VbglR3GuestCtrlDirGetRemove(pHostCtx,
107 /* Directory to remove. */
108 szDir, sizeof(szDir),
109 /* Flags of type DIRREMOVE_FLAG_. */
110 &fFlags);
111 if (RT_SUCCESS(rc))
112 {
113 AssertReturn(!(fFlags & ~DIRREMOVE_FLAG_VALID_MASK), VERR_INVALID_PARAMETER);
114 if (!(fFlags & ~DIRREMOVE_FLAG_VALID_MASK))
115 {
116 if (fFlags & DIRREMOVE_FLAG_RECURSIVE)
117 {
118 uint32_t fFlagsRemRec = RTDIRRMREC_F_CONTENT_AND_DIR; /* Set default. */
119 if (fFlags & DIRREMOVE_FLAG_CONTENT_ONLY)
120 fFlagsRemRec |= RTDIRRMREC_F_CONTENT_ONLY;
121
122 rc = RTDirRemoveRecursive(szDir, fFlagsRemRec);
123 }
124 else /* Only delete directory if not empty. */
125 rc = RTDirRemove(szDir);
126 }
127 else
128 rc = VERR_NOT_SUPPORTED;
129
130 VGSvcVerbose(4, "[Dir %s]: Removing with fFlags=0x%x, rc=%Rrc\n", szDir, fFlags, rc);
131
132 /* Report back in any case. */
133 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
134 if (RT_FAILURE(rc2))
135 VGSvcError("[Dir %s]: Failed to report removing status, rc=%Rrc\n", szDir, rc2);
136 if (RT_SUCCESS(rc))
137 rc = rc2;
138 }
139
140#ifdef DEBUG
141 VGSvcVerbose(4, "Removing directory '%s' returned rc=%Rrc\n", szDir, rc);
142#endif
143 return rc;
144}
145
146
147static int vgsvcGstCtrlSessionHandleFileOpen(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
148{
149 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
150 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
151
152 char szFile[RTPATH_MAX];
153 char szAccess[64];
154 char szDisposition[64];
155 char szSharing[64];
156 uint32_t uCreationMode = 0;
157 uint64_t offOpen = 0;
158 uint32_t uHandle = 0;
159
160 int rc = VbglR3GuestCtrlFileGetOpen(pHostCtx,
161 /* File to open. */
162 szFile, sizeof(szFile),
163 /* Open mode. */
164 szAccess, sizeof(szAccess),
165 /* Disposition. */
166 szDisposition, sizeof(szDisposition),
167 /* Sharing. */
168 szSharing, sizeof(szSharing),
169 /* Creation mode. */
170 &uCreationMode,
171 /* Offset. */
172 &offOpen);
173 VGSvcVerbose(4, "[File %s]: szAccess=%s, szDisposition=%s, szSharing=%s, offOpen=%RU64, rc=%Rrc\n",
174 szFile, szAccess, szDisposition, szSharing, offOpen, rc);
175 if (RT_SUCCESS(rc))
176 {
177 PVBOXSERVICECTRLFILE pFile = (PVBOXSERVICECTRLFILE)RTMemAllocZ(sizeof(VBOXSERVICECTRLFILE));
178 if (pFile)
179 {
180 if (!strlen(szFile))
181 rc = VERR_INVALID_PARAMETER;
182
183 if (RT_SUCCESS(rc))
184 {
185 /** @todo r=bird: Plase, use RTStrCopy for stuff like this! */
186 RTStrPrintf(pFile->szName, sizeof(pFile->szName), "%s", szFile);
187
188 uint64_t fFlags;
189 rc = RTFileModeToFlagsEx(szAccess, szDisposition, NULL /* pszSharing, not used yet */, &fFlags);
190 VGSvcVerbose(4, "[File %s]: Opening with fFlags=0x%x, rc=%Rrc\n", pFile->szName, fFlags, rc);
191
192 if (RT_SUCCESS(rc))
193 rc = RTFileOpen(&pFile->hFile, pFile->szName, fFlags);
194 if ( RT_SUCCESS(rc)
195 && offOpen)
196 {
197 /* Seeking is optional. However, the whole operation
198 * will fail if we don't succeed seeking to the wanted position. */
199 rc = RTFileSeek(pFile->hFile, (int64_t)offOpen, RTFILE_SEEK_BEGIN, NULL /* Current offset */);
200 if (RT_FAILURE(rc))
201 VGSvcError("[File %s]: Seeking to offset %RU64 failed; rc=%Rrc\n", pFile->szName, offOpen, rc);
202 }
203 else if (RT_FAILURE(rc))
204 VGSvcError("[File %s]: Opening failed with rc=%Rrc\n", pFile->szName, rc);
205 }
206
207 if (RT_SUCCESS(rc))
208 {
209 uHandle = VBOX_GUESTCTRL_CONTEXTID_GET_OBJECT(pHostCtx->uContextID);
210 pFile->uHandle = uHandle;
211
212 RTListAppend(&pSession->lstFiles, &pFile->Node);
213
214 VGSvcVerbose(3, "[File %s]: Opened (ID=%RU32)\n", pFile->szName, pFile->uHandle);
215 }
216
217 if (RT_FAILURE(rc))
218 {
219 if (pFile->hFile)
220 RTFileClose(pFile->hFile);
221 RTMemFree(pFile);
222 }
223 }
224 else
225 rc = VERR_NO_MEMORY;
226
227 /* Report back in any case. */
228 int rc2 = VbglR3GuestCtrlFileCbOpen(pHostCtx, rc, uHandle);
229 if (RT_FAILURE(rc2))
230 VGSvcError("[File %s]: Failed to report file open status, rc=%Rrc\n", szFile, rc2);
231 if (RT_SUCCESS(rc))
232 rc = rc2;
233 }
234
235#ifdef DEBUG
236 VGSvcVerbose(4, "Opening file '%s' (open mode='%s', disposition='%s', creation mode=0x%x returned rc=%Rrc\n",
237 szFile, szAccess, szDisposition, uCreationMode, rc);
238#endif
239 return rc;
240}
241
242
243static int vgsvcGstCtrlSessionHandleFileClose(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
244{
245 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
246 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
247
248 PVBOXSERVICECTRLFILE pFile = NULL;
249
250 uint32_t uHandle = 0;
251 int rc = VbglR3GuestCtrlFileGetClose(pHostCtx, &uHandle /* File handle to close */);
252 if (RT_SUCCESS(rc))
253 {
254 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
255 if (pFile)
256 rc = vgsvcGstCtrlSessionFileDestroy(pFile);
257 else
258 rc = VERR_NOT_FOUND;
259
260 /* Report back in any case. */
261 int rc2 = VbglR3GuestCtrlFileCbClose(pHostCtx, rc);
262 if (RT_FAILURE(rc2))
263 VGSvcError("Failed to report file close status, rc=%Rrc\n", rc2);
264 if (RT_SUCCESS(rc))
265 rc = rc2;
266 }
267
268#ifdef DEBUG
269 VGSvcVerbose(4, "Closing file '%s' (handle=%RU32) returned rc=%Rrc\n", pFile ? pFile->szName : "<Not found>", uHandle, rc);
270#endif
271 return rc;
272}
273
274
275static int vgsvcGstCtrlSessionHandleFileRead(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
276 void *pvScratchBuf, size_t cbScratchBuf)
277{
278 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
279 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
280
281 PVBOXSERVICECTRLFILE pFile = NULL;
282
283 uint32_t uHandle = 0;
284 uint32_t cbToRead;
285 int rc = VbglR3GuestCtrlFileGetRead(pHostCtx, &uHandle, &cbToRead);
286 if (RT_SUCCESS(rc))
287 {
288 void *pvDataRead = pvScratchBuf;
289 size_t cbRead = 0;
290
291 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
292 if (pFile)
293 {
294 if (cbToRead)
295 {
296 if (cbToRead > cbScratchBuf)
297 {
298 pvDataRead = RTMemAlloc(cbToRead);
299 if (!pvDataRead)
300 rc = VERR_NO_MEMORY;
301 }
302
303 if (RT_LIKELY(RT_SUCCESS(rc)))
304 rc = RTFileRead(pFile->hFile, pvDataRead, cbToRead, &cbRead);
305 }
306 else
307 rc = VERR_BUFFER_UNDERFLOW;
308 }
309 else
310 rc = VERR_NOT_FOUND;
311
312 /* Report back in any case. */
313 int rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, pvDataRead, (uint32_t)cbRead);
314 if ( cbToRead > cbScratchBuf
315 && pvDataRead)
316 RTMemFree(pvDataRead);
317
318 if (RT_FAILURE(rc2))
319 VGSvcError("Failed to report file read status, rc=%Rrc\n", rc2);
320 if (RT_SUCCESS(rc))
321 rc = rc2;
322 }
323
324#ifdef DEBUG
325 VGSvcVerbose(4, "Reading file '%s' (handle=%RU32) returned rc=%Rrc\n", pFile ? pFile->szName : "<Not found>", uHandle, rc);
326#endif
327 return rc;
328}
329
330
331static int vgsvcGstCtrlSessionHandleFileReadAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
332 void *pvScratchBuf, size_t cbScratchBuf)
333{
334 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
335 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
336
337 PVBOXSERVICECTRLFILE pFile = NULL;
338
339 uint32_t uHandle = 0;
340 uint32_t cbToRead;
341 uint64_t offReadAt;
342 int rc = VbglR3GuestCtrlFileGetReadAt(pHostCtx, &uHandle, &cbToRead, &offReadAt);
343 if (RT_SUCCESS(rc))
344 {
345 void *pvDataRead = pvScratchBuf;
346 size_t cbRead = 0;
347
348 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
349 if (pFile)
350 {
351 if (cbToRead)
352 {
353 if (cbToRead > cbScratchBuf)
354 {
355 pvDataRead = RTMemAlloc(cbToRead);
356 if (!pvDataRead)
357 rc = VERR_NO_MEMORY;
358 }
359
360 if (RT_SUCCESS(rc))
361 rc = RTFileReadAt(pFile->hFile, (RTFOFF)offReadAt, pvDataRead, cbToRead, &cbRead);
362 }
363 else
364 rc = VERR_BUFFER_UNDERFLOW;
365 }
366 else
367 rc = VERR_NOT_FOUND;
368
369 /* Report back in any case. */
370 int rc2 = VbglR3GuestCtrlFileCbRead(pHostCtx, rc, pvDataRead, (uint32_t)cbRead);
371 if ( cbToRead > cbScratchBuf
372 && pvDataRead)
373 RTMemFree(pvDataRead);
374
375 if (RT_FAILURE(rc2))
376 VGSvcError("Failed to report file read status, rc=%Rrc\n", rc2);
377 if (RT_SUCCESS(rc))
378 rc = rc2;
379 }
380
381#ifdef DEBUG
382 VGSvcVerbose(4, "Reading file '%s' at offset (handle=%RU32) returned rc=%Rrc\n",
383 pFile ? pFile->szName : "<Not found>", uHandle, rc);
384#endif
385 return rc;
386}
387
388
389static int vgsvcGstCtrlSessionHandleFileWrite(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
390 void *pvScratchBuf, size_t cbScratchBuf)
391{
392 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
393 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
394 AssertPtrReturn(pvScratchBuf, VERR_INVALID_POINTER);
395 AssertPtrReturn(cbScratchBuf, VERR_INVALID_PARAMETER);
396
397 PVBOXSERVICECTRLFILE pFile = NULL;
398
399 uint32_t uHandle = 0;
400 uint32_t cbToWrite;
401 int rc = VbglR3GuestCtrlFileGetWrite(pHostCtx, &uHandle, pvScratchBuf, (uint32_t)cbScratchBuf, &cbToWrite);
402 if (RT_SUCCESS(rc))
403 {
404 size_t cbWritten = 0;
405 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
406 if (pFile)
407 {
408 rc = RTFileWrite(pFile->hFile, pvScratchBuf, cbToWrite, &cbWritten);
409#ifdef DEBUG
410 VGSvcVerbose(4, "[File %s]: Writing pvScratchBuf=%p, cbToWrite=%RU32, cbWritten=%zu, rc=%Rrc\n",
411 pFile->szName, pvScratchBuf, cbToWrite, cbWritten, rc);
412#endif
413 }
414 else
415 rc = VERR_NOT_FOUND;
416
417 /* Report back in any case. */
418 int rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
419 if (RT_FAILURE(rc2))
420 VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
421 if (RT_SUCCESS(rc))
422 rc = rc2;
423 }
424
425#ifdef DEBUG
426 VGSvcVerbose(4, "Writing file '%s' (handle=%RU32) returned rc=%Rrc\n", pFile ? pFile->szName : "<Not found>", uHandle, rc);
427#endif
428 return rc;
429}
430
431
432static int vgsvcGstCtrlSessionHandleFileWriteAt(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
433 void *pvScratchBuf, size_t cbScratchBuf)
434{
435 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
436 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
437 AssertPtrReturn(pvScratchBuf, VERR_INVALID_POINTER);
438 AssertPtrReturn(cbScratchBuf, VERR_INVALID_PARAMETER);
439
440 PVBOXSERVICECTRLFILE pFile = NULL;
441
442 uint32_t uHandle = 0;
443 uint32_t cbToWrite;
444 uint64_t offWriteAt;
445
446 int rc = VbglR3GuestCtrlFileGetWriteAt(pHostCtx, &uHandle, pvScratchBuf, (uint32_t)cbScratchBuf, &cbToWrite, &offWriteAt);
447 if (RT_SUCCESS(rc))
448 {
449 size_t cbWritten = 0;
450 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
451 if (pFile)
452 {
453 rc = RTFileWriteAt(pFile->hFile, (RTFOFF)offWriteAt, pvScratchBuf, cbToWrite, &cbWritten);
454#ifdef DEBUG
455 VGSvcVerbose(4, "[File %s]: Writing offWriteAt=%RI64, pvScratchBuf=%p, cbToWrite=%RU32, cbWritten=%zu, rc=%Rrc\n",
456 pFile->szName, offWriteAt, pvScratchBuf, cbToWrite, cbWritten, rc);
457#endif
458 }
459 else
460 rc = VERR_NOT_FOUND;
461
462 /* Report back in any case. */
463 int rc2 = VbglR3GuestCtrlFileCbWrite(pHostCtx, rc, (uint32_t)cbWritten);
464 if (RT_FAILURE(rc2))
465 VGSvcError("Failed to report file write status, rc=%Rrc\n", rc2);
466 if (RT_SUCCESS(rc))
467 rc = rc2;
468 }
469
470#ifdef DEBUG
471 VGSvcVerbose(4, "Writing file '%s' at offset (handle=%RU32) returned rc=%Rrc\n",
472 pFile ? pFile->szName : "<Not found>", uHandle, rc);
473#endif
474 return rc;
475}
476
477
478static int vgsvcGstCtrlSessionHandleFileSeek(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
479{
480 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
481 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
482
483 PVBOXSERVICECTRLFILE pFile = NULL;
484
485 uint32_t uHandle = 0;
486 uint32_t uSeekMethod;
487 uint64_t offSeek; /* Will be converted to int64_t. */
488 int rc = VbglR3GuestCtrlFileGetSeek(pHostCtx, &uHandle, &uSeekMethod, &offSeek);
489 if (RT_SUCCESS(rc))
490 {
491 uint64_t offActual = 0;
492 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
493 if (pFile)
494 {
495 unsigned uSeekMethodIprt;
496 switch (uSeekMethod)
497 {
498 case GUEST_FILE_SEEKTYPE_BEGIN:
499 uSeekMethodIprt = RTFILE_SEEK_BEGIN;
500 break;
501
502 case GUEST_FILE_SEEKTYPE_CURRENT:
503 uSeekMethodIprt = RTFILE_SEEK_CURRENT;
504 break;
505
506 case GUEST_FILE_SEEKTYPE_END:
507 uSeekMethodIprt = RTFILE_SEEK_END;
508 break;
509
510 default:
511 rc = VERR_NOT_SUPPORTED;
512 uSeekMethodIprt = RTFILE_SEEK_BEGIN; /* Shut up MSC */
513 break;
514 }
515
516 if (RT_SUCCESS(rc))
517 {
518 rc = RTFileSeek(pFile->hFile, (int64_t)offSeek, uSeekMethodIprt, &offActual);
519#ifdef DEBUG
520 VGSvcVerbose(4, "[File %s]: Seeking to offSeek=%RI64, uSeekMethodIPRT=%RU16, rc=%Rrc\n",
521 pFile->szName, offSeek, uSeekMethodIprt, rc);
522#endif
523 }
524 }
525 else
526 rc = VERR_NOT_FOUND;
527
528 /* Report back in any case. */
529 int rc2 = VbglR3GuestCtrlFileCbSeek(pHostCtx, rc, offActual);
530 if (RT_FAILURE(rc2))
531 VGSvcError("Failed to report file seek status, rc=%Rrc\n", rc2);
532 if (RT_SUCCESS(rc))
533 rc = rc2;
534 }
535
536#ifdef DEBUG
537 VGSvcVerbose(4, "Seeking file '%s' (handle=%RU32) returned rc=%Rrc\n", pFile ? pFile->szName : "<Not found>", uHandle, rc);
538#endif
539 return rc;
540}
541
542
543static int vgsvcGstCtrlSessionHandleFileTell(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
544{
545 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
546 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
547
548 PVBOXSERVICECTRLFILE pFile = NULL;
549
550 uint32_t uHandle = 0;
551 int rc = VbglR3GuestCtrlFileGetTell(pHostCtx, &uHandle);
552 if (RT_SUCCESS(rc))
553 {
554 uint64_t off = 0;
555 pFile = vgsvcGstCtrlSessionFileGetLocked(pSession, uHandle);
556 if (pFile)
557 {
558 off = RTFileTell(pFile->hFile);
559#ifdef DEBUG
560 VGSvcVerbose(4, "[File %s]: Telling off=%RU64\n", pFile->szName, off);
561#endif
562 }
563 else
564 rc = VERR_NOT_FOUND;
565
566 /* Report back in any case. */
567 int rc2 = VbglR3GuestCtrlFileCbTell(pHostCtx, rc, off);
568 if (RT_FAILURE(rc2))
569 VGSvcError("Failed to report file tell status, rc=%Rrc\n", rc2);
570 if (RT_SUCCESS(rc))
571 rc = rc2;
572 }
573
574#ifdef DEBUG
575 VGSvcVerbose(4, "Telling file '%s' (handle=%RU32) returned rc=%Rrc\n", pFile ? pFile->szName : "<Not found>", uHandle, rc);
576#endif
577 return rc;
578}
579
580
581static int vgsvcGstCtrlSessionHandlePathRename(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
582{
583 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
584 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
585
586 char szSource[RTPATH_MAX];
587 char szDest[RTPATH_MAX];
588 uint32_t fFlags = 0;
589
590 int rc = VbglR3GuestCtrlPathGetRename(pHostCtx,
591 szSource, sizeof(szSource),
592 szDest, sizeof(szDest),
593 /* Flags of type PATHRENAME_FLAG_. */
594 &fFlags);
595 if (RT_SUCCESS(rc))
596 {
597 if (fFlags & ~PATHRENAME_FLAG_VALID_MASK)
598 rc = VERR_NOT_SUPPORTED;
599
600 VGSvcVerbose(4, "Renaming '%s' to '%s', fFlags=0x%x, rc=%Rrc\n", szSource, szDest, fFlags, rc);
601
602 if (RT_SUCCESS(rc))
603 {
604/** @todo r=bird: shouldn't you use a different variable here for the IPRT flags??? */
605 if (fFlags & PATHRENAME_FLAG_NO_REPLACE)
606 fFlags |= RTPATHRENAME_FLAGS_NO_REPLACE;
607
608 if (fFlags & PATHRENAME_FLAG_REPLACE)
609 fFlags |= RTPATHRENAME_FLAGS_REPLACE;
610
611 if (fFlags & PATHRENAME_FLAG_NO_SYMLINKS)
612 fFlags |= RTPATHRENAME_FLAGS_NO_SYMLINKS;
613
614 rc = RTPathRename(szSource, szDest, fFlags);
615 }
616
617 /* Report back in any case. */
618 int rc2 = VbglR3GuestCtrlMsgReply(pHostCtx, rc);
619 if (RT_FAILURE(rc2))
620 VGSvcError("Failed to report renaming status, rc=%Rrc\n", rc2);
621 if (RT_SUCCESS(rc))
622 rc = rc2;
623 }
624
625#ifdef DEBUG
626 VGSvcVerbose(4, "Renaming '%s' to '%s' returned rc=%Rrc\n", szSource, szDest, rc);
627#endif
628 return rc;
629}
630
631
632/**
633 * Handles getting the user's documents directory.
634 *
635 * @returns VBox status code.
636 * @param pSession Guest session.
637 * @param pHostCtx Host context.
638 */
639static int vgsvcGstCtrlSessionHandlePathUserDocuments(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
640{
641 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
642 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
643
644 int rc = VbglR3GuestCtrlPathGetUserDocuments(pHostCtx);
645 if (RT_SUCCESS(rc))
646 {
647 char szPath[RTPATH_MAX];
648 rc = RTPathUserDocuments(szPath, sizeof(szPath));
649
650#ifdef DEBUG
651 VGSvcVerbose(2, "User documents is '%s', rc=%Rrc\n", szPath, rc);
652#endif
653 /* Report back in any case. */
654 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */,
655 szPath, (uint32_t)strlen(szPath) + 1 /* Include terminating zero */);
656 if (RT_FAILURE(rc2))
657 VGSvcError("Failed to report user documents, rc=%Rrc\n", rc2);
658 if (RT_SUCCESS(rc))
659 rc = rc2;
660 }
661
662 return rc;
663}
664
665
666/**
667 * Handles getting the user's home directory.
668 *
669 * @returns VBox status code.
670 * @param pSession Guest session.
671 * @param pHostCtx Host context.
672 */
673static int vgsvcGstCtrlSessionHandlePathUserHome(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
674{
675 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
676 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
677
678 int rc = VbglR3GuestCtrlPathGetUserHome(pHostCtx);
679 if (RT_SUCCESS(rc))
680 {
681 char szPath[RTPATH_MAX];
682 rc = RTPathUserHome(szPath, sizeof(szPath));
683
684#ifdef DEBUG
685 VGSvcVerbose(2, "User home is '%s', rc=%Rrc\n", szPath, rc);
686#endif
687 /* Report back in any case. */
688 int rc2 = VbglR3GuestCtrlMsgReplyEx(pHostCtx, rc, 0 /* Type */,
689 szPath, (uint32_t)strlen(szPath) + 1 /* Include terminating zero */);
690 if (RT_FAILURE(rc2))
691 VGSvcError("Failed to report user home, rc=%Rrc\n", rc2);
692 if (RT_SUCCESS(rc))
693 rc = rc2;
694 }
695
696 return rc;
697}
698
699
700/**
701 * Handles starting a guest processes.
702 *
703 * @returns VBox status code.
704 * @param pSession Guest session.
705 * @param pHostCtx Host context.
706 */
707static int vgsvcGstCtrlSessionHandleProcExec(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
708{
709 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
710 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
711
712 int rc = VINF_SUCCESS;
713 bool fStartAllowed = false; /* Flag indicating whether starting a process is allowed or not. */
714
715 switch (pHostCtx->uProtocol)
716 {
717 case 1: /* Guest Additions < 4.3. */
718 if (pHostCtx->uNumParms != 11)
719 rc = VERR_NOT_SUPPORTED;
720 break;
721
722 case 2: /* Guest Additions >= 4.3. */
723 if (pHostCtx->uNumParms != 12)
724 rc = VERR_NOT_SUPPORTED;
725 break;
726
727 default:
728 rc = VERR_NOT_SUPPORTED;
729 break;
730 }
731
732 if (RT_SUCCESS(rc))
733 {
734 VBOXSERVICECTRLPROCSTARTUPINFO startupInfo;
735 RT_ZERO(startupInfo);
736
737 /* Initialize maximum environment block size -- needed as input
738 * parameter to retrieve the stuff from the host. On output this then
739 * will contain the actual block size. */
740 startupInfo.cbEnv = sizeof(startupInfo.szEnv);
741
742 rc = VbglR3GuestCtrlProcGetStart(pHostCtx,
743 /* Command */
744 startupInfo.szCmd, sizeof(startupInfo.szCmd),
745 /* Flags */
746 &startupInfo.uFlags,
747 /* Arguments */
748 startupInfo.szArgs, sizeof(startupInfo.szArgs), &startupInfo.uNumArgs,
749 /* Environment */
750 startupInfo.szEnv, &startupInfo.cbEnv, &startupInfo.uNumEnvVars,
751 /* Credentials; for hosts with VBox < 4.3 (protocol version 1).
752 * For protocl v2 and up the credentials are part of the session
753 * opening call. */
754 startupInfo.szUser, sizeof(startupInfo.szUser),
755 startupInfo.szPassword, sizeof(startupInfo.szPassword),
756 /* Timeout (in ms) */
757 &startupInfo.uTimeLimitMS,
758 /* Process priority */
759 &startupInfo.uPriority,
760 /* Process affinity */
761 startupInfo.uAffinity, sizeof(startupInfo.uAffinity), &startupInfo.uNumAffinity);
762 if (RT_SUCCESS(rc))
763 {
764 VGSvcVerbose(3, "Request to start process szCmd=%s, fFlags=0x%x, szArgs=%s, szEnv=%s, uTimeout=%RU32\n",
765 startupInfo.szCmd, startupInfo.uFlags,
766 startupInfo.uNumArgs ? startupInfo.szArgs : "<None>",
767 startupInfo.uNumEnvVars ? startupInfo.szEnv : "<None>",
768 startupInfo.uTimeLimitMS);
769
770 rc = VGSvcGstCtrlSessionProcessStartAllowed(pSession, &fStartAllowed);
771 if (RT_SUCCESS(rc))
772 {
773 if (fStartAllowed)
774 rc = VGSvcGstCtrlProcessStart(pSession, &startupInfo, pHostCtx->uContextID);
775 else
776 rc = VERR_MAX_PROCS_REACHED; /* Maximum number of processes reached. */
777 }
778 }
779 }
780
781 /* In case of an error we need to notify the host to not wait forever for our response. */
782 if (RT_FAILURE(rc))
783 {
784 VGSvcError("Starting process failed with rc=%Rrc, protocol=%RU32, parameters=%RU32\n",
785 rc, pHostCtx->uProtocol, pHostCtx->uNumParms);
786
787 /* Don't report back if we didn't supply sufficient buffer for getting
788 * the actual command -- we don't have the matching context ID. */
789 if (rc != VERR_TOO_MUCH_DATA)
790 {
791 /*
792 * Note: The context ID can be 0 because we mabye weren't able to fetch the command
793 * from the host. The host in case has to deal with that!
794 */
795 int rc2 = VbglR3GuestCtrlProcCbStatus(pHostCtx, 0 /* PID, invalid */,
796 PROC_STS_ERROR, rc,
797 NULL /* pvData */, 0 /* cbData */);
798 if (RT_FAILURE(rc2))
799 VGSvcError("Error sending start process status to host, rc=%Rrc\n", rc2);
800 }
801 }
802
803 return rc;
804}
805
806
807/**
808 * Sends stdin input to a specific guest process.
809 *
810 * @returns VBox status code.
811 * @param pSession The session which is in charge.
812 * @param pHostCtx The host context to use.
813 * @param pvScratchBuf The scratch buffer.
814 * @param cbScratchBuf The scratch buffer size for retrieving the input
815 * data.
816 */
817static int vgsvcGstCtrlSessionHandleProcInput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
818 void *pvScratchBuf, size_t cbScratchBuf)
819{
820 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
821 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
822 AssertPtrReturn(cbScratchBuf, VERR_INVALID_PARAMETER);
823 AssertPtrReturn(pvScratchBuf, VERR_INVALID_POINTER);
824
825 uint32_t uPID;
826 uint32_t fFlags;
827 uint32_t cbSize;
828
829#if 0 /* unused */
830 uint32_t uStatus = INPUT_STS_UNDEFINED; /* Status sent back to the host. */
831 uint32_t cbWritten = 0; /* Number of bytes written to the guest. */
832#endif
833
834 /*
835 * Ask the host for the input data.
836 */
837 int rc = VbglR3GuestCtrlProcGetInput(pHostCtx, &uPID, &fFlags,
838 pvScratchBuf, (uint32_t)cbScratchBuf, &cbSize);
839 if (RT_FAILURE(rc))
840 VGSvcError("Failed to retrieve process input command for PID=%RU32, rc=%Rrc\n", uPID, rc);
841 else if (cbSize > cbScratchBuf)
842 {
843 VGSvcError("Too much process input received, rejecting: uPID=%RU32, cbSize=%RU32, cbScratchBuf=%RU32\n",
844 uPID, cbSize, cbScratchBuf);
845 rc = VERR_TOO_MUCH_DATA;
846 }
847 else
848 {
849 /*
850 * Is this the last input block we need to deliver? Then let the pipe know ...
851 */
852 bool fPendingClose = false;
853 if (fFlags & INPUT_FLAG_EOF)
854 {
855 fPendingClose = true;
856#ifdef DEBUG
857 VGSvcVerbose(4, "Got last process input block for PID=%RU32 (%RU32 bytes) ...\n", uPID, cbSize);
858#endif
859 }
860
861 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
862 if (pProcess)
863 {
864 rc = VGSvcGstCtrlProcessHandleInput(pProcess, pHostCtx, fPendingClose, pvScratchBuf, cbSize);
865 if (RT_FAILURE(rc))
866 VGSvcError("Error handling input command for PID=%RU32, rc=%Rrc\n", uPID, rc);
867 VGSvcGstCtrlProcessRelease(pProcess);
868 }
869 else
870 rc = VERR_NOT_FOUND;
871 }
872
873#ifdef DEBUG
874 VGSvcVerbose(4, "Setting input for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
875#endif
876 return rc;
877}
878
879
880/**
881 * Gets stdout/stderr output of a specific guest process.
882 *
883 * @returns VBox status code.
884 * @param pSession The session which is in charge.
885 * @param pHostCtx The host context to use.
886 */
887static int vgsvcGstCtrlSessionHandleProcOutput(PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
888{
889 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
890 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
891
892 uint32_t uPID;
893 uint32_t uHandleID;
894 uint32_t fFlags;
895
896 int rc = VbglR3GuestCtrlProcGetOutput(pHostCtx, &uPID, &uHandleID, &fFlags);
897#ifdef DEBUG_andy
898 VGSvcVerbose(4, "Getting output for PID=%RU32, CID=%RU32, uHandleID=%RU32, fFlags=%RU32\n",
899 uPID, pHostCtx->uContextID, uHandleID, fFlags);
900#endif
901 if (RT_SUCCESS(rc))
902 {
903 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
904 if (pProcess)
905 {
906 rc = VGSvcGstCtrlProcessHandleOutput(pProcess, pHostCtx, uHandleID, _64K /* cbToRead */, fFlags);
907 if (RT_FAILURE(rc))
908 VGSvcError("Error getting output for PID=%RU32, rc=%Rrc\n", uPID, rc);
909 VGSvcGstCtrlProcessRelease(pProcess);
910 }
911 else
912 rc = VERR_NOT_FOUND;
913 }
914
915#ifdef DEBUG_andy
916 VGSvcVerbose(4, "Getting output for PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
917#endif
918 return rc;
919}
920
921
922/**
923 * Tells a guest process to terminate.
924 *
925 * @returns VBox status code.
926 * @param pSession The session which is in charge.
927 * @param pHostCtx The host context to use.
928 */
929static int vgsvcGstCtrlSessionHandleProcTerminate(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
930{
931 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
932 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
933
934 uint32_t uPID;
935 int rc = VbglR3GuestCtrlProcGetTerminate(pHostCtx, &uPID);
936 if (RT_SUCCESS(rc))
937 {
938 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
939 if (pProcess)
940 {
941 rc = VGSvcGstCtrlProcessHandleTerm(pProcess);
942
943 VGSvcGstCtrlProcessRelease(pProcess);
944 }
945 else
946 rc = VERR_NOT_FOUND;
947 }
948
949#ifdef DEBUG_andy
950 VGSvcVerbose(4, "Terminating PID=%RU32 resulted in rc=%Rrc\n", uPID, rc);
951#endif
952 return rc;
953}
954
955
956static int vgsvcGstCtrlSessionHandleProcWaitFor(const PVBOXSERVICECTRLSESSION pSession, PVBGLR3GUESTCTRLCMDCTX pHostCtx)
957{
958 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
959 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
960
961 uint32_t uPID;
962 uint32_t uWaitFlags; uint32_t uTimeoutMS;
963
964 int rc = VbglR3GuestCtrlProcGetWaitFor(pHostCtx, &uPID, &uWaitFlags, &uTimeoutMS);
965 if (RT_SUCCESS(rc))
966 {
967 PVBOXSERVICECTRLPROCESS pProcess = VGSvcGstCtrlSessionRetainProcess(pSession, uPID);
968 if (pProcess)
969 {
970 rc = VERR_NOT_IMPLEMENTED; /** @todo */
971 VGSvcGstCtrlProcessRelease(pProcess);
972 }
973 else
974 rc = VERR_NOT_FOUND;
975 }
976
977 return rc;
978}
979
980
981int VGSvcGstCtrlSessionHandler(PVBOXSERVICECTRLSESSION pSession, uint32_t uMsg, PVBGLR3GUESTCTRLCMDCTX pHostCtx,
982 void *pvScratchBuf, size_t cbScratchBuf, volatile bool *pfShutdown)
983{
984 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
985 AssertPtrReturn(pHostCtx, VERR_INVALID_POINTER);
986 AssertPtrReturn(pvScratchBuf, VERR_INVALID_POINTER);
987 AssertPtrReturn(pfShutdown, VERR_INVALID_POINTER);
988
989
990 /*
991 * Only anonymous sessions (that is, sessions which run with local
992 * service privileges) or spawned session processes can do certain
993 * operations.
994 */
995 bool const fImpersonated = RT_BOOL(pSession->fFlags & ( VBOXSERVICECTRLSESSION_FLAG_SPAWN
996 | VBOXSERVICECTRLSESSION_FLAG_ANONYMOUS));
997 int rc = VERR_NOT_SUPPORTED; /* Play safe by default. */
998
999 switch (uMsg)
1000 {
1001 case HOST_SESSION_CLOSE:
1002 /* Shutdown (this spawn). */
1003 rc = VGSvcGstCtrlSessionClose(pSession);
1004 *pfShutdown = true; /* Shutdown in any case. */
1005 break;
1006
1007 case HOST_DIR_REMOVE:
1008 if (fImpersonated)
1009 rc = vgsvcGstCtrlSessionHandleDirRemove(pSession, pHostCtx);
1010 break;
1011
1012 case HOST_EXEC_CMD:
1013 rc = vgsvcGstCtrlSessionHandleProcExec(pSession, pHostCtx);
1014 break;
1015
1016 case HOST_EXEC_SET_INPUT:
1017 rc = vgsvcGstCtrlSessionHandleProcInput(pSession, pHostCtx, pvScratchBuf, cbScratchBuf);
1018 break;
1019
1020 case HOST_EXEC_GET_OUTPUT:
1021 rc = vgsvcGstCtrlSessionHandleProcOutput(pSession, pHostCtx);
1022 break;
1023
1024 case HOST_EXEC_TERMINATE:
1025 rc = vgsvcGstCtrlSessionHandleProcTerminate(pSession, pHostCtx);
1026 break;
1027
1028 case HOST_EXEC_WAIT_FOR:
1029 rc = vgsvcGstCtrlSessionHandleProcWaitFor(pSession, pHostCtx);
1030 break;
1031
1032 case HOST_FILE_OPEN:
1033 if (fImpersonated)
1034 rc = vgsvcGstCtrlSessionHandleFileOpen(pSession, pHostCtx);
1035 break;
1036
1037 case HOST_FILE_CLOSE:
1038 if (fImpersonated)
1039 rc = vgsvcGstCtrlSessionHandleFileClose(pSession, pHostCtx);
1040 break;
1041
1042 case HOST_FILE_READ:
1043 if (fImpersonated)
1044 rc = vgsvcGstCtrlSessionHandleFileRead(pSession, pHostCtx, pvScratchBuf, cbScratchBuf);
1045 break;
1046
1047 case HOST_FILE_READ_AT:
1048 if (fImpersonated)
1049 rc = vgsvcGstCtrlSessionHandleFileReadAt(pSession, pHostCtx, pvScratchBuf, cbScratchBuf);
1050 break;
1051
1052 case HOST_FILE_WRITE:
1053 if (fImpersonated)
1054 rc = vgsvcGstCtrlSessionHandleFileWrite(pSession, pHostCtx, pvScratchBuf, cbScratchBuf);
1055 break;
1056
1057 case HOST_FILE_WRITE_AT:
1058 if (fImpersonated)
1059 rc = vgsvcGstCtrlSessionHandleFileWriteAt(pSession, pHostCtx, pvScratchBuf, cbScratchBuf);
1060 break;
1061
1062 case HOST_FILE_SEEK:
1063 if (fImpersonated)
1064 rc = vgsvcGstCtrlSessionHandleFileSeek(pSession, pHostCtx);
1065 break;
1066
1067 case HOST_FILE_TELL:
1068 if (fImpersonated)
1069 rc = vgsvcGstCtrlSessionHandleFileTell(pSession, pHostCtx);
1070 break;
1071
1072 case HOST_PATH_RENAME:
1073 if (fImpersonated)
1074 rc = vgsvcGstCtrlSessionHandlePathRename(pSession, pHostCtx);
1075 break;
1076
1077 case HOST_PATH_USER_DOCUMENTS:
1078 if (fImpersonated)
1079 rc = vgsvcGstCtrlSessionHandlePathUserDocuments(pSession, pHostCtx);
1080 break;
1081
1082 case HOST_PATH_USER_HOME:
1083 if (fImpersonated)
1084 rc = vgsvcGstCtrlSessionHandlePathUserHome(pSession, pHostCtx);
1085 break;
1086
1087 default: /* Not supported, see next code block. */
1088 break;
1089 }
1090
1091 if (rc == VERR_NOT_SUPPORTED)
1092 {
1093 VGSvcVerbose(3, "Unsupported message (uMsg=%RU32, cParms=%RU32) from host, skipping\n", uMsg, pHostCtx->uNumParms);
1094
1095 /* Tell the host service to skip the message. */
1096 VbglR3GuestCtrlMsgSkip(pHostCtx->uClientID);
1097
1098 rc = VINF_SUCCESS;
1099 }
1100 /* Note: Other replies must be reported to the host service by the appropriate command handlers above. */
1101
1102 if (RT_FAILURE(rc))
1103 VGSvcError("Error while handling message (uMsg=%RU32, cParms=%RU32), rc=%Rrc\n", uMsg, pHostCtx->uNumParms, rc);
1104
1105 return rc;
1106}
1107
1108
1109/**
1110 * Thread main routine for a spawned guest session process.
1111 * This thread runs in the main executable to control the spawned session process.
1112 *
1113 * @returns VBox status code.
1114 * @param hThreadSelf Thread handle.
1115 * @param pvUser Pointer to a VBOXSERVICECTRLSESSIONTHREAD structure.
1116 *
1117 */
1118static DECLCALLBACK(int) vgsvcGstCtrlSessionThread(RTTHREAD hThreadSelf, void *pvUser)
1119{
1120 PVBOXSERVICECTRLSESSIONTHREAD pThread = (PVBOXSERVICECTRLSESSIONTHREAD)pvUser;
1121 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
1122
1123 uint32_t uSessionID = pThread->StartupInfo.uSessionID;
1124
1125 uint32_t uClientID;
1126 int rc = VbglR3GuestCtrlConnect(&uClientID);
1127 if (RT_SUCCESS(rc))
1128 {
1129 VGSvcVerbose(3, "Session ID=%RU32 thread running, client ID=%RU32\n", uSessionID, uClientID);
1130
1131 /* The session thread is not interested in receiving any commands;
1132 * tell the host service. */
1133 rc = VbglR3GuestCtrlMsgFilterSet(uClientID, 0 /* Skip all */, 0 /* Filter mask to add */, 0 /* Filter mask to remove */);
1134 if (RT_FAILURE(rc))
1135 {
1136 VGSvcError("Unable to set message filter, rc=%Rrc\n", rc);
1137 /* Non-critical. */
1138 rc = VINF_SUCCESS;
1139 }
1140 }
1141 else
1142 VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
1143
1144 if (RT_FAILURE(rc))
1145 pThread->fShutdown = true;
1146
1147 /* Let caller know that we're done initializing, regardless of the result. */
1148 int rc2 = RTThreadUserSignal(hThreadSelf);
1149 AssertRC(rc2);
1150
1151 if (RT_FAILURE(rc))
1152 return rc;
1153
1154 bool fProcessAlive = true;
1155 RTPROCSTATUS ProcessStatus;
1156 RT_ZERO(ProcessStatus);
1157
1158 int rcWait;
1159 uint32_t uTimeoutsMS = 30 * 1000; /** @todo Make this configurable. Later. */
1160 uint64_t u64TimeoutStart = 0;
1161
1162 for (;;)
1163 {
1164 rcWait = RTProcWaitNoResume(pThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, &ProcessStatus);
1165 if (RT_UNLIKELY(rcWait == VERR_INTERRUPTED))
1166 continue;
1167
1168 if ( rcWait == VINF_SUCCESS
1169 || rcWait == VERR_PROCESS_NOT_FOUND)
1170 {
1171 fProcessAlive = false;
1172 break;
1173 }
1174 AssertMsgBreak(rcWait == VERR_PROCESS_RUNNING,
1175 ("Got unexpected rc=%Rrc while waiting for session process termination\n", rcWait));
1176
1177 if (ASMAtomicReadBool(&pThread->fShutdown))
1178 {
1179 if (!u64TimeoutStart)
1180 {
1181 VGSvcVerbose(3, "Notifying guest session process (PID=%RU32, session ID=%RU32) ...\n",
1182 pThread->hProcess, uSessionID);
1183
1184 VBGLR3GUESTCTRLCMDCTX hostCtx =
1185 {
1186 /* .idClient = */ uClientID,
1187 /* .idContext = */ VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(uSessionID),
1188 /* .uProtocol = */ pThread->StartupInfo.uProtocol,
1189 /* .cParams = */ 2
1190 };
1191 rc = VbglR3GuestCtrlSessionClose(&hostCtx, 0 /* fFlags */);
1192 if (RT_FAILURE(rc))
1193 {
1194 VGSvcError("Unable to notify guest session process (PID=%RU32, session ID=%RU32), rc=%Rrc\n",
1195 pThread->hProcess, uSessionID, rc);
1196
1197 if (rc == VERR_NOT_SUPPORTED)
1198 {
1199 /* Terminate guest session process in case it's not supported by a too old host. */
1200 rc = RTProcTerminate(pThread->hProcess);
1201 VGSvcVerbose(3, "Terminating guest session process (PID=%RU32) ended with rc=%Rrc\n",
1202 pThread->hProcess, rc);
1203 }
1204 break;
1205 }
1206
1207 VGSvcVerbose(3, "Guest session ID=%RU32 thread was asked to terminate, waiting for session process to exit (%RU32ms timeout) ...\n",
1208 uSessionID, uTimeoutsMS);
1209 u64TimeoutStart = RTTimeMilliTS();
1210 continue; /* Don't waste time on waiting. */
1211 }
1212 if (RTTimeMilliTS() - u64TimeoutStart > uTimeoutsMS)
1213 {
1214 VGSvcVerbose(3, "Guest session ID=%RU32 process did not shut down within time\n", uSessionID);
1215 break;
1216 }
1217 }
1218
1219 RTThreadSleep(100); /* Wait a bit. */
1220 }
1221
1222 if (!fProcessAlive)
1223 {
1224 VGSvcVerbose(2, "Guest session process (ID=%RU32) terminated with rc=%Rrc, reason=%d, status=%d\n",
1225 uSessionID, rcWait, ProcessStatus.enmReason, ProcessStatus.iStatus);
1226 if (ProcessStatus.iStatus == RTEXITCODE_INIT)
1227 {
1228 VGSvcError("Guest session process (ID=%RU32) failed to initialize. Here some hints:\n", uSessionID);
1229 VGSvcError("- Is logging enabled and the output directory is read-only by the guest session user?\n");
1230 /** @todo Add more here. */
1231 }
1232 }
1233
1234 uint32_t uSessionStatus = GUEST_SESSION_NOTIFYTYPE_UNDEFINED;
1235 uint32_t uSessionRc = VINF_SUCCESS; /** uint32_t vs. int. */
1236
1237 if (fProcessAlive)
1238 {
1239 for (int i = 0; i < 3; i++)
1240 {
1241 VGSvcVerbose(2, "Guest session ID=%RU32 process still alive, killing attempt %d/3\n", uSessionID, i + 1);
1242
1243 rc = RTProcTerminate(pThread->hProcess);
1244 if (RT_SUCCESS(rc))
1245 break;
1246 /** @todo r=bird: What's the point of sleeping 3 second after the last attempt? */
1247 RTThreadSleep(3000);
1248 }
1249
1250 VGSvcVerbose(2, "Guest session ID=%RU32 process termination resulted in rc=%Rrc\n", uSessionID, rc);
1251
1252 uSessionStatus = RT_SUCCESS(rc) ? GUEST_SESSION_NOTIFYTYPE_TOK : GUEST_SESSION_NOTIFYTYPE_TOA;
1253 }
1254 else if (RT_SUCCESS(rcWait))
1255 {
1256 switch (ProcessStatus.enmReason)
1257 {
1258 case RTPROCEXITREASON_NORMAL:
1259 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
1260 break;
1261
1262 case RTPROCEXITREASON_ABEND:
1263 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
1264 break;
1265
1266 case RTPROCEXITREASON_SIGNAL:
1267 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TES;
1268 break;
1269
1270 default:
1271 AssertMsgFailed(("Unhandled process termination reason (%d)\n", ProcessStatus.enmReason));
1272 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEA;
1273 break;
1274 }
1275 }
1276 else
1277 {
1278 /* If we didn't find the guest process anymore, just assume it
1279 * terminated normally. */
1280 uSessionStatus = GUEST_SESSION_NOTIFYTYPE_TEN;
1281 }
1282
1283 VGSvcVerbose(3, "Guest session ID=%RU32 thread ended with sessionStatus=%RU32, sessionRc=%Rrc\n",
1284 uSessionID, uSessionStatus, uSessionRc);
1285
1286 /* Report final status. */
1287 Assert(uSessionStatus != GUEST_SESSION_NOTIFYTYPE_UNDEFINED);
1288 VBGLR3GUESTCTRLCMDCTX ctx = { uClientID, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(uSessionID) };
1289 rc2 = VbglR3GuestCtrlSessionNotify(&ctx, uSessionStatus, uSessionRc);
1290 if (RT_FAILURE(rc2))
1291 VGSvcError("Reporting session ID=%RU32 final status failed with rc=%Rrc\n", uSessionID, rc2);
1292
1293 VbglR3GuestCtrlDisconnect(uClientID);
1294
1295 VGSvcVerbose(3, "Session ID=%RU32 thread ended with rc=%Rrc\n", uSessionID, rc);
1296 return rc;
1297}
1298
1299
1300static RTEXITCODE vgsvcGstCtrlSessionSpawnWorker(PVBOXSERVICECTRLSESSION pSession)
1301{
1302 AssertPtrReturn(pSession, RTEXITCODE_FAILURE);
1303
1304 bool fSessionFilter = true;
1305
1306 VGSvcVerbose(0, "Hi, this is guest session ID=%RU32\n", pSession->StartupInfo.uSessionID);
1307
1308 uint32_t uClientID;
1309 int rc = VbglR3GuestCtrlConnect(&uClientID);
1310 if (RT_SUCCESS(rc))
1311 {
1312 /* Set session filter. This prevents the guest control
1313 * host service to send messages which belong to another
1314 * session we don't want to handle. */
1315 uint32_t uFilterAdd = VBOX_GUESTCTRL_FILTER_BY_SESSION(pSession->StartupInfo.uSessionID);
1316 rc = VbglR3GuestCtrlMsgFilterSet(uClientID,
1317 VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID),
1318 uFilterAdd, 0 /* Filter remove */);
1319 VGSvcVerbose(3, "Setting message filterAdd=0x%x returned %Rrc\n", uFilterAdd, rc);
1320
1321 if ( RT_FAILURE(rc)
1322 && rc == VERR_NOT_SUPPORTED)
1323 {
1324 /* No session filter available. Skip. */
1325 fSessionFilter = false;
1326
1327 rc = VINF_SUCCESS;
1328 }
1329
1330 VGSvcVerbose(1, "Using client ID=%RU32\n", uClientID);
1331 }
1332 else
1333 VGSvcError("Error connecting to guest control service, rc=%Rrc\n", rc);
1334
1335 /* Report started status. */
1336 VBGLR3GUESTCTRLCMDCTX ctx = { uClientID, VBOX_GUESTCTRL_CONTEXTID_MAKE_SESSION(pSession->StartupInfo.uSessionID) };
1337 int rc2 = VbglR3GuestCtrlSessionNotify(&ctx, GUEST_SESSION_NOTIFYTYPE_STARTED, VINF_SUCCESS);
1338 if (RT_FAILURE(rc2))
1339 {
1340 VGSvcError("Reporting session ID=%RU32 started status failed with rc=%Rrc\n", pSession->StartupInfo.uSessionID, rc2);
1341
1342 /*
1343 * If session status cannot be posted to the host for
1344 * some reason, bail out.
1345 */
1346 if (RT_SUCCESS(rc))
1347 rc = rc2;
1348 }
1349
1350 /* Allocate a scratch buffer for commands which also send
1351 * payload data with them. */
1352 uint32_t cbScratchBuf = _64K; /** @todo Make buffer size configurable via guest properties/argv! */
1353 AssertReturn(RT_IS_POWER_OF_TWO(cbScratchBuf), RTEXITCODE_FAILURE);
1354 uint8_t *pvScratchBuf = NULL;
1355
1356 if (RT_SUCCESS(rc))
1357 {
1358 pvScratchBuf = (uint8_t*)RTMemAlloc(cbScratchBuf);
1359 if (!pvScratchBuf)
1360 rc = VERR_NO_MEMORY;
1361 }
1362
1363 if (RT_SUCCESS(rc))
1364 {
1365 bool fShutdown = false;
1366
1367 VBGLR3GUESTCTRLCMDCTX ctxHost = { uClientID, 0 /* Context ID */, pSession->StartupInfo.uProtocol };
1368 for (;;)
1369 {
1370 VGSvcVerbose(3, "Waiting for host msg ...\n");
1371 uint32_t uMsg = 0;
1372 uint32_t cParms = 0;
1373 rc = VbglR3GuestCtrlMsgWaitFor(uClientID, &uMsg, &cParms);
1374 if (rc == VERR_TOO_MUCH_DATA)
1375 {
1376#ifdef DEBUG
1377 VGSvcVerbose(4, "Message requires %RU32 parameters, but only 2 supplied -- retrying request (no error!)...\n",
1378 cParms);
1379#endif
1380 rc = VINF_SUCCESS; /* Try to get "real" message in next block below. */
1381 }
1382 else if (RT_FAILURE(rc))
1383 VGSvcVerbose(3, "Getting host message failed with %Rrc\n", rc); /* VERR_GEN_IO_FAILURE seems to be normal if ran into timeout. */
1384 if (RT_SUCCESS(rc))
1385 {
1386 VGSvcVerbose(4, "Msg=%RU32 (%RU32 parms) retrieved\n", uMsg, cParms);
1387
1388 /* Set number of parameters for current host context. */
1389 ctxHost.uNumParms = cParms;
1390
1391 /* ... and pass it on to the session handler. */
1392 rc = VGSvcGstCtrlSessionHandler(pSession, uMsg, &ctxHost, pvScratchBuf, cbScratchBuf, &fShutdown);
1393 }
1394
1395 if (fShutdown)
1396 break;
1397
1398 /* Let others run ... */
1399 RTThreadYield();
1400 }
1401 }
1402
1403 VGSvcVerbose(0, "Session %RU32 ended\n", pSession->StartupInfo.uSessionID);
1404
1405 if (pvScratchBuf)
1406 RTMemFree(pvScratchBuf);
1407
1408 if (uClientID)
1409 {
1410 VGSvcVerbose(3, "Disconnecting client ID=%RU32 ...\n", uClientID);
1411 VbglR3GuestCtrlDisconnect(uClientID);
1412 }
1413
1414 VGSvcVerbose(3, "Session worker returned with rc=%Rrc\n", rc);
1415 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1416}
1417
1418
1419/**
1420 * Finds a (formerly) started guest process given by its PID and increases its
1421 * reference count.
1422 *
1423 * Must be decreased by the caller with VGSvcGstCtrlProcessRelease().
1424 *
1425 * @returns Guest process if found, otherwise NULL.
1426 * @param pSession Pointer to guest session where to search process in.
1427 * @param uPID PID to search for.
1428 *
1429 * @note This does *not lock the process!
1430 */
1431PVBOXSERVICECTRLPROCESS VGSvcGstCtrlSessionRetainProcess(PVBOXSERVICECTRLSESSION pSession, uint32_t uPID)
1432{
1433 AssertPtrReturn(pSession, NULL);
1434
1435 PVBOXSERVICECTRLPROCESS pProcess = NULL;
1436 int rc = RTCritSectEnter(&pSession->CritSect);
1437 if (RT_SUCCESS(rc))
1438 {
1439 PVBOXSERVICECTRLPROCESS pCurProcess;
1440 RTListForEach(&pSession->lstProcesses, pCurProcess, VBOXSERVICECTRLPROCESS, Node)
1441 {
1442 if (pCurProcess->uPID == uPID)
1443 {
1444 rc = RTCritSectEnter(&pCurProcess->CritSect);
1445 if (RT_SUCCESS(rc))
1446 {
1447 pCurProcess->cRefs++;
1448 rc = RTCritSectLeave(&pCurProcess->CritSect);
1449 AssertRC(rc);
1450 }
1451
1452 if (RT_SUCCESS(rc))
1453 pProcess = pCurProcess;
1454 break;
1455 }
1456 }
1457
1458 rc = RTCritSectLeave(&pSession->CritSect);
1459 AssertRC(rc);
1460 }
1461
1462 return pProcess;
1463}
1464
1465
1466int VGSvcGstCtrlSessionClose(PVBOXSERVICECTRLSESSION pSession)
1467{
1468 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1469
1470 VGSvcVerbose(0, "Session %RU32 is about to close ...\n", pSession->StartupInfo.uSessionID);
1471
1472 int rc = RTCritSectEnter(&pSession->CritSect);
1473 if (RT_SUCCESS(rc))
1474 {
1475 /*
1476 * Close all guest processes.
1477 */
1478 VGSvcVerbose(0, "Stopping all guest processes ...\n");
1479
1480 /* Signal all guest processes in the active list that we want to shutdown. */
1481 size_t cProcesses = 0;
1482 PVBOXSERVICECTRLPROCESS pProcess;
1483 RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
1484 {
1485 VGSvcGstCtrlProcessStop(pProcess);
1486 cProcesses++;
1487 }
1488
1489 VGSvcVerbose(1, "%zu guest processes were signalled to stop\n", cProcesses);
1490
1491 /* Wait for all active threads to shutdown and destroy the active thread list. */
1492 pProcess = RTListGetFirst(&pSession->lstProcesses, VBOXSERVICECTRLPROCESS, Node);
1493 while (pProcess)
1494 {
1495 PVBOXSERVICECTRLPROCESS pNext = RTListNodeGetNext(&pProcess->Node, VBOXSERVICECTRLPROCESS, Node);
1496 bool fLast = RTListNodeIsLast(&pSession->lstProcesses, &pProcess->Node);
1497
1498 int rc2 = RTCritSectLeave(&pSession->CritSect);
1499 AssertRC(rc2);
1500
1501 rc2 = VGSvcGstCtrlProcessWait(pProcess, 30 * 1000 /* Wait 30 seconds max. */, NULL /* rc */);
1502
1503 int rc3 = RTCritSectEnter(&pSession->CritSect);
1504 AssertRC(rc3);
1505
1506 if (RT_SUCCESS(rc2))
1507 VGSvcGstCtrlProcessFree(pProcess);
1508
1509 if (fLast)
1510 break;
1511
1512 pProcess = pNext;
1513 }
1514
1515#ifdef DEBUG
1516 pProcess = RTListGetFirst(&pSession->lstProcesses, VBOXSERVICECTRLPROCESS, Node);
1517 while (pProcess)
1518 {
1519 PVBOXSERVICECTRLPROCESS pNext = RTListNodeGetNext(&pProcess->Node, VBOXSERVICECTRLPROCESS, Node);
1520 bool fLast = RTListNodeIsLast(&pSession->lstProcesses, &pProcess->Node);
1521
1522 VGSvcVerbose(1, "Process %p (PID %RU32) still in list\n", pProcess, pProcess->uPID);
1523 if (fLast)
1524 break;
1525
1526 pProcess = pNext;
1527 }
1528#endif
1529 AssertMsg(RTListIsEmpty(&pSession->lstProcesses),
1530 ("Guest process list still contains entries when it should not\n"));
1531
1532 /*
1533 * Close all left guest files.
1534 */
1535 VGSvcVerbose(0, "Closing all guest files ...\n");
1536
1537 PVBOXSERVICECTRLFILE pFile;
1538 pFile = RTListGetFirst(&pSession->lstFiles, VBOXSERVICECTRLFILE, Node);
1539 while (pFile)
1540 {
1541 PVBOXSERVICECTRLFILE pNext = RTListNodeGetNext(&pFile->Node, VBOXSERVICECTRLFILE, Node);
1542 bool fLast = RTListNodeIsLast(&pSession->lstFiles, &pFile->Node);
1543
1544 int rc2 = vgsvcGstCtrlSessionFileDestroy(pFile);
1545 if (RT_FAILURE(rc2))
1546 {
1547 VGSvcError("Unable to close file '%s'; rc=%Rrc\n", pFile->szName, rc2);
1548 if (RT_SUCCESS(rc))
1549 rc = rc2;
1550 /* Keep going. */
1551 }
1552
1553 if (fLast)
1554 break;
1555
1556 pFile = pNext;
1557 }
1558
1559 AssertMsg(RTListIsEmpty(&pSession->lstFiles), ("Guest file list still contains entries when it should not\n"));
1560
1561 int rc2 = RTCritSectLeave(&pSession->CritSect);
1562 if (RT_SUCCESS(rc))
1563 rc = rc2;
1564 }
1565
1566 return rc;
1567}
1568
1569
1570int VGSvcGstCtrlSessionDestroy(PVBOXSERVICECTRLSESSION pSession)
1571{
1572 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1573
1574 int rc = VGSvcGstCtrlSessionClose(pSession);
1575
1576 /* Destroy critical section. */
1577 RTCritSectDelete(&pSession->CritSect);
1578
1579 return rc;
1580}
1581
1582
1583int VGSvcGstCtrlSessionInit(PVBOXSERVICECTRLSESSION pSession, uint32_t fFlags)
1584{
1585 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1586
1587 RTListInit(&pSession->lstProcesses);
1588 RTListInit(&pSession->lstFiles);
1589
1590 pSession->fFlags = fFlags;
1591
1592 /* Init critical section for protecting the thread lists. */
1593 int rc = RTCritSectInit(&pSession->CritSect);
1594 AssertRC(rc);
1595
1596 return rc;
1597}
1598
1599
1600/**
1601 * Adds a guest process to a session's process list.
1602 *
1603 * @return VBox status code.
1604 * @param pSession Guest session to add process to.
1605 * @param pProcess Guest process to add.
1606 */
1607int VGSvcGstCtrlSessionProcessAdd(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
1608{
1609 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1610 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1611
1612 int rc = RTCritSectEnter(&pSession->CritSect);
1613 if (RT_SUCCESS(rc))
1614 {
1615 VGSvcVerbose( 3, "Adding process (PID %RU32) to session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
1616
1617 /* Add process to session list. */
1618 RTListAppend(&pSession->lstProcesses, &pProcess->Node);
1619
1620 int rc2 = RTCritSectLeave(&pSession->CritSect);
1621 if (RT_SUCCESS(rc))
1622 rc = rc2;
1623 }
1624
1625 return VINF_SUCCESS;
1626}
1627
1628
1629/**
1630 * Removes a guest process from a session's process list.
1631 *
1632 * @return VBox status code.
1633 * @param pSession Guest session to remove process from.
1634 * @param pProcess Guest process to remove.
1635 */
1636int VGSvcGstCtrlSessionProcessRemove(PVBOXSERVICECTRLSESSION pSession, PVBOXSERVICECTRLPROCESS pProcess)
1637{
1638 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1639 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1640
1641 int rc = RTCritSectEnter(&pSession->CritSect);
1642 if (RT_SUCCESS(rc))
1643 {
1644 VGSvcVerbose(3, "Removing process (PID %RU32) from session ID=%RU32\n", pProcess->uPID, pSession->StartupInfo.uSessionID);
1645 Assert(pProcess->cRefs == 0);
1646
1647 RTListNodeRemove(&pProcess->Node);
1648
1649 int rc2 = RTCritSectLeave(&pSession->CritSect);
1650 if (RT_SUCCESS(rc))
1651 rc = rc2;
1652 }
1653
1654 return VINF_SUCCESS;
1655}
1656
1657
1658/**
1659 * Determines whether starting a new guest process according to the
1660 * maximum number of concurrent guest processes defined is allowed or not.
1661 *
1662 * @return VBox status code.
1663 * @param pSession The guest session.
1664 * @param pbAllowed True if starting (another) guest process
1665 * is allowed, false if not.
1666 */
1667int VGSvcGstCtrlSessionProcessStartAllowed(const PVBOXSERVICECTRLSESSION pSession, bool *pbAllowed)
1668{
1669 AssertPtrReturn(pSession, VERR_INVALID_POINTER);
1670 AssertPtrReturn(pbAllowed, VERR_INVALID_POINTER);
1671
1672 int rc = RTCritSectEnter(&pSession->CritSect);
1673 if (RT_SUCCESS(rc))
1674 {
1675 /*
1676 * Check if we're respecting our memory policy by checking
1677 * how many guest processes are started and served already.
1678 */
1679 bool fLimitReached = false;
1680 if (pSession->uProcsMaxKept) /* If we allow unlimited processes (=0), take a shortcut. */
1681 {
1682 uint32_t uProcsRunning = 0;
1683 PVBOXSERVICECTRLPROCESS pProcess;
1684 RTListForEach(&pSession->lstProcesses, pProcess, VBOXSERVICECTRLPROCESS, Node)
1685 uProcsRunning++;
1686
1687 VGSvcVerbose(3, "Maximum served guest processes set to %u, running=%u\n", pSession->uProcsMaxKept, uProcsRunning);
1688
1689 int32_t iProcsLeft = (pSession->uProcsMaxKept - uProcsRunning - 1);
1690 if (iProcsLeft < 0)
1691 {
1692 VGSvcVerbose(3, "Maximum running guest processes reached (%u)\n", pSession->uProcsMaxKept);
1693 fLimitReached = true;
1694 }
1695 }
1696
1697 *pbAllowed = !fLimitReached;
1698
1699 int rc2 = RTCritSectLeave(&pSession->CritSect);
1700 if (RT_SUCCESS(rc))
1701 rc = rc2;
1702 }
1703
1704 return rc;
1705}
1706
1707
1708/**
1709 * Creates the process for a guest session.
1710 *
1711 *
1712 * @return VBox status code.
1713 * @param pSessionStartupInfo Session startup info.
1714 * @param pSessionThread The session thread under construction.
1715 * @param uCtrlSessionThread The session thread debug ordinal.
1716 */
1717static int vgsvcVGSvcGstCtrlSessionThreadCreateProcess(const PVBOXSERVICECTRLSESSIONSTARTUPINFO pSessionStartupInfo,
1718 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread, uint32_t uCtrlSessionThread)
1719{
1720 RT_NOREF(uCtrlSessionThread);
1721
1722 /*
1723 * Is this an anonymous session? Anonymous sessions run with the same
1724 * privileges as the main VBoxService executable.
1725 */
1726 bool const fAnonymous = pSessionThread->StartupInfo.szUser[0] == '\0';
1727 if (fAnonymous)
1728 {
1729 Assert(!strlen(pSessionThread->StartupInfo.szPassword));
1730 Assert(!strlen(pSessionThread->StartupInfo.szDomain));
1731
1732 VGSvcVerbose(3, "New anonymous guest session ID=%RU32 created, fFlags=%x, using protocol %RU32\n",
1733 pSessionStartupInfo->uSessionID,
1734 pSessionStartupInfo->fFlags,
1735 pSessionStartupInfo->uProtocol);
1736 }
1737 else
1738 {
1739 VGSvcVerbose(3, "Spawning new guest session ID=%RU32, szUser=%s, szPassword=%s, szDomain=%s, fFlags=%x, using protocol %RU32\n",
1740 pSessionStartupInfo->uSessionID,
1741 pSessionStartupInfo->szUser,
1742#ifdef DEBUG
1743 pSessionStartupInfo->szPassword,
1744#else
1745 "XXX", /* Never show passwords in release mode. */
1746#endif
1747 pSessionStartupInfo->szDomain,
1748 pSessionStartupInfo->fFlags,
1749 pSessionStartupInfo->uProtocol);
1750 }
1751
1752 /*
1753 * Spawn a child process for doing the actual session handling.
1754 * Start by assembling the argument list.
1755 */
1756 int rc = VINF_SUCCESS;
1757 char szExeName[RTPATH_MAX];
1758 char *pszExeName = RTProcGetExecutablePath(szExeName, sizeof(szExeName));
1759 if (pszExeName)
1760 {
1761 char szParmSessionID[32];
1762 RTStrPrintf(szParmSessionID, sizeof(szParmSessionID), "--session-id=%RU32", pSessionThread->StartupInfo.uSessionID);
1763
1764 char szParmSessionProto[32];
1765 RTStrPrintf(szParmSessionProto, sizeof(szParmSessionProto), "--session-proto=%RU32",
1766 pSessionThread->StartupInfo.uProtocol);
1767#ifdef DEBUG
1768 char szParmThreadId[32];
1769 RTStrPrintf(szParmThreadId, sizeof(szParmThreadId), "--thread-id=%RU32", uCtrlSessionThread);
1770#endif
1771 unsigned idxArg = 0; /* Next index in argument vector. */
1772 char const *apszArgs[24];
1773
1774 apszArgs[idxArg++] = pszExeName;
1775 apszArgs[idxArg++] = "guestsession";
1776 apszArgs[idxArg++] = szParmSessionID;
1777 apszArgs[idxArg++] = szParmSessionProto;
1778#ifdef DEBUG
1779 apszArgs[idxArg++] = szParmThreadId;
1780#endif
1781 if (!fAnonymous) /* Do we need to pass a user name? */
1782 {
1783 apszArgs[idxArg++] = "--user";
1784 apszArgs[idxArg++] = pSessionThread->StartupInfo.szUser;
1785
1786 if (strlen(pSessionThread->StartupInfo.szDomain))
1787 {
1788 apszArgs[idxArg++] = "--domain";
1789 apszArgs[idxArg++] = pSessionThread->StartupInfo.szDomain;
1790 }
1791 }
1792
1793 /* Add same verbose flags as parent process. */
1794 char szParmVerbose[32];
1795 if (g_cVerbosity > 0)
1796 {
1797 unsigned cVs = RT_MIN(g_cVerbosity, RT_ELEMENTS(szParmVerbose) - 2);
1798 szParmVerbose[0] = '-';
1799 memset(&szParmVerbose[1], 'v', cVs);
1800 szParmVerbose[1 + cVs] = '\0';
1801 apszArgs[idxArg++] = szParmVerbose;
1802 }
1803
1804 /* Add log file handling. Each session will have an own
1805 * log file, naming based on the parent log file. */
1806 char szParmLogFile[sizeof(g_szLogFile) + 128];
1807 if (g_szLogFile[0])
1808 {
1809 const char *pszSuffix = RTPathSuffix(g_szLogFile);
1810 if (!pszSuffix)
1811 pszSuffix = strchr(g_szLogFile, '\0');
1812 size_t cchBase = pszSuffix - g_szLogFile;
1813#ifndef DEBUG
1814 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%s%s",
1815 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, pSessionStartupInfo->szUser, pszSuffix);
1816#else
1817 RTStrPrintf(szParmLogFile, sizeof(szParmLogFile), "%.*s-%RU32-%RU32-%s%s",
1818 cchBase, g_szLogFile, pSessionStartupInfo->uSessionID, uCtrlSessionThread,
1819 pSessionStartupInfo->szUser, pszSuffix);
1820#endif
1821 apszArgs[idxArg++] = "--logfile";
1822 apszArgs[idxArg++] = szParmLogFile;
1823 }
1824
1825#ifdef DEBUG
1826 VGSvcVerbose(4, "Argv building rc=%Rrc, session flags=%x\n", rc, g_Session.fFlags);
1827 if (RT_SUCCESS(rc))
1828 {
1829 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT)
1830 apszArgs[idxArg++] = "--dump-stdout";
1831 if (g_Session.fFlags & VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR)
1832 apszArgs[idxArg++] = "--dump-stderr";
1833 }
1834#endif
1835 apszArgs[idxArg] = NULL;
1836 Assert(idxArg < RT_ELEMENTS(apszArgs));
1837
1838 if (g_cVerbosity > 3)
1839 {
1840 VGSvcVerbose(4, "Spawning parameters:\n");
1841 for (idxArg = 0; apszArgs[idxArg]; idxArg++)
1842 VGSvcVerbose(4, "\t%s\n", apszArgs[idxArg]);
1843 }
1844
1845 /*
1846 * Configure standard handles and finally create the process.
1847 */
1848 uint32_t fProcCreate = RTPROC_FLAGS_PROFILE;
1849#ifdef RT_OS_WINDOWS /* Windows only flags: */
1850 fProcCreate |= RTPROC_FLAGS_SERVICE
1851 | RTPROC_FLAGS_HIDDEN; /** @todo More flags from startup info? */
1852#endif
1853
1854#if 0 /* Pipe handling not needed (yet). */
1855 /* Setup pipes. */
1856 rc = GstcntlProcessSetupPipe("|", 0 /*STDIN_FILENO*/,
1857 &pSession->StdIn.hChild, &pSession->StdIn.phChild, &pSession->hStdInW);
1858 if (RT_SUCCESS(rc))
1859 {
1860 rc = GstcntlProcessSetupPipe("|", 1 /*STDOUT_FILENO*/,
1861 &pSession->StdOut.hChild, &pSession->StdOut.phChild, &pSession->hStdOutR);
1862 if (RT_SUCCESS(rc))
1863 {
1864 rc = GstcntlProcessSetupPipe("|", 2 /*STDERR_FILENO*/,
1865 &pSession->StdErr.hChild, &pSession->StdErr.phChild, &pSession->hStdErrR);
1866 if (RT_SUCCESS(rc))
1867 {
1868 rc = RTPollSetCreate(&pSession->hPollSet);
1869 if (RT_SUCCESS(rc))
1870 rc = RTPollSetAddPipe(pSession->hPollSet, pSession->hStdInW, RTPOLL_EVT_ERROR,
1871 VBOXSERVICECTRLPIPEID_STDIN);
1872 if (RT_SUCCESS(rc))
1873 rc = RTPollSetAddPipe(pSession->hPollSet, pSession->hStdOutR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
1874 VBOXSERVICECTRLPIPEID_STDOUT);
1875 if (RT_SUCCESS(rc))
1876 rc = RTPollSetAddPipe(pSession->hPollSet, pSession->hStdErrR, RTPOLL_EVT_READ | RTPOLL_EVT_ERROR,
1877 VBOXSERVICECTRLPIPEID_STDERR);
1878 }
1879
1880 if (RT_SUCCESS(rc))
1881 rc = RTProcCreateEx(pszExeName, apszArgs, hEnv, fProcCreate,
1882 pSession->StdIn.phChild, pSession->StdOut.phChild, pSession->StdErr.phChild,
1883 !fAnonymous ? pSession->StartupInfo.szUser : NULL,
1884 !fAnonymous ? pSession->StartupInfo.szPassword : NULL,
1885 &pSession->hProcess);
1886
1887 if (RT_SUCCESS(rc))
1888 {
1889 /*
1890 * Close the child ends of any pipes and redirected files.
1891 */
1892 int rc2 = RTHandleClose(pSession->StdIn.phChild); AssertRC(rc2);
1893 pSession->StdIn.phChild = NULL;
1894 rc2 = RTHandleClose(pSession->StdOut.phChild); AssertRC(rc2);
1895 pSession->StdOut.phChild = NULL;
1896 rc2 = RTHandleClose(pSession->StdErr.phChild); AssertRC(rc2);
1897 pSession->StdErr.phChild = NULL;
1898 }
1899 }
1900 }
1901#else
1902 if (RT_SUCCESS(rc))
1903 {
1904 RTHANDLE hStdIn;
1905 rc = RTFileOpenBitBucket(&hStdIn.u.hFile, RTFILE_O_READ);
1906 if (RT_SUCCESS(rc))
1907 {
1908 hStdIn.enmType = RTHANDLETYPE_FILE;
1909
1910 RTHANDLE hStdOutAndErr;
1911 rc = RTFileOpenBitBucket(&hStdOutAndErr.u.hFile, RTFILE_O_WRITE);
1912 if (RT_SUCCESS(rc))
1913 {
1914 hStdOutAndErr.enmType = RTHANDLETYPE_FILE;
1915
1916 const char *pszUser = pSessionThread->StartupInfo.szUser;
1917# ifdef RT_OS_WINDOWS
1918 /* If a domain name is given, construct an UPN (User Principle Name) with
1919 * the domain name built-in, e.g. "[email protected]". */
1920 char *pszUserUPN = NULL;
1921 if (strlen(pSessionThread->StartupInfo.szDomain))
1922 {
1923 int cbUserUPN = RTStrAPrintf(&pszUserUPN, "%s@%s",
1924 pSessionThread->StartupInfo.szUser,
1925 pSessionThread->StartupInfo.szDomain);
1926 if (cbUserUPN > 0)
1927 {
1928 pszUser = pszUserUPN;
1929 VGSvcVerbose(3, "Using UPN: %s\n", pszUserUPN);
1930 }
1931 }
1932# endif
1933
1934 rc = RTProcCreateEx(pszExeName, apszArgs, RTENV_DEFAULT, fProcCreate,
1935 &hStdIn, &hStdOutAndErr, &hStdOutAndErr,
1936 !fAnonymous ? pszUser : NULL,
1937 !fAnonymous ? pSessionThread->StartupInfo.szPassword : NULL,
1938 &pSessionThread->hProcess);
1939# ifdef RT_OS_WINDOWS
1940 if (pszUserUPN)
1941 RTStrFree(pszUserUPN);
1942# endif
1943 RTFileClose(hStdOutAndErr.u.hFile);
1944 }
1945
1946 RTFileClose(hStdIn.u.hFile);
1947 }
1948 }
1949#endif
1950 }
1951 else
1952 rc = VERR_FILE_NOT_FOUND;
1953 return rc;
1954}
1955
1956
1957/**
1958 * Creates a guest session.
1959 *
1960 * This will spawn a new VBoxService.exe instance under behalf of the given user
1961 * which then will act as a session host. On successful open, the session will
1962 * be added to the given session thread list.
1963 *
1964 * @return VBox status code.
1965 * @param pList Which list to use to store the session thread in.
1966 * @param pSessionStartupInfo Session startup info.
1967 * @param ppSessionThread Returns newly created session thread on success.
1968 * Optional.
1969 */
1970int VGSvcGstCtrlSessionThreadCreate(PRTLISTANCHOR pList, const PVBOXSERVICECTRLSESSIONSTARTUPINFO pSessionStartupInfo,
1971 PVBOXSERVICECTRLSESSIONTHREAD *ppSessionThread)
1972{
1973 AssertPtrReturn(pList, VERR_INVALID_POINTER);
1974 AssertPtrReturn(pSessionStartupInfo, VERR_INVALID_POINTER);
1975 /* ppSessionThread is optional. */
1976
1977#ifdef VBOX_STRICT
1978 /* Check for existing session in debug mode. Should never happen because of
1979 * Main consistency. */
1980 PVBOXSERVICECTRLSESSIONTHREAD pSessionCur;
1981 RTListForEach(pList, pSessionCur, VBOXSERVICECTRLSESSIONTHREAD, Node)
1982 {
1983 AssertMsgReturn(pSessionCur->StartupInfo.uSessionID != pSessionStartupInfo->uSessionID,
1984 ("Guest session thread ID=%RU32 (%p) already exists when it should not\n",
1985 pSessionCur->StartupInfo.uSessionID, pSessionCur), VERR_ALREADY_EXISTS);
1986 }
1987#endif
1988 int rc = VINF_SUCCESS;
1989
1990 /* Static counter to help tracking session thread <-> process relations. */
1991 static uint32_t s_uCtrlSessionThread = 0;
1992 if (s_uCtrlSessionThread++ == UINT32_MAX)
1993 s_uCtrlSessionThread = 0; /* Wrap around to not let IPRT freak out. */
1994
1995 /*
1996 * Allocate and initialize the session thread structure.
1997 */
1998 PVBOXSERVICECTRLSESSIONTHREAD pSessionThread = (PVBOXSERVICECTRLSESSIONTHREAD)RTMemAllocZ(sizeof(*pSessionThread));
1999 if (pSessionThread)
2000 {
2001 /* Copy over session startup info. */
2002 memcpy(&pSessionThread->StartupInfo, pSessionStartupInfo, sizeof(VBOXSERVICECTRLSESSIONSTARTUPINFO));
2003
2004 pSessionThread->fShutdown = false;
2005 pSessionThread->fStarted = false;
2006 pSessionThread->fStopped = false;
2007
2008 rc = RTCritSectInit(&pSessionThread->CritSect);
2009 AssertRC(rc);
2010 if (RT_SUCCESS(rc))
2011 {
2012 /*
2013 * Start the session thread.
2014 */
2015 rc = vgsvcVGSvcGstCtrlSessionThreadCreateProcess(pSessionStartupInfo, pSessionThread, s_uCtrlSessionThread);
2016 if (RT_SUCCESS(rc))
2017 {
2018 /*
2019 * Start the session thread.
2020 */
2021 rc = RTThreadCreateF(&pSessionThread->Thread, vgsvcGstCtrlSessionThread,
2022 pSessionThread /*pvUser*/, 0 /*cbStack*/,
2023 RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "sess%u", s_uCtrlSessionThread);
2024 if (RT_SUCCESS(rc))
2025 {
2026 /* Wait for the thread to initialize. */
2027 rc = RTThreadUserWait(pSessionThread->Thread, RT_MS_1MIN);
2028 if ( RT_SUCCESS(rc)
2029 && !ASMAtomicReadBool(&pSessionThread->fShutdown))
2030 {
2031 VGSvcVerbose(2, "Thread for session ID=%RU32 started\n", pSessionThread->StartupInfo.uSessionID);
2032
2033 ASMAtomicXchgBool(&pSessionThread->fStarted, true);
2034
2035 /* Add session to list. */
2036 RTListAppend(pList, &pSessionThread->Node);
2037 if (ppSessionThread) /* Return session if wanted. */
2038 *ppSessionThread = pSessionThread;
2039 return VINF_SUCCESS;
2040 }
2041
2042 /*
2043 * Bail out.
2044 */
2045 VGSvcError("Thread for session ID=%RU32 failed to start, rc=%Rrc\n",
2046 pSessionThread->StartupInfo.uSessionID, rc);
2047 if (RT_SUCCESS_NP(rc))
2048 rc = VERR_CANT_CREATE; /** @todo Find a better rc. */
2049 }
2050 else
2051 VGSvcError("Creating session thread failed, rc=%Rrc\n", rc);
2052
2053 RTProcTerminate(pSessionThread->hProcess);
2054 uint32_t cMsWait = 1;
2055 while ( RTProcWait(pSessionThread->hProcess, RTPROCWAIT_FLAGS_NOBLOCK, NULL) == VERR_PROCESS_RUNNING
2056 && cMsWait <= 9) /* 1023 ms */
2057 {
2058 RTThreadSleep(cMsWait);
2059 cMsWait <<= 1;
2060 }
2061 }
2062 RTCritSectDelete(&pSessionThread->CritSect);
2063 }
2064 RTMemFree(pSessionThread);
2065 }
2066 else
2067 rc = VERR_NO_MEMORY;
2068
2069 VGSvcVerbose(3, "Spawning session thread returned returned rc=%Rrc\n", rc);
2070 return rc;
2071}
2072
2073
2074/**
2075 * Waits for a formerly opened guest session process to close.
2076 *
2077 * @return VBox status code.
2078 * @param pThread Guest session thread to wait for.
2079 * @param uTimeoutMS Waiting timeout (in ms).
2080 * @param fFlags Closing flags.
2081 */
2082int VGSvcGstCtrlSessionThreadWait(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t uTimeoutMS, uint32_t fFlags)
2083{
2084 RT_NOREF(fFlags);
2085 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2086 /** @todo Validate closing flags. */
2087
2088 AssertMsgReturn(pThread->Thread != NIL_RTTHREAD,
2089 ("Guest session thread of session %p does not exist when it should\n", pThread),
2090 VERR_NOT_FOUND);
2091
2092 int rc = VINF_SUCCESS;
2093
2094 /*
2095 * The spawned session process should have received the same closing request,
2096 * so just wait for the process to close.
2097 */
2098 if (ASMAtomicReadBool(&pThread->fStarted))
2099 {
2100 /* Ask the thread to shutdown. */
2101 ASMAtomicXchgBool(&pThread->fShutdown, true);
2102
2103 VGSvcVerbose(3, "Waiting for session thread ID=%RU32 to close (%RU32ms) ...\n",
2104 pThread->StartupInfo.uSessionID, uTimeoutMS);
2105
2106 int rcThread;
2107 rc = RTThreadWait(pThread->Thread, uTimeoutMS, &rcThread);
2108 if (RT_SUCCESS(rc))
2109 VGSvcVerbose(3, "Session thread ID=%RU32 ended with rc=%Rrc\n", pThread->StartupInfo.uSessionID, rcThread);
2110 else
2111 VGSvcError("Waiting for session thread ID=%RU32 to close failed with rc=%Rrc\n", pThread->StartupInfo.uSessionID, rc);
2112 }
2113
2114 return rc;
2115}
2116
2117/**
2118 * Waits for the specified session thread to end and remove
2119 * it from the session thread list.
2120 *
2121 * @return VBox status code.
2122 * @param pThread Session thread to destroy.
2123 * @param fFlags Closing flags.
2124 */
2125int VGSvcGstCtrlSessionThreadDestroy(PVBOXSERVICECTRLSESSIONTHREAD pThread, uint32_t fFlags)
2126{
2127 AssertPtrReturn(pThread, VERR_INVALID_POINTER);
2128
2129 int rc = VGSvcGstCtrlSessionThreadWait(pThread, 5 * 60 * 1000 /* 5 minutes timeout */, fFlags);
2130
2131 /* Remove session from list and destroy object. */
2132 RTListNodeRemove(&pThread->Node);
2133
2134 RTMemFree(pThread);
2135 pThread = NULL;
2136
2137 return rc;
2138}
2139
2140/**
2141 * Close all open guest session threads.
2142 *
2143 * @note Caller is responsible for locking!
2144 *
2145 * @return VBox status code.
2146 * @param pList Which list to close the session threads for.
2147 * @param fFlags Closing flags.
2148 */
2149int VGSvcGstCtrlSessionThreadDestroyAll(PRTLISTANCHOR pList, uint32_t fFlags)
2150{
2151 AssertPtrReturn(pList, VERR_INVALID_POINTER);
2152
2153 int rc = VINF_SUCCESS;
2154
2155 /*int rc = VbglR3GuestCtrlClose
2156 if (RT_FAILURE(rc))
2157 VGSvcError("Cancelling pending waits failed; rc=%Rrc\n", rc);*/
2158
2159 PVBOXSERVICECTRLSESSIONTHREAD pSessIt;
2160 PVBOXSERVICECTRLSESSIONTHREAD pSessItNext;
2161 RTListForEachSafe(pList, pSessIt, pSessItNext, VBOXSERVICECTRLSESSIONTHREAD, Node)
2162 {
2163 int rc2 = VGSvcGstCtrlSessionThreadDestroy(pSessIt, fFlags);
2164 if (RT_FAILURE(rc2))
2165 {
2166 VGSvcError("Closing session thread '%s' failed with rc=%Rrc\n", RTThreadGetName(pSessIt->Thread), rc2);
2167 if (RT_SUCCESS(rc))
2168 rc = rc2;
2169 /* Keep going. */
2170 }
2171 }
2172
2173 VGSvcVerbose(4, "Destroying guest session threads ended with %Rrc\n", rc);
2174 return rc;
2175}
2176
2177
2178/**
2179 * Main function for the session process.
2180 *
2181 * @returns exit code.
2182 * @param argc Argument count.
2183 * @param argv Argument vector (UTF-8).
2184 */
2185RTEXITCODE VGSvcGstCtrlSessionSpawnInit(int argc, char **argv)
2186{
2187 static const RTGETOPTDEF s_aOptions[] =
2188 {
2189 { "--domain", VBOXSERVICESESSIONOPT_DOMAIN, RTGETOPT_REQ_STRING },
2190#ifdef DEBUG
2191 { "--dump-stdout", VBOXSERVICESESSIONOPT_DUMP_STDOUT, RTGETOPT_REQ_NOTHING },
2192 { "--dump-stderr", VBOXSERVICESESSIONOPT_DUMP_STDERR, RTGETOPT_REQ_NOTHING },
2193#endif
2194 { "--logfile", VBOXSERVICESESSIONOPT_LOG_FILE, RTGETOPT_REQ_STRING },
2195 { "--user", VBOXSERVICESESSIONOPT_USERNAME, RTGETOPT_REQ_STRING },
2196 { "--session-id", VBOXSERVICESESSIONOPT_SESSION_ID, RTGETOPT_REQ_UINT32 },
2197 { "--session-proto", VBOXSERVICESESSIONOPT_SESSION_PROTO, RTGETOPT_REQ_UINT32 },
2198#ifdef DEBUG
2199 { "--thread-id", VBOXSERVICESESSIONOPT_THREAD_ID, RTGETOPT_REQ_UINT32 },
2200#endif /* DEBUG */
2201 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2202 };
2203
2204 int ch;
2205 RTGETOPTUNION ValueUnion;
2206 RTGETOPTSTATE GetState;
2207 RTGetOptInit(&GetState, argc, argv,
2208 s_aOptions, RT_ELEMENTS(s_aOptions),
2209 1 /*iFirst*/, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2210
2211 uint32_t fSession = VBOXSERVICECTRLSESSION_FLAG_SPAWN;
2212
2213 /* Protocol and session ID must be specified explicitly. */
2214 g_Session.StartupInfo.uProtocol = UINT32_MAX;
2215 g_Session.StartupInfo.uSessionID = UINT32_MAX;
2216
2217 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2218 {
2219 /* For options that require an argument, ValueUnion has received the value. */
2220 switch (ch)
2221 {
2222 case VBOXSERVICESESSIONOPT_DOMAIN:
2223 /* Information not needed right now, skip. */
2224 break;
2225#ifdef DEBUG
2226 case VBOXSERVICESESSIONOPT_DUMP_STDOUT:
2227 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDOUT;
2228 break;
2229
2230 case VBOXSERVICESESSIONOPT_DUMP_STDERR:
2231 fSession |= VBOXSERVICECTRLSESSION_FLAG_DUMPSTDERR;
2232 break;
2233#endif
2234 case VBOXSERVICESESSIONOPT_SESSION_ID:
2235 g_Session.StartupInfo.uSessionID = ValueUnion.u32;
2236 break;
2237
2238 case VBOXSERVICESESSIONOPT_SESSION_PROTO:
2239 g_Session.StartupInfo.uProtocol = ValueUnion.u32;
2240 break;
2241#ifdef DEBUG
2242 case VBOXSERVICESESSIONOPT_THREAD_ID:
2243 /* Not handled. Mainly for processs listing. */
2244 break;
2245#endif
2246 case VBOXSERVICESESSIONOPT_LOG_FILE:
2247 {
2248 int rc = RTStrCopy(g_szLogFile, sizeof(g_szLogFile), ValueUnion.psz);
2249 if (RT_FAILURE(rc))
2250 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Error copying log file name: %Rrc", rc);
2251 break;
2252 }
2253
2254 case VBOXSERVICESESSIONOPT_USERNAME:
2255 /* Information not needed right now, skip. */
2256 break;
2257
2258 /** @todo Implement help? */
2259
2260 case 'v':
2261 g_cVerbosity++;
2262 break;
2263
2264 case VINF_GETOPT_NOT_OPTION:
2265 /* Ignore; might be "guestsession" main command. */
2266 /** @todo r=bird: We DO NOT ignore stuff on the command line! */
2267 break;
2268
2269 default:
2270 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "Unknown command '%s'", ValueUnion.psz);
2271 }
2272 }
2273
2274 /* Check that we've got all the required options. */
2275 if (g_Session.StartupInfo.uProtocol == UINT32_MAX)
2276 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No protocol version specified");
2277
2278 if (g_Session.StartupInfo.uSessionID == UINT32_MAX)
2279 return RTMsgErrorExit(RTEXITCODE_SYNTAX, "No session ID specified");
2280
2281 /* Init the session object. */
2282 int rc = VGSvcGstCtrlSessionInit(&g_Session, fSession);
2283 if (RT_FAILURE(rc))
2284 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to initialize session object, rc=%Rrc\n", rc);
2285
2286 rc = VGSvcLogCreate(g_szLogFile[0] ? g_szLogFile : NULL);
2287 if (RT_FAILURE(rc))
2288 return RTMsgErrorExit(RTEXITCODE_INIT, "Failed to create log file '%s', rc=%Rrc\n",
2289 g_szLogFile[0] ? g_szLogFile : "<None>", rc);
2290
2291 RTEXITCODE rcExit = vgsvcGstCtrlSessionSpawnWorker(&g_Session);
2292
2293 VGSvcLogDestroy();
2294 return rcExit;
2295}
2296
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