VirtualBox

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

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

Main,Frontends: s/FileName/Filename/g (API); Took a shot a completing the code for populating IGuestFsObjInfo. bugref:9320 [build fix]

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 130.3 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 75927 2018-12-03 21:55:52Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010-2018 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 command usage flags. */
133 uint32_t fCmdUsage;
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, uint32_t uSubCmd)
230{
231 const uint32_t fAnonSubCmds = USAGE_GSTCTRL_CLOSESESSION
232 | USAGE_GSTCTRL_LIST
233 | USAGE_GSTCTRL_CLOSEPROCESS
234 | USAGE_GSTCTRL_CLOSESESSION
235 | USAGE_GSTCTRL_UPDATEGA
236 | USAGE_GSTCTRL_WATCH;
237
238 /* 0 1 2 3 4 5 6 7 8XXXXXXXXXX */
239 /* 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 */
240 if (~fAnonSubCmds & uSubCmd)
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, uSubCmd == ~0U ? "\n" : "");
246 if (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 (uSubCmd & USAGE_GSTCTRL_RMDIR)
294 RTStrmPrintf(pStrm,
295 " rmdir|removedir[ectory] [common-options]\n"
296 " [-R|--recursive]\n"
297 " <guest directory> [...]\n"
298 "\n");
299 if (uSubCmd & USAGE_GSTCTRL_RM)
300 RTStrmPrintf(pStrm,
301 " removefile|rm [common-options] [-f|--force]\n"
302 " <guest file> [...]\n"
303 "\n");
304 if (uSubCmd & USAGE_GSTCTRL_MV)
305 RTStrmPrintf(pStrm,
306 " mv|move|ren[ame] [common-options]\n"
307 " <source> [source1 [...]] <dest>\n"
308 "\n");
309 if (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 & uSubCmd)
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, uSubCmd == ~0U ? "\n" : "");
331 if (uSubCmd & USAGE_GSTCTRL_LIST)
332 RTStrmPrintf(pStrm,
333 " list <all|sessions|processes|files> [common-opts]\n"
334 "\n");
335 if (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 (uSubCmd & USAGE_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 (uSubCmd & USAGE_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->fCmdUsage, "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, USAGE_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, USAGE_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, USAGE_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 switch (waitResult)
1501 {
1502 case ProcessWaitResult_Start:
1503 fCompletedStartCmd = fCompleted = !fRunCmd; /* Only wait for startup if the 'start' command. */
1504 break;
1505 case ProcessWaitResult_StdOut:
1506 fReadStdOut = true;
1507 break;
1508 case ProcessWaitResult_StdErr:
1509 fReadStdErr = true;
1510 break;
1511 case ProcessWaitResult_Terminate:
1512 if (pCtx->cVerbose)
1513 RTPrintf("Process terminated\n");
1514 /* Process terminated, we're done. */
1515 fCompleted = true;
1516 break;
1517 case ProcessWaitResult_WaitFlagNotSupported:
1518 /* The guest does not support waiting for stdout/err, so
1519 * yield to reduce the CPU load due to busy waiting. */
1520 RTThreadYield();
1521 fReadStdOut = fReadStdErr = true;
1522 break;
1523 case ProcessWaitResult_Timeout:
1524 {
1525 /** @todo It is really unclear whether we will get stuck with the timeout
1526 * result here if the guest side times out the process and fails to
1527 * kill the process... To be on the save side, double the IPC and
1528 * check the process status every time we time out. */
1529 ProcessStatus_T enmProcStatus;
1530 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&enmProcStatus));
1531 if ( enmProcStatus == ProcessStatus_TimedOutKilled
1532 || enmProcStatus == ProcessStatus_TimedOutAbnormally)
1533 fCompleted = true;
1534 fReadStdOut = fReadStdErr = true;
1535 break;
1536 }
1537 case ProcessWaitResult_Status:
1538 /* ignore. */
1539 break;
1540 case ProcessWaitResult_Error:
1541 /* waitFor is dead in the water, I think, so better leave the loop. */
1542 vrc = VERR_CALLBACK_RETURN;
1543 break;
1544
1545 case ProcessWaitResult_StdIn: AssertFailed(); /* did ask for this! */ break;
1546 case ProcessWaitResult_None: AssertFailed(); /* used. */ break;
1547 default: AssertFailed(); /* huh? */ break;
1548 }
1549
1550 if (g_fGuestCtrlCanceled)
1551 break;
1552
1553 /*
1554 * Pump output as needed.
1555 */
1556 if (fReadStdOut)
1557 {
1558 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1559 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdOut, 1 /* StdOut */, cMsTimeLeft);
1560 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1561 vrc = vrc2;
1562 fReadStdOut = false;
1563 }
1564 if (fReadStdErr)
1565 {
1566 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1567 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdErr, 2 /* StdErr */, cMsTimeLeft);
1568 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1569 vrc = vrc2;
1570 fReadStdErr = false;
1571 }
1572 if ( RT_FAILURE(vrc)
1573 || g_fGuestCtrlCanceled)
1574 break;
1575
1576 /*
1577 * Process events before looping.
1578 */
1579 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
1580 } /* while */
1581
1582 /*
1583 * Report status back to the user.
1584 */
1585 if (g_fGuestCtrlCanceled)
1586 {
1587 if (pCtx->cVerbose)
1588 RTPrintf("Process execution aborted!\n");
1589 rcExit = EXITCODEEXEC_CANCELED;
1590 }
1591 else if (fCompletedStartCmd)
1592 {
1593 if (pCtx->cVerbose)
1594 RTPrintf("Process successfully started!\n");
1595 rcExit = RTEXITCODE_SUCCESS;
1596 }
1597 else if (fCompleted)
1598 {
1599 ProcessStatus_T procStatus;
1600 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&procStatus));
1601 if ( procStatus == ProcessStatus_TerminatedNormally
1602 || procStatus == ProcessStatus_TerminatedAbnormally
1603 || procStatus == ProcessStatus_TerminatedSignal)
1604 {
1605 LONG lExitCode;
1606 CHECK_ERROR_BREAK(pProcess, COMGETTER(ExitCode)(&lExitCode));
1607 if (pCtx->cVerbose)
1608 RTPrintf("Exit code=%u (Status=%u [%s])\n",
1609 lExitCode, procStatus, gctlProcessStatusToText(procStatus));
1610
1611 rcExit = gctlRunCalculateExitCode(procStatus, lExitCode, true /*fReturnExitCodes*/);
1612 }
1613 else if ( procStatus == ProcessStatus_TimedOutKilled
1614 || procStatus == ProcessStatus_TimedOutAbnormally)
1615 {
1616 if (pCtx->cVerbose)
1617 RTPrintf("Process timed out (guest side) and %s\n",
1618 procStatus == ProcessStatus_TimedOutAbnormally
1619 ? "failed to terminate so far" : "was terminated");
1620 rcExit = EXITCODEEXEC_TIMEOUT;
1621 }
1622 else
1623 {
1624 if (pCtx->cVerbose)
1625 RTPrintf("Process now is in status [%s] (unexpected)\n", gctlProcessStatusToText(procStatus));
1626 rcExit = RTEXITCODE_FAILURE;
1627 }
1628 }
1629 else if (RT_FAILURE_NP(vrc))
1630 {
1631 if (pCtx->cVerbose)
1632 RTPrintf("Process monitor loop quit with vrc=%Rrc\n", vrc);
1633 rcExit = RTEXITCODE_FAILURE;
1634 }
1635 else
1636 {
1637 if (pCtx->cVerbose)
1638 RTPrintf("Process monitor loop timed out\n");
1639 rcExit = EXITCODEEXEC_TIMEOUT;
1640 }
1641
1642 } while (0);
1643 }
1644 catch (std::bad_alloc &)
1645 {
1646 rc = E_OUTOFMEMORY;
1647 }
1648
1649 /*
1650 * Decide what to do with the guest session.
1651 *
1652 * If it's the 'start' command where detach the guest process after
1653 * starting, don't close the guest session it is part of, except on
1654 * failure or ctrl-c.
1655 *
1656 * For the 'run' command the guest process quits with us.
1657 */
1658 if (!fRunCmd && SUCCEEDED(rc) && !g_fGuestCtrlCanceled)
1659 pCtx->fDetachGuestSession = true;
1660
1661 /* Make sure we return failure on failure. */
1662 if (FAILED(rc) && rcExit == RTEXITCODE_SUCCESS)
1663 rcExit = RTEXITCODE_FAILURE;
1664 return rcExit;
1665}
1666
1667
1668static DECLCALLBACK(RTEXITCODE) gctlHandleRun(PGCTLCMDCTX pCtx, int argc, char **argv)
1669{
1670 return gctlHandleRunCommon(pCtx, argc, argv, true /*fRunCmd*/, USAGE_GSTCTRL_RUN);
1671}
1672
1673
1674static DECLCALLBACK(RTEXITCODE) gctlHandleStart(PGCTLCMDCTX pCtx, int argc, char **argv)
1675{
1676 return gctlHandleRunCommon(pCtx, argc, argv, false /*fRunCmd*/, USAGE_GSTCTRL_START);
1677}
1678
1679
1680static RTEXITCODE gctlHandleCopy(PGCTLCMDCTX pCtx, int argc, char **argv, bool fHostToGuest)
1681{
1682 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1683
1684 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
1685 * is much better (partly because it is much simpler of course). The main
1686 * arguments against this is that (1) all but two options conflicts with
1687 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
1688 * done windows CMD style (though not in a 100% compatible way), and (3)
1689 * that only one source is allowed - efficiently sabotaging default
1690 * wildcard expansion by a unix shell. The best solution here would be
1691 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
1692
1693 /*
1694 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1695 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1696 * does in here.
1697 */
1698 enum GETOPTDEF_COPY
1699 {
1700 GETOPTDEF_COPY_FOLLOW = 1000,
1701 GETOPTDEF_COPY_TARGETDIR
1702 };
1703 static const RTGETOPTDEF s_aOptions[] =
1704 {
1705 GCTLCMD_COMMON_OPTION_DEFS()
1706 { "--follow", GETOPTDEF_COPY_FOLLOW, RTGETOPT_REQ_NOTHING },
1707 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1708 { "--target-directory", GETOPTDEF_COPY_TARGETDIR, RTGETOPT_REQ_STRING }
1709 };
1710
1711 int ch;
1712 RTGETOPTUNION ValueUnion;
1713 RTGETOPTSTATE GetState;
1714 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1715
1716 bool fDstMustBeDir = false;
1717 const char *pszDst = NULL;
1718 bool fFollow = false;
1719 bool fRecursive = false;
1720 uint32_t uUsage = fHostToGuest ? USAGE_GSTCTRL_COPYTO : USAGE_GSTCTRL_COPYFROM;
1721
1722 int vrc = VINF_SUCCESS;
1723 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
1724 && ch != VINF_GETOPT_NOT_OPTION)
1725 {
1726 /* For options that require an argument, ValueUnion has received the value. */
1727 switch (ch)
1728 {
1729 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1730
1731 case GETOPTDEF_COPY_FOLLOW:
1732 fFollow = true;
1733 break;
1734
1735 case 'R': /* Recursive processing */
1736 fRecursive = true;
1737 break;
1738
1739 case GETOPTDEF_COPY_TARGETDIR:
1740 pszDst = ValueUnion.psz;
1741 fDstMustBeDir = true;
1742 break;
1743
1744 default:
1745 return errorGetOptEx(USAGE_GUESTCONTROL, uUsage, ch, &ValueUnion);
1746 }
1747 }
1748
1749 char **papszSources = RTGetOptNonOptionArrayPtr(&GetState);
1750 size_t cSources = &argv[argc] - papszSources;
1751
1752 if (!cSources)
1753 return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No sources specified!");
1754
1755 /* Unless a --target-directory is given, the last argument is the destination, so
1756 bump it from the source list. */
1757 if (pszDst == NULL && cSources >= 2)
1758 pszDst = papszSources[--cSources];
1759
1760 if (pszDst == NULL)
1761 return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No destination specified!");
1762
1763 char szAbsDst[RTPATH_MAX];
1764 if (!fHostToGuest)
1765 {
1766 vrc = RTPathAbs(pszDst, szAbsDst, sizeof(szAbsDst));
1767 if (RT_SUCCESS(vrc))
1768 pszDst = szAbsDst;
1769 else
1770 return RTMsgErrorExitFailure("RTPathAbs failed on '%s': %Rrc", pszDst, vrc);
1771 }
1772
1773 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
1774 if (rcExit != RTEXITCODE_SUCCESS)
1775 return rcExit;
1776
1777 /*
1778 * Done parsing arguments, do some more preparations.
1779 */
1780 if (pCtx->cVerbose)
1781 {
1782 if (fHostToGuest)
1783 RTPrintf("Copying from host to guest ...\n");
1784 else
1785 RTPrintf("Copying from guest to host ...\n");
1786 }
1787
1788 HRESULT rc = S_OK;
1789 ComPtr<IProgress> pProgress;
1790/** @todo r=bird: This codes does nothing to handle the case where there are
1791 * multiple sources. You need to do serveral thing before thats handled
1792 * correctly. For starters the progress object handling needs to be moved
1793 * inside the loop. Next you need to check what the destination is, because you
1794 * can only copy multiple source files/directories to another directory. You
1795 * actually need to check whether the target exists and is a directory
1796 * regardless of you have 1 or 10 source files/dirs.
1797 *
1798 * Btw. the original approach to error handling here was APPALING. If some file
1799 * couldn't be stat'ed or if it was a file/directory, you only spat out messages
1800 * in verbose mode and never set the status code.
1801 *
1802 * The handling of the wildcard filtering expressions in sources was also just
1803 * skipped. I've corrected this, but you still need to make up your mind wrt
1804 * wildcards or not.
1805 *
1806 * Update: I've kicked out the whole SourceFileEntry/vecSources stuff as we can
1807 * use argv directly without any unnecessary copying. You just have to
1808 * look for the wildcards inside this loop instead.
1809 */
1810 NOREF(fDstMustBeDir);
1811 if (cSources != 1)
1812 return RTMsgErrorExitFailure("Only one source file or directory at the moment.");
1813 for (size_t iSrc = 0; iSrc < cSources; iSrc++)
1814 {
1815 const char *pszSource = papszSources[iSrc];
1816
1817 /* Check if the source contains any wilecards in the last component, if so we
1818 don't know how to deal with it yet and refuse. */
1819 const char *pszSrcFinalComp = RTPathFilename(pszSource);
1820 if (pszSrcFinalComp && strpbrk(pszSrcFinalComp, "*?"))
1821 rcExit = RTMsgErrorExitFailure("Skipping '%s' because wildcard expansion isn't implemented yet\n", pszSource);
1822 else if (fHostToGuest)
1823 {
1824 /*
1825 * Source is host, destiation guest.
1826 */
1827 char szAbsSrc[RTPATH_MAX];
1828 vrc = RTPathAbs(pszSource, szAbsSrc, sizeof(szAbsSrc));
1829 if (RT_SUCCESS(vrc))
1830 {
1831 RTFSOBJINFO ObjInfo;
1832 vrc = RTPathQueryInfo(szAbsSrc, &ObjInfo, RTFSOBJATTRADD_NOTHING);
1833 if (RT_SUCCESS(vrc))
1834 {
1835 if (RTFS_IS_FILE(ObjInfo.Attr.fMode))
1836 {
1837 if (pCtx->cVerbose)
1838 RTPrintf("File '%s' -> '%s'\n", szAbsSrc, pszDst);
1839
1840 SafeArray<FileCopyFlag_T> copyFlags;
1841 rc = pCtx->pGuestSession->FileCopyToGuest(Bstr(szAbsSrc).raw(), Bstr(pszDst).raw(),
1842 ComSafeArrayAsInParam(copyFlags), pProgress.asOutParam());
1843 }
1844 else if (RTFS_IS_DIRECTORY(ObjInfo.Attr.fMode))
1845 {
1846 if (pCtx->cVerbose)
1847 RTPrintf("Directory '%s' -> '%s'\n", szAbsSrc, pszDst);
1848
1849 SafeArray<DirectoryCopyFlag_T> copyFlags;
1850 copyFlags.push_back(DirectoryCopyFlag_CopyIntoExisting);
1851 rc = pCtx->pGuestSession->DirectoryCopyToGuest(Bstr(szAbsSrc).raw(), Bstr(pszDst).raw(),
1852 ComSafeArrayAsInParam(copyFlags), pProgress.asOutParam());
1853 }
1854 else
1855 rcExit = RTMsgErrorExitFailure("Not a file or directory: %s\n", szAbsSrc);
1856 }
1857 else
1858 rcExit = RTMsgErrorExitFailure("RTPathQueryInfo failed on '%s': %Rrc", szAbsSrc, vrc);
1859 }
1860 else
1861 rcExit = RTMsgErrorExitFailure("RTPathAbs failed on '%s': %Rrc", pszSource, vrc);
1862 }
1863 else
1864 {
1865 /*
1866 * Source guest, destination host.
1867 */
1868 /* We need to query the source type on the guest first in order to know which copy flavor we need. */
1869 ComPtr<IGuestFsObjInfo> pFsObjInfo;
1870 rc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(pszSource).raw(), TRUE /* fFollowSymlinks */, pFsObjInfo.asOutParam());
1871 if (SUCCEEDED(rc))
1872 {
1873 FsObjType_T enmObjType;
1874 CHECK_ERROR(pFsObjInfo,COMGETTER(Type)(&enmObjType));
1875 if (SUCCEEDED(rc))
1876 {
1877 /* Take action according to source file. */
1878 if (enmObjType == FsObjType_Directory)
1879 {
1880 if (pCtx->cVerbose)
1881 RTPrintf("Directory '%s' -> '%s'\n", pszSource, pszDst);
1882
1883 SafeArray<DirectoryCopyFlag_T> aCopyFlags;
1884 aCopyFlags.push_back(DirectoryCopyFlag_CopyIntoExisting);
1885 rc = pCtx->pGuestSession->DirectoryCopyFromGuest(Bstr(pszSource).raw(), Bstr(pszDst).raw(),
1886 ComSafeArrayAsInParam(aCopyFlags), pProgress.asOutParam());
1887 }
1888 else if (enmObjType == FsObjType_File)
1889 {
1890 if (pCtx->cVerbose)
1891 RTPrintf("File '%s' -> '%s'\n", pszSource, pszDst);
1892
1893 SafeArray<FileCopyFlag_T> aCopyFlags;
1894 rc = pCtx->pGuestSession->FileCopyFromGuest(Bstr(pszSource).raw(), Bstr(pszDst).raw(),
1895 ComSafeArrayAsInParam(aCopyFlags), pProgress.asOutParam());
1896 }
1897 else
1898 rcExit = RTMsgErrorExitFailure("Not a file or directory: %s\n", pszSource);
1899 }
1900 else
1901 rcExit = RTEXITCODE_FAILURE;
1902 }
1903 else
1904 rcExit = RTMsgErrorExitFailure("FsObjQueryInfo failed on '%s': %Rhrc", pszSource, rc);
1905 }
1906 }
1907
1908 if (FAILED(rc))
1909 {
1910 vrc = gctlPrintError(pCtx->pGuestSession, COM_IIDOF(IGuestSession));
1911 }
1912 else if (pProgress.isNotNull())
1913 {
1914 if (pCtx->cVerbose)
1915 rc = showProgress(pProgress);
1916 else
1917 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
1918 if (SUCCEEDED(rc))
1919 CHECK_PROGRESS_ERROR(pProgress, ("File copy failed"));
1920 vrc = gctlPrintProgressError(pProgress);
1921 }
1922 if (RT_FAILURE(vrc))
1923 rcExit = RTEXITCODE_FAILURE;
1924
1925 return rcExit;
1926}
1927
1928static DECLCALLBACK(RTEXITCODE) gctlHandleCopyFrom(PGCTLCMDCTX pCtx, int argc, char **argv)
1929{
1930 return gctlHandleCopy(pCtx, argc, argv, false /* Guest to host */);
1931}
1932
1933static DECLCALLBACK(RTEXITCODE) gctlHandleCopyTo(PGCTLCMDCTX pCtx, int argc, char **argv)
1934{
1935 return gctlHandleCopy(pCtx, argc, argv, true /* Host to guest */);
1936}
1937
1938static DECLCALLBACK(RTEXITCODE) gctrlHandleMkDir(PGCTLCMDCTX pCtx, int argc, char **argv)
1939{
1940 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1941
1942 static const RTGETOPTDEF s_aOptions[] =
1943 {
1944 GCTLCMD_COMMON_OPTION_DEFS()
1945 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
1946 { "--parents", 'P', RTGETOPT_REQ_NOTHING }
1947 };
1948
1949 int ch;
1950 RTGETOPTUNION ValueUnion;
1951 RTGETOPTSTATE GetState;
1952 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1953
1954 SafeArray<DirectoryCreateFlag_T> aDirCreateFlags;
1955 uint32_t fDirMode = 0; /* Default mode. */
1956 uint32_t cDirsCreated = 0;
1957 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1958
1959 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1960 {
1961 /* For options that require an argument, ValueUnion has received the value. */
1962 switch (ch)
1963 {
1964 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1965
1966 case 'm': /* Mode */
1967 fDirMode = ValueUnion.u32;
1968 break;
1969
1970 case 'P': /* Create parents */
1971 aDirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1972 break;
1973
1974 case VINF_GETOPT_NOT_OPTION:
1975 if (cDirsCreated == 0)
1976 {
1977 /*
1978 * First non-option - no more options now.
1979 */
1980 rcExit = gctlCtxPostOptionParsingInit(pCtx);
1981 if (rcExit != RTEXITCODE_SUCCESS)
1982 return rcExit;
1983 if (pCtx->cVerbose)
1984 RTPrintf("Creating %RU32 directories...\n", argc - GetState.iNext + 1);
1985 }
1986 if (g_fGuestCtrlCanceled)
1987 return RTMsgErrorExit(RTEXITCODE_FAILURE, "mkdir was interrupted by Ctrl-C (%u left)\n",
1988 argc - GetState.iNext + 1);
1989
1990 /*
1991 * Create the specified directory.
1992 *
1993 * On failure we'll change the exit status to failure and
1994 * continue with the next directory that needs creating. We do
1995 * this because we only create new things, and because this is
1996 * how /bin/mkdir works on unix.
1997 */
1998 cDirsCreated++;
1999 if (pCtx->cVerbose)
2000 RTPrintf("Creating directory \"%s\" ...\n", ValueUnion.psz);
2001 try
2002 {
2003 HRESULT rc;
2004 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreate(Bstr(ValueUnion.psz).raw(),
2005 fDirMode, ComSafeArrayAsInParam(aDirCreateFlags)));
2006 if (FAILED(rc))
2007 rcExit = RTEXITCODE_FAILURE;
2008 }
2009 catch (std::bad_alloc &)
2010 {
2011 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
2012 }
2013 break;
2014
2015 default:
2016 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKDIR, ch, &ValueUnion);
2017 }
2018 }
2019
2020 if (!cDirsCreated)
2021 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKDIR, "No directory to create specified!");
2022 return rcExit;
2023}
2024
2025
2026static DECLCALLBACK(RTEXITCODE) gctlHandleRmDir(PGCTLCMDCTX pCtx, int argc, char **argv)
2027{
2028 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2029
2030 static const RTGETOPTDEF s_aOptions[] =
2031 {
2032 GCTLCMD_COMMON_OPTION_DEFS()
2033 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
2034 };
2035
2036 int ch;
2037 RTGETOPTUNION ValueUnion;
2038 RTGETOPTSTATE GetState;
2039 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2040
2041 bool fRecursive = false;
2042 uint32_t cDirRemoved = 0;
2043 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2044
2045 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2046 {
2047 /* For options that require an argument, ValueUnion has received the value. */
2048 switch (ch)
2049 {
2050 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2051
2052 case 'R':
2053 fRecursive = true;
2054 break;
2055
2056 case VINF_GETOPT_NOT_OPTION:
2057 {
2058 if (cDirRemoved == 0)
2059 {
2060 /*
2061 * First non-option - no more options now.
2062 */
2063 rcExit = gctlCtxPostOptionParsingInit(pCtx);
2064 if (rcExit != RTEXITCODE_SUCCESS)
2065 return rcExit;
2066 if (pCtx->cVerbose)
2067 RTPrintf("Removing %RU32 directorie%s(s)...\n", argc - GetState.iNext + 1, fRecursive ? "tree" : "");
2068 }
2069 if (g_fGuestCtrlCanceled)
2070 return RTMsgErrorExit(RTEXITCODE_FAILURE, "rmdir was interrupted by Ctrl-C (%u left)\n",
2071 argc - GetState.iNext + 1);
2072
2073 cDirRemoved++;
2074 HRESULT rc;
2075 if (!fRecursive)
2076 {
2077 /*
2078 * Remove exactly one directory.
2079 */
2080 if (pCtx->cVerbose)
2081 RTPrintf("Removing directory \"%s\" ...\n", ValueUnion.psz);
2082 try
2083 {
2084 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemove(Bstr(ValueUnion.psz).raw()));
2085 }
2086 catch (std::bad_alloc &)
2087 {
2088 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
2089 }
2090 }
2091 else
2092 {
2093 /*
2094 * Remove the directory and anything under it, that means files
2095 * and everything. This is in the tradition of the Windows NT
2096 * CMD.EXE "rmdir /s" operation, a tradition which jpsoft's TCC
2097 * strongly warns against (and half-ways questions the sense of).
2098 */
2099 if (pCtx->cVerbose)
2100 RTPrintf("Recursively removing directory \"%s\" ...\n", ValueUnion.psz);
2101 try
2102 {
2103 /** @todo Make flags configurable. */
2104 com::SafeArray<DirectoryRemoveRecFlag_T> aRemRecFlags;
2105 aRemRecFlags.push_back(DirectoryRemoveRecFlag_ContentAndDir);
2106
2107 ComPtr<IProgress> ptrProgress;
2108 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemoveRecursive(Bstr(ValueUnion.psz).raw(),
2109 ComSafeArrayAsInParam(aRemRecFlags),
2110 ptrProgress.asOutParam()));
2111 if (SUCCEEDED(rc))
2112 {
2113 if (pCtx->cVerbose)
2114 rc = showProgress(ptrProgress);
2115 else
2116 rc = ptrProgress->WaitForCompletion(-1 /* indefinitely */);
2117 if (SUCCEEDED(rc))
2118 CHECK_PROGRESS_ERROR(ptrProgress, ("Directory deletion failed"));
2119 ptrProgress.setNull();
2120 }
2121 }
2122 catch (std::bad_alloc &)
2123 {
2124 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory during recursive rmdir\n");
2125 }
2126 }
2127
2128 /*
2129 * This command returns immediately on failure since it's destructive in nature.
2130 */
2131 if (FAILED(rc))
2132 return RTEXITCODE_FAILURE;
2133 break;
2134 }
2135
2136 default:
2137 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RMDIR, ch, &ValueUnion);
2138 }
2139 }
2140
2141 if (!cDirRemoved)
2142 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RMDIR, "No directory to remove specified!");
2143 return rcExit;
2144}
2145
2146static DECLCALLBACK(RTEXITCODE) gctlHandleRm(PGCTLCMDCTX pCtx, int argc, char **argv)
2147{
2148 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2149
2150 static const RTGETOPTDEF s_aOptions[] =
2151 {
2152 GCTLCMD_COMMON_OPTION_DEFS()
2153 { "--force", 'f', RTGETOPT_REQ_NOTHING, },
2154 };
2155
2156 int ch;
2157 RTGETOPTUNION ValueUnion;
2158 RTGETOPTSTATE GetState;
2159 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2160
2161 uint32_t cFilesDeleted = 0;
2162 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2163 bool fForce = true;
2164
2165 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2166 {
2167 /* For options that require an argument, ValueUnion has received the value. */
2168 switch (ch)
2169 {
2170 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2171
2172 case VINF_GETOPT_NOT_OPTION:
2173 if (cFilesDeleted == 0)
2174 {
2175 /*
2176 * First non-option - no more options now.
2177 */
2178 rcExit = gctlCtxPostOptionParsingInit(pCtx);
2179 if (rcExit != RTEXITCODE_SUCCESS)
2180 return rcExit;
2181 if (pCtx->cVerbose)
2182 RTPrintf("Removing %RU32 file(s)...\n", argc - GetState.iNext + 1);
2183 }
2184 if (g_fGuestCtrlCanceled)
2185 return RTMsgErrorExit(RTEXITCODE_FAILURE, "rm was interrupted by Ctrl-C (%u left)\n",
2186 argc - GetState.iNext + 1);
2187
2188 /*
2189 * Remove the specified file.
2190 *
2191 * On failure we will by default stop, however, the force option will
2192 * by unix traditions force us to ignore errors and continue.
2193 */
2194 cFilesDeleted++;
2195 if (pCtx->cVerbose)
2196 RTPrintf("Removing file \"%s\" ...\n", ValueUnion.psz);
2197 try
2198 {
2199 /** @todo How does IGuestSession::FsObjRemove work with read-only files? Do we
2200 * need to do some chmod or whatever to better emulate the --force flag? */
2201 HRESULT rc;
2202 CHECK_ERROR(pCtx->pGuestSession, FsObjRemove(Bstr(ValueUnion.psz).raw()));
2203 if (FAILED(rc) && !fForce)
2204 return RTEXITCODE_FAILURE;
2205 }
2206 catch (std::bad_alloc &)
2207 {
2208 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
2209 }
2210 break;
2211
2212 default:
2213 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RM, ch, &ValueUnion);
2214 }
2215 }
2216
2217 if (!cFilesDeleted && !fForce)
2218 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RM, "No file to remove specified!");
2219 return rcExit;
2220}
2221
2222static DECLCALLBACK(RTEXITCODE) gctlHandleMv(PGCTLCMDCTX pCtx, int argc, char **argv)
2223{
2224 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2225
2226 static const RTGETOPTDEF s_aOptions[] =
2227 {
2228 GCTLCMD_COMMON_OPTION_DEFS()
2229/** @todo Missing --force/-f flag. */
2230 };
2231
2232 int ch;
2233 RTGETOPTUNION ValueUnion;
2234 RTGETOPTSTATE GetState;
2235 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2236
2237 int vrc = VINF_SUCCESS;
2238
2239 bool fDryrun = false;
2240 std::vector< Utf8Str > vecSources;
2241 const char *pszDst = NULL;
2242 com::SafeArray<FsObjRenameFlag_T> aRenameFlags;
2243
2244 try
2245 {
2246 /** @todo Make flags configurable. */
2247 aRenameFlags.push_back(FsObjRenameFlag_NoReplace);
2248
2249 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2250 && RT_SUCCESS(vrc))
2251 {
2252 /* For options that require an argument, ValueUnion has received the value. */
2253 switch (ch)
2254 {
2255 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2256
2257 /** @todo Implement a --dryrun command. */
2258 /** @todo Implement rename flags. */
2259
2260 case VINF_GETOPT_NOT_OPTION:
2261 vecSources.push_back(Utf8Str(ValueUnion.psz));
2262 pszDst = ValueUnion.psz;
2263 break;
2264
2265 default:
2266 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV, ch, &ValueUnion);
2267 }
2268 }
2269 }
2270 catch (std::bad_alloc &)
2271 {
2272 vrc = VERR_NO_MEMORY;
2273 }
2274
2275 if (RT_FAILURE(vrc))
2276 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize, rc=%Rrc\n", vrc);
2277
2278 size_t cSources = vecSources.size();
2279 if (!cSources)
2280 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV,
2281 "No source(s) to move specified!");
2282 if (cSources < 2)
2283 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV,
2284 "No destination specified!");
2285
2286 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2287 if (rcExit != RTEXITCODE_SUCCESS)
2288 return rcExit;
2289
2290 /* Delete last element, which now is the destination. */
2291 vecSources.pop_back();
2292 cSources = vecSources.size();
2293
2294 HRESULT rc = S_OK;
2295
2296 if (cSources > 1)
2297 {
2298 BOOL fExists = FALSE;
2299 rc = pCtx->pGuestSession->DirectoryExists(Bstr(pszDst).raw(), FALSE /*followSymlinks*/, &fExists);
2300 if (FAILED(rc) || !fExists)
2301 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Destination must be a directory when specifying multiple sources\n");
2302 }
2303
2304 /*
2305 * Rename (move) the entries.
2306 */
2307 if (pCtx->cVerbose)
2308 RTPrintf("Renaming %RU32 %s ...\n", cSources, cSources > 1 ? "entries" : "entry");
2309
2310 std::vector< Utf8Str >::iterator it = vecSources.begin();
2311 while ( it != vecSources.end()
2312 && !g_fGuestCtrlCanceled)
2313 {
2314 Utf8Str strCurSource = (*it);
2315
2316 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2317 FsObjType_T enmObjType = FsObjType_Unknown; /* Shut up MSC */
2318 rc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(strCurSource).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
2319 if (SUCCEEDED(rc))
2320 rc = pFsObjInfo->COMGETTER(Type)(&enmObjType);
2321 if (FAILED(rc))
2322 {
2323 if (pCtx->cVerbose)
2324 RTPrintf("Warning: Cannot stat for element \"%s\": No such file or directory\n", strCurSource.c_str());
2325 ++it;
2326 continue; /* Skip. */
2327 }
2328
2329 if (pCtx->cVerbose)
2330 RTPrintf("Renaming %s \"%s\" to \"%s\" ...\n",
2331 enmObjType == FsObjType_Directory ? "directory" : "file",
2332 strCurSource.c_str(), pszDst);
2333
2334 if (!fDryrun)
2335 {
2336 if (enmObjType == FsObjType_Directory)
2337 {
2338 CHECK_ERROR_BREAK(pCtx->pGuestSession, FsObjRename(Bstr(strCurSource).raw(),
2339 Bstr(pszDst).raw(),
2340 ComSafeArrayAsInParam(aRenameFlags)));
2341
2342 /* Break here, since it makes no sense to rename mroe than one source to
2343 * the same directory. */
2344/** @todo r=bird: You are being kind of windowsy (or just DOSish) about the 'sense' part here,
2345 * while being totaly buggy about the behavior. 'VBoxManage guestcontrol ren dir1 dir2 dstdir' will
2346 * stop after 'dir1' and SILENTLY ignore dir2. If you tried this on Windows, you'd see an error
2347 * being displayed. If you 'man mv' on a nearby unixy system, you'd see that they've made perfect
2348 * sense out of any situation with more than one source. */
2349 it = vecSources.end();
2350 break;
2351 }
2352 else
2353 CHECK_ERROR_BREAK(pCtx->pGuestSession, FsObjRename(Bstr(strCurSource).raw(),
2354 Bstr(pszDst).raw(),
2355 ComSafeArrayAsInParam(aRenameFlags)));
2356 }
2357
2358 ++it;
2359 }
2360
2361 if ( (it != vecSources.end())
2362 && pCtx->cVerbose)
2363 {
2364 RTPrintf("Warning: Not all sources were renamed\n");
2365 }
2366
2367 return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2368}
2369
2370static DECLCALLBACK(RTEXITCODE) gctlHandleMkTemp(PGCTLCMDCTX pCtx, int argc, char **argv)
2371{
2372 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2373
2374 static const RTGETOPTDEF s_aOptions[] =
2375 {
2376 GCTLCMD_COMMON_OPTION_DEFS()
2377 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2378 { "--directory", 'D', RTGETOPT_REQ_NOTHING },
2379 { "--secure", 's', RTGETOPT_REQ_NOTHING },
2380 { "--tmpdir", 't', RTGETOPT_REQ_STRING }
2381 };
2382
2383 int ch;
2384 RTGETOPTUNION ValueUnion;
2385 RTGETOPTSTATE GetState;
2386 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2387
2388 Utf8Str strTemplate;
2389 uint32_t fMode = 0; /* Default mode. */
2390 bool fDirectory = false;
2391 bool fSecure = false;
2392 Utf8Str strTempDir;
2393
2394 DESTDIRMAP mapDirs;
2395
2396 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2397 {
2398 /* For options that require an argument, ValueUnion has received the value. */
2399 switch (ch)
2400 {
2401 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2402
2403 case 'm': /* Mode */
2404 fMode = ValueUnion.u32;
2405 break;
2406
2407 case 'D': /* Create directory */
2408 fDirectory = true;
2409 break;
2410
2411 case 's': /* Secure */
2412 fSecure = true;
2413 break;
2414
2415 case 't': /* Temp directory */
2416 strTempDir = ValueUnion.psz;
2417 break;
2418
2419 case VINF_GETOPT_NOT_OPTION:
2420 if (strTemplate.isEmpty())
2421 strTemplate = ValueUnion.psz;
2422 else
2423 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
2424 "More than one template specified!\n");
2425 break;
2426
2427 default:
2428 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP, ch, &ValueUnion);
2429 }
2430 }
2431
2432 if (strTemplate.isEmpty())
2433 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
2434 "No template specified!");
2435
2436 if (!fDirectory)
2437 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
2438 "Creating temporary files is currently not supported!");
2439
2440 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2441 if (rcExit != RTEXITCODE_SUCCESS)
2442 return rcExit;
2443
2444 /*
2445 * Create the directories.
2446 */
2447 if (pCtx->cVerbose)
2448 {
2449 if (fDirectory && !strTempDir.isEmpty())
2450 RTPrintf("Creating temporary directory from template '%s' in directory '%s' ...\n",
2451 strTemplate.c_str(), strTempDir.c_str());
2452 else if (fDirectory)
2453 RTPrintf("Creating temporary directory from template '%s' in default temporary directory ...\n",
2454 strTemplate.c_str());
2455 else if (!fDirectory && !strTempDir.isEmpty())
2456 RTPrintf("Creating temporary file from template '%s' in directory '%s' ...\n",
2457 strTemplate.c_str(), strTempDir.c_str());
2458 else if (!fDirectory)
2459 RTPrintf("Creating temporary file from template '%s' in default temporary directory ...\n",
2460 strTemplate.c_str());
2461 }
2462
2463 HRESULT rc = S_OK;
2464 if (fDirectory)
2465 {
2466 Bstr bstrDirectory;
2467 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreateTemp(Bstr(strTemplate).raw(),
2468 fMode, Bstr(strTempDir).raw(),
2469 fSecure,
2470 bstrDirectory.asOutParam()));
2471 if (SUCCEEDED(rc))
2472 RTPrintf("Directory name: %ls\n", bstrDirectory.raw());
2473 }
2474 else
2475 {
2476 // else - temporary file not yet implemented
2477 /** @todo implement temporary file creation (we fend it off above, no
2478 * worries). */
2479 rc = E_FAIL;
2480 }
2481
2482 return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2483}
2484
2485static DECLCALLBACK(RTEXITCODE) gctlHandleStat(PGCTLCMDCTX pCtx, int argc, char **argv)
2486{
2487 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2488
2489 static const RTGETOPTDEF s_aOptions[] =
2490 {
2491 GCTLCMD_COMMON_OPTION_DEFS()
2492 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
2493 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
2494 { "--format", 'c', RTGETOPT_REQ_STRING },
2495 { "--terse", 't', RTGETOPT_REQ_NOTHING }
2496 };
2497
2498 int ch;
2499 RTGETOPTUNION ValueUnion;
2500 RTGETOPTSTATE GetState;
2501 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2502
2503 while ( (ch = RTGetOpt(&GetState, &ValueUnion)) != 0
2504 && ch != VINF_GETOPT_NOT_OPTION)
2505 {
2506 /* For options that require an argument, ValueUnion has received the value. */
2507 switch (ch)
2508 {
2509 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2510
2511 case 'L': /* Dereference */
2512 case 'f': /* File-system */
2513 case 'c': /* Format */
2514 case 't': /* Terse */
2515 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
2516 "Command \"%s\" not implemented yet!", ValueUnion.psz);
2517
2518 default:
2519 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT, ch, &ValueUnion);
2520 }
2521 }
2522
2523 if (ch != VINF_GETOPT_NOT_OPTION)
2524 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT, "Nothing to stat!");
2525
2526 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2527 if (rcExit != RTEXITCODE_SUCCESS)
2528 return rcExit;
2529
2530
2531 /*
2532 * Do the file stat'ing.
2533 */
2534 while (ch == VINF_GETOPT_NOT_OPTION)
2535 {
2536 if (pCtx->cVerbose)
2537 RTPrintf("Checking for element \"%s\" ...\n", ValueUnion.psz);
2538
2539 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2540 HRESULT hrc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(ValueUnion.psz).raw(), FALSE /*followSymlinks*/,
2541 pFsObjInfo.asOutParam());
2542 if (FAILED(hrc))
2543 {
2544 /** @todo r=bird: There might be other reasons why we end up here than
2545 * non-existing "element" (object or file, please, nobody calls it elements). */
2546 if (pCtx->cVerbose)
2547 RTPrintf("Failed to stat '%s': No such file\n", ValueUnion.psz);
2548 rcExit = RTEXITCODE_FAILURE;
2549 }
2550 else
2551 {
2552 RTPrintf(" File: '%s'\n", ValueUnion.psz); /** @todo escape this name. */
2553
2554 FsObjType_T enmType = FsObjType_Unknown;
2555 CHECK_ERROR2I(pFsObjInfo, COMGETTER(Type)(&enmType));
2556 LONG64 cbObject = 0;
2557 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ObjectSize)(&cbObject));
2558 LONG64 cbAllocated = 0;
2559 CHECK_ERROR2I(pFsObjInfo, COMGETTER(AllocatedSize)(&cbAllocated));
2560 LONG uid = 0;
2561 CHECK_ERROR2I(pFsObjInfo, COMGETTER(UID)(&uid));
2562 LONG gid = 0;
2563 CHECK_ERROR2I(pFsObjInfo, COMGETTER(GID)(&gid));
2564 Bstr bstrUsername;
2565 CHECK_ERROR2I(pFsObjInfo, COMGETTER(UserName)(bstrUsername.asOutParam()));
2566 Bstr bstrGroupName;
2567 CHECK_ERROR2I(pFsObjInfo, COMGETTER(GroupName)(bstrGroupName.asOutParam()));
2568 Bstr bstrAttribs;
2569 CHECK_ERROR2I(pFsObjInfo, COMGETTER(FileAttributes)(bstrAttribs.asOutParam()));
2570 LONG64 idNode = 0;
2571 CHECK_ERROR2I(pFsObjInfo, COMGETTER(NodeId)(&idNode));
2572 ULONG uDevNode = 0;
2573 CHECK_ERROR2I(pFsObjInfo, COMGETTER(NodeIdDevice)(&uDevNode));
2574 ULONG uDeviceNo = 0;
2575 CHECK_ERROR2I(pFsObjInfo, COMGETTER(DeviceNumber)(&uDeviceNo));
2576 ULONG cHardLinks = 1;
2577 CHECK_ERROR2I(pFsObjInfo, COMGETTER(HardLinks)(&cHardLinks));
2578 LONG64 nsBirthTime = 0;
2579 CHECK_ERROR2I(pFsObjInfo, COMGETTER(BirthTime)(&nsBirthTime));
2580 LONG64 nsChangeTime = 0;
2581 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ChangeTime)(&nsChangeTime));
2582 LONG64 nsModificationTime = 0;
2583 CHECK_ERROR2I(pFsObjInfo, COMGETTER(ModificationTime)(&nsModificationTime));
2584 LONG64 nsAccessTime = 0;
2585 CHECK_ERROR2I(pFsObjInfo, COMGETTER(AccessTime)(&nsAccessTime));
2586
2587 RTPrintf(" Size: %-17RU64 Alloc: %-19RU64 Type: %s\n", cbObject, cbAllocated, gctlFsObjTypeToName(enmType));
2588 RTPrintf("Device: %#-17RX32 INode: %-18RU64 Links: %u\n", uDevNode, idNode, cHardLinks);
2589
2590 Utf8Str strAttrib(bstrAttribs);
2591 char *pszMode = strAttrib.mutableRaw();
2592 char *pszAttribs = strchr(pszMode, ' ');
2593 if (pszAttribs)
2594 do *pszAttribs++ = '\0';
2595 while (*pszAttribs == ' ');
2596 else
2597 pszAttribs = strchr(pszMode, '\0');
2598 if (uDeviceNo != 0)
2599 RTPrintf(" Mode: %-16s Attrib: %-17s Dev ID: %#RX32\n", pszMode, pszAttribs, uDeviceNo);
2600 else
2601 RTPrintf(" Mode: %-16s Attrib: %s\n", pszMode, pszAttribs);
2602
2603 RTPrintf(" Owner: %4d/%-12ls Group: %4d/%ls\n", uid, bstrUsername.raw(), gid, bstrGroupName.raw());
2604
2605 RTTIMESPEC TimeSpec;
2606 char szTmp[RTTIME_STR_LEN];
2607 RTPrintf(" Birth: %s\n", RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsBirthTime), szTmp, sizeof(szTmp)));
2608 RTPrintf("Change: %s\n", RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsChangeTime), szTmp, sizeof(szTmp)));
2609 RTPrintf("Modify: %s\n", RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsModificationTime), szTmp, sizeof(szTmp)));
2610 RTPrintf("Access: %s\n", RTTimeSpecToString(RTTimeSpecSetNano(&TimeSpec, nsAccessTime), szTmp, sizeof(szTmp)));
2611
2612 /* Skiping: Generation ID - only the ISO9660 VFS sets this. FreeBSD user flags. */
2613 }
2614
2615 /* Next file. */
2616 ch = RTGetOpt(&GetState, &ValueUnion);
2617 }
2618
2619 return rcExit;
2620}
2621
2622static DECLCALLBACK(RTEXITCODE) gctlHandleUpdateAdditions(PGCTLCMDCTX pCtx, int argc, char **argv)
2623{
2624 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2625
2626 /*
2627 * Check the syntax. We can deduce the correct syntax from the number of
2628 * arguments.
2629 */
2630 Utf8Str strSource;
2631 com::SafeArray<IN_BSTR> aArgs;
2632 bool fWaitStartOnly = false;
2633
2634 static const RTGETOPTDEF s_aOptions[] =
2635 {
2636 GCTLCMD_COMMON_OPTION_DEFS()
2637 { "--source", 's', RTGETOPT_REQ_STRING },
2638 { "--wait-start", 'w', RTGETOPT_REQ_NOTHING }
2639 };
2640
2641 int ch;
2642 RTGETOPTUNION ValueUnion;
2643 RTGETOPTSTATE GetState;
2644 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2645
2646 int vrc = VINF_SUCCESS;
2647 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2648 && RT_SUCCESS(vrc))
2649 {
2650 switch (ch)
2651 {
2652 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2653
2654 case 's':
2655 strSource = ValueUnion.psz;
2656 break;
2657
2658 case 'w':
2659 fWaitStartOnly = true;
2660 break;
2661
2662 case VINF_GETOPT_NOT_OPTION:
2663 if (aArgs.size() == 0 && strSource.isEmpty())
2664 strSource = ValueUnion.psz;
2665 else
2666 aArgs.push_back(Bstr(ValueUnion.psz).raw());
2667 break;
2668
2669 default:
2670 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEGA, ch, &ValueUnion);
2671 }
2672 }
2673
2674 if (pCtx->cVerbose)
2675 RTPrintf("Updating Guest Additions ...\n");
2676
2677 HRESULT rc = S_OK;
2678 while (strSource.isEmpty())
2679 {
2680 ComPtr<ISystemProperties> pProperties;
2681 CHECK_ERROR_BREAK(pCtx->pArg->virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
2682 Bstr strISO;
2683 CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
2684 strSource = strISO;
2685 break;
2686 }
2687
2688 /* Determine source if not set yet. */
2689 if (strSource.isEmpty())
2690 {
2691 RTMsgError("No Guest Additions source found or specified, aborting\n");
2692 vrc = VERR_FILE_NOT_FOUND;
2693 }
2694 else if (!RTFileExists(strSource.c_str()))
2695 {
2696 RTMsgError("Source \"%s\" does not exist!\n", strSource.c_str());
2697 vrc = VERR_FILE_NOT_FOUND;
2698 }
2699
2700 if (RT_SUCCESS(vrc))
2701 {
2702 if (pCtx->cVerbose)
2703 RTPrintf("Using source: %s\n", strSource.c_str());
2704
2705
2706 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2707 if (rcExit != RTEXITCODE_SUCCESS)
2708 return rcExit;
2709
2710
2711 com::SafeArray<AdditionsUpdateFlag_T> aUpdateFlags;
2712 if (fWaitStartOnly)
2713 {
2714 aUpdateFlags.push_back(AdditionsUpdateFlag_WaitForUpdateStartOnly);
2715 if (pCtx->cVerbose)
2716 RTPrintf("Preparing and waiting for Guest Additions installer to start ...\n");
2717 }
2718
2719 ComPtr<IProgress> pProgress;
2720 CHECK_ERROR(pCtx->pGuest, UpdateGuestAdditions(Bstr(strSource).raw(),
2721 ComSafeArrayAsInParam(aArgs),
2722 /* Wait for whole update process to complete. */
2723 ComSafeArrayAsInParam(aUpdateFlags),
2724 pProgress.asOutParam()));
2725 if (FAILED(rc))
2726 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
2727 else
2728 {
2729 if (pCtx->cVerbose)
2730 rc = showProgress(pProgress);
2731 else
2732 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
2733
2734 if (SUCCEEDED(rc))
2735 CHECK_PROGRESS_ERROR(pProgress, ("Guest additions update failed"));
2736 vrc = gctlPrintProgressError(pProgress);
2737 if ( RT_SUCCESS(vrc)
2738 && pCtx->cVerbose)
2739 {
2740 RTPrintf("Guest Additions update successful\n");
2741 }
2742 }
2743 }
2744
2745 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2746}
2747
2748static DECLCALLBACK(RTEXITCODE) gctlHandleList(PGCTLCMDCTX pCtx, int argc, char **argv)
2749{
2750 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2751
2752 static const RTGETOPTDEF s_aOptions[] =
2753 {
2754 GCTLCMD_COMMON_OPTION_DEFS()
2755 };
2756
2757 int ch;
2758 RTGETOPTUNION ValueUnion;
2759 RTGETOPTSTATE GetState;
2760 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2761
2762 bool fSeenListArg = false;
2763 bool fListAll = false;
2764 bool fListSessions = false;
2765 bool fListProcesses = false;
2766 bool fListFiles = false;
2767
2768 int vrc = VINF_SUCCESS;
2769 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2770 && RT_SUCCESS(vrc))
2771 {
2772 switch (ch)
2773 {
2774 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2775
2776 case VINF_GETOPT_NOT_OPTION:
2777 if ( !RTStrICmp(ValueUnion.psz, "sessions")
2778 || !RTStrICmp(ValueUnion.psz, "sess"))
2779 fListSessions = true;
2780 else if ( !RTStrICmp(ValueUnion.psz, "processes")
2781 || !RTStrICmp(ValueUnion.psz, "procs"))
2782 fListSessions = fListProcesses = true; /* Showing processes implies showing sessions. */
2783 else if (!RTStrICmp(ValueUnion.psz, "files"))
2784 fListSessions = fListFiles = true; /* Showing files implies showing sessions. */
2785 else if (!RTStrICmp(ValueUnion.psz, "all"))
2786 fListAll = true;
2787 else
2788 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST,
2789 "Unknown list: '%s'", ValueUnion.psz);
2790 fSeenListArg = true;
2791 break;
2792
2793 default:
2794 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEGA, ch, &ValueUnion);
2795 }
2796 }
2797
2798 if (!fSeenListArg)
2799 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST, "Missing list name");
2800 Assert(fListAll || fListSessions);
2801
2802 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2803 if (rcExit != RTEXITCODE_SUCCESS)
2804 return rcExit;
2805
2806
2807 /** @todo Do we need a machine-readable output here as well? */
2808
2809 HRESULT rc;
2810 size_t cTotalProcs = 0;
2811 size_t cTotalFiles = 0;
2812
2813 SafeIfaceArray <IGuestSession> collSessions;
2814 CHECK_ERROR(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
2815 if (SUCCEEDED(rc))
2816 {
2817 size_t const cSessions = collSessions.size();
2818 if (cSessions)
2819 {
2820 RTPrintf("Active guest sessions:\n");
2821
2822 /** @todo Make this output a bit prettier. No time now. */
2823
2824 for (size_t i = 0; i < cSessions; i++)
2825 {
2826 ComPtr<IGuestSession> pCurSession = collSessions[i];
2827 if (!pCurSession.isNull())
2828 {
2829 do
2830 {
2831 ULONG uID;
2832 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Id)(&uID));
2833 Bstr strName;
2834 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Name)(strName.asOutParam()));
2835 Bstr strUser;
2836 CHECK_ERROR_BREAK(pCurSession, COMGETTER(User)(strUser.asOutParam()));
2837 GuestSessionStatus_T sessionStatus;
2838 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Status)(&sessionStatus));
2839 RTPrintf("\n\tSession #%-3zu ID=%-3RU32 User=%-16ls Status=[%s] Name=%ls",
2840 i, uID, strUser.raw(), gctlGuestSessionStatusToText(sessionStatus), strName.raw());
2841 } while (0);
2842
2843 if ( fListAll
2844 || fListProcesses)
2845 {
2846 SafeIfaceArray <IGuestProcess> collProcesses;
2847 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcesses)));
2848 for (size_t a = 0; a < collProcesses.size(); a++)
2849 {
2850 ComPtr<IGuestProcess> pCurProcess = collProcesses[a];
2851 if (!pCurProcess.isNull())
2852 {
2853 do
2854 {
2855 ULONG uPID;
2856 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(PID)(&uPID));
2857 Bstr strExecPath;
2858 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(ExecutablePath)(strExecPath.asOutParam()));
2859 ProcessStatus_T procStatus;
2860 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(Status)(&procStatus));
2861
2862 RTPrintf("\n\t\tProcess #%-03zu PID=%-6RU32 Status=[%s] Command=%ls",
2863 a, uPID, gctlProcessStatusToText(procStatus), strExecPath.raw());
2864 } while (0);
2865 }
2866 }
2867
2868 cTotalProcs += collProcesses.size();
2869 }
2870
2871 if ( fListAll
2872 || fListFiles)
2873 {
2874 SafeIfaceArray <IGuestFile> collFiles;
2875 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Files)(ComSafeArrayAsOutParam(collFiles)));
2876 for (size_t a = 0; a < collFiles.size(); a++)
2877 {
2878 ComPtr<IGuestFile> pCurFile = collFiles[a];
2879 if (!pCurFile.isNull())
2880 {
2881 do
2882 {
2883 ULONG idFile;
2884 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Id)(&idFile));
2885 Bstr strName;
2886 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Filename)(strName.asOutParam()));
2887 FileStatus_T fileStatus;
2888 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Status)(&fileStatus));
2889
2890 RTPrintf("\n\t\tFile #%-03zu ID=%-6RU32 Status=[%s] Name=%ls",
2891 a, idFile, gctlFileStatusToText(fileStatus), strName.raw());
2892 } while (0);
2893 }
2894 }
2895
2896 cTotalFiles += collFiles.size();
2897 }
2898 }
2899 }
2900
2901 RTPrintf("\n\nTotal guest sessions: %zu\n", collSessions.size());
2902 if (fListAll || fListProcesses)
2903 RTPrintf("Total guest processes: %zu\n", cTotalProcs);
2904 if (fListAll || fListFiles)
2905 RTPrintf("Total guest files: %zu\n", cTotalFiles);
2906 }
2907 else
2908 RTPrintf("No active guest sessions found\n");
2909 }
2910
2911 if (FAILED(rc)) /** @todo yeah, right... Only the last error? */
2912 rcExit = RTEXITCODE_FAILURE;
2913
2914 return rcExit;
2915}
2916
2917static DECLCALLBACK(RTEXITCODE) gctlHandleCloseProcess(PGCTLCMDCTX pCtx, int argc, char **argv)
2918{
2919 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2920
2921 static const RTGETOPTDEF s_aOptions[] =
2922 {
2923 GCTLCMD_COMMON_OPTION_DEFS()
2924 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
2925 { "--session-name", 'n', RTGETOPT_REQ_STRING }
2926 };
2927
2928 int ch;
2929 RTGETOPTUNION ValueUnion;
2930 RTGETOPTSTATE GetState;
2931 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2932
2933 std::vector < uint32_t > vecPID;
2934 ULONG idSession = UINT32_MAX;
2935 Utf8Str strSessionName;
2936
2937 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2938 {
2939 /* For options that require an argument, ValueUnion has received the value. */
2940 switch (ch)
2941 {
2942 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2943
2944 case 'n': /* Session name (or pattern) */
2945 strSessionName = ValueUnion.psz;
2946 break;
2947
2948 case 'i': /* Session ID */
2949 idSession = ValueUnion.u32;
2950 break;
2951
2952 case VINF_GETOPT_NOT_OPTION:
2953 {
2954 /* Treat every else specified as a PID to kill. */
2955 uint32_t uPid;
2956 int rc = RTStrToUInt32Ex(ValueUnion.psz, NULL, 0, &uPid);
2957 if ( RT_SUCCESS(rc)
2958 && rc != VWRN_TRAILING_CHARS
2959 && rc != VWRN_NUMBER_TOO_BIG
2960 && rc != VWRN_NEGATIVE_UNSIGNED)
2961 {
2962 if (uPid != 0)
2963 {
2964 try
2965 {
2966 vecPID.push_back(uPid);
2967 }
2968 catch (std::bad_alloc &)
2969 {
2970 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory");
2971 }
2972 }
2973 else
2974 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "Invalid PID value: 0");
2975 }
2976 else
2977 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "Error parsing PID value: %Rrc", rc);
2978 break;
2979 }
2980
2981 default:
2982 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, ch, &ValueUnion);
2983 }
2984 }
2985
2986 if (vecPID.empty())
2987 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
2988 "At least one PID must be specified to kill!");
2989
2990 if ( strSessionName.isEmpty()
2991 && idSession == UINT32_MAX)
2992 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "No session ID specified!");
2993
2994 if ( strSessionName.isNotEmpty()
2995 && idSession != UINT32_MAX)
2996 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
2997 "Either session ID or name (pattern) must be specified");
2998
2999 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3000 if (rcExit != RTEXITCODE_SUCCESS)
3001 return rcExit;
3002
3003 HRESULT rc = S_OK;
3004
3005 ComPtr<IGuestSession> pSession;
3006 ComPtr<IGuestProcess> pProcess;
3007 do
3008 {
3009 uint32_t uProcsTerminated = 0;
3010
3011 SafeIfaceArray <IGuestSession> collSessions;
3012 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3013 size_t cSessions = collSessions.size();
3014
3015 uint32_t cSessionsHandled = 0;
3016 for (size_t i = 0; i < cSessions; i++)
3017 {
3018 pSession = collSessions[i];
3019 Assert(!pSession.isNull());
3020
3021 ULONG uID; /* Session ID */
3022 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3023 Bstr strName;
3024 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3025 Utf8Str strNameUtf8(strName); /* Session name */
3026
3027 bool fSessionFound;
3028 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3029 fSessionFound = uID == idSession;
3030 else /* ... or by naming pattern. */
3031 fSessionFound = RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str());
3032 if (fSessionFound)
3033 {
3034 AssertStmt(!pSession.isNull(), break);
3035 cSessionsHandled++;
3036
3037 SafeIfaceArray <IGuestProcess> collProcs;
3038 CHECK_ERROR_BREAK(pSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcs)));
3039
3040 size_t cProcs = collProcs.size();
3041 for (size_t p = 0; p < cProcs; p++)
3042 {
3043 pProcess = collProcs[p];
3044 Assert(!pProcess.isNull());
3045
3046 ULONG uPID; /* Process ID */
3047 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
3048
3049 bool fProcFound = false;
3050 for (size_t a = 0; a < vecPID.size(); a++) /* Slow, but works. */
3051 {
3052 fProcFound = vecPID[a] == uPID;
3053 if (fProcFound)
3054 break;
3055 }
3056
3057 if (fProcFound)
3058 {
3059 if (pCtx->cVerbose)
3060 RTPrintf("Terminating process (PID %RU32) (session ID %RU32) ...\n",
3061 uPID, uID);
3062 CHECK_ERROR_BREAK(pProcess, Terminate());
3063 uProcsTerminated++;
3064 }
3065 else
3066 {
3067 if (idSession != UINT32_MAX)
3068 RTPrintf("No matching process(es) for session ID %RU32 found\n",
3069 idSession);
3070 }
3071
3072 pProcess.setNull();
3073 }
3074
3075 pSession.setNull();
3076 }
3077 }
3078
3079 if (!cSessionsHandled)
3080 RTPrintf("No matching session(s) found\n");
3081
3082 if (uProcsTerminated)
3083 RTPrintf("%RU32 %s terminated\n",
3084 uProcsTerminated, uProcsTerminated == 1 ? "process" : "processes");
3085
3086 } while (0);
3087
3088 pProcess.setNull();
3089 pSession.setNull();
3090
3091 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3092}
3093
3094
3095static DECLCALLBACK(RTEXITCODE) gctlHandleCloseSession(PGCTLCMDCTX pCtx, int argc, char **argv)
3096{
3097 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3098
3099 enum GETOPTDEF_SESSIONCLOSE
3100 {
3101 GETOPTDEF_SESSIONCLOSE_ALL = 2000
3102 };
3103 static const RTGETOPTDEF s_aOptions[] =
3104 {
3105 GCTLCMD_COMMON_OPTION_DEFS()
3106 { "--all", GETOPTDEF_SESSIONCLOSE_ALL, RTGETOPT_REQ_NOTHING },
3107 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3108 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3109 };
3110
3111 int ch;
3112 RTGETOPTUNION ValueUnion;
3113 RTGETOPTSTATE GetState;
3114 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3115
3116 ULONG idSession = UINT32_MAX;
3117 Utf8Str strSessionName;
3118
3119 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3120 {
3121 /* For options that require an argument, ValueUnion has received the value. */
3122 switch (ch)
3123 {
3124 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3125
3126 case 'n': /* Session name pattern */
3127 strSessionName = ValueUnion.psz;
3128 break;
3129
3130 case 'i': /* Session ID */
3131 idSession = ValueUnion.u32;
3132 break;
3133
3134 case GETOPTDEF_SESSIONCLOSE_ALL:
3135 strSessionName = "*";
3136 break;
3137
3138 case VINF_GETOPT_NOT_OPTION:
3139 /** @todo Supply a CSV list of IDs or patterns to close?
3140 * break; */
3141 default:
3142 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION, ch, &ValueUnion);
3143 }
3144 }
3145
3146 if ( strSessionName.isEmpty()
3147 && idSession == UINT32_MAX)
3148 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION,
3149 "No session ID specified!");
3150
3151 if ( !strSessionName.isEmpty()
3152 && idSession != UINT32_MAX)
3153 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION,
3154 "Either session ID or name (pattern) must be specified");
3155
3156 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3157 if (rcExit != RTEXITCODE_SUCCESS)
3158 return rcExit;
3159
3160 HRESULT rc = S_OK;
3161
3162 do
3163 {
3164 size_t cSessionsHandled = 0;
3165
3166 SafeIfaceArray <IGuestSession> collSessions;
3167 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3168 size_t cSessions = collSessions.size();
3169
3170 for (size_t i = 0; i < cSessions; i++)
3171 {
3172 ComPtr<IGuestSession> pSession = collSessions[i];
3173 Assert(!pSession.isNull());
3174
3175 ULONG uID; /* Session ID */
3176 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3177 Bstr strName;
3178 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3179 Utf8Str strNameUtf8(strName); /* Session name */
3180
3181 bool fSessionFound;
3182 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3183 fSessionFound = uID == idSession;
3184 else /* ... or by naming pattern. */
3185 fSessionFound = RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str());
3186 if (fSessionFound)
3187 {
3188 cSessionsHandled++;
3189
3190 Assert(!pSession.isNull());
3191 if (pCtx->cVerbose)
3192 RTPrintf("Closing guest session ID=#%RU32 \"%s\" ...\n",
3193 uID, strNameUtf8.c_str());
3194 CHECK_ERROR_BREAK(pSession, Close());
3195 if (pCtx->cVerbose)
3196 RTPrintf("Guest session successfully closed\n");
3197
3198 pSession.setNull();
3199 }
3200 }
3201
3202 if (!cSessionsHandled)
3203 {
3204 RTPrintf("No guest session(s) found\n");
3205 rc = E_ABORT; /* To set exit code accordingly. */
3206 }
3207
3208 } while (0);
3209
3210 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3211}
3212
3213
3214static DECLCALLBACK(RTEXITCODE) gctlHandleWatch(PGCTLCMDCTX pCtx, int argc, char **argv)
3215{
3216 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3217
3218 /*
3219 * Parse arguments.
3220 */
3221 static const RTGETOPTDEF s_aOptions[] =
3222 {
3223 GCTLCMD_COMMON_OPTION_DEFS()
3224 };
3225
3226 int ch;
3227 RTGETOPTUNION ValueUnion;
3228 RTGETOPTSTATE GetState;
3229 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3230
3231 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3232 {
3233 /* For options that require an argument, ValueUnion has received the value. */
3234 switch (ch)
3235 {
3236 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3237
3238 case VINF_GETOPT_NOT_OPTION:
3239 default:
3240 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_WATCH, ch, &ValueUnion);
3241 }
3242 }
3243
3244 /** @todo Specify categories to watch for. */
3245 /** @todo Specify a --timeout for waiting only for a certain amount of time? */
3246
3247 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3248 if (rcExit != RTEXITCODE_SUCCESS)
3249 return rcExit;
3250
3251 HRESULT rc;
3252
3253 try
3254 {
3255 ComObjPtr<GuestEventListenerImpl> pGuestListener;
3256 do
3257 {
3258 /* Listener creation. */
3259 pGuestListener.createObject();
3260 pGuestListener->init(new GuestEventListener());
3261
3262 /* Register for IGuest events. */
3263 ComPtr<IEventSource> es;
3264 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
3265 com::SafeArray<VBoxEventType_T> eventTypes;
3266 eventTypes.push_back(VBoxEventType_OnGuestSessionRegistered);
3267 /** @todo Also register for VBoxEventType_OnGuestUserStateChanged on demand? */
3268 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
3269 true /* Active listener */));
3270 /* Note: All other guest control events have to be registered
3271 * as their corresponding objects appear. */
3272
3273 } while (0);
3274
3275 if (pCtx->cVerbose)
3276 RTPrintf("Waiting for events ...\n");
3277
3278/** @todo r=bird: This are-we-there-yet approach to things could easily be
3279 * replaced by a global event semaphore that gets signalled from the
3280 * signal handler and the callback event. Please fix! */
3281 while (!g_fGuestCtrlCanceled)
3282 {
3283 /** @todo Timeout handling (see above)? */
3284 RTThreadSleep(10);
3285 }
3286
3287 if (pCtx->cVerbose)
3288 RTPrintf("Signal caught, exiting ...\n");
3289
3290 if (!pGuestListener.isNull())
3291 {
3292 /* Guest callback unregistration. */
3293 ComPtr<IEventSource> pES;
3294 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
3295 if (!pES.isNull())
3296 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
3297 pGuestListener.setNull();
3298 }
3299 }
3300 catch (std::bad_alloc &)
3301 {
3302 rc = E_OUTOFMEMORY;
3303 }
3304
3305 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3306}
3307
3308/**
3309 * Access the guest control store.
3310 *
3311 * @returns program exit code.
3312 * @note see the command line API description for parameters
3313 */
3314RTEXITCODE handleGuestControl(HandlerArg *pArg)
3315{
3316 AssertPtr(pArg);
3317
3318#ifdef DEBUG_andy_disabled
3319 if (RT_FAILURE(tstTranslatePath()))
3320 return RTEXITCODE_FAILURE;
3321#endif
3322
3323 /*
3324 * Command definitions.
3325 */
3326 static const GCTLCMDDEF s_aCmdDefs[] =
3327 {
3328 { "run", gctlHandleRun, USAGE_GSTCTRL_RUN, 0, },
3329 { "start", gctlHandleStart, USAGE_GSTCTRL_START, 0, },
3330 { "copyfrom", gctlHandleCopyFrom, USAGE_GSTCTRL_COPYFROM, 0, },
3331 { "copyto", gctlHandleCopyTo, USAGE_GSTCTRL_COPYTO, 0, },
3332
3333 { "mkdir", gctrlHandleMkDir, USAGE_GSTCTRL_MKDIR, 0, },
3334 { "md", gctrlHandleMkDir, USAGE_GSTCTRL_MKDIR, 0, },
3335 { "createdirectory", gctrlHandleMkDir, USAGE_GSTCTRL_MKDIR, 0, },
3336 { "createdir", gctrlHandleMkDir, USAGE_GSTCTRL_MKDIR, 0, },
3337
3338 { "rmdir", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
3339 { "removedir", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
3340 { "removedirectory", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
3341
3342 { "rm", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
3343 { "removefile", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
3344 { "erase", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
3345 { "del", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
3346 { "delete", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
3347
3348 { "mv", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
3349 { "move", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
3350 { "ren", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
3351 { "rename", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
3352
3353 { "mktemp", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
3354 { "createtemp", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
3355 { "createtemporary", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
3356
3357 { "stat", gctlHandleStat, USAGE_GSTCTRL_STAT, 0, },
3358
3359 { "closeprocess", gctlHandleCloseProcess, USAGE_GSTCTRL_CLOSEPROCESS, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3360 { "closesession", gctlHandleCloseSession, USAGE_GSTCTRL_CLOSESESSION, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3361 { "list", gctlHandleList, USAGE_GSTCTRL_LIST, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3362 { "watch", gctlHandleWatch, USAGE_GSTCTRL_WATCH, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3363
3364 {"updateguestadditions",gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3365 { "updateadditions", gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3366 { "updatega", gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
3367 };
3368
3369 /*
3370 * VBoxManage guestcontrol [common-options] <VM> [common-options] <sub-command> ...
3371 *
3372 * Parse common options and VM name until we find a sub-command. Allowing
3373 * the user to put the user and password related options before the
3374 * sub-command makes it easier to edit the command line when doing several
3375 * operations with the same guest user account. (Accidentally, it also
3376 * makes the syntax diagram shorter and easier to read.)
3377 */
3378 GCTLCMDCTX CmdCtx;
3379 RTEXITCODE rcExit = gctrCmdCtxInit(&CmdCtx, pArg);
3380 if (rcExit == RTEXITCODE_SUCCESS)
3381 {
3382 static const RTGETOPTDEF s_CommonOptions[] = { GCTLCMD_COMMON_OPTION_DEFS() };
3383
3384 int ch;
3385 RTGETOPTUNION ValueUnion;
3386 RTGETOPTSTATE GetState;
3387 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_CommonOptions, RT_ELEMENTS(s_CommonOptions), 0, 0 /* No sorting! */);
3388
3389 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3390 {
3391 switch (ch)
3392 {
3393 GCTLCMD_COMMON_OPTION_CASES(&CmdCtx, ch, &ValueUnion);
3394
3395 case VINF_GETOPT_NOT_OPTION:
3396 /* First comes the VM name or UUID. */
3397 if (!CmdCtx.pszVmNameOrUuid)
3398 CmdCtx.pszVmNameOrUuid = ValueUnion.psz;
3399 /*
3400 * The sub-command is next. Look it up and invoke it.
3401 * Note! Currently no warnings about user/password options (like we'll do later on)
3402 * for GCTLCMDCTX_F_SESSION_ANONYMOUS commands. No reason to be too pedantic.
3403 */
3404 else
3405 {
3406 const char *pszCmd = ValueUnion.psz;
3407 uint32_t iCmd;
3408 for (iCmd = 0; iCmd < RT_ELEMENTS(s_aCmdDefs); iCmd++)
3409 if (strcmp(s_aCmdDefs[iCmd].pszName, pszCmd) == 0)
3410 {
3411 CmdCtx.pCmdDef = &s_aCmdDefs[iCmd];
3412
3413 rcExit = s_aCmdDefs[iCmd].pfnHandler(&CmdCtx, pArg->argc - GetState.iNext + 1,
3414 &pArg->argv[GetState.iNext - 1]);
3415
3416 gctlCtxTerm(&CmdCtx);
3417 return rcExit;
3418 }
3419 return errorSyntax(USAGE_GUESTCONTROL, "Unknown sub-command: '%s'", pszCmd);
3420 }
3421 break;
3422
3423 default:
3424 return errorGetOpt(USAGE_GUESTCONTROL, ch, &ValueUnion);
3425 }
3426 }
3427 if (CmdCtx.pszVmNameOrUuid)
3428 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Missing sub-command");
3429 else
3430 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Missing VM name and sub-command");
3431 }
3432 return rcExit;
3433}
3434#endif /* !VBOX_ONLY_DOCS */
3435
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