VirtualBox

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

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

Guest Control/VBoxService: Resolved a @todo in vgsvcGstCtrlSessionHandlePathRename() (now using a dedicated flag for the actual RTPathRename call).

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