VirtualBox

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

Last change on this file since 97395 was 97395, checked in by vboxsync, 2 years ago

Guest Control/Main: Rewrite of the path building and directory walking code for the copyFrom / copyTo guest session tasks, to (hopefully) have a cleaner structure. The new path building now also takes into account whether a destination has a trailing delimiter and then act accordingly (see rules in GuestPath::BuildDestinationPath()). Adjusted VBoxManage and FE/Qt to also reflect that; should now work as common tools like cp. Added new test cases and also re-enabled old ones which were disabled since quite a while (should pass now). ​bugref:10286

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