VirtualBox

source: vbox/trunk/src/VBox/Main/include/GuestCtrlImplPrivate.h@ 83319

最後變更 在這個檔案從83319是 83319,由 vboxsync 提交於 5 年 前

Guest Control/Main: Added some more class/struct constructor initializers.

  • 屬性 svn:eol-style 設為 native
  • 屬性 svn:keywords 設為 Author Date Id Revision
檔案大小: 36.6 KB
 
1/* $Id: GuestCtrlImplPrivate.h 83319 2020-03-18 17:23:39Z vboxsync $ */
2/** @file
3 * Internal helpers/structures for guest control functionality.
4 */
5
6/*
7 * Copyright (C) 2011-2020 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.alldomusa.eu.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#ifndef MAIN_INCLUDED_GuestCtrlImplPrivate_h
19#define MAIN_INCLUDED_GuestCtrlImplPrivate_h
20#ifndef RT_WITHOUT_PRAGMA_ONCE
21# pragma once
22#endif
23
24#include "ConsoleImpl.h"
25#include "Global.h"
26
27#include <iprt/asm.h>
28#include <iprt/env.h>
29#include <iprt/semaphore.h>
30#include <iprt/cpp/utils.h>
31
32#include <VBox/com/com.h>
33#include <VBox/com/ErrorInfo.h>
34#include <VBox/com/string.h>
35#include <VBox/com/VirtualBox.h>
36#include <VBox/err.h> /* VERR_GSTCTL_GUEST_ERROR */
37
38#include <map>
39#include <vector>
40
41using namespace com;
42
43#ifdef VBOX_WITH_GUEST_CONTROL
44# include <VBox/GuestHost/GuestControl.h>
45# include <VBox/HostServices/GuestControlSvc.h>
46using namespace guestControl;
47#endif
48
49/** Vector holding a process' CPU affinity. */
50typedef std::vector <LONG> ProcessAffinity;
51/** Vector holding process startup arguments. */
52typedef std::vector <Utf8Str> ProcessArguments;
53
54class GuestProcessStreamBlock;
55class GuestSession;
56
57
58/**
59 * Simple structure mantaining guest credentials.
60 */
61struct GuestCredentials
62{
63 Utf8Str mUser;
64 Utf8Str mPassword;
65 Utf8Str mDomain;
66};
67
68
69/**
70 * Wrapper around the RTEnv API, unusable base class.
71 *
72 * @remarks Feel free to elevate this class to iprt/cpp/env.h as RTCEnv.
73 */
74class GuestEnvironmentBase
75{
76public:
77 /**
78 * Default constructor.
79 *
80 * The user must invoke one of the init methods before using the object.
81 */
82 GuestEnvironmentBase(void)
83 : m_hEnv(NIL_RTENV)
84 , m_cRefs(1)
85 , m_fFlags(0)
86 { }
87
88 /**
89 * Destructor.
90 */
91 virtual ~GuestEnvironmentBase(void)
92 {
93 Assert(m_cRefs <= 1);
94 int rc = RTEnvDestroy(m_hEnv); AssertRC(rc);
95 m_hEnv = NIL_RTENV;
96 }
97
98 /**
99 * Retains a reference to this object.
100 * @returns New reference count.
101 * @remarks Sharing an object is currently only safe if no changes are made to
102 * it because RTENV does not yet implement any locking. For the only
103 * purpose we need this, implementing IGuestProcess::environment by
104 * using IGuestSession::environmentBase, that's fine as the session
105 * base environment is immutable.
106 */
107 uint32_t retain(void)
108 {
109 uint32_t cRefs = ASMAtomicIncU32(&m_cRefs);
110 Assert(cRefs > 1); Assert(cRefs < _1M);
111 return cRefs;
112
113 }
114 /** Useful shortcut. */
115 uint32_t retainConst(void) const { return unconst(this)->retain(); }
116
117 /**
118 * Releases a reference to this object, deleting the object when reaching zero.
119 * @returns New reference count.
120 */
121 uint32_t release(void)
122 {
123 uint32_t cRefs = ASMAtomicDecU32(&m_cRefs);
124 Assert(cRefs < _1M);
125 if (cRefs == 0)
126 delete this;
127 return cRefs;
128 }
129
130 /** Useful shortcut. */
131 uint32_t releaseConst(void) const { return unconst(this)->retain(); }
132
133 /**
134 * Checks if the environment has been successfully initialized or not.
135 *
136 * @returns @c true if initialized, @c false if not.
137 */
138 bool isInitialized(void) const
139 {
140 return m_hEnv != NIL_RTENV;
141 }
142
143 /**
144 * Returns the variable count.
145 * @return Number of variables.
146 * @sa RTEnvCountEx
147 */
148 uint32_t count(void) const
149 {
150 return RTEnvCountEx(m_hEnv);
151 }
152
153 /**
154 * Deletes the environment change record entirely.
155 *
156 * The count() method will return zero after this call.
157 *
158 * @sa RTEnvReset
159 */
160 void reset(void)
161 {
162 int rc = RTEnvReset(m_hEnv);
163 AssertRC(rc);
164 }
165
166 /**
167 * Exports the environment change block as an array of putenv style strings.
168 *
169 *
170 * @returns VINF_SUCCESS or VERR_NO_MEMORY.
171 * @param pArray The output array.
172 */
173 int queryPutEnvArray(std::vector<com::Utf8Str> *pArray) const
174 {
175 uint32_t cVars = RTEnvCountEx(m_hEnv);
176 try
177 {
178 pArray->resize(cVars);
179 for (uint32_t iVar = 0; iVar < cVars; iVar++)
180 {
181 const char *psz = RTEnvGetByIndexRawEx(m_hEnv, iVar);
182 AssertReturn(psz, VERR_INTERNAL_ERROR_3); /* someone is racing us! */
183 (*pArray)[iVar] = psz;
184 }
185 return VINF_SUCCESS;
186 }
187 catch (std::bad_alloc &)
188 {
189 return VERR_NO_MEMORY;
190 }
191 }
192
193 /**
194 * Applies an array of putenv style strings.
195 *
196 * @returns IPRT status code.
197 * @param rArray The array with the putenv style strings.
198 * @param pidxError Where to return the index causing trouble on
199 * failure. Optional.
200 * @sa RTEnvPutEx
201 */
202 int applyPutEnvArray(const std::vector<com::Utf8Str> &rArray, size_t *pidxError = NULL)
203 {
204 size_t const cArray = rArray.size();
205 for (size_t i = 0; i < cArray; i++)
206 {
207 int rc = RTEnvPutEx(m_hEnv, rArray[i].c_str());
208 if (RT_FAILURE(rc))
209 {
210 if (pidxError)
211 *pidxError = i;
212 return rc;
213 }
214 }
215 return VINF_SUCCESS;
216 }
217
218 /**
219 * Applies the changes from another environment to this.
220 *
221 * @returns IPRT status code.
222 * @param rChanges Reference to an environment which variables will be
223 * imported and, if it's a change record, schedule
224 * variable unsets will be applied.
225 * @sa RTEnvApplyChanges
226 */
227 int applyChanges(const GuestEnvironmentBase &rChanges)
228 {
229 return RTEnvApplyChanges(m_hEnv, rChanges.m_hEnv);
230 }
231
232 /**
233 * See RTEnvQueryUtf8Block for details.
234 * @returns IPRT status code.
235 * @param ppszzBlock Where to return the block pointer.
236 * @param pcbBlock Where to optionally return the block size.
237 * @sa RTEnvQueryUtf8Block
238 */
239 int queryUtf8Block(char **ppszzBlock, size_t *pcbBlock)
240 {
241 return RTEnvQueryUtf8Block(m_hEnv, true /*fSorted*/, ppszzBlock, pcbBlock);
242 }
243
244 /**
245 * Frees what queryUtf8Block returned, NULL ignored.
246 * @sa RTEnvFreeUtf8Block
247 */
248 static void freeUtf8Block(char *pszzBlock)
249 {
250 return RTEnvFreeUtf8Block(pszzBlock);
251 }
252
253 /**
254 * Applies a block on the format returned by queryUtf8Block.
255 *
256 * @returns IPRT status code.
257 * @param pszzBlock Pointer to the block.
258 * @param cbBlock The size of the block.
259 * @param fNoEqualMeansUnset Whether the lack of a '=' (equal) sign in a
260 * string means it should be unset (@c true), or if
261 * it means the variable should be defined with an
262 * empty value (@c false, the default).
263 * @todo move this to RTEnv!
264 */
265 int copyUtf8Block(const char *pszzBlock, size_t cbBlock, bool fNoEqualMeansUnset = false)
266 {
267 int rc = VINF_SUCCESS;
268 while (cbBlock > 0 && *pszzBlock != '\0')
269 {
270 const char *pszEnd = (const char *)memchr(pszzBlock, '\0', cbBlock);
271 if (!pszEnd)
272 return VERR_BUFFER_UNDERFLOW;
273 int rc2;
274 if (fNoEqualMeansUnset || strchr(pszzBlock, '='))
275 rc2 = RTEnvPutEx(m_hEnv, pszzBlock);
276 else
277 rc2 = RTEnvSetEx(m_hEnv, pszzBlock, "");
278 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
279 rc = rc2;
280
281 /* Advance. */
282 cbBlock -= pszEnd - pszzBlock;
283 if (cbBlock < 2)
284 return VERR_BUFFER_UNDERFLOW;
285 cbBlock--;
286 pszzBlock = pszEnd + 1;
287 }
288
289 /* The remainder must be zero padded. */
290 if (RT_SUCCESS(rc))
291 {
292 if (ASMMemIsZero(pszzBlock, cbBlock))
293 return VINF_SUCCESS;
294 return VERR_TOO_MUCH_DATA;
295 }
296 return rc;
297 }
298
299 /**
300 * Get an environment variable.
301 *
302 * @returns IPRT status code.
303 * @param rName The variable name.
304 * @param pValue Where to return the value.
305 * @sa RTEnvGetEx
306 */
307 int getVariable(const com::Utf8Str &rName, com::Utf8Str *pValue) const
308 {
309 size_t cchNeeded;
310 int rc = RTEnvGetEx(m_hEnv, rName.c_str(), NULL, 0, &cchNeeded);
311 if ( RT_SUCCESS(rc)
312 || rc == VERR_BUFFER_OVERFLOW)
313 {
314 try
315 {
316 pValue->reserve(cchNeeded + 1);
317 rc = RTEnvGetEx(m_hEnv, rName.c_str(), pValue->mutableRaw(), pValue->capacity(), NULL);
318 pValue->jolt();
319 }
320 catch (std::bad_alloc &)
321 {
322 rc = VERR_NO_STR_MEMORY;
323 }
324 }
325 return rc;
326 }
327
328 /**
329 * Checks if the given variable exists.
330 *
331 * @returns @c true if it exists, @c false if not or if it's an scheduled unset
332 * in a environment change record.
333 * @param rName The variable name.
334 * @sa RTEnvExistEx
335 */
336 bool doesVariableExist(const com::Utf8Str &rName) const
337 {
338 return RTEnvExistEx(m_hEnv, rName.c_str());
339 }
340
341 /**
342 * Set an environment variable.
343 *
344 * @returns IPRT status code.
345 * @param rName The variable name.
346 * @param rValue The value of the variable.
347 * @sa RTEnvSetEx
348 */
349 int setVariable(const com::Utf8Str &rName, const com::Utf8Str &rValue)
350 {
351 return RTEnvSetEx(m_hEnv, rName.c_str(), rValue.c_str());
352 }
353
354 /**
355 * Unset an environment variable.
356 *
357 * @returns IPRT status code.
358 * @param rName The variable name.
359 * @sa RTEnvUnsetEx
360 */
361 int unsetVariable(const com::Utf8Str &rName)
362 {
363 return RTEnvUnsetEx(m_hEnv, rName.c_str());
364 }
365
366protected:
367 /**
368 * Copy constructor.
369 * @throws HRESULT
370 */
371 GuestEnvironmentBase(const GuestEnvironmentBase &rThat, bool fChangeRecord, uint32_t fFlags = 0)
372 : m_hEnv(NIL_RTENV)
373 , m_cRefs(1)
374 , m_fFlags(fFlags)
375 {
376 int rc = cloneCommon(rThat, fChangeRecord);
377 if (RT_FAILURE(rc))
378 throw (Global::vboxStatusCodeToCOM(rc));
379 }
380
381 /**
382 * Common clone/copy method with type conversion abilities.
383 *
384 * @returns IPRT status code.
385 * @param rThat The object to clone.
386 * @param fChangeRecord Whether the this instance is a change record (true)
387 * or normal (false) environment.
388 */
389 int cloneCommon(const GuestEnvironmentBase &rThat, bool fChangeRecord)
390 {
391 int rc = VINF_SUCCESS;
392 RTENV hNewEnv = NIL_RTENV;
393 if (rThat.m_hEnv != NIL_RTENV)
394 {
395 /*
396 * Clone it.
397 */
398 if (RTEnvIsChangeRecord(rThat.m_hEnv) == fChangeRecord)
399 rc = RTEnvClone(&hNewEnv, rThat.m_hEnv);
400 else
401 {
402 /* Need to type convert it. */
403 if (fChangeRecord)
404 rc = RTEnvCreateChangeRecordEx(&hNewEnv, rThat.m_fFlags);
405 else
406 rc = RTEnvCreateEx(&hNewEnv, rThat.m_fFlags);
407 if (RT_SUCCESS(rc))
408 {
409 rc = RTEnvApplyChanges(hNewEnv, rThat.m_hEnv);
410 if (RT_FAILURE(rc))
411 RTEnvDestroy(hNewEnv);
412 }
413 }
414 }
415 else
416 {
417 /*
418 * Create an empty one so the object works smoothly.
419 * (Relevant for GuestProcessStartupInfo and internal commands.)
420 */
421 if (fChangeRecord)
422 rc = RTEnvCreateChangeRecordEx(&hNewEnv, rThat.m_fFlags);
423 else
424 rc = RTEnvCreateEx(&hNewEnv, rThat.m_fFlags);
425 }
426 if (RT_SUCCESS(rc))
427 {
428 RTEnvDestroy(m_hEnv);
429 m_hEnv = hNewEnv;
430 m_fFlags = rThat.m_fFlags;
431 }
432 return rc;
433 }
434
435
436 /** The environment change record. */
437 RTENV m_hEnv;
438 /** Reference counter. */
439 uint32_t volatile m_cRefs;
440 /** RTENV_CREATE_F_XXX. */
441 uint32_t m_fFlags;
442};
443
444class GuestEnvironmentChanges;
445
446
447/**
448 * Wrapper around the RTEnv API for a normal environment.
449 */
450class GuestEnvironment : public GuestEnvironmentBase
451{
452public:
453 /**
454 * Default constructor.
455 *
456 * The user must invoke one of the init methods before using the object.
457 */
458 GuestEnvironment(void)
459 : GuestEnvironmentBase()
460 { }
461
462 /**
463 * Copy operator.
464 * @param rThat The object to copy.
465 * @throws HRESULT
466 */
467 GuestEnvironment(const GuestEnvironment &rThat)
468 : GuestEnvironmentBase(rThat, false /*fChangeRecord*/)
469 { }
470
471 /**
472 * Copy operator.
473 * @param rThat The object to copy.
474 * @throws HRESULT
475 */
476 GuestEnvironment(const GuestEnvironmentBase &rThat)
477 : GuestEnvironmentBase(rThat, false /*fChangeRecord*/)
478 { }
479
480 /**
481 * Initialize this as a normal environment block.
482 * @returns IPRT status code.
483 * @param fFlags RTENV_CREATE_F_XXX
484 */
485 int initNormal(uint32_t fFlags)
486 {
487 AssertReturn(m_hEnv == NIL_RTENV, VERR_WRONG_ORDER);
488 m_fFlags = fFlags;
489 return RTEnvCreateEx(&m_hEnv, fFlags);
490 }
491
492 /**
493 * Replaces this environemnt with that in @a rThat.
494 *
495 * @returns IPRT status code
496 * @param rThat The environment to copy. If it's a different type
497 * we'll convert the data to a normal environment block.
498 */
499 int copy(const GuestEnvironmentBase &rThat)
500 {
501 return cloneCommon(rThat, false /*fChangeRecord*/);
502 }
503
504 /**
505 * @copydoc copy()
506 */
507 GuestEnvironment &operator=(const GuestEnvironmentBase &rThat)
508 {
509 int rc = copy(rThat);
510 if (RT_FAILURE(rc))
511 throw (Global::vboxStatusCodeToCOM(rc));
512 return *this;
513 }
514
515 /** @copydoc copy() */
516 GuestEnvironment &operator=(const GuestEnvironment &rThat)
517 { return operator=((const GuestEnvironmentBase &)rThat); }
518
519 /** @copydoc copy() */
520 GuestEnvironment &operator=(const GuestEnvironmentChanges &rThat)
521 { return operator=((const GuestEnvironmentBase &)rThat); }
522
523};
524
525
526/**
527 * Wrapper around the RTEnv API for a environment change record.
528 *
529 * This class is used as a record of changes to be applied to a different
530 * environment block (in VBoxService before launching a new process).
531 */
532class GuestEnvironmentChanges : public GuestEnvironmentBase
533{
534public:
535 /**
536 * Default constructor.
537 *
538 * The user must invoke one of the init methods before using the object.
539 */
540 GuestEnvironmentChanges(void)
541 : GuestEnvironmentBase()
542 { }
543
544 /**
545 * Copy operator.
546 * @param rThat The object to copy.
547 * @throws HRESULT
548 */
549 GuestEnvironmentChanges(const GuestEnvironmentChanges &rThat)
550 : GuestEnvironmentBase(rThat, true /*fChangeRecord*/)
551 { }
552
553 /**
554 * Copy operator.
555 * @param rThat The object to copy.
556 * @throws HRESULT
557 */
558 GuestEnvironmentChanges(const GuestEnvironmentBase &rThat)
559 : GuestEnvironmentBase(rThat, true /*fChangeRecord*/)
560 { }
561
562 /**
563 * Initialize this as a environment change record.
564 * @returns IPRT status code.
565 * @param fFlags RTENV_CREATE_F_XXX
566 */
567 int initChangeRecord(uint32_t fFlags)
568 {
569 AssertReturn(m_hEnv == NIL_RTENV, VERR_WRONG_ORDER);
570 m_fFlags = fFlags;
571 return RTEnvCreateChangeRecordEx(&m_hEnv, fFlags);
572 }
573
574 /**
575 * Replaces this environemnt with that in @a rThat.
576 *
577 * @returns IPRT status code
578 * @param rThat The environment to copy. If it's a different type
579 * we'll convert the data to a set of changes.
580 */
581 int copy(const GuestEnvironmentBase &rThat)
582 {
583 return cloneCommon(rThat, true /*fChangeRecord*/);
584 }
585
586 /**
587 * @copydoc copy()
588 */
589 GuestEnvironmentChanges &operator=(const GuestEnvironmentBase &rThat)
590 {
591 int rc = copy(rThat);
592 if (RT_FAILURE(rc))
593 throw (Global::vboxStatusCodeToCOM(rc));
594 return *this;
595 }
596
597 /** @copydoc copy() */
598 GuestEnvironmentChanges &operator=(const GuestEnvironmentChanges &rThat)
599 { return operator=((const GuestEnvironmentBase &)rThat); }
600
601 /** @copydoc copy() */
602 GuestEnvironmentChanges &operator=(const GuestEnvironment &rThat)
603 { return operator=((const GuestEnvironmentBase &)rThat); }
604};
605
606
607/**
608 * Structure for keeping all the relevant guest directory
609 * information around.
610 */
611struct GuestDirectoryOpenInfo
612{
613 GuestDirectoryOpenInfo(void)
614 : mFlags(0) { }
615
616 /** The directory path. */
617 Utf8Str mPath;
618 /** Then open filter. */
619 Utf8Str mFilter;
620 /** Opening flags. */
621 uint32_t mFlags;
622};
623
624
625/**
626 * Structure for keeping all the relevant guest file
627 * information around.
628 */
629struct GuestFileOpenInfo
630{
631 GuestFileOpenInfo(void)
632 : mAccessMode((FileAccessMode_T)0)
633 , mOpenAction((FileOpenAction_T)0)
634 , mSharingMode((FileSharingMode_T)0)
635 , mCreationMode(0)
636 , mfOpenEx(0) { }
637
638 /** The filename. */
639 Utf8Str mFilename;
640 /** The file access mode. */
641 FileAccessMode_T mAccessMode;
642 /** The file open action. */
643 FileOpenAction_T mOpenAction;
644 /** The file sharing mode. */
645 FileSharingMode_T mSharingMode;
646 /** Octal creation mode. */
647 uint32_t mCreationMode;
648 /** Extended open flags (currently none defined). */
649 uint32_t mfOpenEx;
650};
651
652
653/**
654 * Structure representing information of a
655 * file system object.
656 */
657struct GuestFsObjData
658{
659 GuestFsObjData(void)
660 : mType(FsObjType_Unknown)
661 , mObjectSize(0)
662 , mAllocatedSize(0)
663 , mAccessTime(0)
664 , mBirthTime(0)
665 , mChangeTime(0)
666 , mModificationTime(0)
667 , mUID(0)
668 , mGID(0)
669 , mNodeID(0)
670 , mNodeIDDevice(0)
671 , mNumHardLinks(0)
672 , mDeviceNumber(0)
673 , mGenerationID(0)
674 , mUserFlags(0) { }
675
676 /** @name Helper functions to extract the data from a certin VBoxService tool's guest stream block.
677 * @{ */
678 int FromLs(const GuestProcessStreamBlock &strmBlk, bool fLong);
679 int FromStat(const GuestProcessStreamBlock &strmBlk);
680 int FromMkTemp(const GuestProcessStreamBlock &strmBlk);
681 /** @} */
682
683 /** @name Static helper functions to work with time from stream block keys.
684 * @{ */
685 static PRTTIMESPEC TimeSpecFromKey(const GuestProcessStreamBlock &strmBlk, const Utf8Str &strKey, PRTTIMESPEC pTimeSpec);
686 static int64_t UnixEpochNsFromKey(const GuestProcessStreamBlock &strmBlk, const Utf8Str &strKey);
687 /** @} */
688
689 /** @name helper functions to work with IPRT stuff.
690 * @{ */
691 RTFMODE GetFileMode(void) const;
692 /** @} */
693
694 Utf8Str mName;
695 FsObjType_T mType;
696 Utf8Str mFileAttrs;
697 int64_t mObjectSize;
698 int64_t mAllocatedSize;
699 int64_t mAccessTime;
700 int64_t mBirthTime;
701 int64_t mChangeTime;
702 int64_t mModificationTime;
703 Utf8Str mUserName;
704 int32_t mUID;
705 int32_t mGID;
706 Utf8Str mGroupName;
707 Utf8Str mACL;
708 int64_t mNodeID;
709 uint32_t mNodeIDDevice;
710 uint32_t mNumHardLinks;
711 uint32_t mDeviceNumber;
712 uint32_t mGenerationID;
713 uint32_t mUserFlags;
714};
715
716
717/**
718 * Structure for keeping all the relevant guest session
719 * startup parameters around.
720 */
721class GuestSessionStartupInfo
722{
723public:
724
725 GuestSessionStartupInfo(void)
726 : mIsInternal(false /* Non-internal session */),
727 mOpenTimeoutMS(30 * 1000 /* 30s opening timeout */),
728 mOpenFlags(0 /* No opening flags set */) { }
729
730 /** The session's friendly name. Optional. */
731 Utf8Str mName;
732 /** The session's unique ID. Used to encode a context ID. */
733 uint32_t mID;
734 /** Flag indicating if this is an internal session
735 * or not. Internal session are not accessible by
736 * public API clients. */
737 bool mIsInternal;
738 /** Timeout (in ms) used for opening the session. */
739 uint32_t mOpenTimeoutMS;
740 /** Session opening flags. */
741 uint32_t mOpenFlags;
742};
743
744
745/**
746 * Structure for keeping all the relevant guest process
747 * startup parameters around.
748 */
749class GuestProcessStartupInfo
750{
751public:
752
753 GuestProcessStartupInfo(void)
754 : mFlags(ProcessCreateFlag_None),
755 mTimeoutMS(UINT32_MAX /* No timeout by default */),
756 mPriority(ProcessPriority_Default) { }
757
758 /** The process' friendly name. */
759 Utf8Str mName;
760 /** The executable. */
761 Utf8Str mExecutable;
762 /** Arguments vector (starting with argument \#0). */
763 ProcessArguments mArguments;
764 /** The process environment change record. */
765 GuestEnvironmentChanges mEnvironmentChanges;
766 /** Process creation flags. */
767 uint32_t mFlags;
768 /** Timeout (in ms) the process is allowed to run.
769 * Specify UINT32_MAX if no timeout (unlimited run time) is given. */
770 ULONG mTimeoutMS;
771 /** Process priority. */
772 ProcessPriority_T mPriority;
773 /** Process affinity. At the moment we
774 * only support 64 VCPUs. API and
775 * guest can do more already! */
776 uint64_t mAffinity;
777};
778
779
780/**
781 * Class representing the "value" side of a "key=value" pair.
782 */
783class GuestProcessStreamValue
784{
785public:
786
787 GuestProcessStreamValue(void) { }
788 GuestProcessStreamValue(const char *pszValue)
789 : mValue(pszValue) {}
790
791 GuestProcessStreamValue(const GuestProcessStreamValue& aThat)
792 : mValue(aThat.mValue) { }
793
794 /** Copy assignment operator. */
795 GuestProcessStreamValue &operator=(GuestProcessStreamValue const &a_rThat) RT_NOEXCEPT
796 {
797 mValue = a_rThat.mValue;
798
799 return *this;
800 }
801
802 Utf8Str mValue;
803};
804
805/** Map containing "key=value" pairs of a guest process stream. */
806typedef std::pair< Utf8Str, GuestProcessStreamValue > GuestCtrlStreamPair;
807typedef std::map < Utf8Str, GuestProcessStreamValue > GuestCtrlStreamPairMap;
808typedef std::map < Utf8Str, GuestProcessStreamValue >::iterator GuestCtrlStreamPairMapIter;
809typedef std::map < Utf8Str, GuestProcessStreamValue >::const_iterator GuestCtrlStreamPairMapIterConst;
810
811/**
812 * Class representing a block of stream pairs (key=value). Each block in a raw guest
813 * output stream is separated by "\0\0", each pair is separated by "\0". The overall
814 * end of a guest stream is marked by "\0\0\0\0".
815 */
816class GuestProcessStreamBlock
817{
818public:
819
820 GuestProcessStreamBlock(void);
821
822 virtual ~GuestProcessStreamBlock(void);
823
824public:
825
826 void Clear(void);
827
828#ifdef DEBUG
829 void DumpToLog(void) const;
830#endif
831
832 const char *GetString(const char *pszKey) const;
833 size_t GetCount(void) const;
834 int GetRc(void) const;
835 int GetInt64Ex(const char *pszKey, int64_t *piVal) const;
836 int64_t GetInt64(const char *pszKey) const;
837 int GetUInt32Ex(const char *pszKey, uint32_t *puVal) const;
838 uint32_t GetUInt32(const char *pszKey, uint32_t uDefault = 0) const;
839 int32_t GetInt32(const char *pszKey, int32_t iDefault = 0) const;
840
841 bool IsEmpty(void) { return mPairs.empty(); }
842
843 int SetValue(const char *pszKey, const char *pszValue);
844
845protected:
846
847 GuestCtrlStreamPairMap mPairs;
848};
849
850/** Vector containing multiple allocated stream pair objects. */
851typedef std::vector< GuestProcessStreamBlock > GuestCtrlStreamObjects;
852typedef std::vector< GuestProcessStreamBlock >::iterator GuestCtrlStreamObjectsIter;
853typedef std::vector< GuestProcessStreamBlock >::const_iterator GuestCtrlStreamObjectsIterConst;
854
855/**
856 * Class for parsing machine-readable guest process output by VBoxService'
857 * toolbox commands ("vbox_ls", "vbox_stat" etc), aka "guest stream".
858 */
859class GuestProcessStream
860{
861
862public:
863
864 GuestProcessStream();
865
866 virtual ~GuestProcessStream();
867
868public:
869
870 int AddData(const BYTE *pbData, size_t cbData);
871
872 void Destroy();
873
874#ifdef DEBUG
875 void Dump(const char *pszFile);
876#endif
877
878 size_t GetOffset() { return m_offBuffer; }
879
880 size_t GetSize() { return m_cbUsed; }
881
882 int ParseBlock(GuestProcessStreamBlock &streamBlock);
883
884protected:
885
886 /** Currently allocated size of internal stream buffer. */
887 size_t m_cbAllocated;
888 /** Currently used size at m_offBuffer. */
889 size_t m_cbUsed;
890 /** Current byte offset within the internal stream buffer. */
891 size_t m_offBuffer;
892 /** Internal stream buffer. */
893 BYTE *m_pbBuffer;
894};
895
896class Guest;
897class Progress;
898
899class GuestTask
900{
901
902public:
903
904 enum TaskType
905 {
906 /** Copies a file from host to the guest. */
907 TaskType_CopyFileToGuest = 50,
908 /** Copies a file from guest to the host. */
909 TaskType_CopyFileFromGuest = 55,
910 /** Update Guest Additions by directly copying the required installer
911 * off the .ISO file, transfer it to the guest and execute the installer
912 * with system privileges. */
913 TaskType_UpdateGuestAdditions = 100
914 };
915
916 GuestTask(TaskType aTaskType, Guest *aThat, Progress *aProgress);
917
918 virtual ~GuestTask();
919
920 int startThread();
921
922 static int taskThread(RTTHREAD aThread, void *pvUser);
923 static int uploadProgress(unsigned uPercent, void *pvUser);
924 static HRESULT setProgressSuccess(ComObjPtr<Progress> pProgress);
925 static HRESULT setProgressErrorMsg(HRESULT hr,
926 ComObjPtr<Progress> pProgress, const char * pszText, ...);
927 static HRESULT setProgressErrorParent(HRESULT hr,
928 ComObjPtr<Progress> pProgress, ComObjPtr<Guest> pGuest);
929
930 TaskType taskType;
931 ComObjPtr<Guest> pGuest;
932 ComObjPtr<Progress> pProgress;
933 HRESULT rc;
934
935 /* Task data. */
936 Utf8Str strSource;
937 Utf8Str strDest;
938 Utf8Str strUserName;
939 Utf8Str strPassword;
940 ULONG uFlags;
941};
942
943class GuestWaitEventPayload
944{
945
946public:
947
948 GuestWaitEventPayload(void)
949 : uType(0),
950 cbData(0),
951 pvData(NULL) { }
952
953 GuestWaitEventPayload(uint32_t uTypePayload,
954 const void *pvPayload, uint32_t cbPayload)
955 : uType(0),
956 cbData(0),
957 pvData(NULL)
958 {
959 int rc = copyFrom(uTypePayload, pvPayload, cbPayload);
960 if (RT_FAILURE(rc))
961 throw rc;
962 }
963
964 virtual ~GuestWaitEventPayload(void)
965 {
966 Clear();
967 }
968
969 GuestWaitEventPayload& operator=(const GuestWaitEventPayload &that)
970 {
971 CopyFromDeep(that);
972 return *this;
973 }
974
975public:
976
977 void Clear(void)
978 {
979 if (pvData)
980 {
981 Assert(cbData);
982 RTMemFree(pvData);
983 cbData = 0;
984 pvData = NULL;
985 }
986 uType = 0;
987 }
988
989 int CopyFromDeep(const GuestWaitEventPayload &payload)
990 {
991 return copyFrom(payload.uType, payload.pvData, payload.cbData);
992 }
993
994 const void* Raw(void) const { return pvData; }
995
996 size_t Size(void) const { return cbData; }
997
998 uint32_t Type(void) const { return uType; }
999
1000 void* MutableRaw(void) { return pvData; }
1001
1002 Utf8Str ToString(void)
1003 {
1004 const char *pszStr = (const char *)pvData;
1005 size_t cbStr = cbData;
1006
1007 if (RT_FAILURE(RTStrValidateEncodingEx(pszStr, cbStr,
1008 RTSTR_VALIDATE_ENCODING_ZERO_TERMINATED | RTSTR_VALIDATE_ENCODING_EXACT_LENGTH)))
1009 {
1010 AssertFailed();
1011 return "";
1012 }
1013
1014 return Utf8Str(pszStr, cbStr);
1015 }
1016
1017protected:
1018
1019 int copyFrom(uint32_t uTypePayload, const void *pvPayload, uint32_t cbPayload)
1020 {
1021 if (cbPayload > _64K) /* Paranoia. */
1022 return VERR_TOO_MUCH_DATA;
1023
1024 Clear();
1025
1026 int rc = VINF_SUCCESS;
1027
1028 if (cbPayload)
1029 {
1030 pvData = RTMemAlloc(cbPayload);
1031 if (pvData)
1032 {
1033 uType = uTypePayload;
1034
1035 memcpy(pvData, pvPayload, cbPayload);
1036 cbData = cbPayload;
1037 }
1038 else
1039 rc = VERR_NO_MEMORY;
1040 }
1041 else
1042 {
1043 uType = uTypePayload;
1044
1045 pvData = NULL;
1046 cbData = 0;
1047 }
1048
1049 return rc;
1050 }
1051
1052protected:
1053
1054 /** Type of payload. */
1055 uint32_t uType;
1056 /** Size (in bytes) of payload. */
1057 uint32_t cbData;
1058 /** Pointer to actual payload data. */
1059 void *pvData;
1060};
1061
1062class GuestWaitEventBase
1063{
1064
1065protected:
1066
1067 GuestWaitEventBase(void);
1068 virtual ~GuestWaitEventBase(void);
1069
1070public:
1071
1072 uint32_t ContextID(void) { return mCID; };
1073 int GuestResult(void) { return mGuestRc; }
1074 int Result(void) { return mRc; }
1075 GuestWaitEventPayload & Payload(void) { return mPayload; }
1076 int SignalInternal(int rc, int guestRc, const GuestWaitEventPayload *pPayload);
1077 int Wait(RTMSINTERVAL uTimeoutMS);
1078
1079protected:
1080
1081 int Init(uint32_t uCID);
1082
1083protected:
1084
1085 /* Shutdown indicator. */
1086 bool mfAborted;
1087 /* Associated context ID (CID). */
1088 uint32_t mCID;
1089 /** The event semaphore for triggering
1090 * the actual event. */
1091 RTSEMEVENT mEventSem;
1092 /** The event's overall result. If
1093 * set to VERR_GSTCTL_GUEST_ERROR,
1094 * mGuestRc will contain the actual
1095 * error code from the guest side. */
1096 int mRc;
1097 /** The event'S overall result from the
1098 * guest side. If used, mRc must be
1099 * set to VERR_GSTCTL_GUEST_ERROR. */
1100 int mGuestRc;
1101 /** The event's payload data. Optional. */
1102 GuestWaitEventPayload mPayload;
1103};
1104
1105/** List of public guest event types. */
1106typedef std::list < VBoxEventType_T > GuestEventTypes;
1107
1108class GuestWaitEvent : public GuestWaitEventBase
1109{
1110
1111public:
1112
1113 GuestWaitEvent(void);
1114 virtual ~GuestWaitEvent(void);
1115
1116public:
1117
1118 int Init(uint32_t uCID);
1119 int Init(uint32_t uCID, const GuestEventTypes &lstEvents);
1120 int Cancel(void);
1121 const ComPtr<IEvent> Event(void) { return mEvent; }
1122 bool HasGuestError(void) const { return mRc == VERR_GSTCTL_GUEST_ERROR; }
1123 int GetGuestError(void) const { return mGuestRc; }
1124 int SignalExternal(IEvent *pEvent);
1125 const GuestEventTypes &Types(void) { return mEventTypes; }
1126 size_t TypeCount(void) { return mEventTypes.size(); }
1127
1128protected:
1129
1130 /** List of public event types this event should
1131 * be signalled on. Optional. */
1132 GuestEventTypes mEventTypes;
1133 /** Pointer to the actual public event, if any. */
1134 ComPtr<IEvent> mEvent;
1135};
1136/** Map of pointers to guest events. The primary key
1137 * contains the context ID. */
1138typedef std::map < uint32_t, GuestWaitEvent* > GuestWaitEvents;
1139/** Map of wait events per public guest event. Nice for
1140 * faster lookups when signalling a whole event group. */
1141typedef std::map < VBoxEventType_T, GuestWaitEvents > GuestEventGroup;
1142
1143class GuestBase
1144{
1145
1146public:
1147
1148 GuestBase(void);
1149 virtual ~GuestBase(void);
1150
1151public:
1152
1153 /** Signals a wait event using a public guest event; also used for
1154 * for external event listeners. */
1155 int signalWaitEvent(VBoxEventType_T aType, IEvent *aEvent);
1156 /** Signals a wait event using a guest rc. */
1157 int signalWaitEventInternal(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, int guestRc, const GuestWaitEventPayload *pPayload);
1158 /** Signals a wait event without letting public guest events know,
1159 * extended director's cut version. */
1160 int signalWaitEventInternalEx(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, int rc, int guestRc, const GuestWaitEventPayload *pPayload);
1161
1162public:
1163
1164 int baseInit(void);
1165 void baseUninit(void);
1166 int cancelWaitEvents(void);
1167 int dispatchGeneric(PVBOXGUESTCTRLHOSTCBCTX pCtxCb, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb);
1168 int generateContextID(uint32_t uSessionID, uint32_t uObjectID, uint32_t *puContextID);
1169 int registerWaitEvent(uint32_t uSessionID, uint32_t uObjectID, GuestWaitEvent **ppEvent);
1170 int registerWaitEventEx(uint32_t uSessionID, uint32_t uObjectID, const GuestEventTypes &lstEvents, GuestWaitEvent **ppEvent);
1171 int unregisterWaitEvent(GuestWaitEvent *pEvent);
1172 int waitForEvent(GuestWaitEvent *pEvent, uint32_t uTimeoutMS, VBoxEventType_T *pType, IEvent **ppEvent);
1173
1174public:
1175
1176 static FsObjType_T fileModeToFsObjType(RTFMODE fMode);
1177
1178protected:
1179
1180 /** Pointer to the console object. Needed
1181 * for HGCM (VMMDev) communication. */
1182 Console *mConsole;
1183 /** The next context ID counter component for this object. */
1184 uint32_t mNextContextID;
1185 /** Local listener for handling the waiting events
1186 * internally. */
1187 ComPtr<IEventListener> mLocalListener;
1188 /** Critical section for wait events access. */
1189 RTCRITSECT mWaitEventCritSect;
1190 /** Map of registered wait events per event group. */
1191 GuestEventGroup mWaitEventGroups;
1192 /** Map of registered wait events. */
1193 GuestWaitEvents mWaitEvents;
1194};
1195
1196/**
1197 * Virtual class (interface) for guest objects (processes, files, ...) --
1198 * contains all per-object callback management.
1199 */
1200class GuestObject : public GuestBase
1201{
1202 friend class GuestSession;
1203
1204public:
1205
1206 GuestObject(void);
1207 virtual ~GuestObject(void);
1208
1209public:
1210
1211 ULONG getObjectID(void) { return mObjectID; }
1212
1213protected:
1214
1215 /**
1216 * Called by IGuestSession when the session status has been changed.
1217 *
1218 * @returns VBox status code.
1219 * @param enmSessionStatus New session status.
1220 */
1221 virtual int i_onSessionStatusChange(GuestSessionStatus_T enmSessionStatus) = 0;
1222
1223 /**
1224 * Called by IGuestSession right before this object gets
1225 * unregistered (removed) from the public object list.
1226 */
1227 virtual int i_onUnregister(void) = 0;
1228
1229 /** Callback dispatcher -- must be implemented by the actual object. */
1230 virtual int i_callbackDispatcher(PVBOXGUESTCTRLHOSTCBCTX pCbCtx, PVBOXGUESTCTRLHOSTCALLBACK pSvcCb) = 0;
1231
1232protected:
1233
1234 int bindToSession(Console *pConsole, GuestSession *pSession, uint32_t uObjectID);
1235 int registerWaitEvent(const GuestEventTypes &lstEvents, GuestWaitEvent **ppEvent);
1236 int sendMessage(uint32_t uFunction, uint32_t cParms, PVBOXHGCMSVCPARM paParms);
1237
1238protected:
1239
1240 /** @name Common parameters for all derived objects. They have their own
1241 * mData structure to keep their specific data around.
1242 * @{ */
1243 /** Pointer to parent session. Per definition
1244 * this objects *always* lives shorter than the
1245 * parent.
1246 * @todo r=bird: When wanting to use mSession in the
1247 * IGuestProcess::getEnvironment() implementation I wanted to access
1248 * GuestSession::mData::mpBaseEnvironment. Seeing the comment in
1249 * GuestProcess::terminate() saying:
1250 * "Now only API clients still can hold references to it."
1251 * and recalling seeing similar things in VirtualBox.xidl or some such place,
1252 * I'm wondering how this "per definition" behavior is enforced. Is there any
1253 * GuestProcess:uninit() call or similar magic that invalidates objects that
1254 * GuestSession loses track of in place like GuestProcess::terminate() that I've
1255 * failed to spot?
1256 *
1257 * Please enlighten me.
1258 */
1259 GuestSession *mSession;
1260 /** The object ID -- must be unique for each guest
1261 * object and is encoded into the context ID. Must
1262 * be set manually when initializing the object.
1263 *
1264 * For guest processes this is the internal PID,
1265 * for guest files this is the internal file ID. */
1266 uint32_t mObjectID;
1267 /** @} */
1268};
1269#endif /* !MAIN_INCLUDED_GuestCtrlImplPrivate_h */
1270
注意: 瀏覽 TracBrowser 來幫助您使用儲存庫瀏覽器

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