VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxManageGuestCtrl.cpp@ 107380

Last change on this file since 107380 was 107344, checked in by vboxsync, 4 months ago

FE/VBoxManage: Format string fixes for verbose Guest Control sub commands.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 149.3 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 107344 2024-12-17 17:41:21Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010-2024 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
29/*********************************************************************************************************************************
30* Header Files *
31*********************************************************************************************************************************/
32#include "VBoxManage.h"
33#include "VBoxManageGuestCtrl.h"
34
35#include <VBox/com/array.h>
36#include <VBox/com/com.h>
37#include <VBox/com/ErrorInfo.h>
38#include <VBox/com/errorprint.h>
39#include <VBox/com/listeners.h>
40#include <VBox/com/NativeEventQueue.h>
41#include <VBox/com/string.h>
42#include <VBox/com/VirtualBox.h>
43
44#include <VBox/err.h>
45#include <VBox/log.h>
46
47#include <iprt/asm.h>
48#include <iprt/dir.h>
49#include <iprt/file.h>
50#include <iprt/getopt.h>
51#include <iprt/list.h>
52#include <iprt/path.h>
53#include <iprt/process.h> /* For RTProcSelf(). */
54#include <iprt/semaphore.h>
55#include <iprt/thread.h>
56#include <iprt/vfs.h>
57
58#include <iprt/cpp/path.h>
59
60#include <map>
61#include <vector>
62
63#ifdef USE_XPCOM_QUEUE
64# include <sys/select.h>
65# include <errno.h>
66#endif
67
68#include <signal.h>
69
70#ifdef RT_OS_DARWIN
71# include <CoreFoundation/CFRunLoop.h>
72#endif
73
74using namespace com;
75
76
77/*********************************************************************************************************************************
78 * Defined Constants And Macros *
79*********************************************************************************************************************************/
80
81#define GCTLCMD_COMMON_OPT_USER 999 /**< The --username option number. */
82#define GCTLCMD_COMMON_OPT_PASSWORD 998 /**< The --password option number. */
83#define GCTLCMD_COMMON_OPT_PASSWORD_FILE 997 /**< The --password-file option number. */
84#define GCTLCMD_COMMON_OPT_DOMAIN 996 /**< The --domain option number. */
85/** Common option definitions. */
86#define GCTLCMD_COMMON_OPTION_DEFS() \
87 { "--user", GCTLCMD_COMMON_OPT_USER, RTGETOPT_REQ_STRING }, \
88 { "--username", GCTLCMD_COMMON_OPT_USER, RTGETOPT_REQ_STRING }, \
89 { "--passwordfile", GCTLCMD_COMMON_OPT_PASSWORD_FILE, RTGETOPT_REQ_STRING }, \
90 { "--password", GCTLCMD_COMMON_OPT_PASSWORD, RTGETOPT_REQ_STRING }, \
91 { "--domain", GCTLCMD_COMMON_OPT_DOMAIN, RTGETOPT_REQ_STRING }, \
92 { "--quiet", 'q', RTGETOPT_REQ_NOTHING }, \
93 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
94
95/** Handles common options in the typical option parsing switch. */
96#define GCTLCMD_COMMON_OPTION_CASES(a_pCtx, a_ch, a_pValueUnion) \
97 case 'v': \
98 case 'q': \
99 case GCTLCMD_COMMON_OPT_USER: \
100 case GCTLCMD_COMMON_OPT_DOMAIN: \
101 case GCTLCMD_COMMON_OPT_PASSWORD: \
102 case GCTLCMD_COMMON_OPT_PASSWORD_FILE: \
103 { \
104 RTEXITCODE rcExitCommon = gctlCtxSetOption(a_pCtx, a_ch, a_pValueUnion); \
105 if (RT_UNLIKELY(rcExitCommon != RTEXITCODE_SUCCESS)) \
106 return rcExitCommon; \
107 } break
108
109
110/*********************************************************************************************************************************
111* Global Variables *
112*********************************************************************************************************************************/
113/** Set by the signal handler when current guest control
114 * action shall be aborted. */
115static volatile bool g_fGuestCtrlCanceled = false;
116/** Event semaphore used for wait notifications.
117 * Also being used for the listener implementations in VBoxManageGuestCtrlListener.cpp. */
118 RTSEMEVENT g_SemEventGuestCtrlCanceled = NIL_RTSEMEVENT;
119
120
121/*********************************************************************************************************************************
122* Structures and Typedefs *
123*********************************************************************************************************************************/
124/**
125 * Listener declarations.
126 */
127VBOX_LISTENER_DECLARE(GuestFileEventListenerImpl)
128VBOX_LISTENER_DECLARE(GuestProcessEventListenerImpl)
129VBOX_LISTENER_DECLARE(GuestSessionEventListenerImpl)
130VBOX_LISTENER_DECLARE(GuestEventListenerImpl)
131VBOX_LISTENER_DECLARE(GuestAdditionsRunlevelListener)
132
133/**
134 * Definition of a guestcontrol command, with handler and various flags.
135 */
136typedef struct GCTLCMDDEF
137{
138 /** The command name. */
139 const char *pszName;
140
141 /**
142 * Actual command handler callback.
143 *
144 * @param pCtx Pointer to command context to use.
145 */
146 DECLR3CALLBACKMEMBER(RTEXITCODE, pfnHandler, (struct GCTLCMDCTX *pCtx, int argc, char **argv));
147
148 /** The sub-command scope flags. */
149 uint64_t fSubcommandScope;
150 /** Command context flags (GCTLCMDCTX_F_XXX). */
151 uint32_t fCmdCtx;
152} GCTLCMD;
153/** Pointer to a const guest control command definition. */
154typedef GCTLCMDDEF const *PCGCTLCMDDEF;
155
156/** @name GCTLCMDCTX_F_XXX - Command context flags.
157 * @{
158 */
159/** No flags set. */
160#define GCTLCMDCTX_F_NONE 0
161/** Don't install a signal handler (CTRL+C trap). */
162#define GCTLCMDCTX_F_NO_SIGNAL_HANDLER RT_BIT(0)
163/** No guest session needed. */
164#define GCTLCMDCTX_F_SESSION_ANONYMOUS RT_BIT(1)
165/** @} */
166
167/**
168 * Context for handling a specific command.
169 */
170typedef struct GCTLCMDCTX
171{
172 HandlerArg *pArg;
173
174 /** Pointer to the command definition. */
175 PCGCTLCMDDEF pCmdDef;
176 /** The VM name or UUID. */
177 const char *pszVmNameOrUuid;
178
179 /** Whether we've done the post option parsing init already. */
180 bool fPostOptionParsingInited;
181 /** Whether we've locked the VM session. */
182 bool fLockedVmSession;
183 /** Whether to detach (@c true) or close the session. */
184 bool fDetachGuestSession;
185 /** Set if we've installed the signal handler. */
186 bool fInstalledSignalHandler;
187 /** The verbosity level. */
188 uint32_t cVerbose;
189 /** User name. */
190 Utf8Str strUsername;
191 /** Password. */
192 Utf8Str strPassword;
193 /** Domain. */
194 Utf8Str strDomain;
195 /** Pointer to the IGuest interface. */
196 ComPtr<IGuest> pGuest;
197 /** Pointer to the to be used guest session. */
198 ComPtr<IGuestSession> pGuestSession;
199 /** The guest session ID. */
200 ULONG uSessionID;
201
202} GCTLCMDCTX, *PGCTLCMDCTX;
203
204
205/**
206 * An entry for an element which needs to be copied/created to/on the guest.
207 */
208typedef struct DESTFILEENTRY
209{
210 DESTFILEENTRY(Utf8Str strFilename) : mFilename(strFilename) {}
211 Utf8Str mFilename;
212} DESTFILEENTRY, *PDESTFILEENTRY;
213/*
214 * Map for holding destination entries, whereas the key is the destination
215 * directory and the mapped value is a vector holding all elements for this directory.
216 */
217typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> > DESTDIRMAP, *PDESTDIRMAP;
218typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> >::iterator DESTDIRMAPITER, *PDESTDIRMAPITER;
219
220
221enum kStreamTransform
222{
223 kStreamTransform_None = 0,
224 kStreamTransform_Dos2Unix,
225 kStreamTransform_Unix2Dos
226};
227
228
229DECLARE_TRANSLATION_CONTEXT(GuestCtrl);
230
231
232#ifdef RT_OS_WINDOWS
233static BOOL WINAPI gctlSignalHandler(DWORD dwCtrlType) RT_NOTHROW_DEF
234{
235 bool fEventHandled = FALSE;
236 switch (dwCtrlType)
237 {
238 /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
239 * via GenerateConsoleCtrlEvent(). */
240 case CTRL_BREAK_EVENT:
241 case CTRL_CLOSE_EVENT:
242 case CTRL_C_EVENT:
243 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
244 RTSemEventSignal(g_SemEventGuestCtrlCanceled);
245 fEventHandled = TRUE;
246 break;
247 default:
248 break;
249 /** @todo Add other events here. */
250 }
251
252 return fEventHandled;
253}
254#else /* !RT_OS_WINDOWS */
255/**
256 * Signal handler that sets g_fGuestCtrlCanceled.
257 *
258 * This can be executed on any thread in the process, on Windows it may even be
259 * a thread dedicated to delivering this signal. Don't do anything
260 * unnecessary here.
261 */
262static void gctlSignalHandler(int iSignal) RT_NOTHROW_DEF
263{
264 RT_NOREF(iSignal);
265 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
266 RTSemEventSignal(g_SemEventGuestCtrlCanceled);
267}
268#endif
269
270
271/**
272 * Installs a custom signal handler to get notified
273 * whenever the user wants to intercept the program.
274 *
275 * @todo Make this handler available for all VBoxManage modules?
276 */
277static int gctlSignalHandlerInstall(void)
278{
279 g_fGuestCtrlCanceled = false;
280
281 int vrc = VINF_SUCCESS;
282#ifdef RT_OS_WINDOWS
283 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)gctlSignalHandler, TRUE /* Add handler */))
284 {
285 vrc = RTErrConvertFromWin32(GetLastError());
286 RTMsgError(GuestCtrl::tr("Unable to install console control handler, vrc=%Rrc\n"), vrc);
287 }
288#else
289 signal(SIGINT, gctlSignalHandler);
290 signal(SIGTERM, gctlSignalHandler);
291# ifdef SIGBREAK
292 signal(SIGBREAK, gctlSignalHandler);
293# endif
294#endif
295
296 if (RT_SUCCESS(vrc))
297 vrc = RTSemEventCreate(&g_SemEventGuestCtrlCanceled);
298
299 return vrc;
300}
301
302
303/**
304 * Uninstalls a previously installed signal handler.
305 */
306static int gctlSignalHandlerUninstall(void)
307{
308 int vrc = VINF_SUCCESS;
309#ifdef RT_OS_WINDOWS
310 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
311 {
312 vrc = RTErrConvertFromWin32(GetLastError());
313 RTMsgError(GuestCtrl::tr("Unable to uninstall console control handler, vrc=%Rrc\n"), vrc);
314 }
315#else
316 signal(SIGINT, SIG_DFL);
317 signal(SIGTERM, SIG_DFL);
318# ifdef SIGBREAK
319 signal(SIGBREAK, SIG_DFL);
320# endif
321#endif
322
323 if (g_SemEventGuestCtrlCanceled != NIL_RTSEMEVENT)
324 {
325 RTSemEventDestroy(g_SemEventGuestCtrlCanceled);
326 g_SemEventGuestCtrlCanceled = NIL_RTSEMEVENT;
327 }
328 return vrc;
329}
330
331
332/**
333 * Translates a process status to a human readable string.
334 *
335 * @sa GuestProcess::i_statusToString()
336 */
337const char *gctlProcessStatusToText(ProcessStatus_T enmStatus)
338{
339 switch (enmStatus)
340 {
341 case ProcessStatus_Starting:
342 return GuestCtrl::tr("starting");
343 case ProcessStatus_Started:
344 return GuestCtrl::tr("started");
345 case ProcessStatus_Paused:
346 return GuestCtrl::tr("paused");
347 case ProcessStatus_Terminating:
348 return GuestCtrl::tr("terminating");
349 case ProcessStatus_TerminatedNormally:
350 return GuestCtrl::tr("successfully terminated");
351 case ProcessStatus_TerminatedSignal:
352 return GuestCtrl::tr("terminated by signal");
353 case ProcessStatus_TerminatedAbnormally:
354 return GuestCtrl::tr("abnormally aborted");
355 case ProcessStatus_TimedOutKilled:
356 return GuestCtrl::tr("timed out");
357 case ProcessStatus_TimedOutAbnormally:
358 return GuestCtrl::tr("timed out, hanging");
359 case ProcessStatus_Down:
360 return GuestCtrl::tr("killed");
361 case ProcessStatus_Error:
362 return GuestCtrl::tr("error");
363 default:
364 break;
365 }
366 return GuestCtrl::tr("unknown");
367}
368
369/**
370 * Translates a guest process wait result to a human readable string.
371 */
372static const char *gctlProcessWaitResultToText(ProcessWaitResult_T enmWaitResult)
373{
374 switch (enmWaitResult)
375 {
376 case ProcessWaitResult_Start:
377 return GuestCtrl::tr("started");
378 case ProcessWaitResult_Terminate:
379 return GuestCtrl::tr("terminated");
380 case ProcessWaitResult_Status:
381 return GuestCtrl::tr("status changed");
382 case ProcessWaitResult_Error:
383 return GuestCtrl::tr("error");
384 case ProcessWaitResult_Timeout:
385 return GuestCtrl::tr("timed out");
386 case ProcessWaitResult_StdIn:
387 return GuestCtrl::tr("stdin ready");
388 case ProcessWaitResult_StdOut:
389 return GuestCtrl::tr("data on stdout");
390 case ProcessWaitResult_StdErr:
391 return GuestCtrl::tr("data on stderr");
392 case ProcessWaitResult_WaitFlagNotSupported:
393 return GuestCtrl::tr("waiting flag not supported");
394 default:
395 break;
396 }
397 return GuestCtrl::tr("unknown");
398}
399
400/**
401 * Translates a guest session status to a human readable string.
402 */
403const char *gctlGuestSessionStatusToText(GuestSessionStatus_T enmStatus)
404{
405 switch (enmStatus)
406 {
407 case GuestSessionStatus_Starting:
408 return GuestCtrl::tr("starting");
409 case GuestSessionStatus_Started:
410 return GuestCtrl::tr("started");
411 case GuestSessionStatus_Terminating:
412 return GuestCtrl::tr("terminating");
413 case GuestSessionStatus_Terminated:
414 return GuestCtrl::tr("terminated");
415 case GuestSessionStatus_TimedOutKilled:
416 return GuestCtrl::tr("timed out");
417 case GuestSessionStatus_TimedOutAbnormally:
418 return GuestCtrl::tr("timed out, hanging");
419 case GuestSessionStatus_Down:
420 return GuestCtrl::tr("killed");
421 case GuestSessionStatus_Error:
422 return GuestCtrl::tr("error");
423 default:
424 break;
425 }
426 return GuestCtrl::tr("unknown");
427}
428
429/**
430 * Translates a guest file status to a human readable string.
431 */
432const char *gctlFileStatusToText(FileStatus_T enmStatus)
433{
434 switch (enmStatus)
435 {
436 case FileStatus_Opening:
437 return GuestCtrl::tr("opening");
438 case FileStatus_Open:
439 return GuestCtrl::tr("open");
440 case FileStatus_Closing:
441 return GuestCtrl::tr("closing");
442 case FileStatus_Closed:
443 return GuestCtrl::tr("closed");
444 case FileStatus_Down:
445 return GuestCtrl::tr("killed");
446 case FileStatus_Error:
447 return GuestCtrl::tr("error");
448 default:
449 break;
450 }
451 return GuestCtrl::tr("unknown");
452}
453
454/**
455 * Translates a file system objec type to a string.
456 */
457static const char *gctlFsObjTypeToName(FsObjType_T enmType)
458{
459 switch (enmType)
460 {
461 case FsObjType_Unknown: return GuestCtrl::tr("unknown");
462 case FsObjType_Fifo: return GuestCtrl::tr("fifo");
463 case FsObjType_DevChar: return GuestCtrl::tr("char-device");
464 case FsObjType_Directory: return GuestCtrl::tr("directory");
465 case FsObjType_DevBlock: return GuestCtrl::tr("block-device");
466 case FsObjType_File: return GuestCtrl::tr("file");
467 case FsObjType_Symlink: return GuestCtrl::tr("symlink");
468 case FsObjType_Socket: return GuestCtrl::tr("socket");
469 case FsObjType_WhiteOut: return GuestCtrl::tr("white-out");
470#ifdef VBOX_WITH_XPCOM_CPP_ENUM_HACK
471 case FsObjType_32BitHack: break;
472#endif
473 }
474 return GuestCtrl::tr("unknown");
475}
476
477static int gctlPrintError(com::ErrorInfo &errorInfo)
478{
479 if ( errorInfo.isFullAvailable()
480 || errorInfo.isBasicAvailable())
481 {
482 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
483 * because it contains more accurate info about what went wrong. */
484 if (errorInfo.getResultCode() == VBOX_E_IPRT_ERROR)
485 RTMsgError("%ls.", errorInfo.getText().raw());
486 else
487 {
488 RTMsgError(GuestCtrl::tr("Error details:"));
489 GluePrintErrorInfo(errorInfo);
490 }
491 return VERR_GENERAL_FAILURE; /** @todo */
492 }
493 AssertMsgFailedReturn((GuestCtrl::tr("Object has indicated no error (%Rhrc)!?\n"), errorInfo.getResultCode()),
494 VERR_INVALID_PARAMETER);
495}
496
497static int gctlPrintError(IUnknown *pObj, const GUID &aIID)
498{
499 com::ErrorInfo ErrInfo(pObj, aIID);
500 return gctlPrintError(ErrInfo);
501}
502
503static int gctlPrintProgressError(ComPtr<IProgress> pProgress)
504{
505 int vrc = VINF_SUCCESS;
506 HRESULT hrc;
507
508 do
509 {
510 BOOL fCanceled;
511 CHECK_ERROR_BREAK(pProgress, COMGETTER(Canceled)(&fCanceled));
512 if (!fCanceled)
513 {
514 LONG rcProc;
515 CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&rcProc));
516 if (FAILED(rcProc))
517 {
518 com::ProgressErrorInfo ErrInfo(pProgress);
519 vrc = gctlPrintError(ErrInfo);
520 }
521 }
522
523 } while(0);
524
525 AssertMsgStmt(SUCCEEDED(hrc), (GuestCtrl::tr("Could not lookup progress information\n")), vrc = VERR_COM_UNEXPECTED);
526
527 return vrc;
528}
529
530
531
532/*
533 *
534 *
535 * Guest Control Command Context
536 * Guest Control Command Context
537 * Guest Control Command Context
538 * Guest Control Command Context
539 *
540 *
541 *
542 */
543
544
545/**
546 * Initializes a guest control command context structure.
547 *
548 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE on failure (after
549 * informing the user of course).
550 * @param pCtx The command context to init.
551 * @param pArg The handle argument package.
552 */
553static RTEXITCODE gctrCmdCtxInit(PGCTLCMDCTX pCtx, HandlerArg *pArg)
554{
555 pCtx->pArg = pArg;
556 pCtx->pCmdDef = NULL;
557 pCtx->pszVmNameOrUuid = NULL;
558 pCtx->fPostOptionParsingInited = false;
559 pCtx->fLockedVmSession = false;
560 pCtx->fDetachGuestSession = false;
561 pCtx->fInstalledSignalHandler = false;
562 pCtx->cVerbose = 0;
563 pCtx->strUsername.setNull();
564 pCtx->strPassword.setNull();
565 pCtx->strDomain.setNull();
566 pCtx->pGuest.setNull();
567 pCtx->pGuestSession.setNull();
568 pCtx->uSessionID = 0;
569
570 /*
571 * The user name defaults to the host one, if we can get at it.
572 */
573 char szUser[1024];
574 int vrc = RTProcQueryUsername(RTProcSelf(), szUser, sizeof(szUser), NULL);
575 if ( RT_SUCCESS(vrc)
576 && RTStrIsValidEncoding(szUser)) /* paranoia was required on posix at some point, not needed any more! */
577 {
578 try
579 {
580 pCtx->strUsername = szUser;
581 }
582 catch (std::bad_alloc &)
583 {
584 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory"));
585 }
586 }
587 /* else: ignore this failure. */
588
589 return RTEXITCODE_SUCCESS;
590}
591
592
593/**
594 * Worker for GCTLCMD_COMMON_OPTION_CASES.
595 *
596 * @returns RTEXITCODE_SUCCESS if the option was handled successfully. If not,
597 * an error message is printed and an appropriate failure exit code is
598 * returned.
599 * @param pCtx The guest control command context.
600 * @param ch The option char or ordinal.
601 * @param pValueUnion The option value union.
602 */
603static RTEXITCODE gctlCtxSetOption(PGCTLCMDCTX pCtx, int ch, PRTGETOPTUNION pValueUnion)
604{
605 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
606 switch (ch)
607 {
608 case GCTLCMD_COMMON_OPT_USER: /* User name */
609 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
610 pCtx->strUsername = pValueUnion->psz;
611 else
612 RTMsgWarning(GuestCtrl::tr("The --username|-u option is ignored by '%s'"), pCtx->pCmdDef->pszName);
613 break;
614
615 case GCTLCMD_COMMON_OPT_PASSWORD: /* Password */
616 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
617 {
618 if (pCtx->strPassword.isNotEmpty())
619 RTMsgWarning(GuestCtrl::tr("Password is given more than once."));
620 pCtx->strPassword = pValueUnion->psz;
621 }
622 else
623 RTMsgWarning(GuestCtrl::tr("The --password option is ignored by '%s'"), pCtx->pCmdDef->pszName);
624 break;
625
626 case GCTLCMD_COMMON_OPT_PASSWORD_FILE: /* Password file */
627 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
628 rcExit = readPasswordFile(pValueUnion->psz, &pCtx->strPassword);
629 else
630 RTMsgWarning(GuestCtrl::tr("The --password-file|-p option is ignored by '%s'"), pCtx->pCmdDef->pszName);
631 break;
632
633 case GCTLCMD_COMMON_OPT_DOMAIN: /* domain */
634 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
635 pCtx->strDomain = pValueUnion->psz;
636 else
637 RTMsgWarning(GuestCtrl::tr("The --domain option is ignored by '%s'"), pCtx->pCmdDef->pszName);
638 break;
639
640 case 'v': /* --verbose */
641 pCtx->cVerbose++;
642 break;
643
644 case 'q': /* --quiet */
645 if (pCtx->cVerbose)
646 pCtx->cVerbose--;
647 break;
648
649 default:
650 AssertFatalMsgFailed(("ch=%d (%c)\n", ch, ch));
651 }
652 return rcExit;
653}
654
655
656/**
657 * Initializes the VM for IGuest operation.
658 *
659 * This opens a shared session to a running VM and gets hold of IGuest.
660 *
661 * @returns RTEXITCODE_SUCCESS on success. RTEXITCODE_FAILURE and user message
662 * on failure.
663 * @param pCtx The guest control command context.
664 * GCTLCMDCTX::pGuest will be set on success.
665 */
666static RTEXITCODE gctlCtxInitVmSession(PGCTLCMDCTX pCtx)
667{
668 HRESULT hrc;
669 AssertPtr(pCtx);
670 AssertPtr(pCtx->pArg);
671
672 /*
673 * Find the VM and check if it's running.
674 */
675 ComPtr<IMachine> machine;
676 CHECK_ERROR(pCtx->pArg->virtualBox, FindMachine(Bstr(pCtx->pszVmNameOrUuid).raw(), machine.asOutParam()));
677 if (SUCCEEDED(hrc))
678 {
679 MachineState_T enmMachineState;
680 CHECK_ERROR(machine, COMGETTER(State)(&enmMachineState));
681 if ( SUCCEEDED(hrc)
682 && enmMachineState == MachineState_Running)
683 {
684 /*
685 * It's running. So, open a session to it and get the IGuest interface.
686 */
687 CHECK_ERROR(machine, LockMachine(pCtx->pArg->session, LockType_Shared));
688 if (SUCCEEDED(hrc))
689 {
690 pCtx->fLockedVmSession = true;
691 ComPtr<IConsole> ptrConsole;
692 CHECK_ERROR(pCtx->pArg->session, COMGETTER(Console)(ptrConsole.asOutParam()));
693 if (SUCCEEDED(hrc))
694 {
695 if (ptrConsole.isNotNull())
696 {
697 CHECK_ERROR(ptrConsole, COMGETTER(Guest)(pCtx->pGuest.asOutParam()));
698 if (SUCCEEDED(hrc))
699 return RTEXITCODE_SUCCESS;
700 }
701 else
702 RTMsgError(GuestCtrl::tr("Failed to get a IConsole pointer for the machine. Is it still running?\n"));
703 }
704 }
705 }
706 else if (SUCCEEDED(hrc))
707 RTMsgError(GuestCtrl::tr("Machine \"%s\" is not running (currently %s)!\n"),
708 pCtx->pszVmNameOrUuid, machineStateToName(enmMachineState, false));
709 }
710 return RTEXITCODE_FAILURE;
711}
712
713
714/**
715 * Creates a guest session with the VM.
716 *
717 * @retval RTEXITCODE_SUCCESS on success.
718 * @retval RTEXITCODE_FAILURE and user message on failure.
719 * @param pCtx The guest control command context.
720 * GCTCMDCTX::pGuestSession and GCTLCMDCTX::uSessionID
721 * will be set.
722 */
723static RTEXITCODE gctlCtxInitGuestSession(PGCTLCMDCTX pCtx)
724{
725 HRESULT hrc;
726 AssertPtr(pCtx);
727 Assert(!(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS));
728 Assert(pCtx->pGuest.isNotNull());
729
730 /*
731 * Build up a reasonable guest session name. Useful for identifying
732 * a specific session when listing / searching for them.
733 */
734 char *pszSessionName;
735 if (RTStrAPrintf(&pszSessionName,
736 GuestCtrl::tr("[%RU32] VBoxManage Guest Control [%s] - %s"),
737 RTProcSelf(), pCtx->pszVmNameOrUuid, pCtx->pCmdDef->pszName) < 0)
738 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("No enough memory for session name"));
739
740 /*
741 * Create a guest session.
742 */
743 if (pCtx->cVerbose)
744 RTPrintf(GuestCtrl::tr("Creating guest session as user '%s'...\n"), pCtx->strUsername.c_str());
745 try
746 {
747 CHECK_ERROR(pCtx->pGuest, CreateSession(Bstr(pCtx->strUsername).raw(),
748 Bstr(pCtx->strPassword).raw(),
749 Bstr(pCtx->strDomain).raw(),
750 Bstr(pszSessionName).raw(),
751 pCtx->pGuestSession.asOutParam()));
752 }
753 catch (std::bad_alloc &)
754 {
755 RTMsgError(GuestCtrl::tr("Out of memory setting up IGuest::CreateSession call"));
756 hrc = E_OUTOFMEMORY;
757 }
758 if (SUCCEEDED(hrc))
759 {
760 /*
761 * Wait for guest session to start.
762 */
763 if (pCtx->cVerbose)
764 RTPrintf(GuestCtrl::tr("Waiting for guest session to start...\n"));
765 GuestSessionWaitResult_T enmWaitResult = GuestSessionWaitResult_None; /* Shut up MSC */
766 try
767 {
768 com::SafeArray<GuestSessionWaitForFlag_T> aSessionWaitFlags;
769 aSessionWaitFlags.push_back(GuestSessionWaitForFlag_Start);
770 CHECK_ERROR(pCtx->pGuestSession, WaitForArray(ComSafeArrayAsInParam(aSessionWaitFlags),
771 /** @todo Make session handling timeouts configurable. */
772 30 * 1000, &enmWaitResult));
773 }
774 catch (std::bad_alloc &)
775 {
776 RTMsgError(GuestCtrl::tr("Out of memory setting up IGuestSession::WaitForArray call"));
777 hrc = E_OUTOFMEMORY;
778 }
779 if (SUCCEEDED(hrc))
780 {
781 /* The WaitFlagNotSupported result may happen with GAs older than 4.3. */
782 if ( enmWaitResult == GuestSessionWaitResult_Start
783 || enmWaitResult == GuestSessionWaitResult_WaitFlagNotSupported)
784 {
785 /*
786 * Get the session ID and we're ready to rumble.
787 */
788 CHECK_ERROR(pCtx->pGuestSession, COMGETTER(Id)(&pCtx->uSessionID));
789 if (SUCCEEDED(hrc))
790 {
791 if (pCtx->cVerbose)
792 RTPrintf(GuestCtrl::tr("Successfully started guest session (ID %RU32)\n"), pCtx->uSessionID);
793 RTStrFree(pszSessionName);
794 return RTEXITCODE_SUCCESS;
795 }
796 }
797 else
798 {
799 GuestSessionStatus_T enmSessionStatus;
800 CHECK_ERROR(pCtx->pGuestSession, COMGETTER(Status)(&enmSessionStatus));
801 RTMsgError(GuestCtrl::tr("Error starting guest session (current status is: %s)\n"),
802 SUCCEEDED(hrc) ? gctlGuestSessionStatusToText(enmSessionStatus) : GuestCtrl::tr("<unknown>"));
803 }
804 }
805 }
806
807 RTStrFree(pszSessionName);
808 return RTEXITCODE_FAILURE;
809}
810
811
812/**
813 * Completes the guest control context initialization after parsing arguments.
814 *
815 * Will validate common arguments, open a VM session, and if requested open a
816 * guest session and install the CTRL-C signal handler.
817 *
818 * It is good to validate all the options and arguments you can before making
819 * this call. However, the VM session, IGuest and IGuestSession interfaces are
820 * not availabe till after this call, so take care.
821 *
822 * @retval RTEXITCODE_SUCCESS on success.
823 * @retval RTEXITCODE_FAILURE and user message on failure.
824 * @param pCtx The guest control command context.
825 * GCTCMDCTX::pGuestSession and GCTLCMDCTX::uSessionID
826 * will be set.
827 * @remarks Can safely be called multiple times, will only do work once.
828 */
829static RTEXITCODE gctlCtxPostOptionParsingInit(PGCTLCMDCTX pCtx)
830{
831 if (pCtx->fPostOptionParsingInited)
832 return RTEXITCODE_SUCCESS;
833
834 /*
835 * Check that the user name isn't empty when we need it.
836 */
837 RTEXITCODE rcExit;
838 if ( (pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS)
839 || pCtx->strUsername.isNotEmpty())
840 {
841 /*
842 * Open the VM session and if required, a guest session.
843 */
844 rcExit = gctlCtxInitVmSession(pCtx);
845 if ( rcExit == RTEXITCODE_SUCCESS
846 && !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
847 rcExit = gctlCtxInitGuestSession(pCtx);
848 if (rcExit == RTEXITCODE_SUCCESS)
849 {
850 /*
851 * Install signal handler if requested (errors are ignored).
852 */
853 if (!(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_NO_SIGNAL_HANDLER))
854 {
855 int vrc = gctlSignalHandlerInstall();
856 pCtx->fInstalledSignalHandler = RT_SUCCESS(vrc);
857 }
858 }
859 }
860 else
861 rcExit = errorSyntax(GuestCtrl::tr("No user name specified!"));
862
863 pCtx->fPostOptionParsingInited = rcExit == RTEXITCODE_SUCCESS;
864 return rcExit;
865}
866
867
868/**
869 * Cleans up the context when the command returns.
870 *
871 * This will close any open guest session, unless the DETACH flag is set.
872 * It will also close any VM session that may be been established. Any signal
873 * handlers we've installed will also be removed.
874 *
875 * Un-initializes the VM after guest control usage.
876 * @param pCmdCtx Pointer to command context.
877 */
878static void gctlCtxTerm(PGCTLCMDCTX pCtx)
879{
880 HRESULT hrc;
881 AssertPtr(pCtx);
882
883 /*
884 * Uninstall signal handler.
885 */
886 if (pCtx->fInstalledSignalHandler)
887 {
888 gctlSignalHandlerUninstall();
889 pCtx->fInstalledSignalHandler = false;
890 }
891
892 /*
893 * Close, or at least release, the guest session.
894 */
895 if (pCtx->pGuestSession.isNotNull())
896 {
897 if ( !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS)
898 && !pCtx->fDetachGuestSession)
899 {
900 if (pCtx->cVerbose)
901 RTPrintf(GuestCtrl::tr("Closing guest session ...\n"));
902
903 if (pCtx->pGuestSession.isNotNull())
904 CHECK_ERROR(pCtx->pGuestSession, Close());
905
906 if (pCtx->cVerbose > 4)
907 {
908 SafeIfaceArray <IGuestSession> collSessions;
909 CHECK_ERROR(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
910 RTPrintf(GuestCtrl::tr("Now %zu guest sessions registered\n"), collSessions.size());
911 }
912 }
913 else if ( pCtx->fDetachGuestSession
914 && pCtx->cVerbose)
915 RTPrintf(GuestCtrl::tr("Guest session detached\n"));
916
917 pCtx->pGuestSession.setNull();
918 }
919
920 /*
921 * Close the VM session.
922 */
923 if (pCtx->fLockedVmSession)
924 {
925 Assert(pCtx->pArg->session.isNotNull());
926 CHECK_ERROR(pCtx->pArg->session, UnlockMachine());
927 pCtx->fLockedVmSession = false;
928 }
929}
930
931
932
933
934
935/*
936 *
937 *
938 * Guest Control Command Handling.
939 * Guest Control Command Handling.
940 * Guest Control Command Handling.
941 * Guest Control Command Handling.
942 * Guest Control Command Handling.
943 *
944 *
945 */
946
947
948/** @name EXITCODEEXEC_XXX - Special run exit codes.
949 *
950 * Special exit codes for returning errors/information of a started guest
951 * process to the command line VBoxManage was started from. Useful for e.g.
952 * scripting.
953 *
954 * ASSUMING that all platforms have at least 7-bits for the exit code we can do
955 * the following mapping:
956 * - Guest exit code 0 is mapped to 0 on the host.
957 * - Guest exit codes 1 thru 93 (0x5d) are displaced by 32, so that 1
958 * becomes 33 (0x21) on the host and 93 becomes 125 (0x7d) on the host.
959 * - Guest exit codes 94 (0x5e) and above are mapped to 126 (0x5e).
960 *
961 * We ASSUME that all VBoxManage status codes are in the range 0 thru 32.
962 *
963 * @note These are frozen as of 4.1.0.
964 * @note The guest exit code mappings was introduced with 5.0 and the 'run'
965 * command, they are/was not supported by 'exec'.
966 * @sa gctlRunCalculateExitCode
967 */
968/** Process exited normally but with an exit code <> 0. */
969#define EXITCODEEXEC_CODE ((RTEXITCODE)16)
970#define EXITCODEEXEC_FAILED ((RTEXITCODE)17)
971#define EXITCODEEXEC_TERM_SIGNAL ((RTEXITCODE)18)
972#define EXITCODEEXEC_TERM_ABEND ((RTEXITCODE)19)
973#define EXITCODEEXEC_TIMEOUT ((RTEXITCODE)20)
974#define EXITCODEEXEC_DOWN ((RTEXITCODE)21)
975/** Execution was interrupt by user (ctrl-c). */
976#define EXITCODEEXEC_CANCELED ((RTEXITCODE)22)
977/** The first mapped guest (non-zero) exit code. */
978#define EXITCODEEXEC_MAPPED_FIRST 33
979/** The last mapped guest (non-zero) exit code value (inclusive). */
980#define EXITCODEEXEC_MAPPED_LAST 125
981/** The number of exit codes from EXITCODEEXEC_MAPPED_FIRST to
982 * EXITCODEEXEC_MAPPED_LAST. This is also the highest guest exit code number
983 * we're able to map. */
984#define EXITCODEEXEC_MAPPED_RANGE (93)
985/** The guest exit code displacement value. */
986#define EXITCODEEXEC_MAPPED_DISPLACEMENT 32
987/** The guest exit code was too big to be mapped. */
988#define EXITCODEEXEC_MAPPED_BIG ((RTEXITCODE)126)
989/** @} */
990
991/**
992 * Calculates the exit code of VBoxManage.
993 *
994 * @returns The exit code to return.
995 * @param enmStatus The guest process status.
996 * @param uExitCode The associated guest process exit code (where
997 * applicable).
998 * @param fReturnExitCodes Set if we're to use the 32-126 range for guest
999 * exit codes.
1000 */
1001static RTEXITCODE gctlRunCalculateExitCode(ProcessStatus_T enmStatus, ULONG uExitCode, bool fReturnExitCodes)
1002{
1003 switch (enmStatus)
1004 {
1005 case ProcessStatus_TerminatedNormally:
1006 if (uExitCode == 0)
1007 return RTEXITCODE_SUCCESS;
1008 if (!fReturnExitCodes)
1009 return EXITCODEEXEC_CODE;
1010 if (uExitCode <= EXITCODEEXEC_MAPPED_RANGE)
1011 return (RTEXITCODE) (uExitCode + EXITCODEEXEC_MAPPED_DISPLACEMENT);
1012 return EXITCODEEXEC_MAPPED_BIG;
1013
1014 case ProcessStatus_TerminatedAbnormally:
1015 return EXITCODEEXEC_TERM_ABEND;
1016 case ProcessStatus_TerminatedSignal:
1017 return EXITCODEEXEC_TERM_SIGNAL;
1018
1019#if 0 /* see caller! */
1020 case ProcessStatus_TimedOutKilled:
1021 return EXITCODEEXEC_TIMEOUT;
1022 case ProcessStatus_Down:
1023 return EXITCODEEXEC_DOWN; /* Service/OS is stopping, process was killed. */
1024 case ProcessStatus_Error:
1025 return EXITCODEEXEC_FAILED;
1026
1027 /* The following is probably for detached? */
1028 case ProcessStatus_Starting:
1029 return RTEXITCODE_SUCCESS;
1030 case ProcessStatus_Started:
1031 return RTEXITCODE_SUCCESS;
1032 case ProcessStatus_Paused:
1033 return RTEXITCODE_SUCCESS;
1034 case ProcessStatus_Terminating:
1035 return RTEXITCODE_SUCCESS; /** @todo ???? */
1036#endif
1037
1038 default:
1039 AssertMsgFailed(("Unknown exit status (%u/%u) from guest process returned!\n", enmStatus, uExitCode));
1040 return RTEXITCODE_FAILURE;
1041 }
1042}
1043
1044
1045/**
1046 * Pumps guest output to the host.
1047 *
1048 * @return IPRT status code.
1049 * @param pProcess Pointer to appropriate process object.
1050 * @param hVfsIosDst Where to write the data. Can be the bit bucket or a (valid [std]) handle.
1051 * @param uHandle Handle where to read the data from.
1052 * @param cMsTimeout Timeout (in ms) to wait for the operation to
1053 * complete.
1054 */
1055static int gctlRunPumpOutput(IProcess *pProcess, RTVFSIOSTREAM hVfsIosDst, ULONG uHandle, RTMSINTERVAL cMsTimeout)
1056{
1057 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1058 Assert(hVfsIosDst != NIL_RTVFSIOSTREAM);
1059
1060 int vrc;
1061
1062 SafeArray<BYTE> aOutputData;
1063 HRESULT hrc = pProcess->Read(uHandle, _64K, RT_MAX(cMsTimeout, 1), ComSafeArrayAsOutParam(aOutputData));
1064 if (SUCCEEDED(hrc))
1065 {
1066 size_t cbOutputData = aOutputData.size();
1067 if (cbOutputData == 0)
1068 vrc = VINF_SUCCESS;
1069 else
1070 {
1071 BYTE const *pbBuf = aOutputData.raw();
1072 AssertPtr(pbBuf);
1073
1074 vrc = RTVfsIoStrmWrite(hVfsIosDst, pbBuf, cbOutputData, true /*fBlocking*/, NULL);
1075 if (RT_FAILURE(vrc))
1076 RTMsgError(GuestCtrl::tr("Unable to write output, vrc=%Rrc\n"), vrc);
1077 }
1078 }
1079 else
1080 vrc = gctlPrintError(pProcess, COM_IIDOF(IProcess));
1081 return vrc;
1082}
1083
1084
1085/**
1086 * Configures a host handle for pumping guest bits.
1087 *
1088 * @returns true if enabled and we successfully configured it.
1089 * @param fEnabled Whether pumping this pipe is configured to std handles,
1090 * or going to the bit bucket instead.
1091 * @param enmHandle The IPRT standard handle designation.
1092 * @param pszName The name for user messages.
1093 * @param enmTransformation The transformation to apply.
1094 * @param phVfsIos Where to return the resulting I/O stream handle.
1095 */
1096static bool gctlRunSetupHandle(bool fEnabled, RTHANDLESTD enmHandle, const char *pszName,
1097 kStreamTransform enmTransformation, PRTVFSIOSTREAM phVfsIos)
1098{
1099 if (fEnabled)
1100 {
1101 int vrc = RTVfsIoStrmFromStdHandle(enmHandle, 0, true /*fLeaveOpen*/, phVfsIos);
1102 if (RT_SUCCESS(vrc))
1103 {
1104 if (enmTransformation != kStreamTransform_None)
1105 {
1106 RTMsgWarning(GuestCtrl::tr("Unsupported %s line ending conversion"), pszName);
1107 /** @todo Implement dos2unix and unix2dos stream filters. */
1108 }
1109 return true;
1110 }
1111 RTMsgWarning(GuestCtrl::tr("Error getting %s handle: %Rrc"), pszName, vrc);
1112 }
1113 else /* If disabled, all goes to / gets fed to/from the bit bucket. */
1114 {
1115 RTFILE hFile;
1116 int vrc = RTFileOpenBitBucket(&hFile, enmHandle == RTHANDLESTD_INPUT ? RTFILE_O_READ : RTFILE_O_WRITE);
1117 if (RT_SUCCESS(vrc))
1118 {
1119 vrc = RTVfsIoStrmFromRTFile(hFile, 0 /* fOpen */, false /* fLeaveOpen */, phVfsIos);
1120 if (RT_SUCCESS(vrc))
1121 return true;
1122 }
1123 }
1124
1125 return false;
1126}
1127
1128
1129/**
1130 * Returns the remaining time (in ms) based on the start time and a set
1131 * timeout value. Returns RT_INDEFINITE_WAIT if no timeout was specified.
1132 *
1133 * @return RTMSINTERVAL Time left (in ms).
1134 * @param u64StartMs Start time (in ms).
1135 * @param cMsTimeout Timeout value (in ms).
1136 */
1137static RTMSINTERVAL gctlRunGetRemainingTime(uint64_t u64StartMs, RTMSINTERVAL cMsTimeout)
1138{
1139 if (!cMsTimeout || cMsTimeout == RT_INDEFINITE_WAIT) /* If no timeout specified, wait forever. */
1140 return RT_INDEFINITE_WAIT;
1141
1142 uint64_t u64ElapsedMs = RTTimeMilliTS() - u64StartMs;
1143 if (u64ElapsedMs >= cMsTimeout)
1144 return 0;
1145
1146 return cMsTimeout - (RTMSINTERVAL)u64ElapsedMs;
1147}
1148
1149/**
1150 * Common handler for the 'run' and 'start' commands.
1151 *
1152 * @returns Command exit code.
1153 * @param pCtx Guest session context.
1154 * @param argc The argument count.
1155 * @param argv The argument vector for this command.
1156 * @param fRunCmd Set if it's 'run' clear if 'start'.
1157 */
1158static RTEXITCODE gctlHandleRunCommon(PGCTLCMDCTX pCtx, int argc, char **argv, bool fRunCmd)
1159{
1160 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1161
1162 /*
1163 * Parse arguments.
1164 */
1165 enum kGstCtrlRunOpt
1166 {
1167 kGstCtrlRunOpt_IgnoreOrphanedProcesses = 1000,
1168 kGstCtrlRunOpt_NoProfile, /** @todo Deprecated and will be removed soon; use kGstCtrlRunOpt_Profile instead, if needed. */
1169 kGstCtrlRunOpt_Profile,
1170 kGstCtrlRunOpt_Dos2Unix,
1171 kGstCtrlRunOpt_Unix2Dos,
1172 kGstCtrlRunOpt_WaitForStdOut,
1173 kGstCtrlRunOpt_NoWaitForStdOut,
1174 kGstCtrlRunOpt_WaitForStdErr,
1175 kGstCtrlRunOpt_NoWaitForStdErr
1176 };
1177 static const RTGETOPTDEF s_aOptions[] =
1178 {
1179 GCTLCMD_COMMON_OPTION_DEFS()
1180 { "--arg0", '0', RTGETOPT_REQ_STRING },
1181 { "--cwd", 'C', RTGETOPT_REQ_STRING },
1182 { "--putenv", 'E', RTGETOPT_REQ_STRING },
1183 { "--exe", 'e', RTGETOPT_REQ_STRING },
1184 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
1185 { "--unquoted-args", 'u', RTGETOPT_REQ_NOTHING },
1186 { "--ignore-orphaned-processes", kGstCtrlRunOpt_IgnoreOrphanedProcesses, RTGETOPT_REQ_NOTHING },
1187 { "--no-profile", kGstCtrlRunOpt_NoProfile, RTGETOPT_REQ_NOTHING }, /** @todo Deprecated. */
1188 { "--profile", kGstCtrlRunOpt_Profile, RTGETOPT_REQ_NOTHING },
1189 /* run only: 6 - options */
1190 { "--dos2unix", kGstCtrlRunOpt_Dos2Unix, RTGETOPT_REQ_NOTHING },
1191 { "--unix2dos", kGstCtrlRunOpt_Unix2Dos, RTGETOPT_REQ_NOTHING },
1192 { "--no-wait-stdout", kGstCtrlRunOpt_NoWaitForStdOut, RTGETOPT_REQ_NOTHING },
1193 { "--wait-stdout", kGstCtrlRunOpt_WaitForStdOut, RTGETOPT_REQ_NOTHING },
1194 { "--no-wait-stderr", kGstCtrlRunOpt_NoWaitForStdErr, RTGETOPT_REQ_NOTHING },
1195 { "--wait-stderr", kGstCtrlRunOpt_WaitForStdErr, RTGETOPT_REQ_NOTHING },
1196 };
1197
1198 /** @todo stdin handling. */
1199
1200 int ch;
1201 RTGETOPTUNION ValueUnion;
1202 RTGETOPTSTATE GetState;
1203 int vrc = RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions) - (fRunCmd ? 0 : 6),
1204 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1205 AssertRC(vrc);
1206
1207 com::SafeArray<ProcessCreateFlag_T> aCreateFlags;
1208 com::SafeArray<ProcessWaitForFlag_T> aWaitFlags;
1209 com::SafeArray<IN_BSTR> aArgs;
1210 com::SafeArray<IN_BSTR> aEnv;
1211 const char * pszImage = NULL;
1212 const char * pszArg0 = NULL; /* Argument 0 to use. pszImage will be used if not specified. */
1213 const char * pszCwd = NULL;
1214 bool fWaitForStdOut = fRunCmd;
1215 bool fWaitForStdErr = fRunCmd;
1216 RTVFSIOSTREAM hVfsStdOut = NIL_RTVFSIOSTREAM;
1217 RTVFSIOSTREAM hVfsStdErr = NIL_RTVFSIOSTREAM;
1218 enum kStreamTransform enmStdOutTransform = kStreamTransform_None;
1219 enum kStreamTransform enmStdErrTransform = kStreamTransform_None;
1220 RTMSINTERVAL cMsTimeout = 0;
1221
1222 try
1223 {
1224 /* Wait for process start in any case. This is useful for scripting VBoxManage
1225 * when relying on its overall exit code. */
1226 aWaitFlags.push_back(ProcessWaitForFlag_Start);
1227
1228 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1229 {
1230 /* For options that require an argument, ValueUnion has received the value. */
1231 switch (ch)
1232 {
1233 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1234
1235 case 'E':
1236 if ( ValueUnion.psz[0] == '\0'
1237 || ValueUnion.psz[0] == '=')
1238 return errorSyntax(GuestCtrl::tr("Invalid argument variable[=value]: '%s'"), ValueUnion.psz);
1239 aEnv.push_back(Bstr(ValueUnion.psz).raw());
1240 break;
1241
1242 case kGstCtrlRunOpt_IgnoreOrphanedProcesses:
1243 aCreateFlags.push_back(ProcessCreateFlag_IgnoreOrphanedProcesses);
1244 break;
1245
1246 case kGstCtrlRunOpt_NoProfile:
1247 /** @todo Deprecated, will be removed. */
1248 RTPrintf(GuestCtrl::tr("Warning: Deprecated option \"--no-profile\" specified\n"));
1249 break;
1250
1251 case kGstCtrlRunOpt_Profile:
1252 aCreateFlags.push_back(ProcessCreateFlag_Profile);
1253 break;
1254
1255 case '0':
1256 pszArg0 = ValueUnion.psz;
1257 break;
1258
1259 case 'C':
1260 pszCwd = ValueUnion.psz;
1261 break;
1262
1263 case 'e':
1264 pszImage = ValueUnion.psz;
1265 break;
1266
1267 case 'u':
1268 aCreateFlags.push_back(ProcessCreateFlag_UnquotedArguments);
1269 break;
1270
1271 /** @todo Add a hidden flag. */
1272
1273 case 't': /* Timeout */
1274 cMsTimeout = ValueUnion.u32;
1275 break;
1276
1277 /* run only options: */
1278 case kGstCtrlRunOpt_Dos2Unix:
1279 Assert(fRunCmd);
1280 enmStdErrTransform = enmStdOutTransform = kStreamTransform_Dos2Unix;
1281 break;
1282 case kGstCtrlRunOpt_Unix2Dos:
1283 Assert(fRunCmd);
1284 enmStdErrTransform = enmStdOutTransform = kStreamTransform_Unix2Dos;
1285 break;
1286
1287 case kGstCtrlRunOpt_WaitForStdOut:
1288 Assert(fRunCmd);
1289 fWaitForStdOut = true;
1290 break;
1291 case kGstCtrlRunOpt_NoWaitForStdOut:
1292 Assert(fRunCmd);
1293 fWaitForStdOut = false;
1294 break;
1295
1296 case kGstCtrlRunOpt_WaitForStdErr:
1297 Assert(fRunCmd);
1298 fWaitForStdErr = true;
1299 break;
1300 case kGstCtrlRunOpt_NoWaitForStdErr:
1301 Assert(fRunCmd);
1302 fWaitForStdErr = false;
1303 break;
1304
1305 case VINF_GETOPT_NOT_OPTION:
1306 /* VINF_GETOPT_NOT_OPTION comes after all options have been specified;
1307 * so if pszImage still is zero at this stage, we use the first non-option found
1308 * as the image being executed. */
1309 if (!pszImage)
1310 pszImage = ValueUnion.psz;
1311 else /* Add anything else to the arguments vector. */
1312 aArgs.push_back(Bstr(ValueUnion.psz).raw());
1313 break;
1314
1315 default:
1316 return errorGetOpt(ch, &ValueUnion);
1317
1318 } /* switch */
1319 } /* while RTGetOpt */
1320
1321 /* Must have something to execute. */
1322 if (!pszImage || !*pszImage)
1323 return errorSyntax(GuestCtrl::tr("No executable specified!"));
1324
1325 /* Set the arg0 argument (descending precedence):
1326 * - If an argument 0 is explicitly specified (via "--arg0"), use this as argument 0.
1327 * - When an image is specified explicitly (via "--exe <image>"), use <image> as argument 0.
1328 * Note: This is (and ever was) the default behavior users expect, so don't change this! */
1329 if (pszArg0)
1330 aArgs.push_front(Bstr(pszArg0).raw());
1331 else
1332 aArgs.push_front(Bstr(pszImage).raw());
1333
1334 if (pCtx->cVerbose) /* Print the final execution parameters in verbose mode. */
1335 {
1336 RTPrintf(GuestCtrl::tr("Executing:\n Image : %s\n"), pszImage);
1337 for (size_t i = 0; i < aArgs.size(); i++)
1338 RTPrintf(GuestCtrl::tr(" arg[%d]: %ls\n"), i, aArgs[i]);
1339 }
1340 /* No altering of aArgs and/or pszImage after this point! */
1341
1342 /*
1343 * Finalize process creation and wait flags and input/output streams.
1344 */
1345 if (!fRunCmd)
1346 {
1347 aCreateFlags.push_back(ProcessCreateFlag_WaitForProcessStartOnly);
1348 Assert(!fWaitForStdOut);
1349 Assert(!fWaitForStdErr);
1350 }
1351 else
1352 {
1353 aWaitFlags.push_back(ProcessWaitForFlag_Terminate);
1354 if (gctlRunSetupHandle(fWaitForStdOut, RTHANDLESTD_OUTPUT, "stdout", enmStdOutTransform, &hVfsStdOut))
1355 {
1356 if (fWaitForStdOut)
1357 {
1358 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdOut);
1359 aWaitFlags.push_back(ProcessWaitForFlag_StdOut);
1360 }
1361 }
1362 else /* Failed to set up handle, disable. */
1363 fWaitForStdOut = false;
1364
1365 if (gctlRunSetupHandle(fWaitForStdErr, RTHANDLESTD_ERROR, "stderr", enmStdErrTransform, &hVfsStdErr))
1366 {
1367 if (fWaitForStdErr)
1368 {
1369 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdErr);
1370 aWaitFlags.push_back(ProcessWaitForFlag_StdErr);
1371 }
1372 }
1373 else /* Failed to set up handle, disable. */
1374 fWaitForStdErr = false;
1375 }
1376 }
1377 catch (std::bad_alloc &)
1378 {
1379 return RTMsgErrorExit(RTEXITCODE_FAILURE, "VERR_NO_MEMORY\n");
1380 }
1381
1382 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
1383 if (rcExit != RTEXITCODE_SUCCESS)
1384 return rcExit;
1385
1386 HRESULT hrc;
1387
1388 try
1389 {
1390 do
1391 {
1392 /* Get current time stamp to later calculate rest of timeout left. */
1393 uint64_t msStart = RTTimeMilliTS();
1394
1395 /*
1396 * Create the process.
1397 */
1398 if (pCtx->cVerbose)
1399 {
1400 if (cMsTimeout == 0)
1401 RTPrintf(GuestCtrl::tr("Starting guest process ...\n"));
1402 else
1403 RTPrintf(GuestCtrl::tr("Starting guest process (within %ums)\n"), cMsTimeout);
1404 }
1405 ComPtr<IGuestProcess> pProcess;
1406 CHECK_ERROR_BREAK(pCtx->pGuestSession, ProcessCreate(Bstr(pszImage).raw(),
1407 ComSafeArrayAsInParam(aArgs),
1408 Bstr(pszCwd).raw(),
1409 ComSafeArrayAsInParam(aEnv),
1410 ComSafeArrayAsInParam(aCreateFlags),
1411 gctlRunGetRemainingTime(msStart, cMsTimeout),
1412 pProcess.asOutParam()));
1413
1414 /*
1415 * Explicitly wait for the guest process to be in a started state.
1416 */
1417 com::SafeArray<ProcessWaitForFlag_T> aWaitStartFlags;
1418 aWaitStartFlags.push_back(ProcessWaitForFlag_Start);
1419 ProcessWaitResult_T waitResult;
1420 CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitStartFlags),
1421 gctlRunGetRemainingTime(msStart, cMsTimeout), &waitResult));
1422
1423 ULONG uPID = 0;
1424 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
1425 if (fRunCmd && pCtx->cVerbose)
1426 RTPrintf(GuestCtrl::tr("Process '%s' (PID %RU32) started\n"), pszImage, uPID);
1427 else if (!fRunCmd && pCtx->cVerbose)
1428 {
1429 /* Just print plain PID to make it easier for scripts
1430 * invoking VBoxManage. */
1431 RTPrintf(GuestCtrl::tr("[%RU32 - Session %RU32]\n"), uPID, pCtx->uSessionID);
1432 }
1433
1434 /*
1435 * Wait for process to exit/start...
1436 */
1437 RTMSINTERVAL cMsTimeLeft = 1; /* Will be calculated. */
1438 bool fReadStdOut = false;
1439 bool fReadStdErr = false;
1440 bool fCompleted = false;
1441 bool fCompletedStartCmd = false;
1442
1443 vrc = VINF_SUCCESS;
1444 while ( !fCompleted
1445 && cMsTimeLeft > 0)
1446 {
1447 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1448 CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitFlags),
1449 RT_MIN(500 /*ms*/, RT_MAX(cMsTimeLeft, 1 /*ms*/)),
1450 &waitResult));
1451 if (pCtx->cVerbose)
1452 RTPrintf(GuestCtrl::tr("Wait result is '%s' (%d)\n"), gctlProcessWaitResultToText(waitResult), waitResult);
1453 switch (waitResult)
1454 {
1455 case ProcessWaitResult_Start: /** @todo you always wait for 'start', */
1456 fCompletedStartCmd = fCompleted = !fRunCmd; /* Only wait for startup if the 'start' command. */
1457 if (!fCompleted && aWaitFlags[0] == ProcessWaitForFlag_Start)
1458 aWaitFlags[0] = ProcessWaitForFlag_Terminate;
1459 break;
1460 case ProcessWaitResult_StdOut:
1461 fReadStdOut = true;
1462 break;
1463 case ProcessWaitResult_StdErr:
1464 fReadStdErr = true;
1465 break;
1466 case ProcessWaitResult_Terminate:
1467 if (pCtx->cVerbose)
1468 RTPrintf(GuestCtrl::tr("Process terminated\n"));
1469 /* Process terminated, we're done. */
1470 fCompleted = true;
1471 break;
1472 case ProcessWaitResult_WaitFlagNotSupported:
1473 /* The guest does not support waiting for stdout/err, so
1474 * yield to reduce the CPU load due to busy waiting. */
1475 RTThreadYield();
1476 fReadStdOut = fReadStdErr = true;
1477 /* Note: In case the user specified explicitly not wanting to wait for stdout / stderr,
1478 * the configured VFS handle goes to / will be fed from the bit bucket. */
1479 break;
1480 case ProcessWaitResult_Timeout:
1481 {
1482 /** @todo It is really unclear whether we will get stuck with the timeout
1483 * result here if the guest side times out the process and fails to
1484 * kill the process... To be on the save side, double the IPC and
1485 * check the process status every time we time out. */
1486 ProcessStatus_T enmProcStatus;
1487 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&enmProcStatus));
1488 if ( enmProcStatus == ProcessStatus_TimedOutKilled
1489 || enmProcStatus == ProcessStatus_TimedOutAbnormally)
1490 fCompleted = true;
1491 fReadStdOut = fReadStdErr = true;
1492 break;
1493 }
1494 case ProcessWaitResult_Status:
1495 /* ignore. */
1496 break;
1497 case ProcessWaitResult_Error:
1498 /* waitFor is dead in the water, I think, so better leave the loop. */
1499 vrc = VERR_CALLBACK_RETURN;
1500 break;
1501
1502 case ProcessWaitResult_StdIn: AssertFailed(); /* did ask for this! */ break;
1503 case ProcessWaitResult_None: AssertFailed(); /* used. */ break;
1504 default: AssertFailed(); /* huh? */ break;
1505 }
1506
1507 if (g_fGuestCtrlCanceled)
1508 break;
1509
1510 /*
1511 * Pump output as needed.
1512 */
1513 if (fReadStdOut)
1514 {
1515 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1516 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdOut, 1 /* StdOut */, cMsTimeLeft);
1517 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1518 vrc = vrc2;
1519 fReadStdOut = false;
1520 }
1521 if (fReadStdErr)
1522 {
1523 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1524 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdErr, 2 /* StdErr */, cMsTimeLeft);
1525 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1526 vrc = vrc2;
1527 fReadStdErr = false;
1528 }
1529 if ( RT_FAILURE(vrc)
1530 || g_fGuestCtrlCanceled)
1531 break;
1532
1533 /*
1534 * Process events before looping.
1535 */
1536 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
1537 } /* while */
1538
1539 /*
1540 * Report status back to the user.
1541 */
1542 if (g_fGuestCtrlCanceled)
1543 {
1544 if (pCtx->cVerbose)
1545 RTPrintf(GuestCtrl::tr("Process execution aborted!\n"));
1546 rcExit = EXITCODEEXEC_CANCELED;
1547 }
1548 else if (fCompletedStartCmd)
1549 {
1550 if (pCtx->cVerbose)
1551 RTPrintf(GuestCtrl::tr("Process successfully started!\n"));
1552 rcExit = RTEXITCODE_SUCCESS;
1553 }
1554 else if (fCompleted)
1555 {
1556 ProcessStatus_T procStatus;
1557 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&procStatus));
1558 if ( procStatus == ProcessStatus_TerminatedNormally
1559 || procStatus == ProcessStatus_TerminatedAbnormally
1560 || procStatus == ProcessStatus_TerminatedSignal)
1561 {
1562 LONG lExitCode;
1563 CHECK_ERROR_BREAK(pProcess, COMGETTER(ExitCode)(&lExitCode));
1564 if (pCtx->cVerbose)
1565 RTPrintf(GuestCtrl::tr("Exit code=%u (Status=%u [%s])\n"),
1566 lExitCode, procStatus, gctlProcessStatusToText(procStatus));
1567
1568 rcExit = gctlRunCalculateExitCode(procStatus, lExitCode, true /*fReturnExitCodes*/);
1569 }
1570 else if ( procStatus == ProcessStatus_TimedOutKilled
1571 || procStatus == ProcessStatus_TimedOutAbnormally)
1572 {
1573 if (pCtx->cVerbose)
1574 RTPrintf(GuestCtrl::tr("Process timed out (guest side) and %s\n"),
1575 procStatus == ProcessStatus_TimedOutAbnormally
1576 ? GuestCtrl::tr("failed to terminate so far") : GuestCtrl::tr("was terminated"));
1577 rcExit = EXITCODEEXEC_TIMEOUT;
1578 }
1579 else
1580 {
1581 if (pCtx->cVerbose)
1582 RTPrintf(GuestCtrl::tr("Process now is in status [%s] (unexpected)\n"),
1583 gctlProcessStatusToText(procStatus));
1584 rcExit = RTEXITCODE_FAILURE;
1585 }
1586 }
1587 else if (RT_FAILURE_NP(vrc))
1588 {
1589 if (pCtx->cVerbose)
1590 RTPrintf(GuestCtrl::tr("Process monitor loop quit with vrc=%Rrc\n"), vrc);
1591 rcExit = RTEXITCODE_FAILURE;
1592 }
1593 else
1594 {
1595 if (pCtx->cVerbose)
1596 RTPrintf(GuestCtrl::tr("Process monitor loop timed out\n"));
1597 rcExit = EXITCODEEXEC_TIMEOUT;
1598 }
1599
1600 } while (0);
1601 }
1602 catch (std::bad_alloc &)
1603 {
1604 hrc = E_OUTOFMEMORY;
1605 }
1606
1607 /*
1608 * Decide what to do with the guest session.
1609 *
1610 * If it's the 'start' command where detach the guest process after
1611 * starting, don't close the guest session it is part of, except on
1612 * failure or ctrl-c.
1613 *
1614 * For the 'run' command the guest process quits with us.
1615 */
1616 if (!fRunCmd && SUCCEEDED(hrc) && !g_fGuestCtrlCanceled)
1617 pCtx->fDetachGuestSession = true;
1618
1619 /* Make sure we return failure on failure. */
1620 if (FAILED(hrc) && rcExit == RTEXITCODE_SUCCESS)
1621 rcExit = RTEXITCODE_FAILURE;
1622 return rcExit;
1623}
1624
1625
1626static DECLCALLBACK(RTEXITCODE) gctlHandleRun(PGCTLCMDCTX pCtx, int argc, char **argv)
1627{
1628 return gctlHandleRunCommon(pCtx, argc, argv, true /*fRunCmd*/);
1629}
1630
1631
1632static DECLCALLBACK(RTEXITCODE) gctlHandleStart(PGCTLCMDCTX pCtx, int argc, char **argv)
1633{
1634 return gctlHandleRunCommon(pCtx, argc, argv, false /*fRunCmd*/);
1635}
1636
1637
1638static RTEXITCODE gctlHandleCopy(PGCTLCMDCTX pCtx, int argc, char **argv, bool fHostToGuest)
1639{
1640 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1641
1642 /*
1643 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1644 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1645 * does in here.
1646 */
1647 static const RTGETOPTDEF s_aOptions[] =
1648 {
1649 GCTLCMD_COMMON_OPTION_DEFS()
1650 { "--follow", 'L', RTGETOPT_REQ_NOTHING }, /* Kept for backwards-compatibility (VBox < 7.0). */
1651 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
1652 { "--no-replace", 'n', RTGETOPT_REQ_NOTHING }, /* like "-n" via cp. */
1653 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1654 { "--target-directory", 't', RTGETOPT_REQ_STRING },
1655 { "--update", 'u', RTGETOPT_REQ_NOTHING } /* like "-u" via cp. */
1656 };
1657
1658 int ch;
1659 RTGETOPTUNION ValueUnion;
1660 RTGETOPTSTATE GetState;
1661 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1662
1663 bool fDstMustBeDir = false;
1664 const char *pszDst = NULL;
1665 bool fFollow = false;
1666 bool fRecursive = false;
1667 bool fUpdate = false; /* Whether to copy the file only if it's newer than the target. */
1668 bool fNoReplace = false; /* Only copy the file if it does not exist yet. */
1669
1670 int vrc = VINF_SUCCESS;
1671 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
1672 && ch != VINF_GETOPT_NOT_OPTION)
1673 {
1674 /* For options that require an argument, ValueUnion has received the value. */
1675 switch (ch)
1676 {
1677 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1678
1679 case 'L':
1680 if (!RTStrICmp(ValueUnion.pDef->pszLong, "--follow"))
1681 RTMsgWarning("--follow is deprecated; use --dereference instead.");
1682 fFollow = true;
1683 break;
1684
1685 case 'n':
1686 fNoReplace = true;
1687 break;
1688
1689 case 'R':
1690 fRecursive = true;
1691 break;
1692
1693 case 't':
1694 pszDst = ValueUnion.psz;
1695 fDstMustBeDir = true;
1696 break;
1697
1698 case 'u':
1699 fUpdate = true;
1700 break;
1701
1702 default:
1703 return errorGetOpt(ch, &ValueUnion);
1704 }
1705 }
1706
1707 char **papszSources = RTGetOptNonOptionArrayPtr(&GetState);
1708 size_t cSources = &argv[argc] - papszSources;
1709
1710 if (!cSources)
1711 return errorSyntax(GuestCtrl::tr("No sources specified!"));
1712
1713 /* Unless a --target-directory is given, the last argument is the destination, so
1714 bump it from the source list. */
1715 if (pszDst == NULL && cSources >= 2)
1716 pszDst = papszSources[--cSources];
1717
1718 if (pszDst == NULL)
1719 return errorSyntax(GuestCtrl::tr("No destination specified!"));
1720
1721 char szAbsDst[RTPATH_MAX];
1722 if (!fHostToGuest)
1723 {
1724 vrc = RTPathAbs(pszDst, szAbsDst, sizeof(szAbsDst));
1725 if (RT_SUCCESS(vrc))
1726 pszDst = szAbsDst;
1727 else
1728 return RTMsgErrorExitFailure(GuestCtrl::tr("RTPathAbs failed on '%s': %Rrc"), pszDst, vrc);
1729 }
1730
1731 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
1732 if (rcExit != RTEXITCODE_SUCCESS)
1733 return rcExit;
1734
1735 /*
1736 * Done parsing arguments, do some more preparations.
1737 */
1738 if (pCtx->cVerbose)
1739 {
1740 if (fHostToGuest)
1741 RTPrintf(GuestCtrl::tr("Copying from host to guest ...\n"));
1742 else
1743 RTPrintf(GuestCtrl::tr("Copying from guest to host ...\n"));
1744 }
1745
1746 HRESULT hrc = S_OK;
1747
1748 com::SafeArray<IN_BSTR> aSources;
1749 com::SafeArray<IN_BSTR> aFilters; /** @todo Populate those? For now we use caller-based globbing. */
1750 com::SafeArray<IN_BSTR> aCopyFlags;
1751
1752 size_t iSrc = 0;
1753 for (; iSrc < cSources; iSrc++)
1754 {
1755 aSources.push_back(Bstr(papszSources[iSrc]).raw());
1756 aFilters.push_back(Bstr("").raw()); /* Empty for now. See @todo above. */
1757
1758 /* Compile the comma-separated list of flags.
1759 * Certain flags are only available for specific file system objects, e.g. directories. */
1760 bool fIsDir = false;
1761 if (fHostToGuest)
1762 {
1763 RTFSOBJINFO ObjInfo;
1764 vrc = RTPathQueryInfo(papszSources[iSrc], &ObjInfo, RTFSOBJATTRADD_NOTHING);
1765 if (RT_SUCCESS(vrc))
1766 fIsDir = RTFS_IS_DIRECTORY(ObjInfo.Attr.fMode);
1767
1768 if (RT_FAILURE(vrc))
1769 break;
1770 }
1771 else /* Guest to host. */
1772 {
1773 ComPtr<IGuestFsObjInfo> pFsObjInfo;
1774 hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(papszSources[iSrc]).raw(), RT_BOOL(fFollow) /* fFollowSymlinks */,
1775 pFsObjInfo.asOutParam());
1776 if (SUCCEEDED(hrc))
1777 {
1778 FsObjType_T enmObjType;
1779 CHECK_ERROR(pFsObjInfo,COMGETTER(Type)(&enmObjType));
1780 if (SUCCEEDED(hrc))
1781 {
1782 /* Take action according to source file. */
1783 fIsDir = enmObjType == FsObjType_Directory;
1784 }
1785 }
1786
1787 if (FAILED(hrc))
1788 {
1789 vrc = gctlPrintError(pCtx->pGuestSession, COM_IIDOF(IGuestSession));
1790 break;
1791 }
1792 }
1793
1794 if (pCtx->cVerbose)
1795 RTPrintf(GuestCtrl::tr("Source '%s' is a %s\n"), papszSources[iSrc], fIsDir ? "directory" : "file");
1796
1797 Utf8Str strCopyFlags;
1798 if (fRecursive && fIsDir) /* Only available for directories. Just ignore otherwise. */
1799 strCopyFlags += "Recursive,";
1800 if (fFollow)
1801 strCopyFlags += "FollowLinks,";
1802 if (fUpdate) /* Only copy source files which are newer than the destination file. */
1803 strCopyFlags += "Update,";
1804 if (fNoReplace) /* Do not overwrite files. */
1805 strCopyFlags += "NoReplace,";
1806 else if (!fNoReplace && fIsDir)
1807 strCopyFlags += "CopyIntoExisting,"; /* Only copy into existing directories if "--no-replace" isn't specified. */
1808 aCopyFlags.push_back(Bstr(strCopyFlags).raw());
1809 }
1810
1811 if (RT_FAILURE(vrc))
1812 return RTMsgErrorExitFailure(GuestCtrl::tr("Error looking file system information for source '%s', vrc=%Rrc"),
1813 papszSources[iSrc], vrc);
1814
1815 ComPtr<IProgress> pProgress;
1816 if (fHostToGuest)
1817 {
1818 hrc = pCtx->pGuestSession->CopyToGuest(ComSafeArrayAsInParam(aSources),
1819 ComSafeArrayAsInParam(aFilters), ComSafeArrayAsInParam(aCopyFlags),
1820 Bstr(pszDst).raw(), pProgress.asOutParam());
1821 }
1822 else /* Guest to host. */
1823 {
1824 hrc = pCtx->pGuestSession->CopyFromGuest(ComSafeArrayAsInParam(aSources),
1825 ComSafeArrayAsInParam(aFilters), ComSafeArrayAsInParam(aCopyFlags),
1826 Bstr(pszDst).raw(), pProgress.asOutParam());
1827 }
1828
1829 if (FAILED(hrc))
1830 {
1831 vrc = gctlPrintError(pCtx->pGuestSession, COM_IIDOF(IGuestSession));
1832 }
1833 else if (pProgress.isNotNull())
1834 {
1835 if (pCtx->cVerbose)
1836 hrc = showProgress(pProgress);
1837 else
1838 hrc = pProgress->WaitForCompletion(-1 /* No timeout */);
1839 if (SUCCEEDED(hrc))
1840 CHECK_PROGRESS_ERROR(pProgress, (GuestCtrl::tr("File copy failed")));
1841 vrc = gctlPrintProgressError(pProgress);
1842 }
1843
1844 if (RT_FAILURE(vrc))
1845 rcExit = RTEXITCODE_FAILURE;
1846
1847 return rcExit;
1848}
1849
1850static DECLCALLBACK(RTEXITCODE) gctlHandleCopyFrom(PGCTLCMDCTX pCtx, int argc, char **argv)
1851{
1852 return gctlHandleCopy(pCtx, argc, argv, false /* Guest to host */);
1853}
1854
1855static DECLCALLBACK(RTEXITCODE) gctlHandleCopyTo(PGCTLCMDCTX pCtx, int argc, char **argv)
1856{
1857 return gctlHandleCopy(pCtx, argc, argv, true /* Host to guest */);
1858}
1859
1860static DECLCALLBACK(RTEXITCODE) gctrlHandleMkDir(PGCTLCMDCTX pCtx, int argc, char **argv)
1861{
1862 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1863
1864 static const RTGETOPTDEF s_aOptions[] =
1865 {
1866 GCTLCMD_COMMON_OPTION_DEFS()
1867 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
1868 { "--parents", 'P', RTGETOPT_REQ_NOTHING }
1869 };
1870
1871 int ch;
1872 RTGETOPTUNION ValueUnion;
1873 RTGETOPTSTATE GetState;
1874 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1875
1876 SafeArray<DirectoryCreateFlag_T> aDirCreateFlags;
1877 uint32_t fDirMode = 0; /* Default mode. */
1878 uint32_t cDirsCreated = 0;
1879 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1880
1881 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1882 {
1883 /* For options that require an argument, ValueUnion has received the value. */
1884 switch (ch)
1885 {
1886 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1887
1888 case 'm': /* Mode */
1889 fDirMode = ValueUnion.u32;
1890 break;
1891
1892 case 'P': /* Create parents */
1893 aDirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1894 break;
1895
1896 case VINF_GETOPT_NOT_OPTION:
1897 if (cDirsCreated == 0)
1898 {
1899 /*
1900 * First non-option - no more options now.
1901 */
1902 rcExit = gctlCtxPostOptionParsingInit(pCtx);
1903 if (rcExit != RTEXITCODE_SUCCESS)
1904 return rcExit;
1905 if (pCtx->cVerbose)
1906 RTPrintf(GuestCtrl::tr("Creating %RU32 directories...\n"), argc - GetState.iNext + 1);
1907 }
1908 if (g_fGuestCtrlCanceled)
1909 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("mkdir was interrupted by Ctrl-C (%u left)\n"),
1910 argc - GetState.iNext + 1);
1911
1912 /*
1913 * Create the specified directory.
1914 *
1915 * On failure we'll change the exit status to failure and
1916 * continue with the next directory that needs creating. We do
1917 * this because we only create new things, and because this is
1918 * how /bin/mkdir works on unix.
1919 */
1920 cDirsCreated++;
1921 if (pCtx->cVerbose)
1922 RTPrintf(GuestCtrl::tr("Creating directory \"%s\" ...\n"), ValueUnion.psz);
1923 try
1924 {
1925 HRESULT hrc;
1926 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreate(Bstr(ValueUnion.psz).raw(),
1927 fDirMode, ComSafeArrayAsInParam(aDirCreateFlags)));
1928 if (FAILED(hrc))
1929 rcExit = RTEXITCODE_FAILURE;
1930 }
1931 catch (std::bad_alloc &)
1932 {
1933 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory\n"));
1934 }
1935 break;
1936
1937 default:
1938 return errorGetOpt(ch, &ValueUnion);
1939 }
1940 }
1941
1942 if (!cDirsCreated)
1943 return errorSyntax(GuestCtrl::tr("No directory to create specified!"));
1944 return rcExit;
1945}
1946
1947
1948static DECLCALLBACK(RTEXITCODE) gctlHandleRmDir(PGCTLCMDCTX pCtx, int argc, char **argv)
1949{
1950 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1951
1952 static const RTGETOPTDEF s_aOptions[] =
1953 {
1954 GCTLCMD_COMMON_OPTION_DEFS()
1955 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1956 };
1957
1958 int ch;
1959 RTGETOPTUNION ValueUnion;
1960 RTGETOPTSTATE GetState;
1961 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1962
1963 bool fRecursive = false;
1964 uint32_t cDirRemoved = 0;
1965 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1966
1967 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1968 {
1969 /* For options that require an argument, ValueUnion has received the value. */
1970 switch (ch)
1971 {
1972 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1973
1974 case 'R':
1975 fRecursive = true;
1976 break;
1977
1978 case VINF_GETOPT_NOT_OPTION:
1979 {
1980 if (cDirRemoved == 0)
1981 {
1982 /*
1983 * First non-option - no more options now.
1984 */
1985 rcExit = gctlCtxPostOptionParsingInit(pCtx);
1986 if (rcExit != RTEXITCODE_SUCCESS)
1987 return rcExit;
1988 if (pCtx->cVerbose)
1989 {
1990 if (fRecursive)
1991 RTPrintf(GuestCtrl::tr("Removing %RU32 directory tree(s)...\n"), argc - GetState.iNext + 1);
1992 else
1993 RTPrintf(GuestCtrl::tr("Removing %RU32 directorie(s)...\n"), argc - GetState.iNext + 1);
1994 }
1995 }
1996 if (g_fGuestCtrlCanceled)
1997 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("rmdir was interrupted by Ctrl-C (%u left)\n"),
1998 argc - GetState.iNext + 1);
1999
2000 cDirRemoved++;
2001 HRESULT hrc;
2002 if (!fRecursive)
2003 {
2004 /*
2005 * Remove exactly one directory.
2006 */
2007 if (pCtx->cVerbose)
2008 RTPrintf(GuestCtrl::tr("Removing directory \"%s\" ...\n"), ValueUnion.psz);
2009 try
2010 {
2011 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemove(Bstr(ValueUnion.psz).raw()));
2012 }
2013 catch (std::bad_alloc &)
2014 {
2015 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory\n"));
2016 }
2017 }
2018 else
2019 {
2020 /*
2021 * Remove the directory and anything under it, that means files
2022 * and everything. This is in the tradition of the Windows NT
2023 * CMD.EXE "rmdir /s" operation, a tradition which jpsoft's TCC
2024 * strongly warns against (and half-ways questions the sense of).
2025 */
2026 if (pCtx->cVerbose)
2027 RTPrintf(GuestCtrl::tr("Recursively removing directory \"%s\" ...\n"), ValueUnion.psz);
2028 try
2029 {
2030 /** @todo Make flags configurable. */
2031 com::SafeArray<DirectoryRemoveRecFlag_T> aRemRecFlags;
2032 aRemRecFlags.push_back(DirectoryRemoveRecFlag_ContentAndDir);
2033
2034 ComPtr<IProgress> ptrProgress;
2035 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemoveRecursive(Bstr(ValueUnion.psz).raw(),
2036 ComSafeArrayAsInParam(aRemRecFlags),
2037 ptrProgress.asOutParam()));
2038 if (SUCCEEDED(hrc))
2039 {
2040 if (pCtx->cVerbose)
2041 hrc = showProgress(ptrProgress);
2042 else
2043 hrc = ptrProgress->WaitForCompletion(-1 /* indefinitely */);
2044 if (SUCCEEDED(hrc))
2045 CHECK_PROGRESS_ERROR(ptrProgress, (GuestCtrl::tr("Directory deletion failed")));
2046 ptrProgress.setNull();
2047 }
2048 }
2049 catch (std::bad_alloc &)
2050 {
2051 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory during recursive rmdir\n"));
2052 }
2053 }
2054
2055 /*
2056 * This command returns immediately on failure since it's destructive in nature.
2057 */
2058 if (FAILED(hrc))
2059 return RTEXITCODE_FAILURE;
2060 break;
2061 }
2062
2063 default:
2064 return errorGetOpt(ch, &ValueUnion);
2065 }
2066 }
2067
2068 if (!cDirRemoved)
2069 return errorSyntax(GuestCtrl::tr("No directory to remove specified!"));
2070 return rcExit;
2071}
2072
2073static DECLCALLBACK(RTEXITCODE) gctlHandleRm(PGCTLCMDCTX pCtx, int argc, char **argv)
2074{
2075 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2076
2077 static const RTGETOPTDEF s_aOptions[] =
2078 {
2079 GCTLCMD_COMMON_OPTION_DEFS()
2080 { "--force", 'f', RTGETOPT_REQ_NOTHING, },
2081 };
2082
2083 int ch;
2084 RTGETOPTUNION ValueUnion;
2085 RTGETOPTSTATE GetState;
2086 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2087
2088 uint32_t cFilesDeleted = 0;
2089 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2090 bool fForce = true;
2091
2092 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2093 {
2094 /* For options that require an argument, ValueUnion has received the value. */
2095 switch (ch)
2096 {
2097 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2098
2099 case VINF_GETOPT_NOT_OPTION:
2100 if (cFilesDeleted == 0)
2101 {
2102 /*
2103 * First non-option - no more options now.
2104 */
2105 rcExit = gctlCtxPostOptionParsingInit(pCtx);
2106 if (rcExit != RTEXITCODE_SUCCESS)
2107 return rcExit;
2108 if (pCtx->cVerbose)
2109 RTPrintf(GuestCtrl::tr("Removing %RU32 file(s)...\n"), argc - GetState.iNext + 1);
2110 }
2111 if (g_fGuestCtrlCanceled)
2112 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("rm was interrupted by Ctrl-C (%u left)\n"),
2113 argc - GetState.iNext + 1);
2114
2115 /*
2116 * Remove the specified file.
2117 *
2118 * On failure we will by default stop, however, the force option will
2119 * by unix traditions force us to ignore errors and continue.
2120 */
2121 cFilesDeleted++;
2122 if (pCtx->cVerbose)
2123 RTPrintf(GuestCtrl::tr("Removing file \"%s\" ...\n"), ValueUnion.psz);
2124 try
2125 {
2126 /** @todo How does IGuestSession::FsObjRemove work with read-only files? Do we
2127 * need to do some chmod or whatever to better emulate the --force flag? */
2128 HRESULT hrc;
2129 CHECK_ERROR(pCtx->pGuestSession, FsObjRemove(Bstr(ValueUnion.psz).raw()));
2130 if (FAILED(hrc) && !fForce)
2131 return RTEXITCODE_FAILURE;
2132 }
2133 catch (std::bad_alloc &)
2134 {
2135 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory\n"));
2136 }
2137 break;
2138
2139 default:
2140 return errorGetOpt(ch, &ValueUnion);
2141 }
2142 }
2143
2144 if (!cFilesDeleted && !fForce)
2145 return errorSyntax(GuestCtrl::tr("No file to remove specified!"));
2146 return rcExit;
2147}
2148
2149static DECLCALLBACK(RTEXITCODE) gctlHandleMv(PGCTLCMDCTX pCtx, int argc, char **argv)
2150{
2151 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2152
2153 static const RTGETOPTDEF s_aOptions[] =
2154 {
2155 GCTLCMD_COMMON_OPTION_DEFS()
2156/** @todo Missing --force/-f flag. */
2157 };
2158
2159 int ch;
2160 RTGETOPTUNION ValueUnion;
2161 RTGETOPTSTATE GetState;
2162 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2163
2164 int vrc = VINF_SUCCESS;
2165
2166 bool fDryrun = false;
2167 std::vector< Utf8Str > vecSources;
2168 const char *pszDst = NULL;
2169 com::SafeArray<FsObjRenameFlag_T> aRenameFlags;
2170
2171 try
2172 {
2173 /** @todo Make flags configurable. */
2174 aRenameFlags.push_back(FsObjRenameFlag_NoReplace);
2175
2176 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2177 && RT_SUCCESS(vrc))
2178 {
2179 /* For options that require an argument, ValueUnion has received the value. */
2180 switch (ch)
2181 {
2182 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2183
2184 /** @todo Implement a --dryrun command. */
2185 /** @todo Implement rename flags. */
2186
2187 case VINF_GETOPT_NOT_OPTION:
2188 vecSources.push_back(Utf8Str(ValueUnion.psz));
2189 pszDst = ValueUnion.psz;
2190 break;
2191
2192 default:
2193 return errorGetOpt(ch, &ValueUnion);
2194 }
2195 }
2196 }
2197 catch (std::bad_alloc &)
2198 {
2199 vrc = VERR_NO_MEMORY;
2200 }
2201
2202 if (RT_FAILURE(vrc))
2203 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Failed to initialize, vrc=%Rrc\n"), vrc);
2204
2205 size_t cSources = vecSources.size();
2206 if (!cSources)
2207 return errorSyntax(GuestCtrl::tr("No source(s) to move specified!"));
2208 if (cSources < 2)
2209 return errorSyntax(GuestCtrl::tr("No destination specified!"));
2210
2211 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2212 if (rcExit != RTEXITCODE_SUCCESS)
2213 return rcExit;
2214
2215 /* Delete last element, which now is the destination. */
2216 vecSources.pop_back();
2217 cSources = vecSources.size();
2218
2219 HRESULT hrc = S_OK;
2220
2221 /* Destination must be a directory when specifying multiple sources. */
2222 if (cSources > 1)
2223 {
2224 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2225 hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(pszDst).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
2226 if (FAILED(hrc))
2227 {
2228 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Destination does not exist\n"));
2229 }
2230 else
2231 {
2232 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC */
2233 hrc = pFsObjInfo->COMGETTER(Type)(&enmObjType);
2234 if (SUCCEEDED(hrc))
2235 {
2236 if (enmObjType != FsObjType_Directory)
2237 return RTMsgErrorExit(RTEXITCODE_FAILURE,
2238 GuestCtrl::tr("Destination must be a directory when specifying multiple sources\n"));
2239 }
2240 else
2241 return RTMsgErrorExit(RTEXITCODE_FAILURE,
2242 GuestCtrl::tr("Unable to determine destination type: %Rhrc\n"),
2243 hrc);
2244 }
2245 }
2246
2247 /*
2248 * Rename (move) the entries.
2249 */
2250 if (pCtx->cVerbose)
2251 RTPrintf(GuestCtrl::tr("Renaming %RU32 %s ...\n"), cSources,
2252 cSources > 1 ? GuestCtrl::tr("sources", "", cSources) : GuestCtrl::tr("source"));
2253
2254 std::vector< Utf8Str >::iterator it = vecSources.begin();
2255 while ( it != vecSources.end()
2256 && !g_fGuestCtrlCanceled)
2257 {
2258 Utf8Str strSrcCur = (*it);
2259
2260 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2261 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC */
2262 hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(strSrcCur).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
2263 if (SUCCEEDED(hrc))
2264 hrc = pFsObjInfo->COMGETTER(Type)(&enmObjType);
2265 if (FAILED(hrc))
2266 {
2267 RTPrintf(GuestCtrl::tr("Cannot stat \"%s\": No such file or directory\n"), strSrcCur.c_str());
2268 ++it;
2269 continue; /* Skip. */
2270 }
2271
2272 char *pszDstCur = NULL;
2273
2274 if (cSources > 1)
2275 {
2276 pszDstCur = RTPathJoinA(pszDst, RTPathFilename(strSrcCur.c_str()));
2277 }
2278 else
2279 pszDstCur = RTStrDup(pszDst);
2280
2281 AssertPtrBreakStmt(pszDstCur, hrc = E_OUTOFMEMORY);
2282
2283 if (pCtx->cVerbose)
2284 RTPrintf(GuestCtrl::tr("Renaming %s \"%s\" to \"%s\" ...\n"),
2285 enmObjType == FsObjType_Directory ? GuestCtrl::tr("directory", "object") : GuestCtrl::tr("file","object"),
2286 strSrcCur.c_str(), pszDstCur);
2287
2288 if (!fDryrun)
2289 {
2290 CHECK_ERROR(pCtx->pGuestSession, FsObjRename(Bstr(strSrcCur).raw(),
2291 Bstr(pszDstCur).raw(),
2292 ComSafeArrayAsInParam(aRenameFlags)));
2293 /* Keep going with next item in case of errors. */
2294 }
2295
2296 RTStrFree(pszDstCur);
2297
2298 ++it;
2299 }
2300
2301 if ( (it != vecSources.end())
2302 && pCtx->cVerbose)
2303 {
2304 RTPrintf(GuestCtrl::tr("Warning: Not all sources were renamed\n"));
2305 }
2306
2307 return FAILED(hrc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2308}
2309
2310static DECLCALLBACK(RTEXITCODE) gctlHandleMkTemp(PGCTLCMDCTX pCtx, int argc, char **argv)
2311{
2312 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2313
2314 static const RTGETOPTDEF s_aOptions[] =
2315 {
2316 GCTLCMD_COMMON_OPTION_DEFS()
2317 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2318 { "--directory", 'D', RTGETOPT_REQ_NOTHING },
2319 { "--secure", 's', RTGETOPT_REQ_NOTHING },
2320 { "--tmpdir", 't', RTGETOPT_REQ_STRING }
2321 };
2322
2323 int ch;
2324 RTGETOPTUNION ValueUnion;
2325 RTGETOPTSTATE GetState;
2326 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2327
2328 Utf8Str strTemplate;
2329 uint32_t fMode = 0; /* Default mode. */
2330 bool fDirectory = false;
2331 bool fSecure = false;
2332 Utf8Str strTempDir;
2333
2334 DESTDIRMAP mapDirs;
2335
2336 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2337 {
2338 /* For options that require an argument, ValueUnion has received the value. */
2339 switch (ch)
2340 {
2341 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2342
2343 case 'm': /* Mode */
2344 fMode = ValueUnion.u32;
2345 break;
2346
2347 case 'D': /* Create directory */
2348 fDirectory = true;
2349 break;
2350
2351 case 's': /* Secure */
2352 fSecure = true;
2353 break;
2354
2355 case 't': /* Temp directory */
2356 strTempDir = ValueUnion.psz;
2357 break;
2358
2359 case VINF_GETOPT_NOT_OPTION:
2360 if (strTemplate.isEmpty())
2361 strTemplate = ValueUnion.psz;
2362 else
2363 return errorSyntax(GuestCtrl::tr("More than one template specified!\n"));
2364 break;
2365
2366 default:
2367 return errorGetOpt(ch, &ValueUnion);
2368 }
2369 }
2370
2371 if (strTemplate.isEmpty())
2372 return errorSyntax(GuestCtrl::tr("No template specified!"));
2373
2374#ifndef VBOX_WITH_GSTCTL_TOOLBOX_AS_CMDS
2375 if (!fDirectory)
2376 return errorSyntax(GuestCtrl::tr("Creating temporary files is currently not supported!"));
2377#endif
2378
2379 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2380 if (rcExit != RTEXITCODE_SUCCESS)
2381 return rcExit;
2382
2383 /*
2384 * Create the directories.
2385 */
2386 if (pCtx->cVerbose)
2387 {
2388 if (fDirectory && !strTempDir.isEmpty())
2389 RTPrintf(GuestCtrl::tr("Creating temporary directory from template '%s' in directory '%s' ...\n"),
2390 strTemplate.c_str(), strTempDir.c_str());
2391 else if (fDirectory)
2392 RTPrintf(GuestCtrl::tr("Creating temporary directory from template '%s' in default temporary directory ...\n"),
2393 strTemplate.c_str());
2394 else if (!fDirectory && !strTempDir.isEmpty())
2395 RTPrintf(GuestCtrl::tr("Creating temporary file from template '%s' in directory '%s' ...\n"),
2396 strTemplate.c_str(), strTempDir.c_str());
2397 else if (!fDirectory)
2398 RTPrintf(GuestCtrl::tr("Creating temporary file from template '%s' in default temporary directory ...\n"),
2399 strTemplate.c_str());
2400 }
2401
2402 HRESULT hrc = S_OK;
2403 if (fDirectory)
2404 {
2405 Bstr bstrDirectory;
2406 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreateTemp(Bstr(strTemplate).raw(),
2407 fMode, Bstr(strTempDir).raw(),
2408 fSecure,
2409 bstrDirectory.asOutParam()));
2410 if (SUCCEEDED(hrc))
2411 RTPrintf(GuestCtrl::tr("Directory name: %ls\n"), bstrDirectory.raw());
2412 }
2413 else
2414 {
2415 // else - temporary file not yet implemented
2416 /** @todo implement temporary file creation (we fend it off above, no
2417 * worries). */
2418 hrc = E_FAIL;
2419 }
2420
2421 return FAILED(hrc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2422}
2423
2424static DECLCALLBACK(RTEXITCODE) gctlHandleMount(PGCTLCMDCTX pCtx, int argc, char **argv)
2425{
2426 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2427
2428 static const RTGETOPTDEF s_aOptions[] =
2429 {
2430 GCTLCMD_COMMON_OPTION_DEFS()
2431 };
2432
2433 int ch;
2434 RTGETOPTUNION ValueUnion;
2435 RTGETOPTSTATE GetState;
2436 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2437
2438 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2439 {
2440 /* For options that require an argument, ValueUnion has received the value. */
2441 switch (ch)
2442 {
2443 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2444
2445 default:
2446 return errorGetOpt(ch, &ValueUnion);
2447 }
2448 }
2449
2450 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2451 if (rcExit != RTEXITCODE_SUCCESS)
2452 return rcExit;
2453
2454 HRESULT hrc = S_OK;
2455
2456 com::SafeArray<BSTR> mountPoints;
2457 CHECK_ERROR_RET(pCtx->pGuestSession, COMGETTER(MountPoints)(ComSafeArrayAsOutParam(mountPoints)), RTEXITCODE_FAILURE);
2458
2459 for (size_t i = 0; i < mountPoints.size(); ++i)
2460 RTPrintf("%ls\n", mountPoints[i]);
2461
2462 if (pCtx->cVerbose)
2463 RTPrintf("Found %zu mount points\n", mountPoints.size());
2464
2465 return RTEXITCODE_SUCCESS;
2466}
2467
2468static DECLCALLBACK(RTEXITCODE) gctlHandleFsInfo(PGCTLCMDCTX pCtx, int argc, char **argv)
2469{
2470 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2471
2472 /*
2473 * Parse arguments.
2474 */
2475 enum GCTLCMD_FSINFO_OPT
2476 {
2477 GCTLCMD_FSINFO_OPT_TOTAL = 1000
2478 };
2479
2480 static const RTGETOPTDEF s_aOptions[] =
2481 {
2482 GCTLCMD_COMMON_OPTION_DEFS()
2483 { "--human-readable", 'h', RTGETOPT_REQ_NOTHING },
2484 { "--total", GCTLCMD_FSINFO_OPT_TOTAL, RTGETOPT_REQ_NOTHING }
2485 };
2486
2487 int ch;
2488 RTGETOPTUNION ValueUnion;
2489 RTGETOPTSTATE GetState;
2490 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2491
2492 bool fHumanReadable = false;
2493 bool fShowTotal = false;
2494
2495 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
2496 && ch != VINF_GETOPT_NOT_OPTION)
2497 {
2498 /* For options that require an argument, ValueUnion has received the value. */
2499 switch (ch)
2500 {
2501 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2502
2503 case 'h':
2504 fHumanReadable = true;
2505 break;
2506
2507 case GCTLCMD_FSINFO_OPT_TOTAL:
2508 fShowTotal = true;
2509 break;
2510
2511 default:
2512 return errorGetOpt(ch, &ValueUnion);
2513 }
2514 }
2515
2516 if (ch != VINF_GETOPT_NOT_OPTION)
2517 return errorSyntax(GuestCtrl::tr("No path specified to query information for!"));
2518
2519 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2520 if (rcExit != RTEXITCODE_SUCCESS)
2521 return rcExit;
2522
2523 /* Stay within 80 characters width by default. */
2524 unsigned const cwFileSys = 10;
2525 /* When displaying human-readable sizes, we need less space for a column. */
2526 unsigned const cwSize = fHumanReadable ? 10 : 14;
2527 unsigned const cwSizeTotal = cwSize;
2528 unsigned const cwSizeUsed = cwSize;
2529 unsigned const cwSizeAvail = cwSize;
2530 unsigned const cwUsePercent = 6;
2531 unsigned const cwPathSpacing = 3; /* Spacing between last value and actual path. */
2532
2533 RTPrintf("%-*s%*s%*s%*s%*s%*s%s\n",
2534 cwFileSys, GuestCtrl::tr("Filesystem"),
2535 cwSizeTotal, GuestCtrl::tr("Total"), cwSizeUsed, GuestCtrl::tr("Used"), cwSizeAvail, GuestCtrl::tr("Avail"),
2536 cwUsePercent, GuestCtrl::tr("Use%"),
2537 cwPathSpacing, "",
2538 GuestCtrl::tr("Path"));
2539
2540 uint64_t cbTotalSize = 0;
2541 uint64_t cbTotalFree = 0;
2542
2543 while (ch == VINF_GETOPT_NOT_OPTION)
2544 {
2545 ComPtr<IGuestFsInfo> pFsInfo;
2546 HRESULT hrc;
2547 CHECK_ERROR(pCtx->pGuestSession, FsQueryInfo(Bstr(ValueUnion.psz).raw(), pFsInfo.asOutParam()));
2548 if (FAILED(hrc))
2549 {
2550 rcExit = RTEXITCODE_FAILURE;
2551 }
2552 else
2553 {
2554 Bstr bstr;
2555 CHECK_ERROR2I(pFsInfo, COMGETTER(Type)(bstr.asOutParam()));
2556 /** @todo Add label and mount point once we return this. */
2557 LONG64 cbTotal, cbFree;
2558 CHECK_ERROR2I(pFsInfo, COMGETTER(TotalSize)(&cbTotal));
2559 CHECK_ERROR2I(pFsInfo, COMGETTER(FreeSize)(&cbFree));
2560 uint8_t const uPercentUsed = (cbTotal - cbFree) * 100 / cbTotal;
2561 if (fHumanReadable)
2562 {
2563 RTPrintf("%-*ls%*Rhcb%*Rhcb%*Rhcb%*RU8%%%*s%s",
2564 cwFileSys, bstr.raw(), /* Filesystem */
2565 cwSizeTotal, cbTotal, /* Total */
2566 cwSizeUsed, cbTotal - cbFree, /* Used */
2567 cwSizeAvail, cbFree, /* Available */
2568 cwUsePercent - 1 /* For percent sign */, uPercentUsed, /* Percent */
2569 cwPathSpacing, "",
2570 ValueUnion.psz); /* Path */
2571 }
2572 else
2573 {
2574 RTPrintf("%-*ls%*RU64%*RU64%*RU64%*RU8%%%*s%s",
2575 cwFileSys, bstr.raw(), /* Filesystem */
2576 cwSizeTotal, cbTotal, /* Total */
2577 cwSizeUsed, cbTotal - cbFree, /* Used */
2578 cwSizeAvail, cbFree, /* Available */
2579 cwUsePercent - 1 /* For percent sign */, uPercentUsed, /* Percent */
2580 cwPathSpacing, "",
2581 ValueUnion.psz); /* Path */
2582 }
2583
2584 if (fShowTotal)
2585 {
2586 cbTotalSize += cbTotal;
2587 cbTotalFree += cbFree;
2588 }
2589 RTPrintf("\n");
2590 }
2591
2592 /* Next path. */
2593 ch = RTGetOpt(&GetState, &ValueUnion);
2594 }
2595
2596 if (fShowTotal)
2597 {
2598 uint8_t const uPercentUsed = (cbTotalSize - cbTotalFree) * 100 / cbTotalSize;
2599
2600 if (fHumanReadable)
2601 {
2602 RTPrintf("%-*s%*Rhcb%*Rhcb%*Rhcb%*RU8%%%*s%s",
2603 cwFileSys, "total",
2604 cwSizeTotal, cbTotalSize, /* Total */
2605 cwSizeUsed, cbTotalSize - cbTotalFree, /* Used */
2606 cwSizeAvail, cbTotalFree, /* Available */
2607 cwUsePercent - 1 /* For percent sign */, uPercentUsed, /* Percent */
2608 cwPathSpacing, "",
2609 "-"); /* Path */
2610 }
2611 else
2612 {
2613 RTPrintf("%-*s%*RU64%*RU64%*RU64%*RU8%%%*s%s",
2614 cwFileSys, "total", /* Filesystem */
2615 cwSizeTotal, cbTotalSize, /* Total */
2616 cwSizeUsed, cbTotalSize - cbTotalFree, /* Used */
2617 cwSizeAvail, cbTotalFree, /* Available */
2618 cwUsePercent - 1 /* For percent sign */, uPercentUsed, /* Percent */
2619 cwPathSpacing, "",
2620 "-"); /* Path */
2621 }
2622 RTPrintf("\n");
2623 }
2624
2625 return rcExit;
2626}
2627
2628static DECLCALLBACK(RTEXITCODE) gctlHandleStat(PGCTLCMDCTX pCtx, int argc, char **argv)
2629{
2630 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2631
2632 static const RTGETOPTDEF s_aOptions[] =
2633 {
2634 GCTLCMD_COMMON_OPTION_DEFS()
2635 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
2636 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
2637 { "--format", 'c', RTGETOPT_REQ_STRING },
2638 { "--terse", 't', RTGETOPT_REQ_NOTHING }
2639 };
2640
2641 int ch;
2642 RTGETOPTUNION ValueUnion;
2643 RTGETOPTSTATE GetState;
2644 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2645
2646 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
2647 && ch != VINF_GETOPT_NOT_OPTION)
2648 {
2649 /* For options that require an argument, ValueUnion has received the value. */
2650 switch (ch)
2651 {
2652 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2653
2654 case 'L': /* Dereference */
2655 case 'f': /* File-system */
2656 case 'c': /* Format */
2657 case 't': /* Terse */
2658 return errorSyntax(GuestCtrl::tr("Command \"%s\" not implemented yet!"), ValueUnion.psz);
2659
2660 default:
2661 return errorGetOpt(ch, &ValueUnion);
2662 }
2663 }
2664
2665 if (ch != VINF_GETOPT_NOT_OPTION)
2666 return errorSyntax(GuestCtrl::tr("Nothing to stat!"));
2667
2668 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2669 if (rcExit != RTEXITCODE_SUCCESS)
2670 return rcExit;
2671
2672
2673 /*
2674 * Do the file stat'ing.
2675 */
2676 while (ch == VINF_GETOPT_NOT_OPTION)
2677 {
2678 if (pCtx->cVerbose)
2679 RTPrintf(GuestCtrl::tr("Checking for element \"%s\" ...\n"), ValueUnion.psz);
2680
2681 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2682 HRESULT hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(ValueUnion.psz).raw(), FALSE /*followSymlinks*/,
2683 pFsObjInfo.asOutParam());
2684 if (FAILED(hrc))
2685 {
2686 /** @todo r=bird: There might be other reasons why we end up here than
2687 * non-existing "element" (object or file, please, nobody calls it elements). */
2688 if (pCtx->cVerbose)
2689 RTPrintf(GuestCtrl::tr("Failed to stat '%s': No such file\n"), ValueUnion.psz);
2690 rcExit = RTEXITCODE_FAILURE;
2691 }
2692 else
2693 {
2694 RTPrintf(GuestCtrl::tr(" File: '%s'\n"), ValueUnion.psz); /** @todo escape this name. */
2695
2696 FsObjType_T enmType = FsObjType_Unknown;
2697 CHECK_ERROR2I(pFsObjInfo, COMGETTER(Type)(&enmType));
2698 LONG64 cbObject = 0;
2699 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ObjectSize)(&cbObject));
2700 LONG64 cbAllocated = 0;
2701 CHECK_ERROR2I(pFsObjInfo, COMGETTER(AllocatedSize)(&cbAllocated));
2702 LONG uid = 0;
2703 CHECK_ERROR2I(pFsObjInfo, COMGETTER(UID)(&uid));
2704 LONG gid = 0;
2705 CHECK_ERROR2I(pFsObjInfo, COMGETTER(GID)(&gid));
2706 Bstr bstrUsername;
2707 CHECK_ERROR2I(pFsObjInfo, COMGETTER(UserName)(bstrUsername.asOutParam()));
2708 Bstr bstrGroupName;
2709 CHECK_ERROR2I(pFsObjInfo, COMGETTER(GroupName)(bstrGroupName.asOutParam()));
2710 Bstr bstrAttribs;
2711 CHECK_ERROR2I(pFsObjInfo, COMGETTER(FileAttributes)(bstrAttribs.asOutParam()));
2712 LONG64 idNode = 0;
2713 CHECK_ERROR2I(pFsObjInfo, COMGETTER(NodeId)(&idNode));
2714 ULONG uDevNode = 0;
2715 CHECK_ERROR2I(pFsObjInfo, COMGETTER(NodeIdDevice)(&uDevNode));
2716 ULONG uDeviceNo = 0;
2717 CHECK_ERROR2I(pFsObjInfo, COMGETTER(DeviceNumber)(&uDeviceNo));
2718 ULONG cHardLinks = 1;
2719 CHECK_ERROR2I(pFsObjInfo, COMGETTER(HardLinks)(&cHardLinks));
2720 LONG64 nsBirthTime = 0;
2721 CHECK_ERROR2I(pFsObjInfo, COMGETTER(BirthTime)(&nsBirthTime));
2722 LONG64 nsChangeTime = 0;
2723 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ChangeTime)(&nsChangeTime));
2724 LONG64 nsModificationTime = 0;
2725 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ModificationTime)(&nsModificationTime));
2726 LONG64 nsAccessTime = 0;
2727 CHECK_ERROR2I(pFsObjInfo, COMGETTER(AccessTime)(&nsAccessTime));
2728
2729 RTPrintf(GuestCtrl::tr(" Size: %-17RU64 Alloc: %-19RU64 Type: %s\n"),
2730 cbObject, cbAllocated, gctlFsObjTypeToName(enmType));
2731 RTPrintf(GuestCtrl::tr("Device: %#-17RX32 INode: %-18RU64 Links: %u\n"), uDevNode, idNode, cHardLinks);
2732
2733 Utf8Str strAttrib(bstrAttribs);
2734 char *pszMode = strAttrib.mutableRaw();
2735 char *pszAttribs = strchr(pszMode, ' ');
2736 if (pszAttribs)
2737 do *pszAttribs++ = '\0';
2738 while (*pszAttribs == ' ');
2739 else
2740 pszAttribs = strchr(pszMode, '\0');
2741 if (uDeviceNo != 0)
2742 RTPrintf(GuestCtrl::tr(" Mode: %-16s Attrib: %-17s Dev ID: %#RX32\n"), pszMode, pszAttribs, uDeviceNo);
2743 else
2744 RTPrintf(GuestCtrl::tr(" Mode: %-16s Attrib: %s\n"), pszMode, pszAttribs);
2745
2746 RTPrintf(GuestCtrl::tr(" Owner: %4d/%-12ls Group: %4d/%ls\n"), uid, bstrUsername.raw(), gid, bstrGroupName.raw());
2747
2748 RTTIMESPEC TimeSpec;
2749 char szTmp[RTTIME_STR_LEN];
2750 RTPrintf(GuestCtrl::tr(" Birth: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsBirthTime),
2751 szTmp, sizeof(szTmp)));
2752 RTPrintf(GuestCtrl::tr("Change: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsChangeTime),
2753 szTmp, sizeof(szTmp)));
2754 RTPrintf(GuestCtrl::tr("Modify: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsModificationTime),
2755 szTmp, sizeof(szTmp)));
2756 RTPrintf(GuestCtrl::tr("Access: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsAccessTime),
2757 szTmp, sizeof(szTmp)));
2758
2759 /* Skiping: Generation ID - only the ISO9660 VFS sets this. FreeBSD user flags. */
2760 }
2761
2762 /* Next file. */
2763 ch = RTGetOpt(&GetState, &ValueUnion);
2764 }
2765
2766 return rcExit;
2767}
2768
2769/**
2770 * Waits for a Guest Additions run level being reached.
2771 *
2772 * @returns VBox status code.
2773 * Returns VERR_CANCELLED if waiting for cancelled due to signal handling, e.g. when CTRL+C or some sort was pressed.
2774 * @param pCtx The guest control command context.
2775 * @param enmRunLevel Run level to wait for.
2776 * @param cMsTimeout Timeout (in ms) for waiting.
2777 */
2778static int gctlWaitForRunLevel(PGCTLCMDCTX pCtx, AdditionsRunLevelType_T enmRunLevel, RTMSINTERVAL cMsTimeout)
2779{
2780 int vrc = VINF_SUCCESS; /* Shut up MSVC. */
2781
2782 try
2783 {
2784 HRESULT hrc = S_OK;
2785 /** Whether we need to actually wait for the run level or if we already reached it. */
2786 bool fWait = false;
2787
2788 /* Install an event handler first to catch any runlevel changes. */
2789 ComObjPtr<GuestAdditionsRunlevelListenerImpl> pGuestListener;
2790 do
2791 {
2792 /* Listener creation. */
2793 pGuestListener.createObject();
2794 pGuestListener->init(new GuestAdditionsRunlevelListener(enmRunLevel));
2795
2796 /* Register for IGuest events. */
2797 ComPtr<IEventSource> es;
2798 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
2799 com::SafeArray<VBoxEventType_T> eventTypes;
2800 eventTypes.push_back(VBoxEventType_OnGuestAdditionsStatusChanged);
2801 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
2802 true /* Active listener */));
2803
2804 AdditionsRunLevelType_T enmRunLevelCur = AdditionsRunLevelType_None;
2805 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(AdditionsRunLevel)(&enmRunLevelCur));
2806 fWait = enmRunLevelCur != enmRunLevel;
2807
2808 if (pCtx->cVerbose)
2809 RTPrintf(GuestCtrl::tr("Current run level is %RU32\n"), enmRunLevelCur);
2810
2811 } while (0);
2812
2813 if (fWait)
2814 {
2815 if (pCtx->cVerbose)
2816 RTPrintf(GuestCtrl::tr("Waiting for run level %RU32 ...\n"), enmRunLevel);
2817
2818 RTMSINTERVAL tsStart = RTTimeMilliTS();
2819 while (RTTimeMilliTS() - tsStart < cMsTimeout)
2820 {
2821 /* Wait for the global signal semaphore getting signalled. */
2822 vrc = RTSemEventWait(g_SemEventGuestCtrlCanceled, 100 /* ms */);
2823 if (RT_FAILURE(vrc))
2824 {
2825 if (vrc == VERR_TIMEOUT)
2826 continue;
2827 else
2828 {
2829 RTPrintf(GuestCtrl::tr("Waiting failed with %Rrc\n"), vrc);
2830 break;
2831 }
2832 }
2833 else if (pCtx->cVerbose)
2834 {
2835 RTPrintf(GuestCtrl::tr("Run level %RU32 reached\n"), enmRunLevel);
2836 break;
2837 }
2838
2839 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
2840 }
2841
2842 if ( vrc == VERR_TIMEOUT
2843 && pCtx->cVerbose)
2844 RTPrintf(GuestCtrl::tr("Run level %RU32 not reached within time\n"), enmRunLevel);
2845 }
2846
2847 if (!pGuestListener.isNull())
2848 {
2849 /* Guest callback unregistration. */
2850 ComPtr<IEventSource> pES;
2851 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
2852 if (!pES.isNull())
2853 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
2854 pGuestListener.setNull();
2855 }
2856
2857 if (g_fGuestCtrlCanceled)
2858 vrc = VERR_CANCELLED;
2859 }
2860 catch (std::bad_alloc &)
2861 {
2862 vrc = VERR_NO_MEMORY;
2863 }
2864
2865 return vrc;
2866}
2867
2868static DECLCALLBACK(RTEXITCODE) gctlHandleUpdateAdditions(PGCTLCMDCTX pCtx, int argc, char **argv)
2869{
2870 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2871
2872 /** Timeout to wait for the whole updating procedure to complete. */
2873 uint32_t cMsTimeout = RT_INDEFINITE_WAIT;
2874 /** Source path to .ISO Guest Additions file to use. */
2875 Utf8Str strSource;
2876 com::SafeArray<IN_BSTR> aArgs;
2877 /** Whether to reboot the guest automatically when the update process has finished successfully. */
2878 bool fRebootOnFinish = false;
2879 /** Whether to only wait for getting the update process started instead of waiting until it finishes. */
2880 bool fWaitStartOnly = false;
2881 /** Whether to wait for the VM being ready to start the update. Needs Guest Additions facility reporting. */
2882 bool fWaitReady = false;
2883 /** Whether to verify if the Guest Additions were successfully updated on the guest. */
2884 bool fVerify = false;
2885
2886 /*
2887 * Parse arguments.
2888 */
2889 enum KGSTCTRLUPDATEADDITIONSOPT
2890 {
2891 KGSTCTRLUPDATEADDITIONSOPT_REBOOT = 1000,
2892 KGSTCTRLUPDATEADDITIONSOPT_SOURCE,
2893 KGSTCTRLUPDATEADDITIONSOPT_TIMEOUT,
2894 KGSTCTRLUPDATEADDITIONSOPT_VERIFY,
2895 KGSTCTRLUPDATEADDITIONSOPT_WAITREADY,
2896 KGSTCTRLUPDATEADDITIONSOPT_WAITSTART
2897 };
2898
2899 static const RTGETOPTDEF s_aOptions[] =
2900 {
2901 GCTLCMD_COMMON_OPTION_DEFS()
2902 { "--reboot", KGSTCTRLUPDATEADDITIONSOPT_REBOOT, RTGETOPT_REQ_NOTHING },
2903 { "--source", KGSTCTRLUPDATEADDITIONSOPT_SOURCE, RTGETOPT_REQ_STRING },
2904 { "--timeout", KGSTCTRLUPDATEADDITIONSOPT_TIMEOUT, RTGETOPT_REQ_UINT32 },
2905 { "--verify", KGSTCTRLUPDATEADDITIONSOPT_VERIFY, RTGETOPT_REQ_NOTHING },
2906 { "--wait-ready", KGSTCTRLUPDATEADDITIONSOPT_WAITREADY, RTGETOPT_REQ_NOTHING },
2907 { "--wait-start", KGSTCTRLUPDATEADDITIONSOPT_WAITSTART, RTGETOPT_REQ_NOTHING }
2908 };
2909
2910 int ch;
2911 RTGETOPTUNION ValueUnion;
2912 RTGETOPTSTATE GetState;
2913 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2914
2915 int vrc = VINF_SUCCESS;
2916 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2917 && RT_SUCCESS(vrc))
2918 {
2919 switch (ch)
2920 {
2921 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2922
2923 case KGSTCTRLUPDATEADDITIONSOPT_REBOOT:
2924 fRebootOnFinish = true;
2925 break;
2926
2927 case KGSTCTRLUPDATEADDITIONSOPT_SOURCE:
2928 vrc = RTPathAbsCxx(strSource, ValueUnion.psz);
2929 if (RT_FAILURE(vrc))
2930 return RTMsgErrorExitFailure(GuestCtrl::tr("RTPathAbsCxx failed on '%s': %Rrc"), ValueUnion.psz, vrc);
2931 break;
2932
2933 case KGSTCTRLUPDATEADDITIONSOPT_WAITSTART:
2934 fWaitStartOnly = true;
2935 break;
2936
2937 case KGSTCTRLUPDATEADDITIONSOPT_WAITREADY:
2938 fWaitReady = true;
2939 break;
2940
2941 case KGSTCTRLUPDATEADDITIONSOPT_VERIFY:
2942 fVerify = true;
2943 fRebootOnFinish = true; /* Verification needs a mandatory reboot after successful update. */
2944 break;
2945
2946 case VINF_GETOPT_NOT_OPTION:
2947 if (aArgs.size() == 0 && strSource.isEmpty())
2948 strSource = ValueUnion.psz;
2949 else
2950 aArgs.push_back(Bstr(ValueUnion.psz).raw());
2951 break;
2952
2953 default:
2954 return errorGetOpt(ch, &ValueUnion);
2955 }
2956 }
2957
2958 if (pCtx->cVerbose)
2959 RTPrintf(GuestCtrl::tr("Updating Guest Additions ...\n"));
2960
2961 HRESULT hrc = S_OK;
2962 while (strSource.isEmpty())
2963 {
2964 ComPtr<ISystemProperties> pProperties;
2965 CHECK_ERROR_BREAK(pCtx->pArg->virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
2966 Bstr strISO;
2967 CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
2968 strSource = strISO;
2969 break;
2970 }
2971
2972 /* Determine source if not set yet. */
2973 if (strSource.isEmpty())
2974 {
2975 RTMsgError(GuestCtrl::tr("No Guest Additions source found or specified, aborting\n"));
2976 vrc = VERR_FILE_NOT_FOUND;
2977 }
2978 else if (!RTFileExists(strSource.c_str()))
2979 {
2980 RTMsgError(GuestCtrl::tr("Source \"%s\" does not exist!\n"), strSource.c_str());
2981 vrc = VERR_FILE_NOT_FOUND;
2982 }
2983
2984
2985
2986#if 0
2987 ComPtr<IGuest> guest;
2988 HRESULT hrc = pConsole->COMGETTER(Guest)(guest.asOutParam());
2989 if (SUCCEEDED(hrc) && !guest.isNull())
2990 {
2991 SHOW_STRING_PROP_NOT_EMPTY(guest, OSTypeId, "GuestOSType", GuestCtrl::tr("OS type:"));
2992
2993 AdditionsRunLevelType_T guestRunLevel; /** @todo Add a runlevel-to-string (e.g. 0 = "None") method? */
2994 hrc = guest->COMGETTER(AdditionsRunLevel)(&guestRunLevel);
2995 if (SUCCEEDED(hrc))
2996 SHOW_ULONG_VALUE("GuestAdditionsRunLevel", GuestCtrl::tr("Additions run level:"), (ULONG)guestRunLevel, "");
2997
2998 Bstr guestString;
2999 hrc = guest->COMGETTER(AdditionsVersion)(guestString.asOutParam());
3000 if ( SUCCEEDED(hrc)
3001 && !guestString.isEmpty())
3002 {
3003 ULONG uRevision;
3004 hrc = guest->COMGETTER(AdditionsRevision)(&uRevision);
3005 if (FAILED(hrc))
3006 uRevision = 0;
3007 RTStrPrintf(szValue, sizeof(szValue), "%ls r%u", guestString.raw(), uRevision);
3008 SHOW_UTF8_STRING("GuestAdditionsVersion", GuestCtrl::tr("Additions version:"), szValue);
3009 }
3010 }
3011#endif
3012
3013 if (RT_SUCCESS(vrc))
3014 {
3015 if (pCtx->cVerbose)
3016 RTPrintf(GuestCtrl::tr("Using source: %s\n"), strSource.c_str());
3017
3018 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3019 if (rcExit != RTEXITCODE_SUCCESS)
3020 return rcExit;
3021
3022 if (fWaitReady)
3023 {
3024 if (pCtx->cVerbose)
3025 RTPrintf(GuestCtrl::tr("Waiting for current Guest Additions inside VM getting ready for updating ...\n"));
3026
3027 const uint64_t uTsStart = RTTimeMilliTS();
3028 vrc = gctlWaitForRunLevel(pCtx, AdditionsRunLevelType_Userland, cMsTimeout);
3029 if (RT_SUCCESS(vrc))
3030 cMsTimeout = cMsTimeout != RT_INDEFINITE_WAIT ? cMsTimeout - (RTTimeMilliTS() - uTsStart) : cMsTimeout;
3031 }
3032
3033 if (RT_SUCCESS(vrc))
3034 {
3035 /* Get current Guest Additions version / revision. */
3036 Bstr strGstVerCur;
3037 ULONG uGstRevCur = 0;
3038 hrc = pCtx->pGuest->COMGETTER(AdditionsVersion)(strGstVerCur.asOutParam());
3039 if ( SUCCEEDED(hrc)
3040 && !strGstVerCur.isEmpty())
3041 {
3042 hrc = pCtx->pGuest->COMGETTER(AdditionsRevision)(&uGstRevCur);
3043 if (SUCCEEDED(hrc))
3044 {
3045 if (pCtx->cVerbose)
3046 RTPrintf(GuestCtrl::tr("Guest Additions %lsr%RU64 currently installed, waiting for Guest Additions installer to start ...\n"),
3047 strGstVerCur.raw(), uGstRevCur);
3048 }
3049 }
3050
3051 com::SafeArray<AdditionsUpdateFlag_T> aUpdateFlags;
3052 if (fWaitStartOnly)
3053 aUpdateFlags.push_back(AdditionsUpdateFlag_WaitForUpdateStartOnly);
3054
3055 ComPtr<IProgress> pProgress;
3056 CHECK_ERROR(pCtx->pGuest, UpdateGuestAdditions(Bstr(strSource).raw(),
3057 ComSafeArrayAsInParam(aArgs),
3058 ComSafeArrayAsInParam(aUpdateFlags),
3059 pProgress.asOutParam()));
3060 if (FAILED(hrc))
3061 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
3062 else
3063 {
3064 if (pCtx->cVerbose)
3065 hrc = showProgress(pProgress);
3066 else
3067 hrc = pProgress->WaitForCompletion((int32_t)cMsTimeout);
3068
3069 if (SUCCEEDED(hrc))
3070 CHECK_PROGRESS_ERROR(pProgress, (GuestCtrl::tr("Guest Additions update failed")));
3071 vrc = gctlPrintProgressError(pProgress);
3072 if (RT_SUCCESS(vrc))
3073 {
3074 if (pCtx->cVerbose)
3075 RTPrintf(GuestCtrl::tr("Guest Additions update successful.\n"));
3076
3077 if (fRebootOnFinish)
3078 {
3079 if (pCtx->cVerbose)
3080 RTPrintf(GuestCtrl::tr("Rebooting guest ...\n"));
3081 com::SafeArray<GuestShutdownFlag_T> aShutdownFlags;
3082 aShutdownFlags.push_back(GuestShutdownFlag_Reboot);
3083 CHECK_ERROR(pCtx->pGuest, Shutdown(ComSafeArrayAsInParam(aShutdownFlags)));
3084 if (FAILED(hrc))
3085 {
3086 if (hrc == VBOX_E_NOT_SUPPORTED)
3087 {
3088 RTPrintf(GuestCtrl::tr("Current installed Guest Additions don't support automatic rebooting. "
3089 "Please reboot manually.\n"));
3090 vrc = VERR_NOT_SUPPORTED;
3091 }
3092 else
3093 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
3094 }
3095 else
3096 {
3097 if (fWaitReady)
3098 {
3099 if (pCtx->cVerbose)
3100 RTPrintf(GuestCtrl::tr("Waiting for new Guest Additions inside VM getting ready ...\n"));
3101
3102 vrc = gctlWaitForRunLevel(pCtx, AdditionsRunLevelType_Userland, cMsTimeout);
3103 if (RT_SUCCESS(vrc))
3104 {
3105 if (fVerify)
3106 {
3107 if (pCtx->cVerbose)
3108 RTPrintf(GuestCtrl::tr("Verifying Guest Additions update ...\n"));
3109
3110 /* Get new Guest Additions version / revision. */
3111 Bstr strGstVerNew;
3112 ULONG uGstRevNew = 0;
3113 hrc = pCtx->pGuest->COMGETTER(AdditionsVersion)(strGstVerNew.asOutParam());
3114 if ( SUCCEEDED(hrc)
3115 && !strGstVerNew.isEmpty())
3116 {
3117 hrc = pCtx->pGuest->COMGETTER(AdditionsRevision)(&uGstRevNew);
3118 if (FAILED(hrc))
3119 uGstRevNew = 0;
3120 }
3121
3122 /** @todo Do more verification here. */
3123 vrc = uGstRevNew > uGstRevCur ? VINF_SUCCESS : VERR_NO_CHANGE;
3124
3125 if (pCtx->cVerbose)
3126 {
3127 RTPrintf(GuestCtrl::tr("Old Guest Additions: %ls%RU64\n"), strGstVerCur.raw(),
3128 uGstRevCur);
3129 RTPrintf(GuestCtrl::tr("New Guest Additions: %ls%RU64\n"), strGstVerNew.raw(),
3130 uGstRevNew);
3131
3132 if (RT_FAILURE(vrc))
3133 {
3134 RTPrintf(GuestCtrl::tr("\nError updating Guest Additions, please check guest installer log\n"));
3135 }
3136 else
3137 {
3138 if (uGstRevNew < uGstRevCur)
3139 RTPrintf(GuestCtrl::tr("\nWARNING: Guest Additions were downgraded\n"));
3140 }
3141 }
3142 }
3143 }
3144 }
3145 else if (pCtx->cVerbose)
3146 RTPrintf(GuestCtrl::tr("The guest needs to be restarted in order to make use of the updated Guest Additions.\n"));
3147 }
3148 }
3149 }
3150 }
3151 }
3152 }
3153
3154 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3155}
3156
3157/**
3158 * Returns a Guest Additions run level from a string.
3159 *
3160 * @returns Run level if found, or AdditionsRunLevelType_None if not found / invalid.
3161 * @param pcszStr String to return run level for.
3162 */
3163static AdditionsRunLevelType_T gctlGetRunLevelFromStr(const char *pcszStr)
3164{
3165 AssertPtrReturn(pcszStr, AdditionsRunLevelType_None);
3166
3167 if (RTStrICmp(pcszStr, "system") == 0) return AdditionsRunLevelType_System;
3168 else if (RTStrICmp(pcszStr, "userland") == 0) return AdditionsRunLevelType_Userland;
3169 else if (RTStrICmp(pcszStr, "desktop") == 0) return AdditionsRunLevelType_Desktop;
3170
3171 return AdditionsRunLevelType_None;
3172}
3173
3174static DECLCALLBACK(RTEXITCODE) gctlHandleWaitRunLevel(PGCTLCMDCTX pCtx, int argc, char **argv)
3175{
3176 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3177
3178 /** Timeout to wait for run level being reached.
3179 * By default we wait until it's reached. */
3180 uint32_t cMsTimeout = RT_INDEFINITE_WAIT;
3181
3182 /*
3183 * Parse arguments.
3184 */
3185 enum KGSTCTRLWAITRUNLEVELOPT
3186 {
3187 KGSTCTRLWAITRUNLEVELOPT_TIMEOUT = 1000
3188 };
3189
3190 static const RTGETOPTDEF s_aOptions[] =
3191 {
3192 GCTLCMD_COMMON_OPTION_DEFS()
3193 { "--timeout", KGSTCTRLWAITRUNLEVELOPT_TIMEOUT, RTGETOPT_REQ_UINT32 }
3194 };
3195
3196 int ch;
3197 RTGETOPTUNION ValueUnion;
3198 RTGETOPTSTATE GetState;
3199 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3200
3201 AdditionsRunLevelType_T enmRunLevel = AdditionsRunLevelType_None;
3202
3203 int vrc = VINF_SUCCESS;
3204 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3205 && RT_SUCCESS(vrc))
3206 {
3207 switch (ch)
3208 {
3209 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3210
3211 case KGSTCTRLWAITRUNLEVELOPT_TIMEOUT:
3212 cMsTimeout = ValueUnion.u32;
3213 break;
3214
3215 case VINF_GETOPT_NOT_OPTION:
3216 {
3217 enmRunLevel = gctlGetRunLevelFromStr(ValueUnion.psz);
3218 if (enmRunLevel == AdditionsRunLevelType_None)
3219 return errorSyntax(GuestCtrl::tr("Invalid run level specified. Valid values are: system, userland, desktop"));
3220 break;
3221 }
3222
3223 default:
3224 return errorGetOpt(ch, &ValueUnion);
3225 }
3226 }
3227
3228 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3229 if (rcExit != RTEXITCODE_SUCCESS)
3230 return rcExit;
3231
3232 if (enmRunLevel == AdditionsRunLevelType_None)
3233 return errorSyntax(GuestCtrl::tr("Missing run level to wait for"));
3234
3235 vrc = gctlWaitForRunLevel(pCtx, enmRunLevel, cMsTimeout);
3236
3237 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3238}
3239
3240static DECLCALLBACK(RTEXITCODE) gctlHandleList(PGCTLCMDCTX pCtx, int argc, char **argv)
3241{
3242 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3243
3244 static const RTGETOPTDEF s_aOptions[] =
3245 {
3246 GCTLCMD_COMMON_OPTION_DEFS()
3247 };
3248
3249 int ch;
3250 RTGETOPTUNION ValueUnion;
3251 RTGETOPTSTATE GetState;
3252 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3253
3254 bool fSeenListArg = false;
3255 bool fListAll = false;
3256 bool fListSessions = false;
3257 bool fListProcesses = false;
3258 bool fListFiles = false;
3259
3260 int vrc = VINF_SUCCESS;
3261 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3262 && RT_SUCCESS(vrc))
3263 {
3264 switch (ch)
3265 {
3266 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3267
3268 case VINF_GETOPT_NOT_OPTION:
3269 if ( !RTStrICmp(ValueUnion.psz, "sessions")
3270 || !RTStrICmp(ValueUnion.psz, "sess"))
3271 fListSessions = true;
3272 else if ( !RTStrICmp(ValueUnion.psz, "processes")
3273 || !RTStrICmp(ValueUnion.psz, "procs"))
3274 fListSessions = fListProcesses = true; /* Showing processes implies showing sessions. */
3275 else if (!RTStrICmp(ValueUnion.psz, "files"))
3276 fListSessions = fListFiles = true; /* Showing files implies showing sessions. */
3277 else if (!RTStrICmp(ValueUnion.psz, "all"))
3278 fListAll = true;
3279 else
3280 return errorSyntax(GuestCtrl::tr("Unknown list: '%s'"), ValueUnion.psz);
3281 fSeenListArg = true;
3282 break;
3283
3284 default:
3285 return errorGetOpt(ch, &ValueUnion);
3286 }
3287 }
3288
3289 if (!fSeenListArg)
3290 return errorSyntax(GuestCtrl::tr("Missing list name"));
3291 Assert(fListAll || fListSessions);
3292
3293 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3294 if (rcExit != RTEXITCODE_SUCCESS)
3295 return rcExit;
3296
3297
3298 /** @todo Do we need a machine-readable output here as well? */
3299
3300 HRESULT hrc;
3301 size_t cTotalProcs = 0;
3302 size_t cTotalFiles = 0;
3303
3304 SafeIfaceArray <IGuestSession> collSessions;
3305 CHECK_ERROR(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3306 if (SUCCEEDED(hrc))
3307 {
3308 size_t const cSessions = collSessions.size();
3309 if (cSessions)
3310 {
3311 RTPrintf(GuestCtrl::tr("Active guest sessions:\n"));
3312
3313 /** @todo Make this output a bit prettier. No time now. */
3314
3315 for (size_t i = 0; i < cSessions; i++)
3316 {
3317 ComPtr<IGuestSession> pCurSession = collSessions[i];
3318 if (!pCurSession.isNull())
3319 {
3320 do
3321 {
3322 ULONG uID;
3323 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Id)(&uID));
3324 Bstr strName;
3325 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Name)(strName.asOutParam()));
3326 Bstr strUser;
3327 CHECK_ERROR_BREAK(pCurSession, COMGETTER(User)(strUser.asOutParam()));
3328 GuestSessionStatus_T sessionStatus;
3329 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Status)(&sessionStatus));
3330 RTPrintf(GuestCtrl::tr("\n\tSession #%-3zu ID=%-3RU32 User=%-16ls Status=[%s] Name=%ls"),
3331 i, uID, strUser.raw(), gctlGuestSessionStatusToText(sessionStatus), strName.raw());
3332 } while (0);
3333
3334 if ( fListAll
3335 || fListProcesses)
3336 {
3337 SafeIfaceArray <IGuestProcess> collProcesses;
3338 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcesses)));
3339 for (size_t a = 0; a < collProcesses.size(); a++)
3340 {
3341 ComPtr<IGuestProcess> pCurProcess = collProcesses[a];
3342 if (!pCurProcess.isNull())
3343 {
3344 do
3345 {
3346 ULONG uPID;
3347 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(PID)(&uPID));
3348 Bstr strExecPath;
3349 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(ExecutablePath)(strExecPath.asOutParam()));
3350 ProcessStatus_T procStatus;
3351 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(Status)(&procStatus));
3352
3353 RTPrintf(GuestCtrl::tr("\n\t\tProcess #%-03zu PID=%-6RU32 Status=[%s] Command=%ls"),
3354 a, uPID, gctlProcessStatusToText(procStatus), strExecPath.raw());
3355 } while (0);
3356 }
3357 }
3358
3359 cTotalProcs += collProcesses.size();
3360 }
3361
3362 if ( fListAll
3363 || fListFiles)
3364 {
3365 SafeIfaceArray <IGuestFile> collFiles;
3366 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Files)(ComSafeArrayAsOutParam(collFiles)));
3367 for (size_t a = 0; a < collFiles.size(); a++)
3368 {
3369 ComPtr<IGuestFile> pCurFile = collFiles[a];
3370 if (!pCurFile.isNull())
3371 {
3372 do
3373 {
3374 ULONG idFile;
3375 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Id)(&idFile));
3376 Bstr strName;
3377 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Filename)(strName.asOutParam()));
3378 FileStatus_T fileStatus;
3379 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Status)(&fileStatus));
3380
3381 RTPrintf(GuestCtrl::tr("\n\t\tFile #%-03zu ID=%-6RU32 Status=[%s] Name=%ls"),
3382 a, idFile, gctlFileStatusToText(fileStatus), strName.raw());
3383 } while (0);
3384 }
3385 }
3386
3387 cTotalFiles += collFiles.size();
3388 }
3389 }
3390 }
3391
3392 RTPrintf(GuestCtrl::tr("\n\nTotal guest sessions: %zu\n"), collSessions.size());
3393 if (fListAll || fListProcesses)
3394 RTPrintf(GuestCtrl::tr("Total guest processes: %zu\n"), cTotalProcs);
3395 if (fListAll || fListFiles)
3396 RTPrintf(GuestCtrl::tr("Total guest files: %zu\n"), cTotalFiles);
3397 }
3398 else
3399 RTPrintf(GuestCtrl::tr("No active guest sessions found\n"));
3400 }
3401
3402 if (FAILED(hrc)) /** @todo yeah, right... Only the last error? */
3403 rcExit = RTEXITCODE_FAILURE;
3404
3405 return rcExit;
3406}
3407
3408static DECLCALLBACK(RTEXITCODE) gctlHandleCloseProcess(PGCTLCMDCTX pCtx, int argc, char **argv)
3409{
3410 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3411
3412 static const RTGETOPTDEF s_aOptions[] =
3413 {
3414 GCTLCMD_COMMON_OPTION_DEFS()
3415 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3416 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3417 };
3418
3419 int ch;
3420 RTGETOPTUNION ValueUnion;
3421 RTGETOPTSTATE GetState;
3422 int vrc = RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3423 AssertRCReturn(vrc, RTEXITCODE_FAILURE);
3424
3425 std::vector < uint32_t > vecPID;
3426 ULONG idSession = UINT32_MAX;
3427 Utf8Str strSessionName;
3428
3429 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3430 {
3431 /* For options that require an argument, ValueUnion has received the value. */
3432 switch (ch)
3433 {
3434 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3435
3436 case 'n': /* Session name (or pattern) */
3437 strSessionName = ValueUnion.psz;
3438 break;
3439
3440 case 'i': /* Session ID */
3441 idSession = ValueUnion.u32;
3442 break;
3443
3444 case VINF_GETOPT_NOT_OPTION:
3445 {
3446 /* Treat every else specified as a PID to kill. */
3447 uint32_t uPid;
3448 vrc = RTStrToUInt32Ex(ValueUnion.psz, NULL, 0, &uPid);
3449 if ( RT_SUCCESS(vrc)
3450 && vrc != VWRN_TRAILING_CHARS
3451 && vrc != VWRN_NUMBER_TOO_BIG
3452 && vrc != VWRN_NEGATIVE_UNSIGNED)
3453 {
3454 if (uPid != 0)
3455 {
3456 try
3457 {
3458 vecPID.push_back(uPid);
3459 }
3460 catch (std::bad_alloc &)
3461 {
3462 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory"));
3463 }
3464 }
3465 else
3466 return errorSyntax(GuestCtrl::tr("Invalid PID value: 0"));
3467 }
3468 else
3469 return errorSyntax(GuestCtrl::tr("Error parsing PID value: %Rrc"), vrc);
3470 break;
3471 }
3472
3473 default:
3474 return errorGetOpt(ch, &ValueUnion);
3475 }
3476 }
3477
3478 if (vecPID.empty())
3479 return errorSyntax(GuestCtrl::tr("At least one PID must be specified to kill!"));
3480
3481 if ( strSessionName.isEmpty()
3482 && idSession == UINT32_MAX)
3483 return errorSyntax(GuestCtrl::tr("No session ID specified!"));
3484
3485 if ( strSessionName.isNotEmpty()
3486 && idSession != UINT32_MAX)
3487 return errorSyntax(GuestCtrl::tr("Either session ID or name (pattern) must be specified"));
3488
3489 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3490 if (rcExit != RTEXITCODE_SUCCESS)
3491 return rcExit;
3492
3493 HRESULT hrc = S_OK;
3494
3495 ComPtr<IGuestSession> pSession;
3496 ComPtr<IGuestProcess> pProcess;
3497 do
3498 {
3499 uint32_t uProcsTerminated = 0;
3500
3501 SafeIfaceArray <IGuestSession> collSessions;
3502 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3503 size_t cSessions = collSessions.size();
3504
3505 uint32_t cSessionsHandled = 0;
3506 for (size_t i = 0; i < cSessions; i++)
3507 {
3508 pSession = collSessions[i];
3509 Assert(!pSession.isNull());
3510
3511 ULONG uID; /* Session ID */
3512 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3513 Bstr strName;
3514 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3515 Utf8Str strNameUtf8(strName); /* Session name */
3516
3517 bool fSessionFound;
3518 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3519 fSessionFound = uID == idSession;
3520 else /* ... or by naming pattern. */
3521 fSessionFound = RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str());
3522 if (fSessionFound)
3523 {
3524 AssertStmt(!pSession.isNull(), break);
3525 cSessionsHandled++;
3526
3527 SafeIfaceArray <IGuestProcess> collProcs;
3528 CHECK_ERROR_BREAK(pSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcs)));
3529
3530 size_t cProcs = collProcs.size();
3531 for (size_t p = 0; p < cProcs; p++)
3532 {
3533 pProcess = collProcs[p];
3534 Assert(!pProcess.isNull());
3535
3536 ULONG uPID; /* Process ID */
3537 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
3538
3539 bool fProcFound = false;
3540 for (size_t a = 0; a < vecPID.size(); a++) /* Slow, but works. */
3541 {
3542 fProcFound = vecPID[a] == uPID;
3543 if (fProcFound)
3544 break;
3545 }
3546
3547 if (fProcFound)
3548 {
3549 if (pCtx->cVerbose)
3550 RTPrintf(GuestCtrl::tr("Terminating process (PID %RU32) (session ID %RU32) ...\n"),
3551 uPID, uID);
3552 CHECK_ERROR_BREAK(pProcess, Terminate());
3553 uProcsTerminated++;
3554 }
3555 else
3556 {
3557 if (idSession != UINT32_MAX)
3558 RTPrintf(GuestCtrl::tr("No matching process(es) for session ID %RU32 found\n"),
3559 idSession);
3560 }
3561
3562 pProcess.setNull();
3563 }
3564
3565 pSession.setNull();
3566 }
3567 }
3568
3569 if (!cSessionsHandled)
3570 RTPrintf(GuestCtrl::tr("No matching session(s) found\n"));
3571
3572 if (uProcsTerminated)
3573 RTPrintf(GuestCtrl::tr("%RU32 process(es) terminated\n", "", uProcsTerminated), uProcsTerminated);
3574
3575 } while (0);
3576
3577 pProcess.setNull();
3578 pSession.setNull();
3579
3580 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3581}
3582
3583
3584static DECLCALLBACK(RTEXITCODE) gctlHandleCloseSession(PGCTLCMDCTX pCtx, int argc, char **argv)
3585{
3586 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3587
3588 enum GETOPTDEF_SESSIONCLOSE
3589 {
3590 GETOPTDEF_SESSIONCLOSE_ALL = 2000
3591 };
3592 static const RTGETOPTDEF s_aOptions[] =
3593 {
3594 GCTLCMD_COMMON_OPTION_DEFS()
3595 { "--all", GETOPTDEF_SESSIONCLOSE_ALL, RTGETOPT_REQ_NOTHING },
3596 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3597 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3598 };
3599
3600 int ch;
3601 RTGETOPTUNION ValueUnion;
3602 RTGETOPTSTATE GetState;
3603 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3604
3605 ULONG idSession = UINT32_MAX;
3606 Utf8Str strSessionName;
3607
3608 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3609 {
3610 /* For options that require an argument, ValueUnion has received the value. */
3611 switch (ch)
3612 {
3613 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3614
3615 case 'n': /* Session name pattern */
3616 strSessionName = ValueUnion.psz;
3617 break;
3618
3619 case 'i': /* Session ID */
3620 idSession = ValueUnion.u32;
3621 break;
3622
3623 case GETOPTDEF_SESSIONCLOSE_ALL:
3624 strSessionName = "*";
3625 break;
3626
3627 case VINF_GETOPT_NOT_OPTION:
3628 /** @todo Supply a CSV list of IDs or patterns to close?
3629 * break; */
3630 default:
3631 return errorGetOpt(ch, &ValueUnion);
3632 }
3633 }
3634
3635 if ( strSessionName.isEmpty()
3636 && idSession == UINT32_MAX)
3637 return errorSyntax(GuestCtrl::tr("No session ID specified!"));
3638
3639 if ( !strSessionName.isEmpty()
3640 && idSession != UINT32_MAX)
3641 return errorSyntax(GuestCtrl::tr("Either session ID or name (pattern) must be specified"));
3642
3643 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3644 if (rcExit != RTEXITCODE_SUCCESS)
3645 return rcExit;
3646
3647 HRESULT hrc = S_OK;
3648
3649 do
3650 {
3651 size_t cSessionsHandled = 0;
3652
3653 SafeIfaceArray <IGuestSession> collSessions;
3654 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3655 size_t cSessions = collSessions.size();
3656
3657 for (size_t i = 0; i < cSessions; i++)
3658 {
3659 ComPtr<IGuestSession> pSession = collSessions[i];
3660 Assert(!pSession.isNull());
3661
3662 ULONG uID; /* Session ID */
3663 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3664 Bstr strName;
3665 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3666 Utf8Str strNameUtf8(strName); /* Session name */
3667
3668 bool fSessionFound;
3669 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3670 fSessionFound = uID == idSession;
3671 else /* ... or by naming pattern. */
3672 fSessionFound = RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str());
3673 if (fSessionFound)
3674 {
3675 cSessionsHandled++;
3676
3677 Assert(!pSession.isNull());
3678 if (pCtx->cVerbose)
3679 RTPrintf(GuestCtrl::tr("Closing guest session ID=#%RU32 \"%s\" ...\n"),
3680 uID, strNameUtf8.c_str());
3681 CHECK_ERROR_BREAK(pSession, Close());
3682 if (pCtx->cVerbose)
3683 RTPrintf(GuestCtrl::tr("Guest session successfully closed\n"));
3684
3685 pSession.setNull();
3686 }
3687 }
3688
3689 if (!cSessionsHandled)
3690 {
3691 RTPrintf(GuestCtrl::tr("No guest session(s) found\n"));
3692 hrc = E_ABORT; /* To set exit code accordingly. */
3693 }
3694
3695 } while (0);
3696
3697 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3698}
3699
3700
3701static DECLCALLBACK(RTEXITCODE) gctlHandleWatch(PGCTLCMDCTX pCtx, int argc, char **argv)
3702{
3703 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3704
3705 /*
3706 * Parse arguments.
3707 */
3708 static const RTGETOPTDEF s_aOptions[] =
3709 {
3710 GCTLCMD_COMMON_OPTION_DEFS()
3711 { "--timeout", 't', RTGETOPT_REQ_UINT32 }
3712 };
3713
3714 uint32_t cMsTimeout = RT_INDEFINITE_WAIT;
3715
3716 int ch;
3717 RTGETOPTUNION ValueUnion;
3718 RTGETOPTSTATE GetState;
3719 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3720
3721 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3722 {
3723 /* For options that require an argument, ValueUnion has received the value. */
3724 switch (ch)
3725 {
3726 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3727
3728 case 't': /* Timeout */
3729 cMsTimeout = ValueUnion.u32;
3730 break;
3731
3732 case VINF_GETOPT_NOT_OPTION:
3733 default:
3734 return errorGetOpt(ch, &ValueUnion);
3735 }
3736 }
3737
3738 /** @todo Specify categories to watch for. */
3739
3740 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3741 if (rcExit != RTEXITCODE_SUCCESS)
3742 return rcExit;
3743
3744 HRESULT hrc;
3745
3746 try
3747 {
3748 ComObjPtr<GuestEventListenerImpl> pGuestListener;
3749 do
3750 {
3751 /* Listener creation. */
3752 pGuestListener.createObject();
3753 pGuestListener->init(new GuestEventListener());
3754
3755 /* Register for IGuest events. */
3756 ComPtr<IEventSource> es;
3757 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
3758 com::SafeArray<VBoxEventType_T> eventTypes;
3759 eventTypes.push_back(VBoxEventType_OnGuestSessionRegistered);
3760 /** @todo Also register for VBoxEventType_OnGuestUserStateChanged on demand? */
3761 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
3762 true /* Active listener */));
3763 /* Note: All other guest control events have to be registered
3764 * as their corresponding objects appear. */
3765
3766 } while (0);
3767
3768 if (pCtx->cVerbose)
3769 RTPrintf(GuestCtrl::tr("Waiting for events ...\n"));
3770
3771 RTMSINTERVAL tsStart = RTTimeMilliTS();
3772 while (RTTimeMilliTS() - tsStart < cMsTimeout)
3773 {
3774 /* Wait for the global signal semaphore getting signalled. */
3775 int vrc = RTSemEventWait(g_SemEventGuestCtrlCanceled, 100 /* ms */);
3776 if (RT_FAILURE(vrc))
3777 {
3778 if (vrc != VERR_TIMEOUT)
3779 {
3780 RTPrintf(GuestCtrl::tr("Waiting failed with %Rrc\n"), vrc);
3781 break;
3782 }
3783 }
3784 else
3785 break;
3786
3787 /* We need to process the event queue, otherwise our registered listeners won't get any events. */
3788 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
3789 }
3790
3791 if (!pGuestListener.isNull())
3792 {
3793 /* Guest callback unregistration. */
3794 ComPtr<IEventSource> pES;
3795 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
3796 if (!pES.isNull())
3797 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
3798 pGuestListener.setNull();
3799 }
3800 }
3801 catch (std::bad_alloc &)
3802 {
3803 hrc = E_OUTOFMEMORY;
3804 }
3805
3806 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3807}
3808
3809/**
3810 * Access the guest control store.
3811 *
3812 * @returns program exit code.
3813 * @note see the command line API description for parameters
3814 */
3815RTEXITCODE handleGuestControl(HandlerArg *pArg)
3816{
3817 AssertPtr(pArg);
3818
3819 /*
3820 * Command definitions.
3821 */
3822 static const GCTLCMDDEF s_aCmdDefs[] =
3823 {
3824 { "run", gctlHandleRun, HELP_SCOPE_GUESTCONTROL_RUN, 0 },
3825 { "start", gctlHandleStart, HELP_SCOPE_GUESTCONTROL_START, 0 },
3826 { "copyfrom", gctlHandleCopyFrom, HELP_SCOPE_GUESTCONTROL_COPYFROM, 0 },
3827 { "copyto", gctlHandleCopyTo, HELP_SCOPE_GUESTCONTROL_COPYTO, 0 },
3828
3829 { "mkdir", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3830 { "md", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3831 { "createdirectory", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3832 { "createdir", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3833
3834 { "rmdir", gctlHandleRmDir, HELP_SCOPE_GUESTCONTROL_RMDIR, 0 },
3835 { "removedir", gctlHandleRmDir, HELP_SCOPE_GUESTCONTROL_RMDIR, 0 },
3836 { "removedirectory", gctlHandleRmDir, HELP_SCOPE_GUESTCONTROL_RMDIR, 0 },
3837
3838 { "rm", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3839 { "removefile", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3840 { "erase", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3841 { "del", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3842 { "delete", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3843
3844 { "mv", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3845 { "move", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3846 { "ren", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3847 { "rename", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3848
3849 { "mktemp", gctlHandleMkTemp, HELP_SCOPE_GUESTCONTROL_MKTEMP, 0 },
3850 { "createtemp", gctlHandleMkTemp, HELP_SCOPE_GUESTCONTROL_MKTEMP, 0 },
3851 { "createtemporary", gctlHandleMkTemp, HELP_SCOPE_GUESTCONTROL_MKTEMP, 0 },
3852
3853 { "mount", gctlHandleMount, HELP_SCOPE_GUESTCONTROL_MOUNT, 0 },
3854
3855 { "df", gctlHandleFsInfo, HELP_SCOPE_GUESTCONTROL_FSINFO, 0 },
3856 { "fsinfo", gctlHandleFsInfo, HELP_SCOPE_GUESTCONTROL_FSINFO, 0 },
3857
3858 { "stat", gctlHandleStat, HELP_SCOPE_GUESTCONTROL_STAT, 0 },
3859
3860 { "closeprocess", gctlHandleCloseProcess, HELP_SCOPE_GUESTCONTROL_CLOSEPROCESS, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER },
3861 { "closesession", gctlHandleCloseSession, HELP_SCOPE_GUESTCONTROL_CLOSESESSION, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER },
3862 { "list", gctlHandleList, HELP_SCOPE_GUESTCONTROL_LIST, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER },
3863 { "watch", gctlHandleWatch, HELP_SCOPE_GUESTCONTROL_WATCH, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3864
3865 {"updateguestadditions",gctlHandleUpdateAdditions, HELP_SCOPE_GUESTCONTROL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3866 { "updateadditions", gctlHandleUpdateAdditions, HELP_SCOPE_GUESTCONTROL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3867 { "updatega", gctlHandleUpdateAdditions, HELP_SCOPE_GUESTCONTROL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3868
3869 { "waitrunlevel", gctlHandleWaitRunLevel, HELP_SCOPE_GUESTCONTROL_WAITRUNLEVEL, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3870 { "waitforrunlevel", gctlHandleWaitRunLevel, HELP_SCOPE_GUESTCONTROL_WAITRUNLEVEL, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3871 };
3872
3873 /*
3874 * VBoxManage guestcontrol [common-options] <VM> [common-options] <sub-command> ...
3875 *
3876 * Parse common options and VM name until we find a sub-command. Allowing
3877 * the user to put the user and password related options before the
3878 * sub-command makes it easier to edit the command line when doing several
3879 * operations with the same guest user account. (Accidentally, it also
3880 * makes the syntax diagram shorter and easier to read.)
3881 */
3882 GCTLCMDCTX CmdCtx;
3883 RTEXITCODE rcExit = gctrCmdCtxInit(&CmdCtx, pArg);
3884 if (rcExit == RTEXITCODE_SUCCESS)
3885 {
3886 static const RTGETOPTDEF s_CommonOptions[] = { GCTLCMD_COMMON_OPTION_DEFS() };
3887
3888 int ch;
3889 RTGETOPTUNION ValueUnion;
3890 RTGETOPTSTATE GetState;
3891 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_CommonOptions, RT_ELEMENTS(s_CommonOptions), 0, 0 /* No sorting! */);
3892
3893 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3894 {
3895 switch (ch)
3896 {
3897 GCTLCMD_COMMON_OPTION_CASES(&CmdCtx, ch, &ValueUnion);
3898
3899 case VINF_GETOPT_NOT_OPTION:
3900 /* First comes the VM name or UUID. */
3901 if (!CmdCtx.pszVmNameOrUuid)
3902 CmdCtx.pszVmNameOrUuid = ValueUnion.psz;
3903 /*
3904 * The sub-command is next. Look it up and invoke it.
3905 * Note! Currently no warnings about user/password options (like we'll do later on)
3906 * for GCTLCMDCTX_F_SESSION_ANONYMOUS commands. No reason to be too pedantic.
3907 */
3908 else
3909 {
3910 const char *pszCmd = ValueUnion.psz;
3911 uint32_t iCmd;
3912 for (iCmd = 0; iCmd < RT_ELEMENTS(s_aCmdDefs); iCmd++)
3913 if (strcmp(s_aCmdDefs[iCmd].pszName, pszCmd) == 0)
3914 {
3915 CmdCtx.pCmdDef = &s_aCmdDefs[iCmd];
3916
3917 setCurrentSubcommand(s_aCmdDefs[iCmd].fSubcommandScope);
3918 rcExit = s_aCmdDefs[iCmd].pfnHandler(&CmdCtx, pArg->argc - GetState.iNext + 1,
3919 &pArg->argv[GetState.iNext - 1]);
3920
3921 gctlCtxTerm(&CmdCtx);
3922 return rcExit;
3923 }
3924 return errorSyntax(GuestCtrl::tr("Unknown sub-command: '%s'"), pszCmd);
3925 }
3926 break;
3927
3928 default:
3929 return errorGetOpt(ch, &ValueUnion);
3930 }
3931 }
3932 if (CmdCtx.pszVmNameOrUuid)
3933 rcExit = errorSyntax(GuestCtrl::tr("Missing sub-command"));
3934 else
3935 rcExit = errorSyntax(GuestCtrl::tr("Missing VM name and sub-command"));
3936 }
3937 return rcExit;
3938}
Note: See TracBrowser for help on using the repository browser.

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