VirtualBox

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

Last change on this file since 79546 was 79257, checked in by vboxsync, 6 years ago

VBoxManageGuestCtrl.cpp: Must stop waiting for the 'Start' event once it has been received. r131419 corrected the special workaround in main that previously made it 'work'. bugref:9320

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