VirtualBox

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

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

scm copyright and license note update

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 141.7 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 96407 2022-08-22 17:43:14Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010-2022 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * SPDX-License-Identifier: GPL-3.0-only
26 */
27
28
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 rc = VINF_SUCCESS;
282#ifdef RT_OS_WINDOWS
283 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)gctlSignalHandler, TRUE /* Add handler */))
284 {
285 rc = RTErrConvertFromWin32(GetLastError());
286 RTMsgError(GuestCtrl::tr("Unable to install console control handler, rc=%Rrc\n"), rc);
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(rc))
297 rc = RTSemEventCreate(&g_SemEventGuestCtrlCanceled);
298
299 return rc;
300}
301
302
303/**
304 * Uninstalls a previously installed signal handler.
305 */
306static int gctlSignalHandlerUninstall(void)
307{
308 int rc = VINF_SUCCESS;
309#ifdef RT_OS_WINDOWS
310 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
311 {
312 rc = RTErrConvertFromWin32(GetLastError());
313 RTMsgError(GuestCtrl::tr("Unable to uninstall console control handler, rc=%Rrc\n"), rc);
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 rc;
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 */
372const 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 */
457const 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 rc = RTProcQueryUsername(RTProcSelf(), szUser, sizeof(szUser), NULL);
575 if ( RT_SUCCESS(rc)
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 rc = gctlSignalHandlerInstall();
856 pCtx->fInstalledSignalHandler = RT_SUCCESS(rc);
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 CHECK_ERROR(pCtx->pGuestSession, Close());
904 }
905 else if ( pCtx->fDetachGuestSession
906 && pCtx->cVerbose)
907 RTPrintf(GuestCtrl::tr("Guest session detached\n"));
908
909 pCtx->pGuestSession.setNull();
910 }
911
912 /*
913 * Close the VM session.
914 */
915 if (pCtx->fLockedVmSession)
916 {
917 Assert(pCtx->pArg->session.isNotNull());
918 CHECK_ERROR(pCtx->pArg->session, UnlockMachine());
919 pCtx->fLockedVmSession = false;
920 }
921}
922
923
924
925
926
927/*
928 *
929 *
930 * Guest Control Command Handling.
931 * Guest Control Command Handling.
932 * Guest Control Command Handling.
933 * Guest Control Command Handling.
934 * Guest Control Command Handling.
935 *
936 *
937 */
938
939
940/** @name EXITCODEEXEC_XXX - Special run exit codes.
941 *
942 * Special exit codes for returning errors/information of a started guest
943 * process to the command line VBoxManage was started from. Useful for e.g.
944 * scripting.
945 *
946 * ASSUMING that all platforms have at least 7-bits for the exit code we can do
947 * the following mapping:
948 * - Guest exit code 0 is mapped to 0 on the host.
949 * - Guest exit codes 1 thru 93 (0x5d) are displaced by 32, so that 1
950 * becomes 33 (0x21) on the host and 93 becomes 125 (0x7d) on the host.
951 * - Guest exit codes 94 (0x5e) and above are mapped to 126 (0x5e).
952 *
953 * We ASSUME that all VBoxManage status codes are in the range 0 thru 32.
954 *
955 * @note These are frozen as of 4.1.0.
956 * @note The guest exit code mappings was introduced with 5.0 and the 'run'
957 * command, they are/was not supported by 'exec'.
958 * @sa gctlRunCalculateExitCode
959 */
960/** Process exited normally but with an exit code <> 0. */
961#define EXITCODEEXEC_CODE ((RTEXITCODE)16)
962#define EXITCODEEXEC_FAILED ((RTEXITCODE)17)
963#define EXITCODEEXEC_TERM_SIGNAL ((RTEXITCODE)18)
964#define EXITCODEEXEC_TERM_ABEND ((RTEXITCODE)19)
965#define EXITCODEEXEC_TIMEOUT ((RTEXITCODE)20)
966#define EXITCODEEXEC_DOWN ((RTEXITCODE)21)
967/** Execution was interrupt by user (ctrl-c). */
968#define EXITCODEEXEC_CANCELED ((RTEXITCODE)22)
969/** The first mapped guest (non-zero) exit code. */
970#define EXITCODEEXEC_MAPPED_FIRST 33
971/** The last mapped guest (non-zero) exit code value (inclusive). */
972#define EXITCODEEXEC_MAPPED_LAST 125
973/** The number of exit codes from EXITCODEEXEC_MAPPED_FIRST to
974 * EXITCODEEXEC_MAPPED_LAST. This is also the highest guest exit code number
975 * we're able to map. */
976#define EXITCODEEXEC_MAPPED_RANGE (93)
977/** The guest exit code displacement value. */
978#define EXITCODEEXEC_MAPPED_DISPLACEMENT 32
979/** The guest exit code was too big to be mapped. */
980#define EXITCODEEXEC_MAPPED_BIG ((RTEXITCODE)126)
981/** @} */
982
983/**
984 * Calculates the exit code of VBoxManage.
985 *
986 * @returns The exit code to return.
987 * @param enmStatus The guest process status.
988 * @param uExitCode The associated guest process exit code (where
989 * applicable).
990 * @param fReturnExitCodes Set if we're to use the 32-126 range for guest
991 * exit codes.
992 */
993static RTEXITCODE gctlRunCalculateExitCode(ProcessStatus_T enmStatus, ULONG uExitCode, bool fReturnExitCodes)
994{
995 switch (enmStatus)
996 {
997 case ProcessStatus_TerminatedNormally:
998 if (uExitCode == 0)
999 return RTEXITCODE_SUCCESS;
1000 if (!fReturnExitCodes)
1001 return EXITCODEEXEC_CODE;
1002 if (uExitCode <= EXITCODEEXEC_MAPPED_RANGE)
1003 return (RTEXITCODE) (uExitCode + EXITCODEEXEC_MAPPED_DISPLACEMENT);
1004 return EXITCODEEXEC_MAPPED_BIG;
1005
1006 case ProcessStatus_TerminatedAbnormally:
1007 return EXITCODEEXEC_TERM_ABEND;
1008 case ProcessStatus_TerminatedSignal:
1009 return EXITCODEEXEC_TERM_SIGNAL;
1010
1011#if 0 /* see caller! */
1012 case ProcessStatus_TimedOutKilled:
1013 return EXITCODEEXEC_TIMEOUT;
1014 case ProcessStatus_Down:
1015 return EXITCODEEXEC_DOWN; /* Service/OS is stopping, process was killed. */
1016 case ProcessStatus_Error:
1017 return EXITCODEEXEC_FAILED;
1018
1019 /* The following is probably for detached? */
1020 case ProcessStatus_Starting:
1021 return RTEXITCODE_SUCCESS;
1022 case ProcessStatus_Started:
1023 return RTEXITCODE_SUCCESS;
1024 case ProcessStatus_Paused:
1025 return RTEXITCODE_SUCCESS;
1026 case ProcessStatus_Terminating:
1027 return RTEXITCODE_SUCCESS; /** @todo ???? */
1028#endif
1029
1030 default:
1031 AssertMsgFailed(("Unknown exit status (%u/%u) from guest process returned!\n", enmStatus, uExitCode));
1032 return RTEXITCODE_FAILURE;
1033 }
1034}
1035
1036
1037/**
1038 * Pumps guest output to the host.
1039 *
1040 * @return IPRT status code.
1041 * @param pProcess Pointer to appropriate process object.
1042 * @param hVfsIosDst Where to write the data. Can be the bit bucket or a (valid [std]) handle.
1043 * @param uHandle Handle where to read the data from.
1044 * @param cMsTimeout Timeout (in ms) to wait for the operation to
1045 * complete.
1046 */
1047static int gctlRunPumpOutput(IProcess *pProcess, RTVFSIOSTREAM hVfsIosDst, ULONG uHandle, RTMSINTERVAL cMsTimeout)
1048{
1049 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1050 Assert(hVfsIosDst != NIL_RTVFSIOSTREAM);
1051
1052 int vrc;
1053
1054 SafeArray<BYTE> aOutputData;
1055 HRESULT hrc = pProcess->Read(uHandle, _64K, RT_MAX(cMsTimeout, 1), ComSafeArrayAsOutParam(aOutputData));
1056 if (SUCCEEDED(hrc))
1057 {
1058 size_t cbOutputData = aOutputData.size();
1059 if (cbOutputData == 0)
1060 vrc = VINF_SUCCESS;
1061 else
1062 {
1063 BYTE const *pbBuf = aOutputData.raw();
1064 AssertPtr(pbBuf);
1065
1066 vrc = RTVfsIoStrmWrite(hVfsIosDst, pbBuf, cbOutputData, true /*fBlocking*/, NULL);
1067 if (RT_FAILURE(vrc))
1068 RTMsgError(GuestCtrl::tr("Unable to write output, rc=%Rrc\n"), vrc);
1069 }
1070 }
1071 else
1072 vrc = gctlPrintError(pProcess, COM_IIDOF(IProcess));
1073 return vrc;
1074}
1075
1076
1077/**
1078 * Configures a host handle for pumping guest bits.
1079 *
1080 * @returns true if enabled and we successfully configured it.
1081 * @param fEnabled Whether pumping this pipe is configured to std handles,
1082 * or going to the bit bucket instead.
1083 * @param enmHandle The IPRT standard handle designation.
1084 * @param pszName The name for user messages.
1085 * @param enmTransformation The transformation to apply.
1086 * @param phVfsIos Where to return the resulting I/O stream handle.
1087 */
1088static bool gctlRunSetupHandle(bool fEnabled, RTHANDLESTD enmHandle, const char *pszName,
1089 kStreamTransform enmTransformation, PRTVFSIOSTREAM phVfsIos)
1090{
1091 if (fEnabled)
1092 {
1093 int vrc = RTVfsIoStrmFromStdHandle(enmHandle, 0, true /*fLeaveOpen*/, phVfsIos);
1094 if (RT_SUCCESS(vrc))
1095 {
1096 if (enmTransformation != kStreamTransform_None)
1097 {
1098 RTMsgWarning(GuestCtrl::tr("Unsupported %s line ending conversion"), pszName);
1099 /** @todo Implement dos2unix and unix2dos stream filters. */
1100 }
1101 return true;
1102 }
1103 RTMsgWarning(GuestCtrl::tr("Error getting %s handle: %Rrc"), pszName, vrc);
1104 }
1105 else /* If disabled, all goes to / gets fed to/from the bit bucket. */
1106 {
1107 RTFILE hFile;
1108 int vrc = RTFileOpenBitBucket(&hFile, enmHandle == RTHANDLESTD_INPUT ? RTFILE_O_READ : RTFILE_O_WRITE);
1109 if (RT_SUCCESS(vrc))
1110 {
1111 vrc = RTVfsIoStrmFromRTFile(hFile, 0 /* fOpen */, false /* fLeaveOpen */, phVfsIos);
1112 if (RT_SUCCESS(vrc))
1113 return true;
1114 }
1115 }
1116
1117 return false;
1118}
1119
1120
1121/**
1122 * Returns the remaining time (in ms) based on the start time and a set
1123 * timeout value. Returns RT_INDEFINITE_WAIT if no timeout was specified.
1124 *
1125 * @return RTMSINTERVAL Time left (in ms).
1126 * @param u64StartMs Start time (in ms).
1127 * @param cMsTimeout Timeout value (in ms).
1128 */
1129static RTMSINTERVAL gctlRunGetRemainingTime(uint64_t u64StartMs, RTMSINTERVAL cMsTimeout)
1130{
1131 if (!cMsTimeout || cMsTimeout == RT_INDEFINITE_WAIT) /* If no timeout specified, wait forever. */
1132 return RT_INDEFINITE_WAIT;
1133
1134 uint64_t u64ElapsedMs = RTTimeMilliTS() - u64StartMs;
1135 if (u64ElapsedMs >= cMsTimeout)
1136 return 0;
1137
1138 return cMsTimeout - (RTMSINTERVAL)u64ElapsedMs;
1139}
1140
1141/**
1142 * Common handler for the 'run' and 'start' commands.
1143 *
1144 * @returns Command exit code.
1145 * @param pCtx Guest session context.
1146 * @param argc The argument count.
1147 * @param argv The argument vector for this command.
1148 * @param fRunCmd Set if it's 'run' clear if 'start'.
1149 */
1150static RTEXITCODE gctlHandleRunCommon(PGCTLCMDCTX pCtx, int argc, char **argv, bool fRunCmd)
1151{
1152 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1153
1154 /*
1155 * Parse arguments.
1156 */
1157 enum kGstCtrlRunOpt
1158 {
1159 kGstCtrlRunOpt_IgnoreOrphanedProcesses = 1000,
1160 kGstCtrlRunOpt_NoProfile, /** @todo Deprecated and will be removed soon; use kGstCtrlRunOpt_Profile instead, if needed. */
1161 kGstCtrlRunOpt_Profile,
1162 kGstCtrlRunOpt_Dos2Unix,
1163 kGstCtrlRunOpt_Unix2Dos,
1164 kGstCtrlRunOpt_WaitForStdOut,
1165 kGstCtrlRunOpt_NoWaitForStdOut,
1166 kGstCtrlRunOpt_WaitForStdErr,
1167 kGstCtrlRunOpt_NoWaitForStdErr
1168 };
1169 static const RTGETOPTDEF s_aOptions[] =
1170 {
1171 GCTLCMD_COMMON_OPTION_DEFS()
1172 { "--putenv", 'E', RTGETOPT_REQ_STRING },
1173 { "--exe", 'e', RTGETOPT_REQ_STRING },
1174 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
1175 { "--unquoted-args", 'u', RTGETOPT_REQ_NOTHING },
1176 { "--ignore-operhaned-processes", kGstCtrlRunOpt_IgnoreOrphanedProcesses, RTGETOPT_REQ_NOTHING },
1177 { "--no-profile", kGstCtrlRunOpt_NoProfile, RTGETOPT_REQ_NOTHING }, /** @todo Deprecated. */
1178 { "--profile", kGstCtrlRunOpt_Profile, RTGETOPT_REQ_NOTHING },
1179 /* run only: 6 - options */
1180 { "--dos2unix", kGstCtrlRunOpt_Dos2Unix, RTGETOPT_REQ_NOTHING },
1181 { "--unix2dos", kGstCtrlRunOpt_Unix2Dos, RTGETOPT_REQ_NOTHING },
1182 { "--no-wait-stdout", kGstCtrlRunOpt_NoWaitForStdOut, RTGETOPT_REQ_NOTHING },
1183 { "--wait-stdout", kGstCtrlRunOpt_WaitForStdOut, RTGETOPT_REQ_NOTHING },
1184 { "--no-wait-stderr", kGstCtrlRunOpt_NoWaitForStdErr, RTGETOPT_REQ_NOTHING },
1185 { "--wait-stderr", kGstCtrlRunOpt_WaitForStdErr, RTGETOPT_REQ_NOTHING },
1186 };
1187
1188 /** @todo stdin handling. */
1189
1190 int ch;
1191 RTGETOPTUNION ValueUnion;
1192 RTGETOPTSTATE GetState;
1193 int vrc = RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions) - (fRunCmd ? 0 : 6),
1194 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1195 AssertRC(vrc);
1196
1197 com::SafeArray<ProcessCreateFlag_T> aCreateFlags;
1198 com::SafeArray<ProcessWaitForFlag_T> aWaitFlags;
1199 com::SafeArray<IN_BSTR> aArgs;
1200 com::SafeArray<IN_BSTR> aEnv;
1201 const char * pszImage = NULL;
1202 bool fWaitForStdOut = fRunCmd;
1203 bool fWaitForStdErr = fRunCmd;
1204 RTVFSIOSTREAM hVfsStdOut = NIL_RTVFSIOSTREAM;
1205 RTVFSIOSTREAM hVfsStdErr = NIL_RTVFSIOSTREAM;
1206 enum kStreamTransform enmStdOutTransform = kStreamTransform_None;
1207 enum kStreamTransform enmStdErrTransform = kStreamTransform_None;
1208 RTMSINTERVAL cMsTimeout = 0;
1209
1210 try
1211 {
1212 /* Wait for process start in any case. This is useful for scripting VBoxManage
1213 * when relying on its overall exit code. */
1214 aWaitFlags.push_back(ProcessWaitForFlag_Start);
1215
1216 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1217 {
1218 /* For options that require an argument, ValueUnion has received the value. */
1219 switch (ch)
1220 {
1221 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1222
1223 case 'E':
1224 if ( ValueUnion.psz[0] == '\0'
1225 || ValueUnion.psz[0] == '=')
1226 return errorSyntax(GuestCtrl::tr("Invalid argument variable[=value]: '%s'"), ValueUnion.psz);
1227 aEnv.push_back(Bstr(ValueUnion.psz).raw());
1228 break;
1229
1230 case kGstCtrlRunOpt_IgnoreOrphanedProcesses:
1231 aCreateFlags.push_back(ProcessCreateFlag_IgnoreOrphanedProcesses);
1232 break;
1233
1234 case kGstCtrlRunOpt_NoProfile:
1235 /** @todo Deprecated, will be removed. */
1236 RTPrintf(GuestCtrl::tr("Warning: Deprecated option \"--no-profile\" specified\n"));
1237 break;
1238
1239 case kGstCtrlRunOpt_Profile:
1240 aCreateFlags.push_back(ProcessCreateFlag_Profile);
1241 break;
1242
1243 case 'e':
1244 pszImage = ValueUnion.psz;
1245 break;
1246
1247 case 'u':
1248 aCreateFlags.push_back(ProcessCreateFlag_UnquotedArguments);
1249 break;
1250
1251 /** @todo Add a hidden flag. */
1252
1253 case 't': /* Timeout */
1254 cMsTimeout = ValueUnion.u32;
1255 break;
1256
1257 /* run only options: */
1258 case kGstCtrlRunOpt_Dos2Unix:
1259 Assert(fRunCmd);
1260 enmStdErrTransform = enmStdOutTransform = kStreamTransform_Dos2Unix;
1261 break;
1262 case kGstCtrlRunOpt_Unix2Dos:
1263 Assert(fRunCmd);
1264 enmStdErrTransform = enmStdOutTransform = kStreamTransform_Unix2Dos;
1265 break;
1266
1267 case kGstCtrlRunOpt_WaitForStdOut:
1268 Assert(fRunCmd);
1269 fWaitForStdOut = true;
1270 break;
1271 case kGstCtrlRunOpt_NoWaitForStdOut:
1272 Assert(fRunCmd);
1273 fWaitForStdOut = false;
1274 break;
1275
1276 case kGstCtrlRunOpt_WaitForStdErr:
1277 Assert(fRunCmd);
1278 fWaitForStdErr = true;
1279 break;
1280 case kGstCtrlRunOpt_NoWaitForStdErr:
1281 Assert(fRunCmd);
1282 fWaitForStdErr = false;
1283 break;
1284
1285 case VINF_GETOPT_NOT_OPTION:
1286 aArgs.push_back(Bstr(ValueUnion.psz).raw());
1287 if (!pszImage)
1288 {
1289 Assert(aArgs.size() == 1);
1290 pszImage = ValueUnion.psz;
1291 }
1292 break;
1293
1294 default:
1295 return errorGetOpt(ch, &ValueUnion);
1296
1297 } /* switch */
1298 } /* while RTGetOpt */
1299
1300 /* Must have something to execute. */
1301 if (!pszImage || !*pszImage)
1302 return errorSyntax(GuestCtrl::tr("No executable specified!"));
1303
1304 /*
1305 * Finalize process creation and wait flags and input/output streams.
1306 */
1307 if (!fRunCmd)
1308 {
1309 aCreateFlags.push_back(ProcessCreateFlag_WaitForProcessStartOnly);
1310 Assert(!fWaitForStdOut);
1311 Assert(!fWaitForStdErr);
1312 }
1313 else
1314 {
1315 aWaitFlags.push_back(ProcessWaitForFlag_Terminate);
1316 fWaitForStdOut = gctlRunSetupHandle(fWaitForStdOut, RTHANDLESTD_OUTPUT, "stdout", enmStdOutTransform, &hVfsStdOut);
1317 if (fWaitForStdOut)
1318 {
1319 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdOut);
1320 aWaitFlags.push_back(ProcessWaitForFlag_StdOut);
1321 }
1322 fWaitForStdErr = gctlRunSetupHandle(fWaitForStdErr, RTHANDLESTD_ERROR, "stderr", enmStdErrTransform, &hVfsStdErr);
1323 if (fWaitForStdErr)
1324 {
1325 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdErr);
1326 aWaitFlags.push_back(ProcessWaitForFlag_StdErr);
1327 }
1328 }
1329 }
1330 catch (std::bad_alloc &)
1331 {
1332 return RTMsgErrorExit(RTEXITCODE_FAILURE, "VERR_NO_MEMORY\n");
1333 }
1334
1335 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
1336 if (rcExit != RTEXITCODE_SUCCESS)
1337 return rcExit;
1338
1339 HRESULT hrc;
1340
1341 try
1342 {
1343 do
1344 {
1345 /* Get current time stamp to later calculate rest of timeout left. */
1346 uint64_t msStart = RTTimeMilliTS();
1347
1348 /*
1349 * Create the process.
1350 */
1351 if (pCtx->cVerbose)
1352 {
1353 if (cMsTimeout == 0)
1354 RTPrintf(GuestCtrl::tr("Starting guest process ...\n"));
1355 else
1356 RTPrintf(GuestCtrl::tr("Starting guest process (within %ums)\n"), cMsTimeout);
1357 }
1358 ComPtr<IGuestProcess> pProcess;
1359 CHECK_ERROR_BREAK(pCtx->pGuestSession, ProcessCreate(Bstr(pszImage).raw(),
1360 ComSafeArrayAsInParam(aArgs),
1361 ComSafeArrayAsInParam(aEnv),
1362 ComSafeArrayAsInParam(aCreateFlags),
1363 gctlRunGetRemainingTime(msStart, cMsTimeout),
1364 pProcess.asOutParam()));
1365
1366 /*
1367 * Explicitly wait for the guest process to be in a started state.
1368 */
1369 com::SafeArray<ProcessWaitForFlag_T> aWaitStartFlags;
1370 aWaitStartFlags.push_back(ProcessWaitForFlag_Start);
1371 ProcessWaitResult_T waitResult;
1372 CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitStartFlags),
1373 gctlRunGetRemainingTime(msStart, cMsTimeout), &waitResult));
1374
1375 ULONG uPID = 0;
1376 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
1377 if (fRunCmd && pCtx->cVerbose)
1378 RTPrintf(GuestCtrl::tr("Process '%s' (PID %RU32) started\n"), pszImage, uPID);
1379 else if (!fRunCmd && pCtx->cVerbose)
1380 {
1381 /* Just print plain PID to make it easier for scripts
1382 * invoking VBoxManage. */
1383 RTPrintf(GuestCtrl::tr("[%RU32 - Session %RU32]\n"), uPID, pCtx->uSessionID);
1384 }
1385
1386 /*
1387 * Wait for process to exit/start...
1388 */
1389 RTMSINTERVAL cMsTimeLeft = 1; /* Will be calculated. */
1390 bool fReadStdOut = false;
1391 bool fReadStdErr = false;
1392 bool fCompleted = false;
1393 bool fCompletedStartCmd = false;
1394
1395 vrc = VINF_SUCCESS;
1396 while ( !fCompleted
1397 && cMsTimeLeft > 0)
1398 {
1399 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1400 CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitFlags),
1401 RT_MIN(500 /*ms*/, RT_MAX(cMsTimeLeft, 1 /*ms*/)),
1402 &waitResult));
1403 if (pCtx->cVerbose)
1404 RTPrintf(GuestCtrl::tr("waitResult: %d\n"), waitResult);
1405 switch (waitResult)
1406 {
1407 case ProcessWaitResult_Start: /** @todo you always wait for 'start', */
1408 fCompletedStartCmd = fCompleted = !fRunCmd; /* Only wait for startup if the 'start' command. */
1409 if (!fCompleted && aWaitFlags[0] == ProcessWaitForFlag_Start)
1410 aWaitFlags[0] = ProcessWaitForFlag_Terminate;
1411 break;
1412 case ProcessWaitResult_StdOut:
1413 fReadStdOut = true;
1414 break;
1415 case ProcessWaitResult_StdErr:
1416 fReadStdErr = true;
1417 break;
1418 case ProcessWaitResult_Terminate:
1419 if (pCtx->cVerbose)
1420 RTPrintf(GuestCtrl::tr("Process terminated\n"));
1421 /* Process terminated, we're done. */
1422 fCompleted = true;
1423 break;
1424 case ProcessWaitResult_WaitFlagNotSupported:
1425 /* The guest does not support waiting for stdout/err, so
1426 * yield to reduce the CPU load due to busy waiting. */
1427 RTThreadYield();
1428 fReadStdOut = fReadStdErr = true;
1429 /* Note: In case the user specified explicitly not wanting to wait for stdout / stderr,
1430 * the configured VFS handle goes to / will be fed from the bit bucket. */
1431 break;
1432 case ProcessWaitResult_Timeout:
1433 {
1434 /** @todo It is really unclear whether we will get stuck with the timeout
1435 * result here if the guest side times out the process and fails to
1436 * kill the process... To be on the save side, double the IPC and
1437 * check the process status every time we time out. */
1438 ProcessStatus_T enmProcStatus;
1439 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&enmProcStatus));
1440 if ( enmProcStatus == ProcessStatus_TimedOutKilled
1441 || enmProcStatus == ProcessStatus_TimedOutAbnormally)
1442 fCompleted = true;
1443 fReadStdOut = fReadStdErr = true;
1444 break;
1445 }
1446 case ProcessWaitResult_Status:
1447 /* ignore. */
1448 break;
1449 case ProcessWaitResult_Error:
1450 /* waitFor is dead in the water, I think, so better leave the loop. */
1451 vrc = VERR_CALLBACK_RETURN;
1452 break;
1453
1454 case ProcessWaitResult_StdIn: AssertFailed(); /* did ask for this! */ break;
1455 case ProcessWaitResult_None: AssertFailed(); /* used. */ break;
1456 default: AssertFailed(); /* huh? */ break;
1457 }
1458
1459 if (g_fGuestCtrlCanceled)
1460 break;
1461
1462 /*
1463 * Pump output as needed.
1464 */
1465 if (fReadStdOut)
1466 {
1467 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1468 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdOut, 1 /* StdOut */, cMsTimeLeft);
1469 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1470 vrc = vrc2;
1471 fReadStdOut = false;
1472 }
1473 if (fReadStdErr)
1474 {
1475 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1476 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdErr, 2 /* StdErr */, cMsTimeLeft);
1477 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1478 vrc = vrc2;
1479 fReadStdErr = false;
1480 }
1481 if ( RT_FAILURE(vrc)
1482 || g_fGuestCtrlCanceled)
1483 break;
1484
1485 /*
1486 * Process events before looping.
1487 */
1488 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
1489 } /* while */
1490
1491 /*
1492 * Report status back to the user.
1493 */
1494 if (g_fGuestCtrlCanceled)
1495 {
1496 if (pCtx->cVerbose)
1497 RTPrintf(GuestCtrl::tr("Process execution aborted!\n"));
1498 rcExit = EXITCODEEXEC_CANCELED;
1499 }
1500 else if (fCompletedStartCmd)
1501 {
1502 if (pCtx->cVerbose)
1503 RTPrintf(GuestCtrl::tr("Process successfully started!\n"));
1504 rcExit = RTEXITCODE_SUCCESS;
1505 }
1506 else if (fCompleted)
1507 {
1508 ProcessStatus_T procStatus;
1509 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&procStatus));
1510 if ( procStatus == ProcessStatus_TerminatedNormally
1511 || procStatus == ProcessStatus_TerminatedAbnormally
1512 || procStatus == ProcessStatus_TerminatedSignal)
1513 {
1514 LONG lExitCode;
1515 CHECK_ERROR_BREAK(pProcess, COMGETTER(ExitCode)(&lExitCode));
1516 if (pCtx->cVerbose)
1517 RTPrintf(GuestCtrl::tr("Exit code=%u (Status=%u [%s])\n"),
1518 lExitCode, procStatus, gctlProcessStatusToText(procStatus));
1519
1520 rcExit = gctlRunCalculateExitCode(procStatus, lExitCode, true /*fReturnExitCodes*/);
1521 }
1522 else if ( procStatus == ProcessStatus_TimedOutKilled
1523 || procStatus == ProcessStatus_TimedOutAbnormally)
1524 {
1525 if (pCtx->cVerbose)
1526 RTPrintf(GuestCtrl::tr("Process timed out (guest side) and %s\n"),
1527 procStatus == ProcessStatus_TimedOutAbnormally
1528 ? GuestCtrl::tr("failed to terminate so far") : GuestCtrl::tr("was terminated"));
1529 rcExit = EXITCODEEXEC_TIMEOUT;
1530 }
1531 else
1532 {
1533 if (pCtx->cVerbose)
1534 RTPrintf(GuestCtrl::tr("Process now is in status [%s] (unexpected)\n"),
1535 gctlProcessStatusToText(procStatus));
1536 rcExit = RTEXITCODE_FAILURE;
1537 }
1538 }
1539 else if (RT_FAILURE_NP(vrc))
1540 {
1541 if (pCtx->cVerbose)
1542 RTPrintf(GuestCtrl::tr("Process monitor loop quit with vrc=%Rrc\n"), vrc);
1543 rcExit = RTEXITCODE_FAILURE;
1544 }
1545 else
1546 {
1547 if (pCtx->cVerbose)
1548 RTPrintf(GuestCtrl::tr("Process monitor loop timed out\n"));
1549 rcExit = EXITCODEEXEC_TIMEOUT;
1550 }
1551
1552 } while (0);
1553 }
1554 catch (std::bad_alloc &)
1555 {
1556 hrc = E_OUTOFMEMORY;
1557 }
1558
1559 /*
1560 * Decide what to do with the guest session.
1561 *
1562 * If it's the 'start' command where detach the guest process after
1563 * starting, don't close the guest session it is part of, except on
1564 * failure or ctrl-c.
1565 *
1566 * For the 'run' command the guest process quits with us.
1567 */
1568 if (!fRunCmd && SUCCEEDED(hrc) && !g_fGuestCtrlCanceled)
1569 pCtx->fDetachGuestSession = true;
1570
1571 /* Make sure we return failure on failure. */
1572 if (FAILED(hrc) && rcExit == RTEXITCODE_SUCCESS)
1573 rcExit = RTEXITCODE_FAILURE;
1574 return rcExit;
1575}
1576
1577
1578static DECLCALLBACK(RTEXITCODE) gctlHandleRun(PGCTLCMDCTX pCtx, int argc, char **argv)
1579{
1580 return gctlHandleRunCommon(pCtx, argc, argv, true /*fRunCmd*/);
1581}
1582
1583
1584static DECLCALLBACK(RTEXITCODE) gctlHandleStart(PGCTLCMDCTX pCtx, int argc, char **argv)
1585{
1586 return gctlHandleRunCommon(pCtx, argc, argv, false /*fRunCmd*/);
1587}
1588
1589
1590static RTEXITCODE gctlHandleCopy(PGCTLCMDCTX pCtx, int argc, char **argv, bool fHostToGuest)
1591{
1592 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1593
1594 /*
1595 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1596 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1597 * does in here.
1598 */
1599 static const RTGETOPTDEF s_aOptions[] =
1600 {
1601 GCTLCMD_COMMON_OPTION_DEFS()
1602 { "--follow", 'L', RTGETOPT_REQ_NOTHING }, /* Kept for backwards-compatibility (VBox < 7.0). */
1603 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
1604 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1605 { "--target-directory", 't', RTGETOPT_REQ_STRING }
1606 };
1607
1608 int ch;
1609 RTGETOPTUNION ValueUnion;
1610 RTGETOPTSTATE GetState;
1611 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1612
1613 bool fDstMustBeDir = false;
1614 const char *pszDst = NULL;
1615 bool fFollow = false;
1616 bool fRecursive = false;
1617
1618 int vrc = VINF_SUCCESS;
1619 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
1620 && ch != VINF_GETOPT_NOT_OPTION)
1621 {
1622 /* For options that require an argument, ValueUnion has received the value. */
1623 switch (ch)
1624 {
1625 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1626
1627 case 'L':
1628 if (!RTStrICmp(ValueUnion.pDef->pszLong, "--follow"))
1629 RTMsgWarning("--follow is deprecated; use --dereference instead.");
1630 fFollow = true;
1631 break;
1632
1633 case 'R':
1634 fRecursive = true;
1635 break;
1636
1637 case 't':
1638 pszDst = ValueUnion.psz;
1639 fDstMustBeDir = true;
1640 break;
1641
1642 default:
1643 return errorGetOpt(ch, &ValueUnion);
1644 }
1645 }
1646
1647 char **papszSources = RTGetOptNonOptionArrayPtr(&GetState);
1648 size_t cSources = &argv[argc] - papszSources;
1649
1650 if (!cSources)
1651 return errorSyntax(GuestCtrl::tr("No sources specified!"));
1652
1653 /* Unless a --target-directory is given, the last argument is the destination, so
1654 bump it from the source list. */
1655 if (pszDst == NULL && cSources >= 2)
1656 pszDst = papszSources[--cSources];
1657
1658 if (pszDst == NULL)
1659 return errorSyntax(GuestCtrl::tr("No destination specified!"));
1660
1661 char szAbsDst[RTPATH_MAX];
1662 if (!fHostToGuest)
1663 {
1664 vrc = RTPathAbs(pszDst, szAbsDst, sizeof(szAbsDst));
1665 if (RT_SUCCESS(vrc))
1666 pszDst = szAbsDst;
1667 else
1668 return RTMsgErrorExitFailure(GuestCtrl::tr("RTPathAbs failed on '%s': %Rrc"), pszDst, vrc);
1669 }
1670
1671 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
1672 if (rcExit != RTEXITCODE_SUCCESS)
1673 return rcExit;
1674
1675 /*
1676 * Done parsing arguments, do some more preparations.
1677 */
1678 if (pCtx->cVerbose)
1679 {
1680 if (fHostToGuest)
1681 RTPrintf(GuestCtrl::tr("Copying from host to guest ...\n"));
1682 else
1683 RTPrintf(GuestCtrl::tr("Copying from guest to host ...\n"));
1684 }
1685
1686 HRESULT hrc = S_OK;
1687
1688 bool fDstIsDir = false;
1689
1690 if (!fHostToGuest)
1691 {
1692 RTFSOBJINFO ObjInfo;
1693 vrc = RTPathQueryInfo(szAbsDst, &ObjInfo, RTFSOBJATTRADD_NOTHING);
1694 if (RT_FAILURE(vrc))
1695 return RTMsgErrorExitFailure(GuestCtrl::tr("RTPathQueryInfo failed on '%s': %Rrc"), szAbsDst, vrc);
1696 fDstIsDir = RTFS_IS_DIRECTORY(ObjInfo.Attr.fMode);
1697 }
1698 else
1699 {
1700 BOOL fDirExists = FALSE;
1701 hrc = pCtx->pGuestSession->DirectoryExists(Bstr(pszDst).raw(), TRUE /* fFollowSymlinks */, &fDirExists);
1702 if (SUCCEEDED(hrc))
1703 fDstIsDir = RT_BOOL(fDirExists);
1704 }
1705
1706 /* If multiple sources are specified, the destination must be a directory. */
1707 fDstMustBeDir = cSources > 1;
1708
1709 /* If destination must be a directory, check this first before everything else. */
1710 if ( fDstMustBeDir
1711 && !fDstIsDir)
1712 {
1713 return RTMsgErrorExitFailure(GuestCtrl::tr("Destination must be a directory!"));
1714 }
1715
1716 for (size_t iSrc = 0; iSrc < cSources; iSrc++)
1717 {
1718 /*
1719 * Note: Having a dedicated progress object on every single source being copied can be very slow.
1720 * We implement IGuestSession::Copy[From|To]Guest() since quite a while which does most of the below
1721 * under the hood in Main using a multi-staged progress object. However, leave this like it is for now
1722 * to (also) have a different method of API testing.
1723 */
1724 ComPtr<IProgress> pProgress;
1725 const char *pszSource = papszSources[iSrc];
1726
1727 /* Note: Wildcards have to be processed by the calling process (i.e. via globbing, if available). */
1728
1729 if (fHostToGuest)
1730 {
1731 /*
1732 * Source is host, destination guest.
1733 */
1734 char szAbsSrc[RTPATH_MAX];
1735 vrc = RTPathAbs(pszSource, szAbsSrc, sizeof(szAbsSrc));
1736 if (RT_SUCCESS(vrc))
1737 {
1738 RTFSOBJINFO ObjInfo;
1739 vrc = RTPathQueryInfo(szAbsSrc, &ObjInfo, RTFSOBJATTRADD_NOTHING);
1740 if (RT_SUCCESS(vrc))
1741 {
1742 if (RTFS_IS_FILE(ObjInfo.Attr.fMode))
1743 {
1744 if (pCtx->cVerbose)
1745 RTPrintf(GuestCtrl::tr("File '%s' -> '%s'\n"), szAbsSrc, pszDst);
1746
1747 SafeArray<FileCopyFlag_T> aCopyFlags;
1748 hrc = pCtx->pGuestSession->FileCopyToGuest(Bstr(szAbsSrc).raw(), Bstr(pszDst).raw(),
1749 ComSafeArrayAsInParam(aCopyFlags), pProgress.asOutParam());
1750 }
1751 else if (RTFS_IS_DIRECTORY(ObjInfo.Attr.fMode))
1752 {
1753 if (pCtx->cVerbose)
1754 RTPrintf(GuestCtrl::tr("Directory '%s' -> '%s'\n"), szAbsSrc, pszDst);
1755
1756 SafeArray<DirectoryCopyFlag_T> aCopyFlags;
1757 aCopyFlags.push_back(DirectoryCopyFlag_CopyIntoExisting);
1758 if (fRecursive)
1759 aCopyFlags.push_back(DirectoryCopyFlag_Recursive);
1760 if (fFollow)
1761 aCopyFlags.push_back(DirectoryCopyFlag_FollowLinks);
1762 hrc = pCtx->pGuestSession->DirectoryCopyToGuest(Bstr(szAbsSrc).raw(), Bstr(pszDst).raw(),
1763 ComSafeArrayAsInParam(aCopyFlags), pProgress.asOutParam());
1764 }
1765 else
1766 rcExit = RTMsgErrorExitFailure(GuestCtrl::tr("Not a file or directory: %s\n"), szAbsSrc);
1767 }
1768 else
1769 rcExit = RTMsgErrorExitFailure(GuestCtrl::tr("RTPathQueryInfo failed on '%s': %Rrc"), szAbsSrc, vrc);
1770 }
1771 else
1772 rcExit = RTMsgErrorExitFailure(GuestCtrl::tr("RTPathAbs failed on '%s': %Rrc"), pszSource, vrc);
1773 }
1774 else
1775 {
1776 /*
1777 * Source guest, destination host.
1778 */
1779 /* We need to query the source type on the guest first in order to know which copy flavor we need. */
1780 ComPtr<IGuestFsObjInfo> pFsObjInfo;
1781 hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(pszSource).raw(), TRUE /* fFollowSymlinks */, pFsObjInfo.asOutParam());
1782 if (SUCCEEDED(hrc))
1783 {
1784 FsObjType_T enmObjType;
1785 CHECK_ERROR(pFsObjInfo,COMGETTER(Type)(&enmObjType));
1786 if (SUCCEEDED(hrc))
1787 {
1788 /* Take action according to source file. */
1789 if (enmObjType == FsObjType_Directory)
1790 {
1791 if (pCtx->cVerbose)
1792 RTPrintf(GuestCtrl::tr("Directory '%s' -> '%s'\n"), pszSource, pszDst);
1793
1794 SafeArray<DirectoryCopyFlag_T> aCopyFlags;
1795 aCopyFlags.push_back(DirectoryCopyFlag_CopyIntoExisting);
1796 if (fRecursive)
1797 aCopyFlags.push_back(DirectoryCopyFlag_Recursive);
1798 if (fFollow)
1799 aCopyFlags.push_back(DirectoryCopyFlag_FollowLinks);
1800 hrc = pCtx->pGuestSession->DirectoryCopyFromGuest(Bstr(pszSource).raw(), Bstr(pszDst).raw(),
1801 ComSafeArrayAsInParam(aCopyFlags), pProgress.asOutParam());
1802 }
1803 else if (enmObjType == FsObjType_File)
1804 {
1805 if (pCtx->cVerbose)
1806 RTPrintf(GuestCtrl::tr("File '%s' -> '%s'\n"), pszSource, pszDst);
1807
1808 SafeArray<FileCopyFlag_T> aCopyFlags;
1809 if (fFollow)
1810 aCopyFlags.push_back(FileCopyFlag_FollowLinks);
1811 hrc = pCtx->pGuestSession->FileCopyFromGuest(Bstr(pszSource).raw(), Bstr(pszDst).raw(),
1812 ComSafeArrayAsInParam(aCopyFlags), pProgress.asOutParam());
1813 }
1814 else
1815 rcExit = RTMsgErrorExitFailure(GuestCtrl::tr("Not a file or directory: %s\n"), pszSource);
1816 }
1817 else
1818 rcExit = RTEXITCODE_FAILURE;
1819 }
1820 else
1821 rcExit = RTMsgErrorExitFailure(GuestCtrl::tr("FsObjQueryInfo failed on '%s': %Rhrc"), pszSource, hrc);
1822 }
1823
1824 if (FAILED(hrc))
1825 {
1826 vrc = gctlPrintError(pCtx->pGuestSession, COM_IIDOF(IGuestSession));
1827 }
1828 else if (pProgress.isNotNull())
1829 {
1830 if (pCtx->cVerbose)
1831 hrc = showProgress(pProgress);
1832 else
1833 hrc = pProgress->WaitForCompletion(-1 /* No timeout */);
1834 if (SUCCEEDED(hrc))
1835 CHECK_PROGRESS_ERROR(pProgress, (GuestCtrl::tr("File copy failed")));
1836 vrc = gctlPrintProgressError(pProgress);
1837 }
1838
1839 /* Keep going. */
1840 }
1841
1842 if (RT_FAILURE(vrc))
1843 rcExit = RTEXITCODE_FAILURE;
1844
1845 return rcExit;
1846}
1847
1848static DECLCALLBACK(RTEXITCODE) gctlHandleCopyFrom(PGCTLCMDCTX pCtx, int argc, char **argv)
1849{
1850 return gctlHandleCopy(pCtx, argc, argv, false /* Guest to host */);
1851}
1852
1853static DECLCALLBACK(RTEXITCODE) gctlHandleCopyTo(PGCTLCMDCTX pCtx, int argc, char **argv)
1854{
1855 return gctlHandleCopy(pCtx, argc, argv, true /* Host to guest */);
1856}
1857
1858static DECLCALLBACK(RTEXITCODE) gctrlHandleMkDir(PGCTLCMDCTX pCtx, int argc, char **argv)
1859{
1860 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1861
1862 static const RTGETOPTDEF s_aOptions[] =
1863 {
1864 GCTLCMD_COMMON_OPTION_DEFS()
1865 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
1866 { "--parents", 'P', RTGETOPT_REQ_NOTHING }
1867 };
1868
1869 int ch;
1870 RTGETOPTUNION ValueUnion;
1871 RTGETOPTSTATE GetState;
1872 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1873
1874 SafeArray<DirectoryCreateFlag_T> aDirCreateFlags;
1875 uint32_t fDirMode = 0; /* Default mode. */
1876 uint32_t cDirsCreated = 0;
1877 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1878
1879 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1880 {
1881 /* For options that require an argument, ValueUnion has received the value. */
1882 switch (ch)
1883 {
1884 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1885
1886 case 'm': /* Mode */
1887 fDirMode = ValueUnion.u32;
1888 break;
1889
1890 case 'P': /* Create parents */
1891 aDirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1892 break;
1893
1894 case VINF_GETOPT_NOT_OPTION:
1895 if (cDirsCreated == 0)
1896 {
1897 /*
1898 * First non-option - no more options now.
1899 */
1900 rcExit = gctlCtxPostOptionParsingInit(pCtx);
1901 if (rcExit != RTEXITCODE_SUCCESS)
1902 return rcExit;
1903 if (pCtx->cVerbose)
1904 RTPrintf(GuestCtrl::tr("Creating %RU32 directories...\n", "", argc - GetState.iNext + 1),
1905 argc - GetState.iNext + 1);
1906 }
1907 if (g_fGuestCtrlCanceled)
1908 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("mkdir was interrupted by Ctrl-C (%u left)\n"),
1909 argc - GetState.iNext + 1);
1910
1911 /*
1912 * Create the specified directory.
1913 *
1914 * On failure we'll change the exit status to failure and
1915 * continue with the next directory that needs creating. We do
1916 * this because we only create new things, and because this is
1917 * how /bin/mkdir works on unix.
1918 */
1919 cDirsCreated++;
1920 if (pCtx->cVerbose)
1921 RTPrintf(GuestCtrl::tr("Creating directory \"%s\" ...\n"), ValueUnion.psz);
1922 try
1923 {
1924 HRESULT hrc;
1925 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreate(Bstr(ValueUnion.psz).raw(),
1926 fDirMode, ComSafeArrayAsInParam(aDirCreateFlags)));
1927 if (FAILED(hrc))
1928 rcExit = RTEXITCODE_FAILURE;
1929 }
1930 catch (std::bad_alloc &)
1931 {
1932 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory\n"));
1933 }
1934 break;
1935
1936 default:
1937 return errorGetOpt(ch, &ValueUnion);
1938 }
1939 }
1940
1941 if (!cDirsCreated)
1942 return errorSyntax(GuestCtrl::tr("No directory to create specified!"));
1943 return rcExit;
1944}
1945
1946
1947static DECLCALLBACK(RTEXITCODE) gctlHandleRmDir(PGCTLCMDCTX pCtx, int argc, char **argv)
1948{
1949 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1950
1951 static const RTGETOPTDEF s_aOptions[] =
1952 {
1953 GCTLCMD_COMMON_OPTION_DEFS()
1954 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1955 };
1956
1957 int ch;
1958 RTGETOPTUNION ValueUnion;
1959 RTGETOPTSTATE GetState;
1960 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1961
1962 bool fRecursive = false;
1963 uint32_t cDirRemoved = 0;
1964 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1965
1966 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1967 {
1968 /* For options that require an argument, ValueUnion has received the value. */
1969 switch (ch)
1970 {
1971 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1972
1973 case 'R':
1974 fRecursive = true;
1975 break;
1976
1977 case VINF_GETOPT_NOT_OPTION:
1978 {
1979 if (cDirRemoved == 0)
1980 {
1981 /*
1982 * First non-option - no more options now.
1983 */
1984 rcExit = gctlCtxPostOptionParsingInit(pCtx);
1985 if (rcExit != RTEXITCODE_SUCCESS)
1986 return rcExit;
1987 if (pCtx->cVerbose)
1988 {
1989 if (fRecursive)
1990 RTPrintf(GuestCtrl::tr("Removing %RU32 directory tree(s)...\n", "", argc - GetState.iNext + 1),
1991 argc - GetState.iNext + 1);
1992 else
1993 RTPrintf(GuestCtrl::tr("Removing %RU32 directorie(s)...\n", "", argc - GetState.iNext + 1),
1994 argc - GetState.iNext + 1);
1995 }
1996 }
1997 if (g_fGuestCtrlCanceled)
1998 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("rmdir was interrupted by Ctrl-C (%u left)\n"),
1999 argc - GetState.iNext + 1);
2000
2001 cDirRemoved++;
2002 HRESULT hrc;
2003 if (!fRecursive)
2004 {
2005 /*
2006 * Remove exactly one directory.
2007 */
2008 if (pCtx->cVerbose)
2009 RTPrintf(GuestCtrl::tr("Removing directory \"%s\" ...\n"), ValueUnion.psz);
2010 try
2011 {
2012 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemove(Bstr(ValueUnion.psz).raw()));
2013 }
2014 catch (std::bad_alloc &)
2015 {
2016 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory\n"));
2017 }
2018 }
2019 else
2020 {
2021 /*
2022 * Remove the directory and anything under it, that means files
2023 * and everything. This is in the tradition of the Windows NT
2024 * CMD.EXE "rmdir /s" operation, a tradition which jpsoft's TCC
2025 * strongly warns against (and half-ways questions the sense of).
2026 */
2027 if (pCtx->cVerbose)
2028 RTPrintf(GuestCtrl::tr("Recursively removing directory \"%s\" ...\n"), ValueUnion.psz);
2029 try
2030 {
2031 /** @todo Make flags configurable. */
2032 com::SafeArray<DirectoryRemoveRecFlag_T> aRemRecFlags;
2033 aRemRecFlags.push_back(DirectoryRemoveRecFlag_ContentAndDir);
2034
2035 ComPtr<IProgress> ptrProgress;
2036 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemoveRecursive(Bstr(ValueUnion.psz).raw(),
2037 ComSafeArrayAsInParam(aRemRecFlags),
2038 ptrProgress.asOutParam()));
2039 if (SUCCEEDED(hrc))
2040 {
2041 if (pCtx->cVerbose)
2042 hrc = showProgress(ptrProgress);
2043 else
2044 hrc = ptrProgress->WaitForCompletion(-1 /* indefinitely */);
2045 if (SUCCEEDED(hrc))
2046 CHECK_PROGRESS_ERROR(ptrProgress, (GuestCtrl::tr("Directory deletion failed")));
2047 ptrProgress.setNull();
2048 }
2049 }
2050 catch (std::bad_alloc &)
2051 {
2052 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory during recursive rmdir\n"));
2053 }
2054 }
2055
2056 /*
2057 * This command returns immediately on failure since it's destructive in nature.
2058 */
2059 if (FAILED(hrc))
2060 return RTEXITCODE_FAILURE;
2061 break;
2062 }
2063
2064 default:
2065 return errorGetOpt(ch, &ValueUnion);
2066 }
2067 }
2068
2069 if (!cDirRemoved)
2070 return errorSyntax(GuestCtrl::tr("No directory to remove specified!"));
2071 return rcExit;
2072}
2073
2074static DECLCALLBACK(RTEXITCODE) gctlHandleRm(PGCTLCMDCTX pCtx, int argc, char **argv)
2075{
2076 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2077
2078 static const RTGETOPTDEF s_aOptions[] =
2079 {
2080 GCTLCMD_COMMON_OPTION_DEFS()
2081 { "--force", 'f', RTGETOPT_REQ_NOTHING, },
2082 };
2083
2084 int ch;
2085 RTGETOPTUNION ValueUnion;
2086 RTGETOPTSTATE GetState;
2087 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2088
2089 uint32_t cFilesDeleted = 0;
2090 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2091 bool fForce = true;
2092
2093 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2094 {
2095 /* For options that require an argument, ValueUnion has received the value. */
2096 switch (ch)
2097 {
2098 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2099
2100 case VINF_GETOPT_NOT_OPTION:
2101 if (cFilesDeleted == 0)
2102 {
2103 /*
2104 * First non-option - no more options now.
2105 */
2106 rcExit = gctlCtxPostOptionParsingInit(pCtx);
2107 if (rcExit != RTEXITCODE_SUCCESS)
2108 return rcExit;
2109 if (pCtx->cVerbose)
2110 RTPrintf(GuestCtrl::tr("Removing %RU32 file(s)...\n", "", argc - GetState.iNext + 1),
2111 argc - GetState.iNext + 1);
2112 }
2113 if (g_fGuestCtrlCanceled)
2114 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("rm was interrupted by Ctrl-C (%u left)\n"),
2115 argc - GetState.iNext + 1);
2116
2117 /*
2118 * Remove the specified file.
2119 *
2120 * On failure we will by default stop, however, the force option will
2121 * by unix traditions force us to ignore errors and continue.
2122 */
2123 cFilesDeleted++;
2124 if (pCtx->cVerbose)
2125 RTPrintf(GuestCtrl::tr("Removing file \"%s\" ...\n", ValueUnion.psz));
2126 try
2127 {
2128 /** @todo How does IGuestSession::FsObjRemove work with read-only files? Do we
2129 * need to do some chmod or whatever to better emulate the --force flag? */
2130 HRESULT hrc;
2131 CHECK_ERROR(pCtx->pGuestSession, FsObjRemove(Bstr(ValueUnion.psz).raw()));
2132 if (FAILED(hrc) && !fForce)
2133 return RTEXITCODE_FAILURE;
2134 }
2135 catch (std::bad_alloc &)
2136 {
2137 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory\n"));
2138 }
2139 break;
2140
2141 default:
2142 return errorGetOpt(ch, &ValueUnion);
2143 }
2144 }
2145
2146 if (!cFilesDeleted && !fForce)
2147 return errorSyntax(GuestCtrl::tr("No file to remove specified!"));
2148 return rcExit;
2149}
2150
2151static DECLCALLBACK(RTEXITCODE) gctlHandleMv(PGCTLCMDCTX pCtx, int argc, char **argv)
2152{
2153 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2154
2155 static const RTGETOPTDEF s_aOptions[] =
2156 {
2157 GCTLCMD_COMMON_OPTION_DEFS()
2158/** @todo Missing --force/-f flag. */
2159 };
2160
2161 int ch;
2162 RTGETOPTUNION ValueUnion;
2163 RTGETOPTSTATE GetState;
2164 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2165
2166 int vrc = VINF_SUCCESS;
2167
2168 bool fDryrun = false;
2169 std::vector< Utf8Str > vecSources;
2170 const char *pszDst = NULL;
2171 com::SafeArray<FsObjRenameFlag_T> aRenameFlags;
2172
2173 try
2174 {
2175 /** @todo Make flags configurable. */
2176 aRenameFlags.push_back(FsObjRenameFlag_NoReplace);
2177
2178 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2179 && RT_SUCCESS(vrc))
2180 {
2181 /* For options that require an argument, ValueUnion has received the value. */
2182 switch (ch)
2183 {
2184 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2185
2186 /** @todo Implement a --dryrun command. */
2187 /** @todo Implement rename flags. */
2188
2189 case VINF_GETOPT_NOT_OPTION:
2190 vecSources.push_back(Utf8Str(ValueUnion.psz));
2191 pszDst = ValueUnion.psz;
2192 break;
2193
2194 default:
2195 return errorGetOpt(ch, &ValueUnion);
2196 }
2197 }
2198 }
2199 catch (std::bad_alloc &)
2200 {
2201 vrc = VERR_NO_MEMORY;
2202 }
2203
2204 if (RT_FAILURE(vrc))
2205 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Failed to initialize, rc=%Rrc\n"), vrc);
2206
2207 size_t cSources = vecSources.size();
2208 if (!cSources)
2209 return errorSyntax(GuestCtrl::tr("No source(s) to move specified!"));
2210 if (cSources < 2)
2211 return errorSyntax(GuestCtrl::tr("No destination specified!"));
2212
2213 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2214 if (rcExit != RTEXITCODE_SUCCESS)
2215 return rcExit;
2216
2217 /* Delete last element, which now is the destination. */
2218 vecSources.pop_back();
2219 cSources = vecSources.size();
2220
2221 HRESULT hrc = S_OK;
2222
2223 /* Destination must be a directory when specifying multiple sources. */
2224 if (cSources > 1)
2225 {
2226 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2227 hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(pszDst).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
2228 if (FAILED(hrc))
2229 {
2230 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Destination does not exist\n"));
2231 }
2232 else
2233 {
2234 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC */
2235 hrc = pFsObjInfo->COMGETTER(Type)(&enmObjType);
2236 if (SUCCEEDED(hrc))
2237 {
2238 if (enmObjType != FsObjType_Directory)
2239 return RTMsgErrorExit(RTEXITCODE_FAILURE,
2240 GuestCtrl::tr("Destination must be a directory when specifying multiple sources\n"));
2241 }
2242 else
2243 return RTMsgErrorExit(RTEXITCODE_FAILURE,
2244 GuestCtrl::tr("Unable to determine destination type: %Rhrc\n"),
2245 hrc);
2246 }
2247 }
2248
2249 /*
2250 * Rename (move) the entries.
2251 */
2252 if (pCtx->cVerbose)
2253 RTPrintf(GuestCtrl::tr("Renaming %RU32 %s ...\n"), cSources,
2254 cSources > 1 ? GuestCtrl::tr("sources", "", cSources) : GuestCtrl::tr("source"));
2255
2256 std::vector< Utf8Str >::iterator it = vecSources.begin();
2257 while ( it != vecSources.end()
2258 && !g_fGuestCtrlCanceled)
2259 {
2260 Utf8Str strSrcCur = (*it);
2261
2262 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2263 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC */
2264 hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(strSrcCur).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
2265 if (SUCCEEDED(hrc))
2266 hrc = pFsObjInfo->COMGETTER(Type)(&enmObjType);
2267 if (FAILED(hrc))
2268 {
2269 RTPrintf(GuestCtrl::tr("Cannot stat \"%s\": No such file or directory\n"), strSrcCur.c_str());
2270 ++it;
2271 continue; /* Skip. */
2272 }
2273
2274 char *pszDstCur = NULL;
2275
2276 if (cSources > 1)
2277 {
2278 pszDstCur = RTPathJoinA(pszDst, RTPathFilename(strSrcCur.c_str()));
2279 }
2280 else
2281 pszDstCur = RTStrDup(pszDst);
2282
2283 AssertPtrBreakStmt(pszDstCur, VERR_NO_MEMORY);
2284
2285 if (pCtx->cVerbose)
2286 RTPrintf(GuestCtrl::tr("Renaming %s \"%s\" to \"%s\" ...\n"),
2287 enmObjType == FsObjType_Directory ? GuestCtrl::tr("directory", "object") : GuestCtrl::tr("file","object"),
2288 strSrcCur.c_str(), pszDstCur);
2289
2290 if (!fDryrun)
2291 {
2292 CHECK_ERROR(pCtx->pGuestSession, FsObjRename(Bstr(strSrcCur).raw(),
2293 Bstr(pszDstCur).raw(),
2294 ComSafeArrayAsInParam(aRenameFlags)));
2295 /* Keep going with next item in case of errors. */
2296 }
2297
2298 RTStrFree(pszDstCur);
2299
2300 ++it;
2301 }
2302
2303 if ( (it != vecSources.end())
2304 && pCtx->cVerbose)
2305 {
2306 RTPrintf(GuestCtrl::tr("Warning: Not all sources were renamed\n"));
2307 }
2308
2309 return FAILED(hrc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2310}
2311
2312static DECLCALLBACK(RTEXITCODE) gctlHandleMkTemp(PGCTLCMDCTX pCtx, int argc, char **argv)
2313{
2314 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2315
2316 static const RTGETOPTDEF s_aOptions[] =
2317 {
2318 GCTLCMD_COMMON_OPTION_DEFS()
2319 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2320 { "--directory", 'D', RTGETOPT_REQ_NOTHING },
2321 { "--secure", 's', RTGETOPT_REQ_NOTHING },
2322 { "--tmpdir", 't', RTGETOPT_REQ_STRING }
2323 };
2324
2325 int ch;
2326 RTGETOPTUNION ValueUnion;
2327 RTGETOPTSTATE GetState;
2328 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2329
2330 Utf8Str strTemplate;
2331 uint32_t fMode = 0; /* Default mode. */
2332 bool fDirectory = false;
2333 bool fSecure = false;
2334 Utf8Str strTempDir;
2335
2336 DESTDIRMAP mapDirs;
2337
2338 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2339 {
2340 /* For options that require an argument, ValueUnion has received the value. */
2341 switch (ch)
2342 {
2343 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2344
2345 case 'm': /* Mode */
2346 fMode = ValueUnion.u32;
2347 break;
2348
2349 case 'D': /* Create directory */
2350 fDirectory = true;
2351 break;
2352
2353 case 's': /* Secure */
2354 fSecure = true;
2355 break;
2356
2357 case 't': /* Temp directory */
2358 strTempDir = ValueUnion.psz;
2359 break;
2360
2361 case VINF_GETOPT_NOT_OPTION:
2362 if (strTemplate.isEmpty())
2363 strTemplate = ValueUnion.psz;
2364 else
2365 return errorSyntax(GuestCtrl::tr("More than one template specified!\n"));
2366 break;
2367
2368 default:
2369 return errorGetOpt(ch, &ValueUnion);
2370 }
2371 }
2372
2373 if (strTemplate.isEmpty())
2374 return errorSyntax(GuestCtrl::tr("No template specified!"));
2375
2376 if (!fDirectory)
2377 return errorSyntax(GuestCtrl::tr("Creating temporary files is currently not supported!"));
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) gctlHandleStat(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 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
2432 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
2433 { "--format", 'c', RTGETOPT_REQ_STRING },
2434 { "--terse", 't', RTGETOPT_REQ_NOTHING }
2435 };
2436
2437 int ch;
2438 RTGETOPTUNION ValueUnion;
2439 RTGETOPTSTATE GetState;
2440 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2441
2442 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
2443 && ch != VINF_GETOPT_NOT_OPTION)
2444 {
2445 /* For options that require an argument, ValueUnion has received the value. */
2446 switch (ch)
2447 {
2448 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2449
2450 case 'L': /* Dereference */
2451 case 'f': /* File-system */
2452 case 'c': /* Format */
2453 case 't': /* Terse */
2454 return errorSyntax(GuestCtrl::tr("Command \"%s\" not implemented yet!"), ValueUnion.psz);
2455
2456 default:
2457 return errorGetOpt(ch, &ValueUnion);
2458 }
2459 }
2460
2461 if (ch != VINF_GETOPT_NOT_OPTION)
2462 return errorSyntax(GuestCtrl::tr("Nothing to stat!"));
2463
2464 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2465 if (rcExit != RTEXITCODE_SUCCESS)
2466 return rcExit;
2467
2468
2469 /*
2470 * Do the file stat'ing.
2471 */
2472 while (ch == VINF_GETOPT_NOT_OPTION)
2473 {
2474 if (pCtx->cVerbose)
2475 RTPrintf(GuestCtrl::tr("Checking for element \"%s\" ...\n"), ValueUnion.psz);
2476
2477 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2478 HRESULT hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(ValueUnion.psz).raw(), FALSE /*followSymlinks*/,
2479 pFsObjInfo.asOutParam());
2480 if (FAILED(hrc))
2481 {
2482 /** @todo r=bird: There might be other reasons why we end up here than
2483 * non-existing "element" (object or file, please, nobody calls it elements). */
2484 if (pCtx->cVerbose)
2485 RTPrintf(GuestCtrl::tr("Failed to stat '%s': No such file\n"), ValueUnion.psz);
2486 rcExit = RTEXITCODE_FAILURE;
2487 }
2488 else
2489 {
2490 RTPrintf(GuestCtrl::tr(" File: '%s'\n"), ValueUnion.psz); /** @todo escape this name. */
2491
2492 FsObjType_T enmType = FsObjType_Unknown;
2493 CHECK_ERROR2I(pFsObjInfo, COMGETTER(Type)(&enmType));
2494 LONG64 cbObject = 0;
2495 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ObjectSize)(&cbObject));
2496 LONG64 cbAllocated = 0;
2497 CHECK_ERROR2I(pFsObjInfo, COMGETTER(AllocatedSize)(&cbAllocated));
2498 LONG uid = 0;
2499 CHECK_ERROR2I(pFsObjInfo, COMGETTER(UID)(&uid));
2500 LONG gid = 0;
2501 CHECK_ERROR2I(pFsObjInfo, COMGETTER(GID)(&gid));
2502 Bstr bstrUsername;
2503 CHECK_ERROR2I(pFsObjInfo, COMGETTER(UserName)(bstrUsername.asOutParam()));
2504 Bstr bstrGroupName;
2505 CHECK_ERROR2I(pFsObjInfo, COMGETTER(GroupName)(bstrGroupName.asOutParam()));
2506 Bstr bstrAttribs;
2507 CHECK_ERROR2I(pFsObjInfo, COMGETTER(FileAttributes)(bstrAttribs.asOutParam()));
2508 LONG64 idNode = 0;
2509 CHECK_ERROR2I(pFsObjInfo, COMGETTER(NodeId)(&idNode));
2510 ULONG uDevNode = 0;
2511 CHECK_ERROR2I(pFsObjInfo, COMGETTER(NodeIdDevice)(&uDevNode));
2512 ULONG uDeviceNo = 0;
2513 CHECK_ERROR2I(pFsObjInfo, COMGETTER(DeviceNumber)(&uDeviceNo));
2514 ULONG cHardLinks = 1;
2515 CHECK_ERROR2I(pFsObjInfo, COMGETTER(HardLinks)(&cHardLinks));
2516 LONG64 nsBirthTime = 0;
2517 CHECK_ERROR2I(pFsObjInfo, COMGETTER(BirthTime)(&nsBirthTime));
2518 LONG64 nsChangeTime = 0;
2519 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ChangeTime)(&nsChangeTime));
2520 LONG64 nsModificationTime = 0;
2521 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ModificationTime)(&nsModificationTime));
2522 LONG64 nsAccessTime = 0;
2523 CHECK_ERROR2I(pFsObjInfo, COMGETTER(AccessTime)(&nsAccessTime));
2524
2525 RTPrintf(GuestCtrl::tr(" Size: %-17RU64 Alloc: %-19RU64 Type: %s\n"),
2526 cbObject, cbAllocated, gctlFsObjTypeToName(enmType));
2527 RTPrintf(GuestCtrl::tr("Device: %#-17RX32 INode: %-18RU64 Links: %u\n"), uDevNode, idNode, cHardLinks);
2528
2529 Utf8Str strAttrib(bstrAttribs);
2530 char *pszMode = strAttrib.mutableRaw();
2531 char *pszAttribs = strchr(pszMode, ' ');
2532 if (pszAttribs)
2533 do *pszAttribs++ = '\0';
2534 while (*pszAttribs == ' ');
2535 else
2536 pszAttribs = strchr(pszMode, '\0');
2537 if (uDeviceNo != 0)
2538 RTPrintf(GuestCtrl::tr(" Mode: %-16s Attrib: %-17s Dev ID: %#RX32\n"), pszMode, pszAttribs, uDeviceNo);
2539 else
2540 RTPrintf(GuestCtrl::tr(" Mode: %-16s Attrib: %s\n"), pszMode, pszAttribs);
2541
2542 RTPrintf(GuestCtrl::tr(" Owner: %4d/%-12ls Group: %4d/%ls\n"), uid, bstrUsername.raw(), gid, bstrGroupName.raw());
2543
2544 RTTIMESPEC TimeSpec;
2545 char szTmp[RTTIME_STR_LEN];
2546 RTPrintf(GuestCtrl::tr(" Birth: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsBirthTime),
2547 szTmp, sizeof(szTmp)));
2548 RTPrintf(GuestCtrl::tr("Change: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsChangeTime),
2549 szTmp, sizeof(szTmp)));
2550 RTPrintf(GuestCtrl::tr("Modify: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsModificationTime),
2551 szTmp, sizeof(szTmp)));
2552 RTPrintf(GuestCtrl::tr("Access: %s\n"), RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsAccessTime),
2553 szTmp, sizeof(szTmp)));
2554
2555 /* Skiping: Generation ID - only the ISO9660 VFS sets this. FreeBSD user flags. */
2556 }
2557
2558 /* Next file. */
2559 ch = RTGetOpt(&GetState, &ValueUnion);
2560 }
2561
2562 return rcExit;
2563}
2564
2565/**
2566 * Waits for a Guest Additions run level being reached.
2567 *
2568 * @returns VBox status code.
2569 * Returns VERR_CANCELLED if waiting for cancelled due to signal handling, e.g. when CTRL+C or some sort was pressed.
2570 * @param pCtx The guest control command context.
2571 * @param enmRunLevel Run level to wait for.
2572 * @param cMsTimeout Timeout (in ms) for waiting.
2573 */
2574static int gctlWaitForRunLevel(PGCTLCMDCTX pCtx, AdditionsRunLevelType_T enmRunLevel, RTMSINTERVAL cMsTimeout)
2575{
2576 int vrc = VINF_SUCCESS; /* Shut up MSVC. */
2577
2578 try
2579 {
2580 HRESULT hrc = S_OK;
2581 /** Whether we need to actually wait for the run level or if we already reached it. */
2582 bool fWait = false;
2583
2584 /* Install an event handler first to catch any runlevel changes. */
2585 ComObjPtr<GuestAdditionsRunlevelListenerImpl> pGuestListener;
2586 do
2587 {
2588 /* Listener creation. */
2589 pGuestListener.createObject();
2590 pGuestListener->init(new GuestAdditionsRunlevelListener(enmRunLevel));
2591
2592 /* Register for IGuest events. */
2593 ComPtr<IEventSource> es;
2594 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
2595 com::SafeArray<VBoxEventType_T> eventTypes;
2596 eventTypes.push_back(VBoxEventType_OnGuestAdditionsStatusChanged);
2597 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
2598 true /* Active listener */));
2599
2600 AdditionsRunLevelType_T enmRunLevelCur = AdditionsRunLevelType_None;
2601 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(AdditionsRunLevel)(&enmRunLevelCur));
2602 fWait = enmRunLevelCur != enmRunLevel;
2603
2604 if (pCtx->cVerbose)
2605 RTPrintf(GuestCtrl::tr("Current run level is %RU32\n"), enmRunLevelCur);
2606
2607 } while (0);
2608
2609 if (fWait)
2610 {
2611 if (pCtx->cVerbose)
2612 RTPrintf(GuestCtrl::tr("Waiting for run level %RU32 ...\n"), enmRunLevel);
2613
2614 RTMSINTERVAL tsStart = RTTimeMilliTS();
2615 while (RTTimeMilliTS() - tsStart < cMsTimeout)
2616 {
2617 /* Wait for the global signal semaphore getting signalled. */
2618 vrc = RTSemEventWait(g_SemEventGuestCtrlCanceled, 100 /* ms */);
2619 if (RT_FAILURE(vrc))
2620 {
2621 if (vrc == VERR_TIMEOUT)
2622 continue;
2623 else
2624 {
2625 RTPrintf(GuestCtrl::tr("Waiting failed with %Rrc\n"), vrc);
2626 break;
2627 }
2628 }
2629 else if (pCtx->cVerbose)
2630 {
2631 RTPrintf(GuestCtrl::tr("Run level %RU32 reached\n"), enmRunLevel);
2632 break;
2633 }
2634
2635 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
2636 }
2637
2638 if ( vrc == VERR_TIMEOUT
2639 && pCtx->cVerbose)
2640 RTPrintf(GuestCtrl::tr("Run level %RU32 not reached within time\n"), enmRunLevel);
2641 }
2642
2643 if (!pGuestListener.isNull())
2644 {
2645 /* Guest callback unregistration. */
2646 ComPtr<IEventSource> pES;
2647 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
2648 if (!pES.isNull())
2649 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
2650 pGuestListener.setNull();
2651 }
2652
2653 if (g_fGuestCtrlCanceled)
2654 vrc = VERR_CANCELLED;
2655 }
2656 catch (std::bad_alloc &)
2657 {
2658 vrc = VERR_NO_MEMORY;
2659 }
2660
2661 return vrc;
2662}
2663
2664static DECLCALLBACK(RTEXITCODE) gctlHandleUpdateAdditions(PGCTLCMDCTX pCtx, int argc, char **argv)
2665{
2666 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2667
2668 /** Timeout to wait for the whole updating procedure to complete. */
2669 uint32_t cMsTimeout = RT_INDEFINITE_WAIT;
2670 /** Source path to .ISO Guest Additions file to use. */
2671 Utf8Str strSource;
2672 com::SafeArray<IN_BSTR> aArgs;
2673 /** Whether to reboot the guest automatically when the update process has finished successfully. */
2674 bool fRebootOnFinish = false;
2675 /** Whether to only wait for getting the update process started instead of waiting until it finishes. */
2676 bool fWaitStartOnly = false;
2677 /** Whether to wait for the VM being ready to start the update. Needs Guest Additions facility reporting. */
2678 bool fWaitReady = false;
2679 /** Whether to verify if the Guest Additions were successfully updated on the guest. */
2680 bool fVerify = false;
2681
2682 /*
2683 * Parse arguments.
2684 */
2685 enum KGSTCTRLUPDATEADDITIONSOPT
2686 {
2687 KGSTCTRLUPDATEADDITIONSOPT_REBOOT = 1000,
2688 KGSTCTRLUPDATEADDITIONSOPT_SOURCE,
2689 KGSTCTRLUPDATEADDITIONSOPT_TIMEOUT,
2690 KGSTCTRLUPDATEADDITIONSOPT_VERIFY,
2691 KGSTCTRLUPDATEADDITIONSOPT_WAITREADY,
2692 KGSTCTRLUPDATEADDITIONSOPT_WAITSTART
2693 };
2694
2695 static const RTGETOPTDEF s_aOptions[] =
2696 {
2697 GCTLCMD_COMMON_OPTION_DEFS()
2698 { "--reboot", KGSTCTRLUPDATEADDITIONSOPT_REBOOT, RTGETOPT_REQ_NOTHING },
2699 { "--source", KGSTCTRLUPDATEADDITIONSOPT_SOURCE, RTGETOPT_REQ_STRING },
2700 { "--timeout", KGSTCTRLUPDATEADDITIONSOPT_TIMEOUT, RTGETOPT_REQ_UINT32 },
2701 { "--verify", KGSTCTRLUPDATEADDITIONSOPT_VERIFY, RTGETOPT_REQ_NOTHING },
2702 { "--wait-ready", KGSTCTRLUPDATEADDITIONSOPT_WAITREADY, RTGETOPT_REQ_NOTHING },
2703 { "--wait-start", KGSTCTRLUPDATEADDITIONSOPT_WAITSTART, RTGETOPT_REQ_NOTHING }
2704 };
2705
2706 int ch;
2707 RTGETOPTUNION ValueUnion;
2708 RTGETOPTSTATE GetState;
2709 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2710
2711 int vrc = VINF_SUCCESS;
2712 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2713 && RT_SUCCESS(vrc))
2714 {
2715 switch (ch)
2716 {
2717 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2718
2719 case KGSTCTRLUPDATEADDITIONSOPT_REBOOT:
2720 fRebootOnFinish = true;
2721 break;
2722
2723 case KGSTCTRLUPDATEADDITIONSOPT_SOURCE:
2724 vrc = RTPathAbsCxx(strSource, ValueUnion.psz);
2725 if (RT_FAILURE(vrc))
2726 return RTMsgErrorExitFailure(GuestCtrl::tr("RTPathAbsCxx failed on '%s': %Rrc"), ValueUnion.psz, vrc);
2727 break;
2728
2729 case KGSTCTRLUPDATEADDITIONSOPT_WAITSTART:
2730 fWaitStartOnly = true;
2731 break;
2732
2733 case KGSTCTRLUPDATEADDITIONSOPT_WAITREADY:
2734 fWaitReady = true;
2735 break;
2736
2737 case KGSTCTRLUPDATEADDITIONSOPT_VERIFY:
2738 fVerify = true;
2739 fRebootOnFinish = true; /* Verification needs a mandatory reboot after successful update. */
2740 break;
2741
2742 case VINF_GETOPT_NOT_OPTION:
2743 if (aArgs.size() == 0 && strSource.isEmpty())
2744 strSource = ValueUnion.psz;
2745 else
2746 aArgs.push_back(Bstr(ValueUnion.psz).raw());
2747 break;
2748
2749 default:
2750 return errorGetOpt(ch, &ValueUnion);
2751 }
2752 }
2753
2754 if (pCtx->cVerbose)
2755 RTPrintf(GuestCtrl::tr("Updating Guest Additions ...\n"));
2756
2757 HRESULT hrc = S_OK;
2758 while (strSource.isEmpty())
2759 {
2760 ComPtr<ISystemProperties> pProperties;
2761 CHECK_ERROR_BREAK(pCtx->pArg->virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
2762 Bstr strISO;
2763 CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
2764 strSource = strISO;
2765 break;
2766 }
2767
2768 /* Determine source if not set yet. */
2769 if (strSource.isEmpty())
2770 {
2771 RTMsgError(GuestCtrl::tr("No Guest Additions source found or specified, aborting\n"));
2772 vrc = VERR_FILE_NOT_FOUND;
2773 }
2774 else if (!RTFileExists(strSource.c_str()))
2775 {
2776 RTMsgError(GuestCtrl::tr("Source \"%s\" does not exist!\n"), strSource.c_str());
2777 vrc = VERR_FILE_NOT_FOUND;
2778 }
2779
2780
2781
2782#if 0
2783 ComPtr<IGuest> guest;
2784 rc = pConsole->COMGETTER(Guest)(guest.asOutParam());
2785 if (SUCCEEDED(hrc) && !guest.isNull())
2786 {
2787 SHOW_STRING_PROP_NOT_EMPTY(guest, OSTypeId, "GuestOSType", GuestCtrl::tr("OS type:"));
2788
2789 AdditionsRunLevelType_T guestRunLevel; /** @todo Add a runlevel-to-string (e.g. 0 = "None") method? */
2790 rc = guest->COMGETTER(AdditionsRunLevel)(&guestRunLevel);
2791 if (SUCCEEDED(hrc))
2792 SHOW_ULONG_VALUE("GuestAdditionsRunLevel", GuestCtrl::tr("Additions run level:"), (ULONG)guestRunLevel, "");
2793
2794 Bstr guestString;
2795 rc = guest->COMGETTER(AdditionsVersion)(guestString.asOutParam());
2796 if ( SUCCEEDED(hrc)
2797 && !guestString.isEmpty())
2798 {
2799 ULONG uRevision;
2800 rc = guest->COMGETTER(AdditionsRevision)(&uRevision);
2801 if (FAILED(hrc))
2802 uRevision = 0;
2803 RTStrPrintf(szValue, sizeof(szValue), "%ls r%u", guestString.raw(), uRevision);
2804 SHOW_UTF8_STRING("GuestAdditionsVersion", GuestCtrl::tr("Additions version:"), szValue);
2805 }
2806 }
2807#endif
2808
2809 if (RT_SUCCESS(vrc))
2810 {
2811 if (pCtx->cVerbose)
2812 RTPrintf(GuestCtrl::tr("Using source: %s\n"), strSource.c_str());
2813
2814 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2815 if (rcExit != RTEXITCODE_SUCCESS)
2816 return rcExit;
2817
2818 if (fWaitReady)
2819 {
2820 if (pCtx->cVerbose)
2821 RTPrintf(GuestCtrl::tr("Waiting for current Guest Additions inside VM getting ready for updating ...\n"));
2822
2823 const uint64_t uTsStart = RTTimeMilliTS();
2824 vrc = gctlWaitForRunLevel(pCtx, AdditionsRunLevelType_Userland, cMsTimeout);
2825 if (RT_SUCCESS(vrc))
2826 cMsTimeout = cMsTimeout != RT_INDEFINITE_WAIT ? cMsTimeout - (RTTimeMilliTS() - uTsStart) : cMsTimeout;
2827 }
2828
2829 if (RT_SUCCESS(vrc))
2830 {
2831 /* Get current Guest Additions version / revision. */
2832 Bstr strGstVerCur;
2833 ULONG uGstRevCur = 0;
2834 hrc = pCtx->pGuest->COMGETTER(AdditionsVersion)(strGstVerCur.asOutParam());
2835 if ( SUCCEEDED(hrc)
2836 && !strGstVerCur.isEmpty())
2837 {
2838 hrc = pCtx->pGuest->COMGETTER(AdditionsRevision)(&uGstRevCur);
2839 if (SUCCEEDED(hrc))
2840 {
2841 if (pCtx->cVerbose)
2842 RTPrintf(GuestCtrl::tr("Guest Additions %lsr%RU64 currently installed, waiting for Guest Additions installer to start ...\n"),
2843 strGstVerCur.raw(), uGstRevCur);
2844 }
2845 }
2846
2847 com::SafeArray<AdditionsUpdateFlag_T> aUpdateFlags;
2848 if (fWaitStartOnly)
2849 aUpdateFlags.push_back(AdditionsUpdateFlag_WaitForUpdateStartOnly);
2850
2851 ComPtr<IProgress> pProgress;
2852 CHECK_ERROR(pCtx->pGuest, UpdateGuestAdditions(Bstr(strSource).raw(),
2853 ComSafeArrayAsInParam(aArgs),
2854 ComSafeArrayAsInParam(aUpdateFlags),
2855 pProgress.asOutParam()));
2856 if (FAILED(hrc))
2857 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
2858 else
2859 {
2860 if (pCtx->cVerbose)
2861 hrc = showProgress(pProgress);
2862 else
2863 hrc = pProgress->WaitForCompletion((int32_t)cMsTimeout);
2864
2865 if (SUCCEEDED(hrc))
2866 CHECK_PROGRESS_ERROR(pProgress, (GuestCtrl::tr("Guest Additions update failed")));
2867 vrc = gctlPrintProgressError(pProgress);
2868 if (RT_SUCCESS(vrc))
2869 {
2870 if (pCtx->cVerbose)
2871 RTPrintf(GuestCtrl::tr("Guest Additions update successful.\n"));
2872
2873 if (fRebootOnFinish)
2874 {
2875 if (pCtx->cVerbose)
2876 RTPrintf(GuestCtrl::tr("Rebooting guest ...\n"));
2877 com::SafeArray<GuestShutdownFlag_T> aShutdownFlags;
2878 aShutdownFlags.push_back(GuestShutdownFlag_Reboot);
2879 CHECK_ERROR(pCtx->pGuest, Shutdown(ComSafeArrayAsInParam(aShutdownFlags)));
2880 if (FAILED(hrc))
2881 {
2882 if (hrc == VBOX_E_NOT_SUPPORTED)
2883 {
2884 RTPrintf(GuestCtrl::tr("Current installed Guest Additions don't support automatic rebooting. "
2885 "Please reboot manually.\n"));
2886 vrc = VERR_NOT_SUPPORTED;
2887 }
2888 else
2889 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
2890 }
2891 else
2892 {
2893 if (fWaitReady)
2894 {
2895 if (pCtx->cVerbose)
2896 RTPrintf(GuestCtrl::tr("Waiting for new Guest Additions inside VM getting ready ...\n"));
2897
2898 vrc = gctlWaitForRunLevel(pCtx, AdditionsRunLevelType_Userland, cMsTimeout);
2899 if (RT_SUCCESS(vrc))
2900 {
2901 if (fVerify)
2902 {
2903 if (pCtx->cVerbose)
2904 RTPrintf(GuestCtrl::tr("Verifying Guest Additions update ...\n"));
2905
2906 /* Get new Guest Additions version / revision. */
2907 Bstr strGstVerNew;
2908 ULONG uGstRevNew = 0;
2909 hrc = pCtx->pGuest->COMGETTER(AdditionsVersion)(strGstVerNew.asOutParam());
2910 if ( SUCCEEDED(hrc)
2911 && !strGstVerNew.isEmpty())
2912 {
2913 hrc = pCtx->pGuest->COMGETTER(AdditionsRevision)(&uGstRevNew);
2914 if (FAILED(hrc))
2915 uGstRevNew = 0;
2916 }
2917
2918 /** @todo Do more verification here. */
2919 vrc = uGstRevNew > uGstRevCur ? VINF_SUCCESS : VERR_NO_CHANGE;
2920
2921 if (pCtx->cVerbose)
2922 {
2923 RTPrintf(GuestCtrl::tr("Old Guest Additions: %ls%RU64\n"), strGstVerCur.raw(),
2924 uGstRevCur);
2925 RTPrintf(GuestCtrl::tr("New Guest Additions: %ls%RU64\n"), strGstVerNew.raw(),
2926 uGstRevNew);
2927
2928 if (RT_FAILURE(vrc))
2929 {
2930 RTPrintf(GuestCtrl::tr("\nError updating Guest Additions, please check guest installer log\n"));
2931 }
2932 else
2933 {
2934 if (uGstRevNew < uGstRevCur)
2935 RTPrintf(GuestCtrl::tr("\nWARNING: Guest Additions were downgraded\n"));
2936 }
2937 }
2938 }
2939 }
2940 }
2941 else if (pCtx->cVerbose)
2942 RTPrintf(GuestCtrl::tr("The guest needs to be restarted in order to make use of the updated Guest Additions.\n"));
2943 }
2944 }
2945 }
2946 }
2947 }
2948 }
2949
2950 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2951}
2952
2953/**
2954 * Returns a Guest Additions run level from a string.
2955 *
2956 * @returns Run level if found, or AdditionsRunLevelType_None if not found / invalid.
2957 * @param pcszStr String to return run level for.
2958 */
2959static AdditionsRunLevelType_T gctlGetRunLevelFromStr(const char *pcszStr)
2960{
2961 AssertPtrReturn(pcszStr, AdditionsRunLevelType_None);
2962
2963 if (RTStrICmp(pcszStr, "system") == 0) return AdditionsRunLevelType_System;
2964 else if (RTStrICmp(pcszStr, "userland") == 0) return AdditionsRunLevelType_Userland;
2965 else if (RTStrICmp(pcszStr, "desktop") == 0) return AdditionsRunLevelType_Desktop;
2966
2967 return AdditionsRunLevelType_None;
2968}
2969
2970static DECLCALLBACK(RTEXITCODE) gctlHandleWaitRunLevel(PGCTLCMDCTX pCtx, int argc, char **argv)
2971{
2972 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2973
2974 /** Timeout to wait for run level being reached.
2975 * By default we wait until it's reached. */
2976 uint32_t cMsTimeout = RT_INDEFINITE_WAIT;
2977
2978 /*
2979 * Parse arguments.
2980 */
2981 enum KGSTCTRLWAITRUNLEVELOPT
2982 {
2983 KGSTCTRLWAITRUNLEVELOPT_TIMEOUT = 1000
2984 };
2985
2986 static const RTGETOPTDEF s_aOptions[] =
2987 {
2988 GCTLCMD_COMMON_OPTION_DEFS()
2989 { "--timeout", KGSTCTRLWAITRUNLEVELOPT_TIMEOUT, RTGETOPT_REQ_UINT32 }
2990 };
2991
2992 int ch;
2993 RTGETOPTUNION ValueUnion;
2994 RTGETOPTSTATE GetState;
2995 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2996
2997 AdditionsRunLevelType_T enmRunLevel = AdditionsRunLevelType_None;
2998
2999 int vrc = VINF_SUCCESS;
3000 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3001 && RT_SUCCESS(vrc))
3002 {
3003 switch (ch)
3004 {
3005 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3006
3007 case KGSTCTRLWAITRUNLEVELOPT_TIMEOUT:
3008 cMsTimeout = ValueUnion.u32;
3009 break;
3010
3011 case VINF_GETOPT_NOT_OPTION:
3012 {
3013 enmRunLevel = gctlGetRunLevelFromStr(ValueUnion.psz);
3014 if (enmRunLevel == AdditionsRunLevelType_None)
3015 return errorSyntax(GuestCtrl::tr("Invalid run level specified. Valid values are: system, userland, desktop"));
3016 break;
3017 }
3018
3019 default:
3020 return errorGetOpt(ch, &ValueUnion);
3021 }
3022 }
3023
3024 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3025 if (rcExit != RTEXITCODE_SUCCESS)
3026 return rcExit;
3027
3028 if (enmRunLevel == AdditionsRunLevelType_None)
3029 return errorSyntax(GuestCtrl::tr("Missing run level to wait for"));
3030
3031 vrc = gctlWaitForRunLevel(pCtx, enmRunLevel, cMsTimeout);
3032
3033 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3034}
3035
3036static DECLCALLBACK(RTEXITCODE) gctlHandleList(PGCTLCMDCTX pCtx, int argc, char **argv)
3037{
3038 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3039
3040 static const RTGETOPTDEF s_aOptions[] =
3041 {
3042 GCTLCMD_COMMON_OPTION_DEFS()
3043 };
3044
3045 int ch;
3046 RTGETOPTUNION ValueUnion;
3047 RTGETOPTSTATE GetState;
3048 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3049
3050 bool fSeenListArg = false;
3051 bool fListAll = false;
3052 bool fListSessions = false;
3053 bool fListProcesses = false;
3054 bool fListFiles = false;
3055
3056 int vrc = VINF_SUCCESS;
3057 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3058 && RT_SUCCESS(vrc))
3059 {
3060 switch (ch)
3061 {
3062 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3063
3064 case VINF_GETOPT_NOT_OPTION:
3065 if ( !RTStrICmp(ValueUnion.psz, "sessions")
3066 || !RTStrICmp(ValueUnion.psz, "sess"))
3067 fListSessions = true;
3068 else if ( !RTStrICmp(ValueUnion.psz, "processes")
3069 || !RTStrICmp(ValueUnion.psz, "procs"))
3070 fListSessions = fListProcesses = true; /* Showing processes implies showing sessions. */
3071 else if (!RTStrICmp(ValueUnion.psz, "files"))
3072 fListSessions = fListFiles = true; /* Showing files implies showing sessions. */
3073 else if (!RTStrICmp(ValueUnion.psz, "all"))
3074 fListAll = true;
3075 else
3076 return errorSyntax(GuestCtrl::tr("Unknown list: '%s'"), ValueUnion.psz);
3077 fSeenListArg = true;
3078 break;
3079
3080 default:
3081 return errorGetOpt(ch, &ValueUnion);
3082 }
3083 }
3084
3085 if (!fSeenListArg)
3086 return errorSyntax(GuestCtrl::tr("Missing list name"));
3087 Assert(fListAll || fListSessions);
3088
3089 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3090 if (rcExit != RTEXITCODE_SUCCESS)
3091 return rcExit;
3092
3093
3094 /** @todo Do we need a machine-readable output here as well? */
3095
3096 HRESULT hrc;
3097 size_t cTotalProcs = 0;
3098 size_t cTotalFiles = 0;
3099
3100 SafeIfaceArray <IGuestSession> collSessions;
3101 CHECK_ERROR(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3102 if (SUCCEEDED(hrc))
3103 {
3104 size_t const cSessions = collSessions.size();
3105 if (cSessions)
3106 {
3107 RTPrintf(GuestCtrl::tr("Active guest sessions:\n"));
3108
3109 /** @todo Make this output a bit prettier. No time now. */
3110
3111 for (size_t i = 0; i < cSessions; i++)
3112 {
3113 ComPtr<IGuestSession> pCurSession = collSessions[i];
3114 if (!pCurSession.isNull())
3115 {
3116 do
3117 {
3118 ULONG uID;
3119 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Id)(&uID));
3120 Bstr strName;
3121 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Name)(strName.asOutParam()));
3122 Bstr strUser;
3123 CHECK_ERROR_BREAK(pCurSession, COMGETTER(User)(strUser.asOutParam()));
3124 GuestSessionStatus_T sessionStatus;
3125 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Status)(&sessionStatus));
3126 RTPrintf(GuestCtrl::tr("\n\tSession #%-3zu ID=%-3RU32 User=%-16ls Status=[%s] Name=%ls"),
3127 i, uID, strUser.raw(), gctlGuestSessionStatusToText(sessionStatus), strName.raw());
3128 } while (0);
3129
3130 if ( fListAll
3131 || fListProcesses)
3132 {
3133 SafeIfaceArray <IGuestProcess> collProcesses;
3134 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcesses)));
3135 for (size_t a = 0; a < collProcesses.size(); a++)
3136 {
3137 ComPtr<IGuestProcess> pCurProcess = collProcesses[a];
3138 if (!pCurProcess.isNull())
3139 {
3140 do
3141 {
3142 ULONG uPID;
3143 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(PID)(&uPID));
3144 Bstr strExecPath;
3145 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(ExecutablePath)(strExecPath.asOutParam()));
3146 ProcessStatus_T procStatus;
3147 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(Status)(&procStatus));
3148
3149 RTPrintf(GuestCtrl::tr("\n\t\tProcess #%-03zu PID=%-6RU32 Status=[%s] Command=%ls"),
3150 a, uPID, gctlProcessStatusToText(procStatus), strExecPath.raw());
3151 } while (0);
3152 }
3153 }
3154
3155 cTotalProcs += collProcesses.size();
3156 }
3157
3158 if ( fListAll
3159 || fListFiles)
3160 {
3161 SafeIfaceArray <IGuestFile> collFiles;
3162 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Files)(ComSafeArrayAsOutParam(collFiles)));
3163 for (size_t a = 0; a < collFiles.size(); a++)
3164 {
3165 ComPtr<IGuestFile> pCurFile = collFiles[a];
3166 if (!pCurFile.isNull())
3167 {
3168 do
3169 {
3170 ULONG idFile;
3171 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Id)(&idFile));
3172 Bstr strName;
3173 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Filename)(strName.asOutParam()));
3174 FileStatus_T fileStatus;
3175 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Status)(&fileStatus));
3176
3177 RTPrintf(GuestCtrl::tr("\n\t\tFile #%-03zu ID=%-6RU32 Status=[%s] Name=%ls"),
3178 a, idFile, gctlFileStatusToText(fileStatus), strName.raw());
3179 } while (0);
3180 }
3181 }
3182
3183 cTotalFiles += collFiles.size();
3184 }
3185 }
3186 }
3187
3188 RTPrintf(GuestCtrl::tr("\n\nTotal guest sessions: %zu\n"), collSessions.size());
3189 if (fListAll || fListProcesses)
3190 RTPrintf(GuestCtrl::tr("Total guest processes: %zu\n"), cTotalProcs);
3191 if (fListAll || fListFiles)
3192 RTPrintf(GuestCtrl::tr("Total guest files: %zu\n"), cTotalFiles);
3193 }
3194 else
3195 RTPrintf(GuestCtrl::tr("No active guest sessions found\n"));
3196 }
3197
3198 if (FAILED(hrc)) /** @todo yeah, right... Only the last error? */
3199 rcExit = RTEXITCODE_FAILURE;
3200
3201 return rcExit;
3202}
3203
3204static DECLCALLBACK(RTEXITCODE) gctlHandleCloseProcess(PGCTLCMDCTX pCtx, int argc, char **argv)
3205{
3206 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3207
3208 static const RTGETOPTDEF s_aOptions[] =
3209 {
3210 GCTLCMD_COMMON_OPTION_DEFS()
3211 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3212 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3213 };
3214
3215 int ch;
3216 RTGETOPTUNION ValueUnion;
3217 RTGETOPTSTATE GetState;
3218 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3219
3220 std::vector < uint32_t > vecPID;
3221 ULONG idSession = UINT32_MAX;
3222 Utf8Str strSessionName;
3223
3224 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3225 {
3226 /* For options that require an argument, ValueUnion has received the value. */
3227 switch (ch)
3228 {
3229 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3230
3231 case 'n': /* Session name (or pattern) */
3232 strSessionName = ValueUnion.psz;
3233 break;
3234
3235 case 'i': /* Session ID */
3236 idSession = ValueUnion.u32;
3237 break;
3238
3239 case VINF_GETOPT_NOT_OPTION:
3240 {
3241 /* Treat every else specified as a PID to kill. */
3242 uint32_t uPid;
3243 int rc = RTStrToUInt32Ex(ValueUnion.psz, NULL, 0, &uPid);
3244 if ( RT_SUCCESS(rc)
3245 && rc != VWRN_TRAILING_CHARS
3246 && rc != VWRN_NUMBER_TOO_BIG
3247 && rc != VWRN_NEGATIVE_UNSIGNED)
3248 {
3249 if (uPid != 0)
3250 {
3251 try
3252 {
3253 vecPID.push_back(uPid);
3254 }
3255 catch (std::bad_alloc &)
3256 {
3257 return RTMsgErrorExit(RTEXITCODE_FAILURE, GuestCtrl::tr("Out of memory"));
3258 }
3259 }
3260 else
3261 return errorSyntax(GuestCtrl::tr("Invalid PID value: 0"));
3262 }
3263 else
3264 return errorSyntax(GuestCtrl::tr("Error parsing PID value: %Rrc"), rc);
3265 break;
3266 }
3267
3268 default:
3269 return errorGetOpt(ch, &ValueUnion);
3270 }
3271 }
3272
3273 if (vecPID.empty())
3274 return errorSyntax(GuestCtrl::tr("At least one PID must be specified to kill!"));
3275
3276 if ( strSessionName.isEmpty()
3277 && idSession == UINT32_MAX)
3278 return errorSyntax(GuestCtrl::tr("No session ID specified!"));
3279
3280 if ( strSessionName.isNotEmpty()
3281 && idSession != UINT32_MAX)
3282 return errorSyntax(GuestCtrl::tr("Either session ID or name (pattern) must be specified"));
3283
3284 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3285 if (rcExit != RTEXITCODE_SUCCESS)
3286 return rcExit;
3287
3288 HRESULT hrc = S_OK;
3289
3290 ComPtr<IGuestSession> pSession;
3291 ComPtr<IGuestProcess> pProcess;
3292 do
3293 {
3294 uint32_t uProcsTerminated = 0;
3295
3296 SafeIfaceArray <IGuestSession> collSessions;
3297 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3298 size_t cSessions = collSessions.size();
3299
3300 uint32_t cSessionsHandled = 0;
3301 for (size_t i = 0; i < cSessions; i++)
3302 {
3303 pSession = collSessions[i];
3304 Assert(!pSession.isNull());
3305
3306 ULONG uID; /* Session ID */
3307 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3308 Bstr strName;
3309 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3310 Utf8Str strNameUtf8(strName); /* Session name */
3311
3312 bool fSessionFound;
3313 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3314 fSessionFound = uID == idSession;
3315 else /* ... or by naming pattern. */
3316 fSessionFound = RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str());
3317 if (fSessionFound)
3318 {
3319 AssertStmt(!pSession.isNull(), break);
3320 cSessionsHandled++;
3321
3322 SafeIfaceArray <IGuestProcess> collProcs;
3323 CHECK_ERROR_BREAK(pSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcs)));
3324
3325 size_t cProcs = collProcs.size();
3326 for (size_t p = 0; p < cProcs; p++)
3327 {
3328 pProcess = collProcs[p];
3329 Assert(!pProcess.isNull());
3330
3331 ULONG uPID; /* Process ID */
3332 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
3333
3334 bool fProcFound = false;
3335 for (size_t a = 0; a < vecPID.size(); a++) /* Slow, but works. */
3336 {
3337 fProcFound = vecPID[a] == uPID;
3338 if (fProcFound)
3339 break;
3340 }
3341
3342 if (fProcFound)
3343 {
3344 if (pCtx->cVerbose)
3345 RTPrintf(GuestCtrl::tr("Terminating process (PID %RU32) (session ID %RU32) ...\n"),
3346 uPID, uID);
3347 CHECK_ERROR_BREAK(pProcess, Terminate());
3348 uProcsTerminated++;
3349 }
3350 else
3351 {
3352 if (idSession != UINT32_MAX)
3353 RTPrintf(GuestCtrl::tr("No matching process(es) for session ID %RU32 found\n"),
3354 idSession);
3355 }
3356
3357 pProcess.setNull();
3358 }
3359
3360 pSession.setNull();
3361 }
3362 }
3363
3364 if (!cSessionsHandled)
3365 RTPrintf(GuestCtrl::tr("No matching session(s) found\n"));
3366
3367 if (uProcsTerminated)
3368 RTPrintf(GuestCtrl::tr("%RU32 process(es) terminated\n", "", uProcsTerminated), uProcsTerminated);
3369
3370 } while (0);
3371
3372 pProcess.setNull();
3373 pSession.setNull();
3374
3375 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3376}
3377
3378
3379static DECLCALLBACK(RTEXITCODE) gctlHandleCloseSession(PGCTLCMDCTX pCtx, int argc, char **argv)
3380{
3381 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3382
3383 enum GETOPTDEF_SESSIONCLOSE
3384 {
3385 GETOPTDEF_SESSIONCLOSE_ALL = 2000
3386 };
3387 static const RTGETOPTDEF s_aOptions[] =
3388 {
3389 GCTLCMD_COMMON_OPTION_DEFS()
3390 { "--all", GETOPTDEF_SESSIONCLOSE_ALL, RTGETOPT_REQ_NOTHING },
3391 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3392 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3393 };
3394
3395 int ch;
3396 RTGETOPTUNION ValueUnion;
3397 RTGETOPTSTATE GetState;
3398 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3399
3400 ULONG idSession = UINT32_MAX;
3401 Utf8Str strSessionName;
3402
3403 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3404 {
3405 /* For options that require an argument, ValueUnion has received the value. */
3406 switch (ch)
3407 {
3408 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3409
3410 case 'n': /* Session name pattern */
3411 strSessionName = ValueUnion.psz;
3412 break;
3413
3414 case 'i': /* Session ID */
3415 idSession = ValueUnion.u32;
3416 break;
3417
3418 case GETOPTDEF_SESSIONCLOSE_ALL:
3419 strSessionName = "*";
3420 break;
3421
3422 case VINF_GETOPT_NOT_OPTION:
3423 /** @todo Supply a CSV list of IDs or patterns to close?
3424 * break; */
3425 default:
3426 return errorGetOpt(ch, &ValueUnion);
3427 }
3428 }
3429
3430 if ( strSessionName.isEmpty()
3431 && idSession == UINT32_MAX)
3432 return errorSyntax(GuestCtrl::tr("No session ID specified!"));
3433
3434 if ( !strSessionName.isEmpty()
3435 && idSession != UINT32_MAX)
3436 return errorSyntax(GuestCtrl::tr("Either session ID or name (pattern) must be specified"));
3437
3438 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3439 if (rcExit != RTEXITCODE_SUCCESS)
3440 return rcExit;
3441
3442 HRESULT hrc = S_OK;
3443
3444 do
3445 {
3446 size_t cSessionsHandled = 0;
3447
3448 SafeIfaceArray <IGuestSession> collSessions;
3449 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3450 size_t cSessions = collSessions.size();
3451
3452 for (size_t i = 0; i < cSessions; i++)
3453 {
3454 ComPtr<IGuestSession> pSession = collSessions[i];
3455 Assert(!pSession.isNull());
3456
3457 ULONG uID; /* Session ID */
3458 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3459 Bstr strName;
3460 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3461 Utf8Str strNameUtf8(strName); /* Session name */
3462
3463 bool fSessionFound;
3464 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3465 fSessionFound = uID == idSession;
3466 else /* ... or by naming pattern. */
3467 fSessionFound = RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str());
3468 if (fSessionFound)
3469 {
3470 cSessionsHandled++;
3471
3472 Assert(!pSession.isNull());
3473 if (pCtx->cVerbose)
3474 RTPrintf(GuestCtrl::tr("Closing guest session ID=#%RU32 \"%s\" ...\n"),
3475 uID, strNameUtf8.c_str());
3476 CHECK_ERROR_BREAK(pSession, Close());
3477 if (pCtx->cVerbose)
3478 RTPrintf(GuestCtrl::tr("Guest session successfully closed\n"));
3479
3480 pSession.setNull();
3481 }
3482 }
3483
3484 if (!cSessionsHandled)
3485 {
3486 RTPrintf(GuestCtrl::tr("No guest session(s) found\n"));
3487 hrc = E_ABORT; /* To set exit code accordingly. */
3488 }
3489
3490 } while (0);
3491
3492 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3493}
3494
3495
3496static DECLCALLBACK(RTEXITCODE) gctlHandleWatch(PGCTLCMDCTX pCtx, int argc, char **argv)
3497{
3498 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3499
3500 /*
3501 * Parse arguments.
3502 */
3503 static const RTGETOPTDEF s_aOptions[] =
3504 {
3505 GCTLCMD_COMMON_OPTION_DEFS()
3506 { "--timeout", 't', RTGETOPT_REQ_UINT32 }
3507 };
3508
3509 uint32_t cMsTimeout = RT_INDEFINITE_WAIT;
3510
3511 int ch;
3512 RTGETOPTUNION ValueUnion;
3513 RTGETOPTSTATE GetState;
3514 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3515
3516 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3517 {
3518 /* For options that require an argument, ValueUnion has received the value. */
3519 switch (ch)
3520 {
3521 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3522
3523 case 't': /* Timeout */
3524 cMsTimeout = ValueUnion.u32;
3525 break;
3526
3527 case VINF_GETOPT_NOT_OPTION:
3528 default:
3529 return errorGetOpt(ch, &ValueUnion);
3530 }
3531 }
3532
3533 /** @todo Specify categories to watch for. */
3534
3535 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3536 if (rcExit != RTEXITCODE_SUCCESS)
3537 return rcExit;
3538
3539 HRESULT hrc;
3540
3541 try
3542 {
3543 ComObjPtr<GuestEventListenerImpl> pGuestListener;
3544 do
3545 {
3546 /* Listener creation. */
3547 pGuestListener.createObject();
3548 pGuestListener->init(new GuestEventListener());
3549
3550 /* Register for IGuest events. */
3551 ComPtr<IEventSource> es;
3552 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
3553 com::SafeArray<VBoxEventType_T> eventTypes;
3554 eventTypes.push_back(VBoxEventType_OnGuestSessionRegistered);
3555 /** @todo Also register for VBoxEventType_OnGuestUserStateChanged on demand? */
3556 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
3557 true /* Active listener */));
3558 /* Note: All other guest control events have to be registered
3559 * as their corresponding objects appear. */
3560
3561 } while (0);
3562
3563 if (pCtx->cVerbose)
3564 RTPrintf(GuestCtrl::tr("Waiting for events ...\n"));
3565
3566 RTMSINTERVAL tsStart = RTTimeMilliTS();
3567 while (RTTimeMilliTS() - tsStart < cMsTimeout)
3568 {
3569 /* Wait for the global signal semaphore getting signalled. */
3570 int vrc = RTSemEventWait(g_SemEventGuestCtrlCanceled, 100 /* ms */);
3571 if (RT_FAILURE(vrc))
3572 {
3573 if (vrc != VERR_TIMEOUT)
3574 {
3575 RTPrintf(GuestCtrl::tr("Waiting failed with %Rrc\n"), vrc);
3576 break;
3577 }
3578 }
3579 else
3580 break;
3581
3582 /* We need to process the event queue, otherwise our registered listeners won't get any events. */
3583 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
3584 }
3585
3586 if (!pGuestListener.isNull())
3587 {
3588 /* Guest callback unregistration. */
3589 ComPtr<IEventSource> pES;
3590 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
3591 if (!pES.isNull())
3592 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
3593 pGuestListener.setNull();
3594 }
3595 }
3596 catch (std::bad_alloc &)
3597 {
3598 hrc = E_OUTOFMEMORY;
3599 }
3600
3601 return SUCCEEDED(hrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3602}
3603
3604/**
3605 * Access the guest control store.
3606 *
3607 * @returns program exit code.
3608 * @note see the command line API description for parameters
3609 */
3610RTEXITCODE handleGuestControl(HandlerArg *pArg)
3611{
3612 AssertPtr(pArg);
3613
3614 /*
3615 * Command definitions.
3616 */
3617 static const GCTLCMDDEF s_aCmdDefs[] =
3618 {
3619 { "run", gctlHandleRun, HELP_SCOPE_GUESTCONTROL_RUN, 0 },
3620 { "start", gctlHandleStart, HELP_SCOPE_GUESTCONTROL_START, 0 },
3621 { "copyfrom", gctlHandleCopyFrom, HELP_SCOPE_GUESTCONTROL_COPYFROM_HOSTDEST, 0 },
3622 { "copyto", gctlHandleCopyTo, HELP_SCOPE_GUESTCONTROL_COPYTO_HOSTDEST, 0 },
3623
3624 { "mkdir", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3625 { "md", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3626 { "createdirectory", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3627 { "createdir", gctrlHandleMkDir, HELP_SCOPE_GUESTCONTROL_MKDIR, 0 },
3628
3629 { "rmdir", gctlHandleRmDir, HELP_SCOPE_GUESTCONTROL_RMDIR, 0 },
3630 { "removedir", gctlHandleRmDir, HELP_SCOPE_GUESTCONTROL_RMDIR, 0 },
3631 { "removedirectory", gctlHandleRmDir, HELP_SCOPE_GUESTCONTROL_RMDIR, 0 },
3632
3633 { "rm", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3634 { "removefile", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3635 { "erase", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3636 { "del", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3637 { "delete", gctlHandleRm, HELP_SCOPE_GUESTCONTROL_RM, 0 },
3638
3639 { "mv", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3640 { "move", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3641 { "ren", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3642 { "rename", gctlHandleMv, HELP_SCOPE_GUESTCONTROL_MV, 0 },
3643
3644 { "mktemp", gctlHandleMkTemp, HELP_SCOPE_GUESTCONTROL_MKTEMP, 0 },
3645 { "createtemp", gctlHandleMkTemp, HELP_SCOPE_GUESTCONTROL_MKTEMP, 0 },
3646 { "createtemporary", gctlHandleMkTemp, HELP_SCOPE_GUESTCONTROL_MKTEMP, 0 },
3647
3648 { "stat", gctlHandleStat, HELP_SCOPE_GUESTCONTROL_STAT, 0 },
3649
3650 { "closeprocess", gctlHandleCloseProcess, HELP_SCOPE_GUESTCONTROL_CLOSEPROCESS, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER },
3651 { "closesession", gctlHandleCloseSession, HELP_SCOPE_GUESTCONTROL_CLOSESESSION, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER },
3652 { "list", gctlHandleList, HELP_SCOPE_GUESTCONTROL_LIST, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER },
3653 { "watch", gctlHandleWatch, HELP_SCOPE_GUESTCONTROL_WATCH, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3654
3655 {"updateguestadditions",gctlHandleUpdateAdditions, HELP_SCOPE_GUESTCONTROL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3656 { "updateadditions", gctlHandleUpdateAdditions, HELP_SCOPE_GUESTCONTROL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3657 { "updatega", gctlHandleUpdateAdditions, HELP_SCOPE_GUESTCONTROL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3658
3659 { "waitrunlevel", gctlHandleWaitRunLevel, HELP_SCOPE_GUESTCONTROL_WAITRUNLEVEL, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3660 { "waitforrunlevel", gctlHandleWaitRunLevel, HELP_SCOPE_GUESTCONTROL_WAITRUNLEVEL, GCTLCMDCTX_F_SESSION_ANONYMOUS },
3661 };
3662
3663 /*
3664 * VBoxManage guestcontrol [common-options] <VM> [common-options] <sub-command> ...
3665 *
3666 * Parse common options and VM name until we find a sub-command. Allowing
3667 * the user to put the user and password related options before the
3668 * sub-command makes it easier to edit the command line when doing several
3669 * operations with the same guest user account. (Accidentally, it also
3670 * makes the syntax diagram shorter and easier to read.)
3671 */
3672 GCTLCMDCTX CmdCtx;
3673 RTEXITCODE rcExit = gctrCmdCtxInit(&CmdCtx, pArg);
3674 if (rcExit == RTEXITCODE_SUCCESS)
3675 {
3676 static const RTGETOPTDEF s_CommonOptions[] = { GCTLCMD_COMMON_OPTION_DEFS() };
3677
3678 int ch;
3679 RTGETOPTUNION ValueUnion;
3680 RTGETOPTSTATE GetState;
3681 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_CommonOptions, RT_ELEMENTS(s_CommonOptions), 0, 0 /* No sorting! */);
3682
3683 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3684 {
3685 switch (ch)
3686 {
3687 GCTLCMD_COMMON_OPTION_CASES(&CmdCtx, ch, &ValueUnion);
3688
3689 case VINF_GETOPT_NOT_OPTION:
3690 /* First comes the VM name or UUID. */
3691 if (!CmdCtx.pszVmNameOrUuid)
3692 CmdCtx.pszVmNameOrUuid = ValueUnion.psz;
3693 /*
3694 * The sub-command is next. Look it up and invoke it.
3695 * Note! Currently no warnings about user/password options (like we'll do later on)
3696 * for GCTLCMDCTX_F_SESSION_ANONYMOUS commands. No reason to be too pedantic.
3697 */
3698 else
3699 {
3700 const char *pszCmd = ValueUnion.psz;
3701 uint32_t iCmd;
3702 for (iCmd = 0; iCmd < RT_ELEMENTS(s_aCmdDefs); iCmd++)
3703 if (strcmp(s_aCmdDefs[iCmd].pszName, pszCmd) == 0)
3704 {
3705 CmdCtx.pCmdDef = &s_aCmdDefs[iCmd];
3706
3707 setCurrentSubcommand(s_aCmdDefs[iCmd].fSubcommandScope);
3708 rcExit = s_aCmdDefs[iCmd].pfnHandler(&CmdCtx, pArg->argc - GetState.iNext + 1,
3709 &pArg->argv[GetState.iNext - 1]);
3710
3711 gctlCtxTerm(&CmdCtx);
3712 return rcExit;
3713 }
3714 return errorSyntax(GuestCtrl::tr("Unknown sub-command: '%s'"), pszCmd);
3715 }
3716 break;
3717
3718 default:
3719 return errorGetOpt(ch, &ValueUnion);
3720 }
3721 }
3722 if (CmdCtx.pszVmNameOrUuid)
3723 rcExit = errorSyntax(GuestCtrl::tr("Missing sub-command"));
3724 else
3725 rcExit = errorSyntax(GuestCtrl::tr("Missing VM name and sub-command"));
3726 }
3727 return rcExit;
3728}
Note: See TracBrowser for help on using the repository browser.

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