VirtualBox

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

Last change on this file since 55594 was 55594, checked in by vboxsync, 9 years ago

copy by assignment fix.

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