VirtualBox

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

Last change on this file since 55609 was 55609, checked in by vboxsync, 10 years ago

VBoxManageGuestCtrl.cpp: Implemented parsing vm and sub-command name along with common options, dialing back the pedanticness when using --username and the rest with commands requiring no guest session. Also replaced several C++ maps/vectors/whatever inefficient stuff that threatens to throw bad-alloc with processing non-options in the VINF_GETOPT_NOT_OPTION case (argv could also be worked directly from the first occurence of VINF_GETOPT_NOT_OPTION if we liked). These changes concerns mkdir, rmdir rm and mv so far - haven't had time to test these. Added '-f' to the 'rm' command. Updated usage info.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 158.6 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 55609 2015-05-03 01:00:22Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010-2015 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/isofs.h>
43#include <iprt/getopt.h>
44#include <iprt/list.h>
45#include <iprt/path.h>
46#include <iprt/process.h> /* For RTProcSelf(). */
47#include <iprt/thread.h>
48#include <iprt/vfs.h>
49
50#include <map>
51#include <vector>
52
53#ifdef USE_XPCOM_QUEUE
54# include <sys/select.h>
55# include <errno.h>
56#endif
57
58#include <signal.h>
59
60#ifdef RT_OS_DARWIN
61# include <CoreFoundation/CFRunLoop.h>
62#endif
63
64using namespace com;
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
189typedef struct COPYCONTEXT
190{
191 COPYCONTEXT()
192 : fDryRun(false),
193 fHostToGuest(false)
194 {
195 }
196
197 PGCTLCMDCTX pCmdCtx;
198 bool fDryRun;
199 bool fHostToGuest;
200
201} COPYCONTEXT, *PCOPYCONTEXT;
202
203/**
204 * An entry for a source element, including an optional DOS-like wildcard (*,?).
205 */
206class SOURCEFILEENTRY
207{
208 public:
209
210 SOURCEFILEENTRY(const char *pszSource, const char *pszFilter)
211 : mSource(pszSource),
212 mFilter(pszFilter) {}
213
214 SOURCEFILEENTRY(const char *pszSource)
215 : mSource(pszSource)
216 {
217 Parse(pszSource);
218 }
219
220 const char* GetSource() const
221 {
222 return mSource.c_str();
223 }
224
225 const char* GetFilter() const
226 {
227 return mFilter.c_str();
228 }
229
230 private:
231
232 int Parse(const char *pszPath)
233 {
234 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
235
236 if ( !RTFileExists(pszPath)
237 && !RTDirExists(pszPath))
238 {
239 /* No file and no directory -- maybe a filter? */
240 char *pszFilename = RTPathFilename(pszPath);
241 if ( pszFilename
242 && strpbrk(pszFilename, "*?"))
243 {
244 /* Yep, get the actual filter part. */
245 mFilter = RTPathFilename(pszPath);
246 /* Remove the filter from actual sourcec directory name. */
247 RTPathStripFilename(mSource.mutableRaw());
248 mSource.jolt();
249 }
250 }
251
252 return VINF_SUCCESS; /* @todo */
253 }
254
255 private:
256
257 Utf8Str mSource;
258 Utf8Str mFilter;
259};
260typedef std::vector<SOURCEFILEENTRY> SOURCEVEC, *PSOURCEVEC;
261
262/**
263 * An entry for an element which needs to be copied/created to/on the guest.
264 */
265typedef struct DESTFILEENTRY
266{
267 DESTFILEENTRY(Utf8Str strFileName) : mFileName(strFileName) {}
268 Utf8Str mFileName;
269} DESTFILEENTRY, *PDESTFILEENTRY;
270/*
271 * Map for holding destination entires, whereas the key is the destination
272 * directory and the mapped value is a vector holding all elements for this directoy.
273 */
274typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> > DESTDIRMAP, *PDESTDIRMAP;
275typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> >::iterator DESTDIRMAPITER, *PDESTDIRMAPITER;
276
277
278/**
279 * RTGetOpt-IDs for the guest execution control command line.
280 */
281enum GETOPTDEF_EXEC
282{
283 GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES = 1000,
284 GETOPTDEF_EXEC_NO_PROFILE,
285 GETOPTDEF_EXEC_OUTPUTFORMAT,
286 GETOPTDEF_EXEC_DOS2UNIX,
287 GETOPTDEF_EXEC_UNIX2DOS,
288 GETOPTDEF_EXEC_WAITFOREXIT,
289 GETOPTDEF_EXEC_WAITFORSTDOUT,
290 GETOPTDEF_EXEC_WAITFORSTDERR
291};
292
293enum kStreamTransform
294{
295 kStreamTransform_None = 0,
296 kStreamTransform_Dos2Unix,
297 kStreamTransform_Unix2Dos
298};
299
300
301/*******************************************************************************
302* Internal Functions *
303*******************************************************************************/
304static int gctlCopyDirExists(PCOPYCONTEXT pContext, bool bGuest, const char *pszDir, bool *fExists);
305
306#endif /* VBOX_ONLY_DOCS */
307
308
309
310void usageGuestControl(PRTSTREAM pStrm, const char *pcszSep1, const char *pcszSep2, uint32_t uSubCmd)
311{
312 const uint32_t fAnonSubCmds = USAGE_GSTCTRL_CLOSESESSION
313 | USAGE_GSTCTRL_LIST
314 | USAGE_GSTCTRL_CLOSEPROCESS
315 | USAGE_GSTCTRL_CLOSESESSION
316 | USAGE_GSTCTRL_UPDATEGA
317 | USAGE_GSTCTRL_WATCH;
318
319 /* 0 1 2 3 4 5 6 7 8XXXXXXXXXX */
320 /* 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 */
321 if (~fAnonSubCmds & uSubCmd)
322 RTStrmPrintf(pStrm,
323 "%s guestcontrol %s <uuid|vmname> [--verbose|-v] [--quiet|-q]\n"
324 " [--username <name>] [--domain <domain>]\n"
325 " [--passwordfile <file> | --password <password>]\n%s",
326 pcszSep1, pcszSep2, uSubCmd == ~0U ? "\n" : "");
327 if (uSubCmd & USAGE_GSTCTRL_RUN)
328 RTStrmPrintf(pStrm,
329 " run [common-options]\n"
330 " [--exe <path to executable>] [--timeout <msec>]\n"
331 " [-E|--putenv <NAME>[=<VALUE>]] [--unquoted-args]\n"
332 " [--ignore-operhaned-processes] [--no-profile]\n"
333 " [--no-wait-stdout|--wait-stdout]\n"
334 " [--no-wait-stderr|--wait-stderr]\n"
335 " [--dos2unix] [--unix2dos]\n"
336 " -- <program/arg0> [argument1] ... [argumentN]]\n"
337 "\n");
338 if (uSubCmd & USAGE_GSTCTRL_START)
339 RTStrmPrintf(pStrm,
340 " start [common-options]\n"
341 " [--exe <path to executable>] [--timeout <msec>]\n"
342 " [-E|--putenv <NAME>[=<VALUE>]] [--unquoted-args]\n"
343 " [--ignore-operhaned-processes] [--no-profile]\n"
344 " -- <program/arg0> [argument1] ... [argumentN]]\n"
345 "\n");
346 if (uSubCmd & USAGE_GSTCTRL_COPYFROM)
347 RTStrmPrintf(pStrm,
348 " copyfrom [common-options]\n"
349 " [--dryrun] [--follow] [-R|--recursive]\n"
350 " <guest-src0> [guest-src1 [...]] <host-dst>\n"
351 "\n"
352 " copyfrom [common-options]\n"
353 " [--dryrun] [--follow] [-R|--recursive]\n"
354 " [--target-directory <host-dst-dir>]\n"
355 " <guest-src0> [guest-src1 [...]]\n"
356 "\n");
357 if (uSubCmd & USAGE_GSTCTRL_COPYTO)
358 RTStrmPrintf(pStrm,
359 " copyto [common-options]\n"
360 " [--dryrun] [--follow] [-R|--recursive]\n"
361 " <host-src0> [host-src1 [...]] <guest-dst>\n"
362 "\n"
363 " copyto [common-options]\n"
364 " [--dryrun] [--follow] [-R|--recursive]\n"
365 " [--target-directory <guest-dst>]\n"
366 " <host-src0> [host-src1 [...]]\n"
367 "\n");
368 if (uSubCmd & USAGE_GSTCTRL_MKDIR)
369 RTStrmPrintf(pStrm,
370 " mkdir|createdir[ectory] [common-options]\n"
371 " [--parents] [--mode <mode>]\n"
372 " <guest directory> [...]\n"
373 "\n");
374 if (uSubCmd & USAGE_GSTCTRL_RMDIR)
375 RTStrmPrintf(pStrm,
376 " rmdir|removedir[ectory] [common-options]\n"
377 " [-R|--recursive]\n"
378 " <guest directory> [...]\n"
379 "\n");
380 if (uSubCmd & USAGE_GSTCTRL_RM)
381 RTStrmPrintf(pStrm,
382 " removefile|rm [common-options] [-f|--force]\n"
383 " <guest file> [...]\n"
384 "\n");
385 if (uSubCmd & USAGE_GSTCTRL_MV)
386 RTStrmPrintf(pStrm,
387 " mv|move|ren[ame] [common-options]\n"
388 " <source> [source1 [...]] <dest>\n"
389 "\n");
390 if (uSubCmd & USAGE_GSTCTRL_MKTEMP)
391 RTStrmPrintf(pStrm,
392 " mktemp|createtemp[orary] [common-options]\n"
393 " [--secure] [--mode <mode>] [--tmpdir <directory>]\n"
394 " <template>\n"
395 "\n");
396 if (uSubCmd & USAGE_GSTCTRL_STAT)
397 RTStrmPrintf(pStrm,
398 " stat [common-options]\n"
399 " <file> [...]\n"
400 "\n");
401
402 /*
403 * Command not requiring authentication.
404 */
405 if (fAnonSubCmds & uSubCmd)
406 {
407 /* 0 1 2 3 4 5 6 7 8XXXXXXXXXX */
408 /* 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 */
409 RTStrmPrintf(pStrm,
410 "%s guestcontrol %s <uuid|vmname> [--verbose|-v] [--quiet|-q]\n%s",
411 pcszSep1, pcszSep2, uSubCmd == ~0U ? "\n" : "");
412 if (uSubCmd & USAGE_GSTCTRL_LIST)
413 RTStrmPrintf(pStrm,
414 " list <all|sessions|processes|files> [common-opts]\n"
415 "\n");
416 if (uSubCmd & USAGE_GSTCTRL_CLOSEPROCESS)
417 RTStrmPrintf(pStrm,
418 " closeprocess [common-options]\n"
419 " < --session-id <ID>\n"
420 " | --session-name <name or pattern>\n"
421 " <PID1> [PID1 [...]]\n"
422 "\n");
423 if (uSubCmd & USAGE_GSTCTRL_CLOSESESSION)
424 RTStrmPrintf(pStrm,
425 " closesession [common-options]\n"
426 " < --all | --session-id <ID>\n"
427 " | --session-name <name or pattern> >\n"
428 "\n");
429 if (uSubCmd & USAGE_GSTCTRL_UPDATEGA)
430 RTStrmPrintf(pStrm,
431 " updatega|updateguestadditions|updateadditions\n"
432 " [--source <guest additions .ISO>]\n"
433 " [--wait-start] [common-options]\n"
434 " [-- [<argument1>] ... [<argumentN>]]\n"
435 "\n");
436 if (uSubCmd & USAGE_GSTCTRL_WATCH)
437 RTStrmPrintf(pStrm,
438 " watch [common-options]\n"
439 "\n");
440 }
441}
442
443#ifndef VBOX_ONLY_DOCS
444
445
446#ifdef RT_OS_WINDOWS
447static BOOL WINAPI gctlSignalHandler(DWORD dwCtrlType)
448{
449 bool fEventHandled = FALSE;
450 switch (dwCtrlType)
451 {
452 /* User pressed CTRL+C or CTRL+BREAK or an external event was sent
453 * via GenerateConsoleCtrlEvent(). */
454 case CTRL_BREAK_EVENT:
455 case CTRL_CLOSE_EVENT:
456 case CTRL_C_EVENT:
457 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
458 fEventHandled = TRUE;
459 break;
460 default:
461 break;
462 /** @todo Add other events here. */
463 }
464
465 return fEventHandled;
466}
467#else /* !RT_OS_WINDOWS */
468/**
469 * Signal handler that sets g_fGuestCtrlCanceled.
470 *
471 * This can be executed on any thread in the process, on Windows it may even be
472 * a thread dedicated to delivering this signal. Don't do anything
473 * unnecessary here.
474 */
475static void gctlSignalHandler(int iSignal)
476{
477 NOREF(iSignal);
478 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
479}
480#endif
481
482
483/**
484 * Installs a custom signal handler to get notified
485 * whenever the user wants to intercept the program.
486 *
487 * @todo Make this handler available for all VBoxManage modules?
488 */
489static int gctlSignalHandlerInstall(void)
490{
491 g_fGuestCtrlCanceled = false;
492
493 int rc = VINF_SUCCESS;
494#ifdef RT_OS_WINDOWS
495 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)gctlSignalHandler, TRUE /* Add handler */))
496 {
497 rc = RTErrConvertFromWin32(GetLastError());
498 RTMsgError("Unable to install console control handler, rc=%Rrc\n", rc);
499 }
500#else
501 signal(SIGINT, gctlSignalHandler);
502# ifdef SIGBREAK
503 signal(SIGBREAK, gctlSignalHandler);
504# endif
505#endif
506 return rc;
507}
508
509
510/**
511 * Uninstalls a previously installed signal handler.
512 */
513static int gctlSignalHandlerUninstall(void)
514{
515 int rc = VINF_SUCCESS;
516#ifdef RT_OS_WINDOWS
517 if (!SetConsoleCtrlHandler((PHANDLER_ROUTINE)NULL, FALSE /* Remove handler */))
518 {
519 rc = RTErrConvertFromWin32(GetLastError());
520 RTMsgError("Unable to uninstall console control handler, rc=%Rrc\n", rc);
521 }
522#else
523 signal(SIGINT, SIG_DFL);
524# ifdef SIGBREAK
525 signal(SIGBREAK, SIG_DFL);
526# endif
527#endif
528 return rc;
529}
530
531
532/**
533 * Translates a process status to a human readable string.
534 */
535const char *gctlProcessStatusToText(ProcessStatus_T enmStatus)
536{
537 switch (enmStatus)
538 {
539 case ProcessStatus_Starting:
540 return "starting";
541 case ProcessStatus_Started:
542 return "started";
543 case ProcessStatus_Paused:
544 return "paused";
545 case ProcessStatus_Terminating:
546 return "terminating";
547 case ProcessStatus_TerminatedNormally:
548 return "successfully terminated";
549 case ProcessStatus_TerminatedSignal:
550 return "terminated by signal";
551 case ProcessStatus_TerminatedAbnormally:
552 return "abnormally aborted";
553 case ProcessStatus_TimedOutKilled:
554 return "timed out";
555 case ProcessStatus_TimedOutAbnormally:
556 return "timed out, hanging";
557 case ProcessStatus_Down:
558 return "killed";
559 case ProcessStatus_Error:
560 return "error";
561 default:
562 break;
563 }
564 return "unknown";
565}
566
567/**
568 * Translates a guest process wait result to a human readable string.
569 */
570const char *gctlProcessWaitResultToText(ProcessWaitResult_T enmWaitResult)
571{
572 switch (enmWaitResult)
573 {
574 case ProcessWaitResult_Start:
575 return "started";
576 case ProcessWaitResult_Terminate:
577 return "terminated";
578 case ProcessWaitResult_Status:
579 return "status changed";
580 case ProcessWaitResult_Error:
581 return "error";
582 case ProcessWaitResult_Timeout:
583 return "timed out";
584 case ProcessWaitResult_StdIn:
585 return "stdin ready";
586 case ProcessWaitResult_StdOut:
587 return "data on stdout";
588 case ProcessWaitResult_StdErr:
589 return "data on stderr";
590 case ProcessWaitResult_WaitFlagNotSupported:
591 return "waiting flag not supported";
592 default:
593 break;
594 }
595 return "unknown";
596}
597
598/**
599 * Translates a guest session status to a human readable string.
600 */
601const char *gctlGuestSessionStatusToText(GuestSessionStatus_T enmStatus)
602{
603 switch (enmStatus)
604 {
605 case GuestSessionStatus_Starting:
606 return "starting";
607 case GuestSessionStatus_Started:
608 return "started";
609 case GuestSessionStatus_Terminating:
610 return "terminating";
611 case GuestSessionStatus_Terminated:
612 return "terminated";
613 case GuestSessionStatus_TimedOutKilled:
614 return "timed out";
615 case GuestSessionStatus_TimedOutAbnormally:
616 return "timed out, hanging";
617 case GuestSessionStatus_Down:
618 return "killed";
619 case GuestSessionStatus_Error:
620 return "error";
621 default:
622 break;
623 }
624 return "unknown";
625}
626
627/**
628 * Translates a guest file status to a human readable string.
629 */
630const char *gctlFileStatusToText(FileStatus_T enmStatus)
631{
632 switch (enmStatus)
633 {
634 case FileStatus_Opening:
635 return "opening";
636 case FileStatus_Open:
637 return "open";
638 case FileStatus_Closing:
639 return "closing";
640 case FileStatus_Closed:
641 return "closed";
642 case FileStatus_Down:
643 return "killed";
644 case FileStatus_Error:
645 return "error";
646 default:
647 break;
648 }
649 return "unknown";
650}
651
652static int gctlPrintError(com::ErrorInfo &errorInfo)
653{
654 if ( errorInfo.isFullAvailable()
655 || errorInfo.isBasicAvailable())
656 {
657 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
658 * because it contains more accurate info about what went wrong. */
659 if (errorInfo.getResultCode() == VBOX_E_IPRT_ERROR)
660 RTMsgError("%ls.", errorInfo.getText().raw());
661 else
662 {
663 RTMsgError("Error details:");
664 GluePrintErrorInfo(errorInfo);
665 }
666 return VERR_GENERAL_FAILURE; /** @todo */
667 }
668 AssertMsgFailedReturn(("Object has indicated no error (%Rhrc)!?\n", errorInfo.getResultCode()),
669 VERR_INVALID_PARAMETER);
670}
671
672static int gctlPrintError(IUnknown *pObj, const GUID &aIID)
673{
674 com::ErrorInfo ErrInfo(pObj, aIID);
675 return gctlPrintError(ErrInfo);
676}
677
678static int gctlPrintProgressError(ComPtr<IProgress> pProgress)
679{
680 int vrc = VINF_SUCCESS;
681 HRESULT rc;
682
683 do
684 {
685 BOOL fCanceled;
686 CHECK_ERROR_BREAK(pProgress, COMGETTER(Canceled)(&fCanceled));
687 if (!fCanceled)
688 {
689 LONG rcProc;
690 CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&rcProc));
691 if (FAILED(rcProc))
692 {
693 com::ProgressErrorInfo ErrInfo(pProgress);
694 vrc = gctlPrintError(ErrInfo);
695 }
696 }
697
698 } while(0);
699
700 AssertMsgStmt(SUCCEEDED(rc), ("Could not lookup progress information\n"), vrc = VERR_COM_UNEXPECTED);
701
702 return vrc;
703}
704
705
706
707/*
708 *
709 *
710 * Guest Control Command Context
711 * Guest Control Command Context
712 * Guest Control Command Context
713 * Guest Control Command Context
714 *
715 *
716 *
717 */
718
719
720/**
721 * Initializes a guest control command context structure.
722 *
723 * @returns RTEXITCODE_SUCCESS on success, RTEXITCODE_FAILURE on failure (after
724 * informing the user of course).
725 * @param pCtx The command context to init.
726 * @param pArg The handle argument package.
727 */
728static RTEXITCODE gctrCmdCtxInit(PGCTLCMDCTX pCtx, HandlerArg *pArg)
729{
730 RT_ZERO(*pCtx);
731 pCtx->pArg = pArg;
732
733 /*
734 * The user name defaults to the host one, if we can get at it.
735 */
736 char szUser[1024];
737 int rc = RTProcQueryUsername(RTProcSelf(), szUser, sizeof(szUser), NULL);
738 if ( RT_SUCCESS(rc)
739 && RTStrIsValidEncoding(szUser)) /* paranoia required on posix */
740 {
741 try
742 {
743 pCtx->strUsername = szUser;
744 }
745 catch (std::bad_alloc &)
746 {
747 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory");
748 }
749 }
750 /* else: ignore this failure. */
751
752 return RTEXITCODE_SUCCESS;
753}
754
755
756/**
757 * Worker for GCTLCMD_COMMON_OPTION_CASES.
758 *
759 * @returns RTEXITCODE_SUCCESS if the option was handled successfully. If not,
760 * an error message is printed and an appropriate failure exit code is
761 * returned.
762 * @param pCtx The guest control command context.
763 * @param ch The option char or ordinal.
764 * @param pValueUnion The option value union.
765 */
766static RTEXITCODE gctlCtxSetOption(PGCTLCMDCTX pCtx, int ch, PRTGETOPTUNION pValueUnion)
767{
768 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
769 switch (ch)
770 {
771 case GCTLCMD_COMMON_OPT_USER: /* User name */
772 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
773 pCtx->strUsername = pValueUnion->psz;
774 else
775 RTMsgWarning("The --username|-u option is ignored by '%s'", pCtx->pCmdDef->pszName);
776 break;
777
778 case GCTLCMD_COMMON_OPT_PASSWORD: /* Password */
779 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
780 {
781 if (pCtx->strPassword.isNotEmpty())
782 RTMsgWarning("Password is given more than once.");
783 pCtx->strPassword = pValueUnion->psz;
784 }
785 else
786 RTMsgWarning("The --password option is ignored by '%s'", pCtx->pCmdDef->pszName);
787 break;
788
789 case GCTLCMD_COMMON_OPT_PASSWORD_FILE: /* Password file */
790 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
791 rcExit = readPasswordFile(pValueUnion->psz, &pCtx->strPassword);
792 else
793 RTMsgWarning("The --password-file|-p option is ignored by '%s'", pCtx->pCmdDef->pszName);
794 break;
795
796 case GCTLCMD_COMMON_OPT_DOMAIN: /* domain */
797 if (!pCtx->pCmdDef || !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
798 pCtx->strDomain = pValueUnion->psz;
799 else
800 RTMsgWarning("The --domain option is ignored by '%s'", pCtx->pCmdDef->pszName);
801 break;
802
803 case 'v': /* --verbose */
804 pCtx->cVerbose++;
805 break;
806
807 case 'q': /* --quiet */
808 if (pCtx->cVerbose)
809 pCtx->cVerbose--;
810 break;
811
812 default:
813 AssertFatalMsgFailed(("ch=%d (%c)\n", ch, ch));
814 }
815 return rcExit;
816}
817
818
819/**
820 * Initializes the VM for IGuest operation.
821 *
822 * This opens a shared session to a running VM and gets hold of IGuest.
823 *
824 * @returns RTEXITCODE_SUCCESS on success. RTEXITCODE_FAILURE and user message
825 * on failure.
826 * @param pCtx The guest control command context.
827 * GCTLCMDCTX::pGuest will be set on success.
828 */
829static RTEXITCODE gctlCtxInitVmSession(PGCTLCMDCTX pCtx)
830{
831 HRESULT rc;
832 AssertPtr(pCtx);
833 AssertPtr(pCtx->pArg);
834
835 /*
836 * Find the VM and check if it's running.
837 */
838 ComPtr<IMachine> machine;
839 CHECK_ERROR(pCtx->pArg->virtualBox, FindMachine(Bstr(pCtx->pszVmNameOrUuid).raw(), machine.asOutParam()));
840 if (SUCCEEDED(rc))
841 {
842 MachineState_T enmMachineState;
843 CHECK_ERROR(machine, COMGETTER(State)(&enmMachineState));
844 if ( SUCCEEDED(rc)
845 && enmMachineState == MachineState_Running)
846 {
847 /*
848 * It's running. So, open a session to it and get the IGuest interface.
849 */
850 CHECK_ERROR(machine, LockMachine(pCtx->pArg->session, LockType_Shared));
851 if (SUCCEEDED(rc))
852 {
853 pCtx->fLockedVmSession = true;
854 ComPtr<IConsole> ptrConsole;
855 CHECK_ERROR(pCtx->pArg->session, COMGETTER(Console)(ptrConsole.asOutParam()));
856 if (SUCCEEDED(rc))
857 {
858 CHECK_ERROR(ptrConsole, COMGETTER(Guest)(pCtx->pGuest.asOutParam()));
859 if (SUCCEEDED(rc))
860 return RTEXITCODE_SUCCESS;
861 }
862 }
863 }
864 else if(SUCCEEDED(rc))
865 RTMsgError("Machine \"%s\" is not running (currently %s)!\n",
866 pCtx->pszVmNameOrUuid, machineStateToName(enmMachineState, false));
867 }
868 return RTEXITCODE_FAILURE;
869}
870
871
872/**
873 * Creates a guest session with the VM.
874 *
875 * @retval RTEXITCODE_SUCCESS on success.
876 * @retval RTEXITCODE_FAILURE and user message on failure.
877 * @param pCtx The guest control command context.
878 * GCTCMDCTX::pGuestSession and GCTLCMDCTX::uSessionID
879 * will be set.
880 */
881static RTEXITCODE gctlCtxInitGuestSession(PGCTLCMDCTX pCtx)
882{
883 HRESULT rc;
884 AssertPtr(pCtx);
885 Assert(!(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS));
886 Assert(pCtx->pGuest.isNotNull());
887
888 /*
889 * Build up a reasonable guest session name. Useful for identifying
890 * a specific session when listing / searching for them.
891 */
892 char *pszSessionName;
893 if (RTStrAPrintf(&pszSessionName,
894 "[%RU32] VBoxManage Guest Control [%s] - %s",
895 RTProcSelf(), pCtx->pszVmNameOrUuid, pCtx->pCmdDef->pszName) < 0)
896 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No enough memory for session name");
897
898 /*
899 * Create a guest session.
900 */
901 if (pCtx->cVerbose > 1)
902 RTPrintf("Creating guest session as user '%s'...\n", pCtx->strUsername.c_str());
903 try
904 {
905 CHECK_ERROR(pCtx->pGuest, CreateSession(Bstr(pCtx->strUsername).raw(),
906 Bstr(pCtx->strPassword).raw(),
907 Bstr(pCtx->strDomain).raw(),
908 Bstr(pszSessionName).raw(),
909 pCtx->pGuestSession.asOutParam()));
910 }
911 catch (std::bad_alloc &)
912 {
913 RTMsgError("Out of memory setting up IGuest::CreateSession call");
914 rc = E_OUTOFMEMORY;
915 }
916 if (SUCCEEDED(rc))
917 {
918 /*
919 * Wait for guest session to start.
920 */
921 if (pCtx->cVerbose > 1)
922 RTPrintf("Waiting for guest session to start...\n");
923 GuestSessionWaitResult_T enmWaitResult;
924 try
925 {
926 com::SafeArray<GuestSessionWaitForFlag_T> aSessionWaitFlags;
927 aSessionWaitFlags.push_back(GuestSessionWaitForFlag_Start);
928 CHECK_ERROR(pCtx->pGuestSession, WaitForArray(ComSafeArrayAsInParam(aSessionWaitFlags),
929 /** @todo Make session handling timeouts configurable. */
930 30 * 1000, &enmWaitResult));
931 }
932 catch (std::bad_alloc &)
933 {
934 RTMsgError("Out of memory setting up IGuestSession::WaitForArray call");
935 rc = E_OUTOFMEMORY;
936 }
937 if (SUCCEEDED(rc))
938 {
939 /* The WaitFlagNotSupported result may happen with GAs older than 4.3. */
940 if ( enmWaitResult == GuestSessionWaitResult_Start
941 || enmWaitResult == GuestSessionWaitResult_WaitFlagNotSupported)
942 {
943 /*
944 * Get the session ID and we're ready to rumble.
945 */
946 CHECK_ERROR(pCtx->pGuestSession, COMGETTER(Id)(&pCtx->uSessionID));
947 if (SUCCEEDED(rc))
948 {
949 if (pCtx->cVerbose > 1)
950 RTPrintf("Successfully started guest session (ID %RU32)\n", pCtx->uSessionID);
951 RTStrFree(pszSessionName);
952 return RTEXITCODE_SUCCESS;
953 }
954 }
955 else
956 {
957 GuestSessionStatus_T enmSessionStatus;
958 CHECK_ERROR(pCtx->pGuestSession, COMGETTER(Status)(&enmSessionStatus));
959 RTMsgError("Error starting guest session (current status is: %s)\n",
960 SUCCEEDED(rc) ? gctlGuestSessionStatusToText(enmSessionStatus) : "<unknown>");
961 }
962 }
963 }
964
965 RTStrFree(pszSessionName);
966 return RTEXITCODE_FAILURE;
967}
968
969
970/**
971 * Completes the guest control context initialization after parsing arguments.
972 *
973 * Will validate common arguments, open a VM session, and if requested open a
974 * guest session and install the CTRL-C signal handler.
975 *
976 * It is good to validate all the options and arguments you can before making
977 * this call. However, the VM session, IGuest and IGuestSession interfaces are
978 * not availabe till after this call, so take care.
979 *
980 * @retval RTEXITCODE_SUCCESS on success.
981 * @retval RTEXITCODE_FAILURE and user message on failure.
982 * @param pCtx The guest control command context.
983 * GCTCMDCTX::pGuestSession and GCTLCMDCTX::uSessionID
984 * will be set.
985 * @remarks Can safely be called multiple times, will only do work once.
986 */
987static RTEXITCODE gctlCtxPostOptionParsingInit(PGCTLCMDCTX pCtx)
988{
989 if (pCtx->fPostOptionParsingInited)
990 return RTEXITCODE_SUCCESS;
991
992 /*
993 * Check that the user name isn't empty when we need it.
994 */
995 RTEXITCODE rcExit;
996 if ( (pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS)
997 || pCtx->strUsername.isNotEmpty())
998 {
999 /*
1000 * Open the VM session and if required, a guest session.
1001 */
1002 rcExit = gctlCtxInitVmSession(pCtx);
1003 if ( rcExit == RTEXITCODE_SUCCESS
1004 && !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS))
1005 rcExit = gctlCtxInitGuestSession(pCtx);
1006 if (rcExit == RTEXITCODE_SUCCESS)
1007 {
1008 /*
1009 * Install signal handler if requested (errors are ignored).
1010 */
1011 if (!(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_NO_SIGNAL_HANDLER))
1012 {
1013 int rc = gctlSignalHandlerInstall();
1014 pCtx->fInstalledSignalHandler = RT_SUCCESS(rc);
1015 }
1016 }
1017 }
1018 else
1019 rcExit = errorSyntaxEx(USAGE_GUESTCONTROL, pCtx->pCmdDef->fCmdUsage, "No user name specified!");
1020
1021 pCtx->fPostOptionParsingInited = rcExit == RTEXITCODE_SUCCESS;
1022 return rcExit;
1023}
1024
1025
1026/**
1027 * Cleans up the context when the command returns.
1028 *
1029 * This will close any open guest session, unless the DETACH flag is set.
1030 * It will also close any VM session that may be been established. Any signal
1031 * handlers we've installed will also be removed.
1032 *
1033 * Un-initializes the VM after guest control usage.
1034 * @param pCmdCtx Pointer to command context.
1035 */
1036static void gctlCtxTerm(PGCTLCMDCTX pCtx)
1037{
1038 HRESULT rc;
1039 AssertPtr(pCtx);
1040
1041 /*
1042 * Uninstall signal handler.
1043 */
1044 if (pCtx->fInstalledSignalHandler)
1045 {
1046 gctlSignalHandlerUninstall();
1047 pCtx->fInstalledSignalHandler = false;
1048 }
1049
1050 /*
1051 * Close, or at least release, the guest session.
1052 */
1053 if (pCtx->pGuestSession.isNotNull())
1054 {
1055 if ( !(pCtx->pCmdDef->fCmdCtx & GCTLCMDCTX_F_SESSION_ANONYMOUS)
1056 && !pCtx->fDetachGuestSession)
1057 {
1058 if (pCtx->cVerbose > 1)
1059 RTPrintf("Closing guest session ...\n");
1060
1061 CHECK_ERROR(pCtx->pGuestSession, Close());
1062 }
1063 else if ( pCtx->fDetachGuestSession
1064 && pCtx->cVerbose > 1)
1065 RTPrintf("Guest session detached\n");
1066
1067 pCtx->pGuestSession.setNull();
1068 }
1069
1070 /*
1071 * Close the VM session.
1072 */
1073 if (pCtx->fLockedVmSession)
1074 {
1075 Assert(pCtx->pArg->session.isNotNull());
1076 CHECK_ERROR(pCtx->pArg->session, UnlockMachine());
1077 pCtx->fLockedVmSession = false;
1078 }
1079}
1080
1081
1082
1083
1084
1085/*
1086 *
1087 *
1088 * Guest Control Command Handling.
1089 * Guest Control Command Handling.
1090 * Guest Control Command Handling.
1091 * Guest Control Command Handling.
1092 * Guest Control Command Handling.
1093 *
1094 *
1095 */
1096
1097
1098/** @name EXITCODEEXEC_XXX - Special run exit codes.
1099 *
1100 * Special exit codes for returning errors/information of a started guest
1101 * process to the command line VBoxManage was started from. Useful for e.g.
1102 * scripting.
1103 *
1104 * ASSUMING that all platforms have at least 7-bits for the exit code we can do
1105 * the following mapping:
1106 * - Guest exit code 0 is mapped to 0 on the host.
1107 * - Guest exit codes 1 thru 93 (0x5d) are displaced by 32, so that 1
1108 * becomes 33 (0x21) on the host and 93 becomes 125 (0x7d) on the host.
1109 * - Guest exit codes 94 (0x5e) and above are mapped to 126 (0x5e).
1110 *
1111 * We ASSUME that all VBoxManage status codes are in the range 0 thru 32.
1112 *
1113 * @note These are frozen as of 4.1.0.
1114 * @note The guest exit code mappings was introduced with 5.0 and the 'run'
1115 * command, they are/was not supported by 'exec'.
1116 * @sa gctlRunCalculateExitCode
1117 */
1118/** Process exited normally but with an exit code <> 0. */
1119#define EXITCODEEXEC_CODE ((RTEXITCODE)16)
1120#define EXITCODEEXEC_FAILED ((RTEXITCODE)17)
1121#define EXITCODEEXEC_TERM_SIGNAL ((RTEXITCODE)18)
1122#define EXITCODEEXEC_TERM_ABEND ((RTEXITCODE)19)
1123#define EXITCODEEXEC_TIMEOUT ((RTEXITCODE)20)
1124#define EXITCODEEXEC_DOWN ((RTEXITCODE)21)
1125/** Execution was interrupt by user (ctrl-c). */
1126#define EXITCODEEXEC_CANCELED ((RTEXITCODE)22)
1127/** The first mapped guest (non-zero) exit code. */
1128#define EXITCODEEXEC_MAPPED_FIRST 33
1129/** The last mapped guest (non-zero) exit code value (inclusive). */
1130#define EXITCODEEXEC_MAPPED_LAST 125
1131/** The number of exit codes from EXITCODEEXEC_MAPPED_FIRST to
1132 * EXITCODEEXEC_MAPPED_LAST. This is also the highest guest exit code number
1133 * we're able to map. */
1134#define EXITCODEEXEC_MAPPED_RANGE (93)
1135/** The guest exit code displacement value. */
1136#define EXITCODEEXEC_MAPPED_DISPLACEMENT 32
1137/** The guest exit code was too big to be mapped. */
1138#define EXITCODEEXEC_MAPPED_BIG ((RTEXITCODE)126)
1139/** @} */
1140
1141/**
1142 * Calculates the exit code of VBoxManage.
1143 *
1144 * @returns The exit code to return.
1145 * @param enmStatus The guest process status.
1146 * @param uExitCode The associated guest process exit code (where
1147 * applicable).
1148 * @param fReturnExitCodes Set if we're to use the 32-126 range for guest
1149 * exit codes.
1150 */
1151static RTEXITCODE gctlRunCalculateExitCode(ProcessStatus_T enmStatus, ULONG uExitCode, bool fReturnExitCodes)
1152{
1153 int vrc = RTEXITCODE_SUCCESS;
1154 switch (enmStatus)
1155 {
1156 case ProcessStatus_TerminatedNormally:
1157 if (uExitCode == 0)
1158 return RTEXITCODE_SUCCESS;
1159 if (!fReturnExitCodes)
1160 return EXITCODEEXEC_CODE;
1161 if (uExitCode <= EXITCODEEXEC_MAPPED_RANGE)
1162 return (RTEXITCODE) (uExitCode + EXITCODEEXEC_MAPPED_DISPLACEMENT);
1163 return EXITCODEEXEC_MAPPED_BIG;
1164
1165 case ProcessStatus_TerminatedAbnormally:
1166 return EXITCODEEXEC_TERM_ABEND;
1167 case ProcessStatus_TerminatedSignal:
1168 return EXITCODEEXEC_TERM_SIGNAL;
1169
1170#if 0 /* see caller! */
1171 case ProcessStatus_TimedOutKilled:
1172 return EXITCODEEXEC_TIMEOUT;
1173 case ProcessStatus_Down:
1174 return EXITCODEEXEC_DOWN; /* Service/OS is stopping, process was killed. */
1175 case ProcessStatus_Error:
1176 return EXITCODEEXEC_FAILED;
1177
1178 /* The following is probably for detached? */
1179 case ProcessStatus_Starting:
1180 return RTEXITCODE_SUCCESS;
1181 case ProcessStatus_Started:
1182 return RTEXITCODE_SUCCESS;
1183 case ProcessStatus_Paused:
1184 return RTEXITCODE_SUCCESS;
1185 case ProcessStatus_Terminating:
1186 return RTEXITCODE_SUCCESS; /** @todo ???? */
1187#endif
1188
1189 default:
1190 AssertMsgFailed(("Unknown exit status (%u/%u) from guest process returned!\n", enmStatus, uExitCode));
1191 return RTEXITCODE_FAILURE;
1192 }
1193}
1194
1195
1196/**
1197 * Pumps guest output to the host.
1198 *
1199 * @return IPRT status code.
1200 * @param pProcess Pointer to appropriate process object.
1201 * @param hVfsIosDst Where to write the data.
1202 * @param uHandle Handle where to read the data from.
1203 * @param cMsTimeout Timeout (in ms) to wait for the operation to
1204 * complete.
1205 */
1206static int gctlRunPumpOutput(IProcess *pProcess, RTVFSIOSTREAM hVfsIosDst, ULONG uHandle, RTMSINTERVAL cMsTimeout)
1207{
1208 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1209 Assert(hVfsIosDst != NIL_RTVFSIOSTREAM);
1210
1211 int vrc;
1212
1213 SafeArray<BYTE> aOutputData;
1214 HRESULT hrc = pProcess->Read(uHandle, _64K, RT_MAX(cMsTimeout, 1), ComSafeArrayAsOutParam(aOutputData));
1215 if (SUCCEEDED(hrc))
1216 {
1217 size_t cbOutputData = aOutputData.size();
1218 if (cbOutputData == 0)
1219 vrc = VINF_SUCCESS;
1220 else
1221 {
1222 BYTE const *pbBuf = aOutputData.raw();
1223 AssertPtr(pbBuf);
1224
1225 vrc = RTVfsIoStrmWrite(hVfsIosDst, pbBuf, cbOutputData, true /*fBlocking*/, NULL);
1226 if (RT_FAILURE(vrc))
1227 RTMsgError("Unable to write output, rc=%Rrc\n", vrc);
1228 }
1229 }
1230 else
1231 vrc = gctlPrintError(pProcess, COM_IIDOF(IProcess));
1232 return vrc;
1233}
1234
1235
1236/**
1237 * Configures a host handle for pumping guest bits.
1238 *
1239 * @returns true if enabled and we successfully configured it.
1240 * @param fEnabled Whether pumping this pipe is configured.
1241 * @param enmHandle The IPRT standard handle designation.
1242 * @param pszName The name for user messages.
1243 * @param enmTransformation The transformation to apply.
1244 * @param phVfsIos Where to return the resulting I/O stream handle.
1245 */
1246static bool gctlRunSetupHandle(bool fEnabled, RTHANDLESTD enmHandle, const char *pszName,
1247 kStreamTransform enmTransformation, PRTVFSIOSTREAM phVfsIos)
1248{
1249 if (fEnabled)
1250 {
1251 int vrc = RTVfsIoStrmFromStdHandle(enmHandle, 0, true /*fLeaveOpen*/, phVfsIos);
1252 if (RT_SUCCESS(vrc))
1253 {
1254 if (enmTransformation != kStreamTransform_None)
1255 {
1256 RTMsgWarning("Unsupported %s line ending conversion", pszName);
1257 /** @todo Implement dos2unix and unix2dos stream filters. */
1258 }
1259 return true;
1260 }
1261 RTMsgWarning("Error getting %s handle: %Rrc", pszName, vrc);
1262 }
1263 return false;
1264}
1265
1266
1267/**
1268 * Returns the remaining time (in ms) based on the start time and a set
1269 * timeout value. Returns RT_INDEFINITE_WAIT if no timeout was specified.
1270 *
1271 * @return RTMSINTERVAL Time left (in ms).
1272 * @param u64StartMs Start time (in ms).
1273 * @param cMsTimeout Timeout value (in ms).
1274 */
1275static RTMSINTERVAL gctlRunGetRemainingTime(uint64_t u64StartMs, RTMSINTERVAL cMsTimeout)
1276{
1277 if (!cMsTimeout || cMsTimeout == RT_INDEFINITE_WAIT) /* If no timeout specified, wait forever. */
1278 return RT_INDEFINITE_WAIT;
1279
1280 uint64_t u64ElapsedMs = RTTimeMilliTS() - u64StartMs;
1281 if (u64ElapsedMs >= cMsTimeout)
1282 return 0;
1283
1284 return cMsTimeout - (RTMSINTERVAL)u64ElapsedMs;
1285}
1286
1287/**
1288 * Common handler for the 'run' and 'start' commands.
1289 *
1290 * @returns Command exit code.
1291 * @param pCtx Guest session context.
1292 * @param argc The argument count.
1293 * @param argv The argument vector for this command.
1294 * @param fRunCmd Set if it's 'run' clear if 'start'.
1295 * @param fHelp The help flag for the command.
1296 */
1297static RTEXITCODE gctlHandleRunCommon(PGCTLCMDCTX pCtx, int argc, char **argv, bool fRunCmd, uint32_t fHelp)
1298{
1299 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
1300
1301 /*
1302 * Parse arguments.
1303 */
1304 enum kGstCtrlRunOpt
1305 {
1306 kGstCtrlRunOpt_IgnoreOrphanedProcesses = 1000,
1307 kGstCtrlRunOpt_NoProfile,
1308 kGstCtrlRunOpt_Dos2Unix,
1309 kGstCtrlRunOpt_Unix2Dos,
1310 kGstCtrlRunOpt_WaitForStdOut,
1311 kGstCtrlRunOpt_NoWaitForStdOut,
1312 kGstCtrlRunOpt_WaitForStdErr,
1313 kGstCtrlRunOpt_NoWaitForStdErr
1314 };
1315 static const RTGETOPTDEF s_aOptions[] =
1316 {
1317 GCTLCMD_COMMON_OPTION_DEFS()
1318 { "--putenv", 'E', RTGETOPT_REQ_STRING },
1319 { "--exe", 'e', RTGETOPT_REQ_STRING },
1320 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
1321 { "--unquoted-args", 'u', RTGETOPT_REQ_NOTHING },
1322 { "--ignore-operhaned-processes", kGstCtrlRunOpt_IgnoreOrphanedProcesses, RTGETOPT_REQ_NOTHING },
1323 { "--no-profile", kGstCtrlRunOpt_NoProfile, RTGETOPT_REQ_NOTHING },
1324 /* run only: 6 - options */
1325 { "--dos2unix", kGstCtrlRunOpt_Dos2Unix, RTGETOPT_REQ_NOTHING },
1326 { "--unix2dos", kGstCtrlRunOpt_Unix2Dos, RTGETOPT_REQ_NOTHING },
1327 { "--no-wait-stdout", kGstCtrlRunOpt_NoWaitForStdOut, RTGETOPT_REQ_NOTHING },
1328 { "--wait-stdout", kGstCtrlRunOpt_WaitForStdOut, RTGETOPT_REQ_NOTHING },
1329 { "--no-wait-stderr", kGstCtrlRunOpt_NoWaitForStdErr, RTGETOPT_REQ_NOTHING },
1330 { "--wait-stderr", kGstCtrlRunOpt_WaitForStdErr, RTGETOPT_REQ_NOTHING },
1331 };
1332
1333 /** @todo stdin handling. */
1334
1335 int ch;
1336 RTGETOPTUNION ValueUnion;
1337 RTGETOPTSTATE GetState;
1338 size_t cOptions =
1339 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions) - (fRunCmd ? 0 : 6),
1340 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1341
1342 com::SafeArray<ProcessCreateFlag_T> aCreateFlags;
1343 com::SafeArray<ProcessWaitForFlag_T> aWaitFlags;
1344 com::SafeArray<IN_BSTR> aArgs;
1345 com::SafeArray<IN_BSTR> aEnv;
1346 const char * pszImage = NULL;
1347 bool fWaitForStdOut = fRunCmd;
1348 bool fWaitForStdErr = fRunCmd;
1349 RTVFSIOSTREAM hVfsStdOut = NIL_RTVFSIOSTREAM;
1350 RTVFSIOSTREAM hVfsStdErr = NIL_RTVFSIOSTREAM;
1351 enum kStreamTransform enmStdOutTransform = kStreamTransform_None;
1352 enum kStreamTransform enmStdErrTransform = kStreamTransform_None;
1353 RTMSINTERVAL cMsTimeout = 0;
1354
1355 try
1356 {
1357 /* Wait for process start in any case. This is useful for scripting VBoxManage
1358 * when relying on its overall exit code. */
1359 aWaitFlags.push_back(ProcessWaitForFlag_Start);
1360
1361 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
1362 {
1363 /* For options that require an argument, ValueUnion has received the value. */
1364 switch (ch)
1365 {
1366 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
1367
1368 case 'E':
1369 if ( ValueUnion.psz[0] == '\0'
1370 || ValueUnion.psz[0] == '=')
1371 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RUN,
1372 "Invalid argument variable[=value]: '%s'", ValueUnion.psz);
1373 aEnv.push_back(Bstr(ValueUnion.psz).raw());
1374 break;
1375
1376 case kGstCtrlRunOpt_IgnoreOrphanedProcesses:
1377 aCreateFlags.push_back(ProcessCreateFlag_IgnoreOrphanedProcesses);
1378 break;
1379
1380 case kGstCtrlRunOpt_NoProfile:
1381 aCreateFlags.push_back(ProcessCreateFlag_NoProfile);
1382 break;
1383
1384 case 'e':
1385 pszImage = ValueUnion.psz;
1386 break;
1387
1388 case 'u':
1389 aCreateFlags.push_back(ProcessCreateFlag_UnquotedArguments);
1390 break;
1391
1392 /** @todo Add a hidden flag. */
1393
1394 case 't': /* Timeout */
1395 cMsTimeout = ValueUnion.u32;
1396 break;
1397
1398 /* run only options: */
1399 case kGstCtrlRunOpt_Dos2Unix:
1400 Assert(fRunCmd);
1401 enmStdErrTransform = enmStdOutTransform = kStreamTransform_Dos2Unix;
1402 break;
1403 case kGstCtrlRunOpt_Unix2Dos:
1404 Assert(fRunCmd);
1405 enmStdErrTransform = enmStdOutTransform = kStreamTransform_Unix2Dos;
1406 break;
1407
1408 case kGstCtrlRunOpt_WaitForStdOut:
1409 Assert(fRunCmd);
1410 fWaitForStdOut = true;
1411 break;
1412 case kGstCtrlRunOpt_NoWaitForStdOut:
1413 Assert(fRunCmd);
1414 fWaitForStdOut = false;
1415 break;
1416
1417 case kGstCtrlRunOpt_WaitForStdErr:
1418 Assert(fRunCmd);
1419 fWaitForStdErr = true;
1420 break;
1421 case kGstCtrlRunOpt_NoWaitForStdErr:
1422 Assert(fRunCmd);
1423 fWaitForStdErr = false;
1424 break;
1425
1426 case VINF_GETOPT_NOT_OPTION:
1427 aArgs.push_back(Bstr(ValueUnion.psz).raw());
1428 if (!pszImage)
1429 {
1430 Assert(aArgs.size() == 1);
1431 pszImage = ValueUnion.psz;
1432 }
1433 break;
1434
1435 default:
1436 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RUN, ch, &ValueUnion);
1437
1438 } /* switch */
1439 } /* while RTGetOpt */
1440
1441 /* Must have something to execute. */
1442 if (!pszImage || !*pszImage)
1443 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RUN, "No executable specified!");
1444
1445 /*
1446 * Finalize process creation and wait flags and input/output streams.
1447 */
1448 if (!fRunCmd)
1449 {
1450 aCreateFlags.push_back(ProcessCreateFlag_WaitForProcessStartOnly);
1451 Assert(!fWaitForStdOut);
1452 Assert(!fWaitForStdErr);
1453 }
1454 else
1455 {
1456 aWaitFlags.push_back(ProcessWaitForFlag_Terminate);
1457 fWaitForStdOut = gctlRunSetupHandle(fWaitForStdOut, RTHANDLESTD_OUTPUT, "stdout", enmStdOutTransform, &hVfsStdOut);
1458 if (fWaitForStdOut)
1459 {
1460 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdOut);
1461 aWaitFlags.push_back(ProcessWaitForFlag_StdOut);
1462 }
1463 fWaitForStdErr = gctlRunSetupHandle(fWaitForStdErr, RTHANDLESTD_ERROR, "stderr", enmStdErrTransform, &hVfsStdErr);
1464 if (fWaitForStdErr)
1465 {
1466 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdErr);
1467 aWaitFlags.push_back(ProcessWaitForFlag_StdErr);
1468 }
1469 }
1470 }
1471 catch (std::bad_alloc &)
1472 {
1473 return RTMsgErrorExit(RTEXITCODE_FAILURE, "VERR_NO_MEMORY\n");
1474 }
1475
1476 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
1477 if (rcExit != RTEXITCODE_SUCCESS)
1478 return rcExit;
1479
1480 HRESULT rc;
1481
1482 try
1483 {
1484 do
1485 {
1486 /* Get current time stamp to later calculate rest of timeout left. */
1487 uint64_t msStart = RTTimeMilliTS();
1488
1489 /*
1490 * Create the process.
1491 */
1492 if (pCtx->cVerbose > 1)
1493 {
1494 if (cMsTimeout == 0)
1495 RTPrintf("Starting guest process ...\n");
1496 else
1497 RTPrintf("Starting guest process (within %ums)\n", cMsTimeout);
1498 }
1499 ComPtr<IGuestProcess> pProcess;
1500 CHECK_ERROR_BREAK(pCtx->pGuestSession, ProcessCreate(Bstr(pszImage).raw(),
1501 ComSafeArrayAsInParam(aArgs),
1502 ComSafeArrayAsInParam(aEnv),
1503 ComSafeArrayAsInParam(aCreateFlags),
1504 gctlRunGetRemainingTime(msStart, cMsTimeout),
1505 pProcess.asOutParam()));
1506
1507 /*
1508 * Explicitly wait for the guest process to be in a started state.
1509 */
1510 com::SafeArray<ProcessWaitForFlag_T> aWaitStartFlags;
1511 aWaitStartFlags.push_back(ProcessWaitForFlag_Start);
1512 ProcessWaitResult_T waitResult;
1513 CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitStartFlags),
1514 gctlRunGetRemainingTime(msStart, cMsTimeout), &waitResult));
1515
1516 ULONG uPID = 0;
1517 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
1518 if (fRunCmd && pCtx->cVerbose > 1)
1519 RTPrintf("Process '%s' (PID %RU32) started\n", pszImage, uPID);
1520 else if (!fRunCmd && pCtx->cVerbose)
1521 {
1522 /* Just print plain PID to make it easier for scripts
1523 * invoking VBoxManage. */
1524 RTPrintf("[%RU32 - Session %RU32]\n", uPID, pCtx->uSessionID);
1525 }
1526
1527 /*
1528 * Wait for process to exit/start...
1529 */
1530 RTMSINTERVAL cMsTimeLeft = 1; /* Will be calculated. */
1531 bool fReadStdOut = false;
1532 bool fReadStdErr = false;
1533 bool fCompleted = false;
1534 bool fCompletedStartCmd = false;
1535 int vrc = VINF_SUCCESS;
1536
1537 while ( !fCompleted
1538 && cMsTimeLeft > 0)
1539 {
1540 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1541 CHECK_ERROR_BREAK(pProcess, WaitForArray(ComSafeArrayAsInParam(aWaitFlags),
1542 RT_MIN(500 /*ms*/, RT_MAX(cMsTimeLeft, 1 /*ms*/)),
1543 &waitResult));
1544 switch (waitResult)
1545 {
1546 case ProcessWaitResult_Start:
1547 fCompletedStartCmd = fCompleted = !fRunCmd; /* Only wait for startup if the 'start' command. */
1548 break;
1549 case ProcessWaitResult_StdOut:
1550 fReadStdOut = true;
1551 break;
1552 case ProcessWaitResult_StdErr:
1553 fReadStdErr = true;
1554 break;
1555 case ProcessWaitResult_Terminate:
1556 if (pCtx->cVerbose > 1)
1557 RTPrintf("Process terminated\n");
1558 /* Process terminated, we're done. */
1559 fCompleted = true;
1560 break;
1561 case ProcessWaitResult_WaitFlagNotSupported:
1562 /* The guest does not support waiting for stdout/err, so
1563 * yield to reduce the CPU load due to busy waiting. */
1564 RTThreadYield();
1565 fReadStdOut = fReadStdErr = true;
1566 break;
1567 case ProcessWaitResult_Timeout:
1568 {
1569 /** @todo It is really unclear whether we will get stuck with the timeout
1570 * result here if the guest side times out the process and fails to
1571 * kill the process... To be on the save side, double the IPC and
1572 * check the process status every time we time out. */
1573 ProcessStatus_T enmProcStatus;
1574 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&enmProcStatus));
1575 if ( enmProcStatus == ProcessStatus_TimedOutKilled
1576 || enmProcStatus == ProcessStatus_TimedOutAbnormally)
1577 fCompleted = true;
1578 fReadStdOut = fReadStdErr = true;
1579 break;
1580 }
1581 case ProcessWaitResult_Status:
1582 /* ignore. */
1583 break;
1584 case ProcessWaitResult_Error:
1585 /* waitFor is dead in the water, I think, so better leave the loop. */
1586 vrc = VERR_CALLBACK_RETURN;
1587 break;
1588
1589 case ProcessWaitResult_StdIn: AssertFailed(); /* did ask for this! */ break;
1590 case ProcessWaitResult_None: AssertFailed(); /* used. */ break;
1591 default: AssertFailed(); /* huh? */ break;
1592 }
1593
1594 if (g_fGuestCtrlCanceled)
1595 break;
1596
1597 /*
1598 * Pump output as needed.
1599 */
1600 if (fReadStdOut)
1601 {
1602 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1603 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdOut, 1 /* StdOut */, cMsTimeLeft);
1604 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1605 vrc = vrc2;
1606 fReadStdOut = false;
1607 }
1608 if (fReadStdErr)
1609 {
1610 cMsTimeLeft = gctlRunGetRemainingTime(msStart, cMsTimeout);
1611 int vrc2 = gctlRunPumpOutput(pProcess, hVfsStdErr, 2 /* StdErr */, cMsTimeLeft);
1612 if (RT_FAILURE(vrc2) && RT_SUCCESS(vrc))
1613 vrc = vrc2;
1614 fReadStdErr = false;
1615 }
1616 if ( RT_FAILURE(vrc)
1617 || g_fGuestCtrlCanceled)
1618 break;
1619
1620 /*
1621 * Process events before looping.
1622 */
1623 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
1624 } /* while */
1625
1626 /*
1627 * Report status back to the user.
1628 */
1629 if (g_fGuestCtrlCanceled)
1630 {
1631 if (pCtx->cVerbose > 1)
1632 RTPrintf("Process execution aborted!\n");
1633 rcExit = EXITCODEEXEC_CANCELED;
1634 }
1635 else if (fCompletedStartCmd)
1636 {
1637 if (pCtx->cVerbose > 1)
1638 RTPrintf("Process successfully started!\n");
1639 rcExit = RTEXITCODE_SUCCESS;
1640 }
1641 else if (fCompleted)
1642 {
1643 ProcessStatus_T procStatus;
1644 CHECK_ERROR_BREAK(pProcess, COMGETTER(Status)(&procStatus));
1645 if ( procStatus == ProcessStatus_TerminatedNormally
1646 || procStatus == ProcessStatus_TerminatedAbnormally
1647 || procStatus == ProcessStatus_TerminatedSignal)
1648 {
1649 LONG lExitCode;
1650 CHECK_ERROR_BREAK(pProcess, COMGETTER(ExitCode)(&lExitCode));
1651 if (pCtx->cVerbose > 1)
1652 RTPrintf("Exit code=%u (Status=%u [%s])\n",
1653 lExitCode, procStatus, gctlProcessStatusToText(procStatus));
1654
1655 rcExit = gctlRunCalculateExitCode(procStatus, lExitCode, true /*fReturnExitCodes*/);
1656 }
1657 else if ( procStatus == ProcessStatus_TimedOutKilled
1658 || procStatus == ProcessStatus_TimedOutAbnormally)
1659 {
1660 if (pCtx->cVerbose > 1)
1661 RTPrintf("Process timed out (guest side) and\n",
1662 procStatus == ProcessStatus_TimedOutAbnormally
1663 ? " failed to terminate so far" : " was terminated");
1664 rcExit = EXITCODEEXEC_TIMEOUT;
1665 }
1666 else
1667 {
1668 if (pCtx->cVerbose > 1)
1669 RTPrintf("Process now is in status [%s] (unexpected)\n", gctlProcessStatusToText(procStatus));
1670 rcExit = RTEXITCODE_FAILURE;
1671 }
1672 }
1673 else if (RT_FAILURE_NP(vrc))
1674 {
1675 if (pCtx->cVerbose > 1)
1676 RTPrintf("Process monitor loop quit with vrc=%Rrc\n", vrc);
1677 rcExit = RTEXITCODE_FAILURE;
1678 }
1679 else
1680 {
1681 if (pCtx->cVerbose > 1)
1682 RTPrintf("Process monitor loop timed out\n");
1683 rcExit = EXITCODEEXEC_TIMEOUT;
1684 }
1685
1686 } while (0);
1687 }
1688 catch (std::bad_alloc)
1689 {
1690 rc = E_OUTOFMEMORY;
1691 }
1692
1693 /*
1694 * Decide what to do with the guest session.
1695 *
1696 * If it's the 'start' command where detach the guest process after
1697 * starting, don't close the guest session it is part of, except on
1698 * failure or ctrl-c.
1699 *
1700 * For the 'run' command the guest process quits with us.
1701 */
1702 if (!fRunCmd && SUCCEEDED(rc) && !g_fGuestCtrlCanceled)
1703 pCtx->fDetachGuestSession = true;
1704
1705 /* Make sure we return failure on failure. */
1706 if (FAILED(rc) && rcExit == RTEXITCODE_SUCCESS)
1707 rcExit = RTEXITCODE_FAILURE;
1708 return rcExit;
1709}
1710
1711
1712static DECLCALLBACK(RTEXITCODE) gctlHandleRun(PGCTLCMDCTX pCtx, int argc, char **argv)
1713{
1714 return gctlHandleRunCommon(pCtx, argc, argv, true /*fRunCmd*/, USAGE_GSTCTRL_RUN);
1715}
1716
1717
1718static DECLCALLBACK(RTEXITCODE) gctlHandleStart(PGCTLCMDCTX pCtx, int argc, char **argv)
1719{
1720 return gctlHandleRunCommon(pCtx, argc, argv, false /*fRunCmd*/, USAGE_GSTCTRL_START);
1721}
1722
1723
1724/**
1725 * Creates a copy context structure which then can be used with various
1726 * guest control copy functions. Needs to be free'd with gctlCopyContextFree().
1727 *
1728 * @return IPRT status code.
1729 * @param pCtx Pointer to command context.
1730 * @param fDryRun Flag indicating if we want to run a dry run only.
1731 * @param fHostToGuest Flag indicating if we want to copy from host to guest
1732 * or vice versa.
1733 * @param strSessionName Session name (only for identification purposes).
1734 * @param ppContext Pointer which receives the allocated copy context.
1735 */
1736static int gctlCopyContextCreate(PGCTLCMDCTX pCtx, bool fDryRun, bool fHostToGuest,
1737 const Utf8Str &strSessionName,
1738 PCOPYCONTEXT *ppContext)
1739{
1740 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
1741
1742 int vrc = VINF_SUCCESS;
1743 try
1744 {
1745 PCOPYCONTEXT pContext = new COPYCONTEXT();
1746
1747 pContext->pCmdCtx = pCtx;
1748 pContext->fDryRun = fDryRun;
1749 pContext->fHostToGuest = fHostToGuest;
1750
1751 *ppContext = pContext;
1752 }
1753 catch (std::bad_alloc)
1754 {
1755 vrc = VERR_NO_MEMORY;
1756 }
1757
1758 return vrc;
1759}
1760
1761/**
1762 * Frees are previously allocated copy context structure.
1763 *
1764 * @param pContext Pointer to copy context to free.
1765 */
1766static void gctlCopyContextFree(PCOPYCONTEXT pContext)
1767{
1768 if (pContext)
1769 delete pContext;
1770}
1771
1772/**
1773 * Translates a source path to a destination path (can be both sides,
1774 * either host or guest). The source root is needed to determine the start
1775 * of the relative source path which also needs to present in the destination
1776 * path.
1777 *
1778 * @return IPRT status code.
1779 * @param pszSourceRoot Source root path. No trailing directory slash!
1780 * @param pszSource Actual source to transform. Must begin with
1781 * the source root path!
1782 * @param pszDest Destination path.
1783 * @param ppszTranslated Pointer to the allocated, translated destination
1784 * path. Must be free'd with RTStrFree().
1785 */
1786static int gctlCopyTranslatePath(const char *pszSourceRoot, const char *pszSource,
1787 const char *pszDest, char **ppszTranslated)
1788{
1789 AssertPtrReturn(pszSourceRoot, VERR_INVALID_POINTER);
1790 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1791 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1792 AssertPtrReturn(ppszTranslated, VERR_INVALID_POINTER);
1793#if 0 /** @todo r=bird: It does not make sense to apply host path parsing semantics onto guest paths. I hope this code isn't mixing host/guest paths in the same way anywhere else... @bugref{6344} */
1794 AssertReturn(RTPathStartsWith(pszSource, pszSourceRoot), VERR_INVALID_PARAMETER);
1795#endif
1796
1797 /* Construct the relative dest destination path by "subtracting" the
1798 * source from the source root, e.g.
1799 *
1800 * source root path = "e:\foo\", source = "e:\foo\bar"
1801 * dest = "d:\baz\"
1802 * translated = "d:\baz\bar\"
1803 */
1804 char szTranslated[RTPATH_MAX];
1805 size_t srcOff = strlen(pszSourceRoot);
1806 AssertReturn(srcOff, VERR_INVALID_PARAMETER);
1807
1808 char *pszDestPath = RTStrDup(pszDest);
1809 AssertPtrReturn(pszDestPath, VERR_NO_MEMORY);
1810
1811 int vrc;
1812 if (!RTPathFilename(pszDestPath))
1813 {
1814 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1815 pszDestPath, &pszSource[srcOff]);
1816 }
1817 else
1818 {
1819 char *pszDestFileName = RTStrDup(RTPathFilename(pszDestPath));
1820 if (pszDestFileName)
1821 {
1822 RTPathStripFilename(pszDestPath);
1823 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1824 pszDestPath, pszDestFileName);
1825 RTStrFree(pszDestFileName);
1826 }
1827 else
1828 vrc = VERR_NO_MEMORY;
1829 }
1830 RTStrFree(pszDestPath);
1831
1832 if (RT_SUCCESS(vrc))
1833 {
1834 *ppszTranslated = RTStrDup(szTranslated);
1835#if 0
1836 RTPrintf("Root: %s, Source: %s, Dest: %s, Translated: %s\n",
1837 pszSourceRoot, pszSource, pszDest, *ppszTranslated);
1838#endif
1839 }
1840 return vrc;
1841}
1842
1843#ifdef DEBUG_andy
1844static int tstTranslatePath()
1845{
1846 RTAssertSetMayPanic(false /* Do not freak out, please. */);
1847
1848 static struct
1849 {
1850 const char *pszSourceRoot;
1851 const char *pszSource;
1852 const char *pszDest;
1853 const char *pszTranslated;
1854 int iResult;
1855 } aTests[] =
1856 {
1857 /* Invalid stuff. */
1858 { NULL, NULL, NULL, NULL, VERR_INVALID_POINTER },
1859#ifdef RT_OS_WINDOWS
1860 /* Windows paths. */
1861 { "c:\\foo", "c:\\foo\\bar.txt", "c:\\test", "c:\\test\\bar.txt", VINF_SUCCESS },
1862 { "c:\\foo", "c:\\foo\\baz\\bar.txt", "c:\\test", "c:\\test\\baz\\bar.txt", VINF_SUCCESS },
1863#else /* RT_OS_WINDOWS */
1864 { "/home/test/foo", "/home/test/foo/bar.txt", "/opt/test", "/opt/test/bar.txt", VINF_SUCCESS },
1865 { "/home/test/foo", "/home/test/foo/baz/bar.txt", "/opt/test", "/opt/test/baz/bar.txt", VINF_SUCCESS },
1866#endif /* !RT_OS_WINDOWS */
1867 /* Mixed paths*/
1868 /** @todo */
1869 { NULL }
1870 };
1871
1872 size_t iTest = 0;
1873 for (iTest; iTest < RT_ELEMENTS(aTests); iTest++)
1874 {
1875 RTPrintf("=> Test %d\n", iTest);
1876 RTPrintf("\tSourceRoot=%s, Source=%s, Dest=%s\n",
1877 aTests[iTest].pszSourceRoot, aTests[iTest].pszSource, aTests[iTest].pszDest);
1878
1879 char *pszTranslated = NULL;
1880 int iResult = gctlCopyTranslatePath(aTests[iTest].pszSourceRoot, aTests[iTest].pszSource,
1881 aTests[iTest].pszDest, &pszTranslated);
1882 if (iResult != aTests[iTest].iResult)
1883 {
1884 RTPrintf("\tReturned %Rrc, expected %Rrc\n",
1885 iResult, aTests[iTest].iResult);
1886 }
1887 else if ( pszTranslated
1888 && strcmp(pszTranslated, aTests[iTest].pszTranslated))
1889 {
1890 RTPrintf("\tReturned translated path %s, expected %s\n",
1891 pszTranslated, aTests[iTest].pszTranslated);
1892 }
1893
1894 if (pszTranslated)
1895 {
1896 RTPrintf("\tTranslated=%s\n", pszTranslated);
1897 RTStrFree(pszTranslated);
1898 }
1899 }
1900
1901 return VINF_SUCCESS; /* @todo */
1902}
1903#endif
1904
1905/**
1906 * Creates a directory on the destination, based on the current copy
1907 * context.
1908 *
1909 * @return IPRT status code.
1910 * @param pContext Pointer to current copy control context.
1911 * @param pszDir Directory to create.
1912 */
1913static int gctlCopyDirCreate(PCOPYCONTEXT pContext, const char *pszDir)
1914{
1915 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1916 AssertPtrReturn(pszDir, VERR_INVALID_POINTER);
1917
1918 bool fDirExists;
1919 int vrc = gctlCopyDirExists(pContext, pContext->fHostToGuest, pszDir, &fDirExists);
1920 if ( RT_SUCCESS(vrc)
1921 && fDirExists)
1922 {
1923 if (pContext->pCmdCtx->cVerbose > 1)
1924 RTPrintf("Directory \"%s\" already exists\n", pszDir);
1925 return VINF_SUCCESS;
1926 }
1927
1928 /* If querying for a directory existence fails there's no point of even trying
1929 * to create such a directory. */
1930 if (RT_FAILURE(vrc))
1931 return vrc;
1932
1933 if (pContext->pCmdCtx->cVerbose > 1)
1934 RTPrintf("Creating directory \"%s\" ...\n", pszDir);
1935
1936 if (pContext->fDryRun)
1937 return VINF_SUCCESS;
1938
1939 if (pContext->fHostToGuest) /* We want to create directories on the guest. */
1940 {
1941 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
1942 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1943 HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryCreate(Bstr(pszDir).raw(),
1944 0700, ComSafeArrayAsInParam(dirCreateFlags));
1945 if (FAILED(rc))
1946 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
1947 }
1948 else /* ... or on the host. */
1949 {
1950 vrc = RTDirCreateFullPath(pszDir, 0700);
1951 if (vrc == VERR_ALREADY_EXISTS)
1952 vrc = VINF_SUCCESS;
1953 }
1954 return vrc;
1955}
1956
1957/**
1958 * Checks whether a specific host/guest directory exists.
1959 *
1960 * @return IPRT status code.
1961 * @param pContext Pointer to current copy control context.
1962 * @param fOnGuest true if directory needs to be checked on the guest
1963 * or false if on the host.
1964 * @param pszDir Actual directory to check.
1965 * @param fExists Pointer which receives the result if the
1966 * given directory exists or not.
1967 */
1968static int gctlCopyDirExists(PCOPYCONTEXT pContext, bool fOnGuest,
1969 const char *pszDir, bool *fExists)
1970{
1971 AssertPtrReturn(pContext, false);
1972 AssertPtrReturn(pszDir, false);
1973 AssertPtrReturn(fExists, false);
1974
1975 int vrc = VINF_SUCCESS;
1976 if (fOnGuest)
1977 {
1978 BOOL fDirExists = FALSE;
1979 HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryExists(Bstr(pszDir).raw(), &fDirExists);
1980 if (FAILED(rc))
1981 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
1982 else
1983 *fExists = fDirExists ? true : false;
1984 }
1985 else
1986 *fExists = RTDirExists(pszDir);
1987 return vrc;
1988}
1989
1990/**
1991 * Checks whether a specific directory exists on the destination, based
1992 * on the current copy context.
1993 *
1994 * @return IPRT status code.
1995 * @param pContext Pointer to current copy control context.
1996 * @param pszDir Actual directory to check.
1997 * @param fExists Pointer which receives the result if the
1998 * given directory exists or not.
1999 */
2000static int gctlCopyDirExistsOnDest(PCOPYCONTEXT pContext, const char *pszDir,
2001 bool *fExists)
2002{
2003 return gctlCopyDirExists(pContext, pContext->fHostToGuest,
2004 pszDir, fExists);
2005}
2006
2007/**
2008 * Checks whether a specific directory exists on the source, based
2009 * on the current copy context.
2010 *
2011 * @return IPRT status code.
2012 * @param pContext Pointer to current copy control context.
2013 * @param pszDir Actual directory to check.
2014 * @param fExists Pointer which receives the result if the
2015 * given directory exists or not.
2016 */
2017static int gctlCopyDirExistsOnSource(PCOPYCONTEXT pContext, const char *pszDir,
2018 bool *fExists)
2019{
2020 return gctlCopyDirExists(pContext, !pContext->fHostToGuest,
2021 pszDir, fExists);
2022}
2023
2024/**
2025 * Checks whether a specific host/guest file exists.
2026 *
2027 * @return IPRT status code.
2028 * @param pContext Pointer to current copy control context.
2029 * @param bGuest true if file needs to be checked on the guest
2030 * or false if on the host.
2031 * @param pszFile Actual file to check.
2032 * @param fExists Pointer which receives the result if the
2033 * given file exists or not.
2034 */
2035static int gctlCopyFileExists(PCOPYCONTEXT pContext, bool bOnGuest,
2036 const char *pszFile, bool *fExists)
2037{
2038 AssertPtrReturn(pContext, false);
2039 AssertPtrReturn(pszFile, false);
2040 AssertPtrReturn(fExists, false);
2041
2042 int vrc = VINF_SUCCESS;
2043 if (bOnGuest)
2044 {
2045 BOOL fFileExists = FALSE;
2046 HRESULT rc = pContext->pCmdCtx->pGuestSession->FileExists(Bstr(pszFile).raw(), &fFileExists);
2047 if (FAILED(rc))
2048 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2049 else
2050 *fExists = fFileExists ? true : false;
2051 }
2052 else
2053 *fExists = RTFileExists(pszFile);
2054 return vrc;
2055}
2056
2057/**
2058 * Checks whether a specific file exists on the destination, based on the
2059 * current copy context.
2060 *
2061 * @return IPRT status code.
2062 * @param pContext Pointer to current copy control context.
2063 * @param pszFile Actual file to check.
2064 * @param fExists Pointer which receives the result if the
2065 * given file exists or not.
2066 */
2067static int gctlCopyFileExistsOnDest(PCOPYCONTEXT pContext, const char *pszFile,
2068 bool *fExists)
2069{
2070 return gctlCopyFileExists(pContext, pContext->fHostToGuest,
2071 pszFile, fExists);
2072}
2073
2074/**
2075 * Checks whether a specific file exists on the source, based on the
2076 * current copy context.
2077 *
2078 * @return IPRT status code.
2079 * @param pContext Pointer to current copy control context.
2080 * @param pszFile Actual file to check.
2081 * @param fExists Pointer which receives the result if the
2082 * given file exists or not.
2083 */
2084static int gctlCopyFileExistsOnSource(PCOPYCONTEXT pContext, const char *pszFile,
2085 bool *fExists)
2086{
2087 return gctlCopyFileExists(pContext, !pContext->fHostToGuest,
2088 pszFile, fExists);
2089}
2090
2091/**
2092 * Copies a source file to the destination.
2093 *
2094 * @return IPRT status code.
2095 * @param pContext Pointer to current copy control context.
2096 * @param pszFileSource Source file to copy to the destination.
2097 * @param pszFileDest Name of copied file on the destination.
2098 * @param fFlags Copy flags. No supported at the moment and needs
2099 * to be set to 0.
2100 */
2101static int gctlCopyFileToDest(PCOPYCONTEXT pContext, const char *pszFileSource,
2102 const char *pszFileDest, uint32_t fFlags)
2103{
2104 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
2105 AssertPtrReturn(pszFileSource, VERR_INVALID_POINTER);
2106 AssertPtrReturn(pszFileDest, VERR_INVALID_POINTER);
2107 AssertReturn(!fFlags, VERR_INVALID_POINTER); /* No flags supported yet. */
2108
2109 if (pContext->pCmdCtx->cVerbose > 1)
2110 RTPrintf("Copying \"%s\" to \"%s\" ...\n",
2111 pszFileSource, pszFileDest);
2112
2113 if (pContext->fDryRun)
2114 return VINF_SUCCESS;
2115
2116 int vrc = VINF_SUCCESS;
2117 ComPtr<IProgress> pProgress;
2118 HRESULT rc;
2119 if (pContext->fHostToGuest)
2120 {
2121 SafeArray<CopyFileFlag_T> copyFlags;
2122 rc = pContext->pCmdCtx->pGuestSession->CopyTo(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
2123 ComSafeArrayAsInParam(copyFlags),
2124 pProgress.asOutParam());
2125 }
2126 else
2127 {
2128 SafeArray<CopyFileFlag_T> copyFlags;
2129 rc = pContext->pCmdCtx->pGuestSession->CopyFrom(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
2130 ComSafeArrayAsInParam(copyFlags),
2131 pProgress.asOutParam());
2132 }
2133
2134 if (FAILED(rc))
2135 {
2136 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2137 }
2138 else
2139 {
2140 if (pContext->pCmdCtx->cVerbose > 1)
2141 rc = showProgress(pProgress);
2142 else
2143 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
2144 if (SUCCEEDED(rc))
2145 CHECK_PROGRESS_ERROR(pProgress, ("File copy failed"));
2146 vrc = gctlPrintProgressError(pProgress);
2147 }
2148
2149 return vrc;
2150}
2151
2152/**
2153 * Copys a directory (tree) from host to the guest.
2154 *
2155 * @return IPRT status code.
2156 * @param pContext Pointer to current copy control context.
2157 * @param pszSource Source directory on the host to copy to the guest.
2158 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
2159 * @param pszDest Destination directory on the guest.
2160 * @param fFlags Copy flags, such as recursive copying.
2161 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
2162 * is needed for recursion.
2163 */
2164static int gctlCopyDirToGuest(PCOPYCONTEXT pContext,
2165 const char *pszSource, const char *pszFilter,
2166 const char *pszDest, uint32_t fFlags,
2167 const char *pszSubDir /* For recursion. */)
2168{
2169 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
2170 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
2171 /* Filter is optional. */
2172 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
2173 /* Sub directory is optional. */
2174
2175 /*
2176 * Construct current path.
2177 */
2178 char szCurDir[RTPATH_MAX];
2179 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
2180 if (RT_SUCCESS(vrc) && pszSubDir)
2181 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
2182
2183 if (pContext->pCmdCtx->cVerbose > 1)
2184 RTPrintf("Processing host directory: %s\n", szCurDir);
2185
2186 /* Flag indicating whether the current directory was created on the
2187 * target or not. */
2188 bool fDirCreated = false;
2189
2190 /*
2191 * Open directory without a filter - RTDirOpenFiltered unfortunately
2192 * cannot handle sub directories so we have to do the filtering ourselves.
2193 */
2194 PRTDIR pDir = NULL;
2195 if (RT_SUCCESS(vrc))
2196 {
2197 vrc = RTDirOpen(&pDir, szCurDir);
2198 if (RT_FAILURE(vrc))
2199 pDir = NULL;
2200 }
2201 if (RT_SUCCESS(vrc))
2202 {
2203 /*
2204 * Enumerate the directory tree.
2205 */
2206 while (RT_SUCCESS(vrc))
2207 {
2208 RTDIRENTRY DirEntry;
2209 vrc = RTDirRead(pDir, &DirEntry, NULL);
2210 if (RT_FAILURE(vrc))
2211 {
2212 if (vrc == VERR_NO_MORE_FILES)
2213 vrc = VINF_SUCCESS;
2214 break;
2215 }
2216 /** @todo r=bird: This ain't gonna work on most UNIX file systems because
2217 * enmType is RTDIRENTRYTYPE_UNKNOWN. This is clearly documented in
2218 * RTDIRENTRY::enmType. For trunk, RTDirQueryUnknownType can be used. */
2219 switch (DirEntry.enmType)
2220 {
2221 case RTDIRENTRYTYPE_DIRECTORY:
2222 {
2223 /* Skip "." and ".." entries. */
2224 if ( !strcmp(DirEntry.szName, ".")
2225 || !strcmp(DirEntry.szName, ".."))
2226 break;
2227
2228 if (pContext->pCmdCtx->cVerbose > 1)
2229 RTPrintf("Directory: %s\n", DirEntry.szName);
2230
2231 if (fFlags & CopyFileFlag_Recursive)
2232 {
2233 char *pszNewSub = NULL;
2234 if (pszSubDir)
2235 pszNewSub = RTPathJoinA(pszSubDir, DirEntry.szName);
2236 else
2237 {
2238 pszNewSub = RTStrDup(DirEntry.szName);
2239 RTPathStripTrailingSlash(pszNewSub);
2240 }
2241
2242 if (pszNewSub)
2243 {
2244 vrc = gctlCopyDirToGuest(pContext,
2245 pszSource, pszFilter,
2246 pszDest, fFlags, pszNewSub);
2247 RTStrFree(pszNewSub);
2248 }
2249 else
2250 vrc = VERR_NO_MEMORY;
2251 }
2252 break;
2253 }
2254
2255 case RTDIRENTRYTYPE_SYMLINK:
2256 if ( (fFlags & CopyFileFlag_Recursive)
2257 && (fFlags & CopyFileFlag_FollowLinks))
2258 {
2259 /* Fall through to next case is intentional. */
2260 }
2261 else
2262 break;
2263
2264 case RTDIRENTRYTYPE_FILE:
2265 {
2266 if ( pszFilter
2267 && !RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
2268 {
2269 break; /* Filter does not match. */
2270 }
2271
2272 if (pContext->pCmdCtx->cVerbose > 1)
2273 RTPrintf("File: %s\n", DirEntry.szName);
2274
2275 if (!fDirCreated)
2276 {
2277 char *pszDestDir;
2278 vrc = gctlCopyTranslatePath(pszSource, szCurDir,
2279 pszDest, &pszDestDir);
2280 if (RT_SUCCESS(vrc))
2281 {
2282 vrc = gctlCopyDirCreate(pContext, pszDestDir);
2283 RTStrFree(pszDestDir);
2284
2285 fDirCreated = true;
2286 }
2287 }
2288
2289 if (RT_SUCCESS(vrc))
2290 {
2291 char *pszFileSource = RTPathJoinA(szCurDir, DirEntry.szName);
2292 if (pszFileSource)
2293 {
2294 char *pszFileDest;
2295 vrc = gctlCopyTranslatePath(pszSource, pszFileSource,
2296 pszDest, &pszFileDest);
2297 if (RT_SUCCESS(vrc))
2298 {
2299 vrc = gctlCopyFileToDest(pContext, pszFileSource,
2300 pszFileDest, 0 /* Flags */);
2301 RTStrFree(pszFileDest);
2302 }
2303 RTStrFree(pszFileSource);
2304 }
2305 }
2306 break;
2307 }
2308
2309 default:
2310 break;
2311 }
2312 if (RT_FAILURE(vrc))
2313 break;
2314 }
2315
2316 RTDirClose(pDir);
2317 }
2318 return vrc;
2319}
2320
2321/**
2322 * Copys a directory (tree) from guest to the host.
2323 *
2324 * @return IPRT status code.
2325 * @param pContext Pointer to current copy control context.
2326 * @param pszSource Source directory on the guest to copy to the host.
2327 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
2328 * @param pszDest Destination directory on the host.
2329 * @param fFlags Copy flags, such as recursive copying.
2330 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
2331 * is needed for recursion.
2332 */
2333static int gctlCopyDirToHost(PCOPYCONTEXT pContext,
2334 const char *pszSource, const char *pszFilter,
2335 const char *pszDest, uint32_t fFlags,
2336 const char *pszSubDir /* For recursion. */)
2337{
2338 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
2339 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
2340 /* Filter is optional. */
2341 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
2342 /* Sub directory is optional. */
2343
2344 /*
2345 * Construct current path.
2346 */
2347 char szCurDir[RTPATH_MAX];
2348 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
2349 if (RT_SUCCESS(vrc) && pszSubDir)
2350 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
2351
2352 if (RT_FAILURE(vrc))
2353 return vrc;
2354
2355 if (pContext->pCmdCtx->cVerbose > 1)
2356 RTPrintf("Processing guest directory: %s\n", szCurDir);
2357
2358 /* Flag indicating whether the current directory was created on the
2359 * target or not. */
2360 bool fDirCreated = false;
2361 SafeArray<DirectoryOpenFlag_T> dirOpenFlags; /* No flags supported yet. */
2362 ComPtr<IGuestDirectory> pDirectory;
2363 HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(),
2364 ComSafeArrayAsInParam(dirOpenFlags),
2365 pDirectory.asOutParam());
2366 if (FAILED(rc))
2367 return gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2368 ComPtr<IFsObjInfo> dirEntry;
2369 while (true)
2370 {
2371 rc = pDirectory->Read(dirEntry.asOutParam());
2372 if (FAILED(rc))
2373 break;
2374
2375 FsObjType_T enmType;
2376 dirEntry->COMGETTER(Type)(&enmType);
2377
2378 Bstr strName;
2379 dirEntry->COMGETTER(Name)(strName.asOutParam());
2380
2381 switch (enmType)
2382 {
2383 case FsObjType_Directory:
2384 {
2385 Assert(!strName.isEmpty());
2386
2387 /* Skip "." and ".." entries. */
2388 if ( !strName.compare(Bstr("."))
2389 || !strName.compare(Bstr("..")))
2390 break;
2391
2392 if (pContext->pCmdCtx->cVerbose > 1)
2393 {
2394 Utf8Str strDir(strName);
2395 RTPrintf("Directory: %s\n", strDir.c_str());
2396 }
2397
2398 if (fFlags & CopyFileFlag_Recursive)
2399 {
2400 Utf8Str strDir(strName);
2401 char *pszNewSub = NULL;
2402 if (pszSubDir)
2403 pszNewSub = RTPathJoinA(pszSubDir, strDir.c_str());
2404 else
2405 {
2406 pszNewSub = RTStrDup(strDir.c_str());
2407 RTPathStripTrailingSlash(pszNewSub);
2408 }
2409 if (pszNewSub)
2410 {
2411 vrc = gctlCopyDirToHost(pContext,
2412 pszSource, pszFilter,
2413 pszDest, fFlags, pszNewSub);
2414 RTStrFree(pszNewSub);
2415 }
2416 else
2417 vrc = VERR_NO_MEMORY;
2418 }
2419 break;
2420 }
2421
2422 case FsObjType_Symlink:
2423 if ( (fFlags & CopyFileFlag_Recursive)
2424 && (fFlags & CopyFileFlag_FollowLinks))
2425 {
2426 /* Fall through to next case is intentional. */
2427 }
2428 else
2429 break;
2430
2431 case FsObjType_File:
2432 {
2433 Assert(!strName.isEmpty());
2434
2435 Utf8Str strFile(strName);
2436 if ( pszFilter
2437 && !RTStrSimplePatternMatch(pszFilter, strFile.c_str()))
2438 {
2439 break; /* Filter does not match. */
2440 }
2441
2442 if (pContext->pCmdCtx->cVerbose > 1)
2443 RTPrintf("File: %s\n", strFile.c_str());
2444
2445 if (!fDirCreated)
2446 {
2447 char *pszDestDir;
2448 vrc = gctlCopyTranslatePath(pszSource, szCurDir,
2449 pszDest, &pszDestDir);
2450 if (RT_SUCCESS(vrc))
2451 {
2452 vrc = gctlCopyDirCreate(pContext, pszDestDir);
2453 RTStrFree(pszDestDir);
2454
2455 fDirCreated = true;
2456 }
2457 }
2458
2459 if (RT_SUCCESS(vrc))
2460 {
2461 char *pszFileSource = RTPathJoinA(szCurDir, strFile.c_str());
2462 if (pszFileSource)
2463 {
2464 char *pszFileDest;
2465 vrc = gctlCopyTranslatePath(pszSource, pszFileSource,
2466 pszDest, &pszFileDest);
2467 if (RT_SUCCESS(vrc))
2468 {
2469 vrc = gctlCopyFileToDest(pContext, pszFileSource,
2470 pszFileDest, 0 /* Flags */);
2471 RTStrFree(pszFileDest);
2472 }
2473 RTStrFree(pszFileSource);
2474 }
2475 else
2476 vrc = VERR_NO_MEMORY;
2477 }
2478 break;
2479 }
2480
2481 default:
2482 RTPrintf("Warning: Directory entry of type %ld not handled, skipping ...\n",
2483 enmType);
2484 break;
2485 }
2486
2487 if (RT_FAILURE(vrc))
2488 break;
2489 }
2490
2491 if (RT_UNLIKELY(FAILED(rc)))
2492 {
2493 switch (rc)
2494 {
2495 case E_ABORT: /* No more directory entries left to process. */
2496 break;
2497
2498 case VBOX_E_FILE_ERROR: /* Current entry cannot be accessed to
2499 to missing rights. */
2500 {
2501 RTPrintf("Warning: Cannot access \"%s\", skipping ...\n",
2502 szCurDir);
2503 break;
2504 }
2505
2506 default:
2507 vrc = gctlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
2508 break;
2509 }
2510 }
2511
2512 HRESULT rc2 = pDirectory->Close();
2513 if (FAILED(rc2))
2514 {
2515 int vrc2 = gctlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
2516 if (RT_SUCCESS(vrc))
2517 vrc = vrc2;
2518 }
2519 else if (SUCCEEDED(rc))
2520 rc = rc2;
2521
2522 return vrc;
2523}
2524
2525/**
2526 * Copys a directory (tree) to the destination, based on the current copy
2527 * context.
2528 *
2529 * @return IPRT status code.
2530 * @param pContext Pointer to current copy control context.
2531 * @param pszSource Source directory to copy to the destination.
2532 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
2533 * @param pszDest Destination directory where to copy in the source
2534 * source directory.
2535 * @param fFlags Copy flags, such as recursive copying.
2536 */
2537static int gctlCopyDirToDest(PCOPYCONTEXT pContext,
2538 const char *pszSource, const char *pszFilter,
2539 const char *pszDest, uint32_t fFlags)
2540{
2541 if (pContext->fHostToGuest)
2542 return gctlCopyDirToGuest(pContext, pszSource, pszFilter,
2543 pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
2544 return gctlCopyDirToHost(pContext, pszSource, pszFilter,
2545 pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
2546}
2547
2548/**
2549 * Creates a source root by stripping file names or filters of the specified source.
2550 *
2551 * @return IPRT status code.
2552 * @param pszSource Source to create source root for.
2553 * @param ppszSourceRoot Pointer that receives the allocated source root. Needs
2554 * to be free'd with gctlCopyFreeSourceRoot().
2555 */
2556static int gctlCopyCreateSourceRoot(const char *pszSource, char **ppszSourceRoot)
2557{
2558 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
2559 AssertPtrReturn(ppszSourceRoot, VERR_INVALID_POINTER);
2560
2561 char *pszNewRoot = RTStrDup(pszSource);
2562 if (!pszNewRoot)
2563 return VERR_NO_MEMORY;
2564
2565 size_t lenRoot = strlen(pszNewRoot);
2566 if ( lenRoot
2567 && ( pszNewRoot[lenRoot - 1] == '/'
2568 || pszNewRoot[lenRoot - 1] == '\\')
2569 )
2570 {
2571 pszNewRoot[lenRoot - 1] = '\0';
2572 }
2573
2574 if ( lenRoot > 1
2575 && ( pszNewRoot[lenRoot - 2] == '/'
2576 || pszNewRoot[lenRoot - 2] == '\\')
2577 )
2578 {
2579 pszNewRoot[lenRoot - 2] = '\0';
2580 }
2581
2582 if (!lenRoot)
2583 {
2584 /* If there's anything (like a file name or a filter),
2585 * strip it! */
2586 RTPathStripFilename(pszNewRoot);
2587 }
2588
2589 *ppszSourceRoot = pszNewRoot;
2590
2591 return VINF_SUCCESS;
2592}
2593
2594/**
2595 * Frees a previously allocated source root.
2596 *
2597 * @return IPRT status code.
2598 * @param pszSourceRoot Source root to free.
2599 */
2600static void gctlCopyFreeSourceRoot(char *pszSourceRoot)
2601{
2602 RTStrFree(pszSourceRoot);
2603}
2604
2605static RTEXITCODE gctlHandleCopy(PGCTLCMDCTX pCtx, int argc, char **argv, bool fHostToGuest)
2606{
2607 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2608
2609 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
2610 * is much better (partly because it is much simpler of course). The main
2611 * arguments against this is that (1) all but two options conflicts with
2612 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
2613 * done windows CMD style (though not in a 100% compatible way), and (3)
2614 * that only one source is allowed - efficiently sabotaging default
2615 * wildcard expansion by a unix shell. The best solution here would be
2616 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
2617
2618 /*
2619 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
2620 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
2621 * does in here.
2622 */
2623 enum GETOPTDEF_COPY
2624 {
2625 GETOPTDEF_COPY_DRYRUN = 1000,
2626 GETOPTDEF_COPY_FOLLOW,
2627 GETOPTDEF_COPY_TARGETDIR
2628 };
2629 static const RTGETOPTDEF s_aOptions[] =
2630 {
2631 GCTLCMD_COMMON_OPTION_DEFS()
2632 { "--dryrun", GETOPTDEF_COPY_DRYRUN, RTGETOPT_REQ_NOTHING },
2633 { "--follow", GETOPTDEF_COPY_FOLLOW, RTGETOPT_REQ_NOTHING },
2634 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
2635 { "--target-directory", GETOPTDEF_COPY_TARGETDIR, RTGETOPT_REQ_STRING }
2636 };
2637
2638 int ch;
2639 RTGETOPTUNION ValueUnion;
2640 RTGETOPTSTATE GetState;
2641 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2642
2643 Utf8Str strSource;
2644 const char *pszDst = NULL;
2645 uint32_t fFlags = CopyFileFlag_None;
2646 bool fCopyRecursive = false;
2647 bool fDryRun = false;
2648 uint32_t uUsage = fHostToGuest ? USAGE_GSTCTRL_COPYTO : USAGE_GSTCTRL_COPYFROM;
2649
2650 SOURCEVEC vecSources;
2651
2652 int vrc = VINF_SUCCESS;
2653 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2654 {
2655 /* For options that require an argument, ValueUnion has received the value. */
2656 switch (ch)
2657 {
2658 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2659
2660 case GETOPTDEF_COPY_DRYRUN:
2661 fDryRun = true;
2662 break;
2663
2664 case GETOPTDEF_COPY_FOLLOW:
2665 fFlags |= CopyFileFlag_FollowLinks;
2666 break;
2667
2668 case 'R': /* Recursive processing */
2669 fFlags |= CopyFileFlag_Recursive;
2670 break;
2671
2672 case GETOPTDEF_COPY_TARGETDIR:
2673 pszDst = ValueUnion.psz;
2674 break;
2675
2676 case VINF_GETOPT_NOT_OPTION:
2677 /* Last argument and no destination specified with
2678 * --target-directory yet? Then use the current
2679 * (= last) argument as destination. */
2680 if ( pCtx->pArg->argc == GetState.iNext
2681 && pszDst == NULL)
2682 pszDst = ValueUnion.psz;
2683 else
2684 {
2685 try
2686 { /* Save the source directory. */
2687 vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
2688 }
2689 catch (std::bad_alloc &)
2690 {
2691 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory");
2692 }
2693 }
2694 break;
2695
2696 default:
2697 return errorGetOptEx(USAGE_GUESTCONTROL, uUsage, ch, &ValueUnion);
2698 }
2699 }
2700
2701 if (!vecSources.size())
2702 return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No source(s) specified!");
2703
2704 if (pszDst == NULL)
2705 return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No destination specified!");
2706
2707 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2708 if (rcExit != RTEXITCODE_SUCCESS)
2709 return rcExit;
2710
2711 /*
2712 * Done parsing arguments, do some more preparations.
2713 */
2714 if (pCtx->cVerbose > 1)
2715 {
2716 if (fHostToGuest)
2717 RTPrintf("Copying from host to guest ...\n");
2718 else
2719 RTPrintf("Copying from guest to host ...\n");
2720 if (fDryRun)
2721 RTPrintf("Dry run - no files copied!\n");
2722 }
2723
2724 /* Create the copy context -- it contains all information
2725 * the routines need to know when handling the actual copying. */
2726 PCOPYCONTEXT pContext = NULL;
2727 vrc = gctlCopyContextCreate(pCtx, fDryRun, fHostToGuest,
2728 fHostToGuest
2729 ? "VBoxManage Guest Control - Copy to guest"
2730 : "VBoxManage Guest Control - Copy from guest", &pContext);
2731 if (RT_FAILURE(vrc))
2732 {
2733 RTMsgError("Unable to create copy context, rc=%Rrc\n", vrc);
2734 return RTEXITCODE_FAILURE;
2735 }
2736
2737/** @todo r=bird: RTPathFilename and RTPathStripFilename won't work
2738 * correctly on non-windows hosts when the guest is from the DOS world (Windows,
2739 * OS/2, DOS). The host doesn't know about DOS slashes, only UNIX slashes and
2740 * will get the wrong idea if some dilligent user does:
2741 *
2742 * copyto myfile.txt 'C:\guestfile.txt'
2743 * or
2744 * copyto myfile.txt 'D:guestfile.txt'
2745 *
2746 * @bugref{6344}
2747 */
2748 if (!RTPathFilename(pszDst))
2749 {
2750 vrc = gctlCopyDirCreate(pContext, pszDst);
2751 }
2752 else
2753 {
2754 /* We assume we got a file name as destination -- so strip
2755 * the actual file name and make sure the appropriate
2756 * directories get created. */
2757 char *pszDstDir = RTStrDup(pszDst);
2758 AssertPtr(pszDstDir);
2759 RTPathStripFilename(pszDstDir);
2760 vrc = gctlCopyDirCreate(pContext, pszDstDir);
2761 RTStrFree(pszDstDir);
2762 }
2763
2764 if (RT_SUCCESS(vrc))
2765 {
2766 /*
2767 * Here starts the actual fun!
2768 * Handle all given sources one by one.
2769 */
2770 for (unsigned long s = 0; s < vecSources.size(); s++)
2771 {
2772 char *pszSource = RTStrDup(vecSources[s].GetSource());
2773 AssertPtrBreakStmt(pszSource, vrc = VERR_NO_MEMORY);
2774 const char *pszFilter = vecSources[s].GetFilter();
2775 if (!strlen(pszFilter))
2776 pszFilter = NULL; /* If empty filter then there's no filter :-) */
2777
2778 char *pszSourceRoot;
2779 vrc = gctlCopyCreateSourceRoot(pszSource, &pszSourceRoot);
2780 if (RT_FAILURE(vrc))
2781 {
2782 RTMsgError("Unable to create source root, rc=%Rrc\n", vrc);
2783 break;
2784 }
2785
2786 if (pCtx->cVerbose > 1)
2787 RTPrintf("Source: %s\n", pszSource);
2788
2789 /** @todo Files with filter?? */
2790 bool fSourceIsFile = false;
2791 bool fSourceExists;
2792
2793 size_t cchSource = strlen(pszSource);
2794 if ( cchSource > 1
2795 && RTPATH_IS_SLASH(pszSource[cchSource - 1]))
2796 {
2797 if (pszFilter) /* Directory with filter (so use source root w/o the actual filter). */
2798 vrc = gctlCopyDirExistsOnSource(pContext, pszSourceRoot, &fSourceExists);
2799 else /* Regular directory without filter. */
2800 vrc = gctlCopyDirExistsOnSource(pContext, pszSource, &fSourceExists);
2801
2802 if (fSourceExists)
2803 {
2804 /* Strip trailing slash from our source element so that other functions
2805 * can use this stuff properly (like RTPathStartsWith). */
2806 RTPathStripTrailingSlash(pszSource);
2807 }
2808 }
2809 else
2810 {
2811 vrc = gctlCopyFileExistsOnSource(pContext, pszSource, &fSourceExists);
2812 if ( RT_SUCCESS(vrc)
2813 && fSourceExists)
2814 {
2815 fSourceIsFile = true;
2816 }
2817 }
2818
2819 if ( RT_SUCCESS(vrc)
2820 && fSourceExists)
2821 {
2822 if (fSourceIsFile)
2823 {
2824 /* Single file. */
2825 char *pszDstFile;
2826 vrc = gctlCopyTranslatePath(pszSourceRoot, pszSource, pszDst, &pszDstFile);
2827 if (RT_SUCCESS(vrc))
2828 {
2829 vrc = gctlCopyFileToDest(pContext, pszSource, pszDstFile, 0 /* Flags */);
2830 RTStrFree(pszDstFile);
2831 }
2832 else
2833 RTMsgError("Unable to translate path for \"%s\", rc=%Rrc\n", pszSource, vrc);
2834 }
2835 else
2836 {
2837 /* Directory (with filter?). */
2838 vrc = gctlCopyDirToDest(pContext, pszSource, pszFilter, pszDst, fFlags);
2839 }
2840 }
2841
2842 gctlCopyFreeSourceRoot(pszSourceRoot);
2843
2844 if ( RT_SUCCESS(vrc)
2845 && !fSourceExists)
2846 {
2847 RTMsgError("Warning: Source \"%s\" does not exist, skipping!\n",
2848 pszSource);
2849 RTStrFree(pszSource);
2850 continue;
2851 }
2852 else if (RT_FAILURE(vrc))
2853 {
2854 RTMsgError("Error processing \"%s\", rc=%Rrc\n",
2855 pszSource, vrc);
2856 RTStrFree(pszSource);
2857 break;
2858 }
2859
2860 RTStrFree(pszSource);
2861 }
2862 }
2863
2864 gctlCopyContextFree(pContext);
2865
2866 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2867}
2868
2869static DECLCALLBACK(RTEXITCODE) gctlHandleCopyFrom(PGCTLCMDCTX pCtx, int argc, char **argv)
2870{
2871 return gctlHandleCopy(pCtx, argc, argv, false /* Guest to host */);
2872}
2873
2874static DECLCALLBACK(RTEXITCODE) gctlHandleCopyTo(PGCTLCMDCTX pCtx, int argc, char **argv)
2875{
2876 return gctlHandleCopy(pCtx, argc, argv, true /* Host to guest */);
2877}
2878
2879static DECLCALLBACK(RTEXITCODE) handleCtrtMkDir(PGCTLCMDCTX pCtx, int argc, char **argv)
2880{
2881 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2882
2883 static const RTGETOPTDEF s_aOptions[] =
2884 {
2885 GCTLCMD_COMMON_OPTION_DEFS()
2886 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2887 { "--parents", 'P', RTGETOPT_REQ_NOTHING }
2888 };
2889
2890 int ch;
2891 RTGETOPTUNION ValueUnion;
2892 RTGETOPTSTATE GetState;
2893 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 2, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2894
2895 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
2896 uint32_t fDirMode = 0; /* Default mode. */
2897 uint32_t cDirsCreated = 0;
2898 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2899
2900 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2901 {
2902 /* For options that require an argument, ValueUnion has received the value. */
2903 switch (ch)
2904 {
2905 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2906
2907 case 'm': /* Mode */
2908 fDirMode = ValueUnion.u32;
2909 break;
2910
2911 case 'P': /* Create parents */
2912 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
2913 break;
2914
2915 case VINF_GETOPT_NOT_OPTION:
2916 if (cDirsCreated == 0)
2917 {
2918 /*
2919 * First non-option - no more options now.
2920 */
2921 rcExit = gctlCtxPostOptionParsingInit(pCtx);
2922 if (rcExit != RTEXITCODE_SUCCESS)
2923 return rcExit;
2924 if (pCtx->cVerbose > 1)
2925 RTPrintf("Creating %RU32 directories...\n", argc - GetState.iNext + 1);
2926 }
2927 if (g_fGuestCtrlCanceled)
2928 return RTMsgErrorExit(RTEXITCODE_FAILURE, "mkdir was interrupted by Ctrl-C (%u left)\n",
2929 argc - GetState.iNext + 1);
2930
2931 /*
2932 * Create the specified directory.
2933 *
2934 * On failure we'll change the exit status to failure and
2935 * continue with the next directory that needs creating. We do
2936 * this because we only create new things, and because this is
2937 * how /bin/mkdir works on unix.
2938 */
2939 cDirsCreated++;
2940 if (pCtx->cVerbose > 1)
2941 RTPrintf("Creating directory \"%s\" ...\n", ValueUnion.psz);
2942 try
2943 {
2944 HRESULT rc;
2945 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreate(Bstr(ValueUnion.psz).raw(),
2946 fDirMode, ComSafeArrayAsInParam(dirCreateFlags)));
2947 if (FAILED(rc))
2948 rcExit = RTEXITCODE_FAILURE;
2949 }
2950 catch (std::bad_alloc &)
2951 {
2952 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
2953 }
2954 break;
2955
2956 default:
2957 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKDIR, ch, &ValueUnion);
2958 }
2959 }
2960
2961 if (!cDirsCreated)
2962 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKDIR, "No directory to create specified!");
2963 return rcExit;
2964}
2965
2966
2967static DECLCALLBACK(RTEXITCODE) gctlHandleRmDir(PGCTLCMDCTX pCtx, int argc, char **argv)
2968{
2969 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2970
2971 static const RTGETOPTDEF s_aOptions[] =
2972 {
2973 GCTLCMD_COMMON_OPTION_DEFS()
2974 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
2975 };
2976
2977 int ch;
2978 RTGETOPTUNION ValueUnion;
2979 RTGETOPTSTATE GetState;
2980 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2981
2982 bool fRecursive = false;
2983 uint32_t cDirRemoved = 0;
2984 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2985
2986 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2987 {
2988 /* For options that require an argument, ValueUnion has received the value. */
2989 switch (ch)
2990 {
2991 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2992
2993 case 'R':
2994 fRecursive = true;
2995 break;
2996
2997 case VINF_GETOPT_NOT_OPTION:
2998 {
2999 if (cDirRemoved == 0)
3000 {
3001 /*
3002 * First non-option - no more options now.
3003 */
3004 rcExit = gctlCtxPostOptionParsingInit(pCtx);
3005 if (rcExit != RTEXITCODE_SUCCESS)
3006 return rcExit;
3007 if (pCtx->cVerbose > 1)
3008 RTPrintf("Removing %RU32 directorie%ss...\n", argc - GetState.iNext + 1, fRecursive ? "trees" : "");
3009 }
3010 if (g_fGuestCtrlCanceled)
3011 return RTMsgErrorExit(RTEXITCODE_FAILURE, "rmdir was interrupted by Ctrl-C (%u left)\n",
3012 argc - GetState.iNext + 1);
3013
3014 cDirRemoved++;
3015 HRESULT rc;
3016 if (!fRecursive)
3017 {
3018 /*
3019 * Remove exactly one directory.
3020 */
3021 if (pCtx->cVerbose > 1)
3022 RTPrintf("Removing directory \"%s\" ...\n", ValueUnion.psz);
3023 try
3024 {
3025 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemove(Bstr(ValueUnion.psz).raw()));
3026 }
3027 catch (std::bad_alloc &)
3028 {
3029 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
3030 }
3031 }
3032 else
3033 {
3034 /*
3035 * Remove the directory and anything under it, that means files
3036 * and everything. This is in the tradition of the Windows NT
3037 * CMD.EXE "rmdir /s" operation, a tradition which jpsoft's TCC
3038 * strongly warns against (and half-ways questions the sense of).
3039 */
3040 if (pCtx->cVerbose > 1)
3041 RTPrintf("Recursively removing directory \"%s\" ...\n", ValueUnion.psz);
3042 try
3043 {
3044 /** @todo Make flags configurable. */
3045 com::SafeArray<DirectoryRemoveRecFlag_T> aRemRecFlags;
3046 aRemRecFlags.push_back(DirectoryRemoveRecFlag_ContentAndDir);
3047
3048 ComPtr<IProgress> ptrProgress;
3049 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemoveRecursive(Bstr(ValueUnion.psz).raw(),
3050 ComSafeArrayAsInParam(aRemRecFlags),
3051 ptrProgress.asOutParam()));
3052 if (SUCCEEDED(rc))
3053 {
3054 if (pCtx->cVerbose > 1)
3055 rc = showProgress(ptrProgress);
3056 else
3057 rc = ptrProgress->WaitForCompletion(-1 /* indefinitely */);
3058 if (SUCCEEDED(rc))
3059 CHECK_PROGRESS_ERROR(ptrProgress, ("Directory deletion failed"));
3060 ptrProgress.setNull();
3061 }
3062 }
3063 catch (std::bad_alloc &)
3064 {
3065 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory during recursive rmdir\n");
3066 }
3067 }
3068
3069 /*
3070 * This command returns immediately on failure since it's destructive in nature.
3071 */
3072 if (FAILED(rc))
3073 return RTEXITCODE_FAILURE;
3074 break;
3075 }
3076
3077 default:
3078 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RMDIR, ch, &ValueUnion);
3079 }
3080 }
3081
3082 if (!cDirRemoved)
3083 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RMDIR, "No directory to remove specified!");
3084 return rcExit;
3085}
3086
3087static DECLCALLBACK(RTEXITCODE) gctlHandleRm(PGCTLCMDCTX pCtx, int argc, char **argv)
3088{
3089 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3090
3091 static const RTGETOPTDEF s_aOptions[] =
3092 {
3093 GCTLCMD_COMMON_OPTION_DEFS()
3094 { "--force", 'f', RTGETOPT_REQ_NOTHING, },
3095 };
3096
3097 int ch;
3098 RTGETOPTUNION ValueUnion;
3099 RTGETOPTSTATE GetState;
3100 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3101
3102 uint32_t cFilesDeleted = 0;
3103 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
3104 bool fForce = true;
3105
3106 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3107 {
3108 /* For options that require an argument, ValueUnion has received the value. */
3109 switch (ch)
3110 {
3111 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3112
3113 case VINF_GETOPT_NOT_OPTION:
3114 if (cFilesDeleted == 0)
3115 {
3116 /*
3117 * First non-option - no more options now.
3118 */
3119 rcExit = gctlCtxPostOptionParsingInit(pCtx);
3120 if (rcExit != RTEXITCODE_SUCCESS)
3121 return rcExit;
3122 if (pCtx->cVerbose > 1)
3123 RTPrintf("Removing %RU32 file(s)...\n", argc - GetState.iNext + 1);
3124 }
3125 if (g_fGuestCtrlCanceled)
3126 return RTMsgErrorExit(RTEXITCODE_FAILURE, "rm was interrupted by Ctrl-C (%u left)\n",
3127 argc - GetState.iNext + 1);
3128
3129 /*
3130 * Remove the specified file.
3131 *
3132 * On failure we will by default stop, however, the force option will
3133 * by unix traditions force us to ignore errors and continue.
3134 */
3135 cFilesDeleted++;
3136 if (pCtx->cVerbose > 1)
3137 RTPrintf("Removing file \"%s\" ...\n", ValueUnion.psz);
3138 try
3139 {
3140 /** @todo How does IGuestSession::FileRemove work with read-only files? Do we
3141 * need to do some chmod or whatever to better emulate the --force flag? */
3142 HRESULT rc;
3143 CHECK_ERROR(pCtx->pGuestSession, FileRemove(Bstr(ValueUnion.psz).raw()));
3144 if (FAILED(rc) && !fForce)
3145 return RTEXITCODE_FAILURE;
3146 }
3147 catch (std::bad_alloc &)
3148 {
3149 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
3150 }
3151 break;
3152
3153 default:
3154 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RM, ch, &ValueUnion);
3155 }
3156 }
3157
3158 if (!cFilesDeleted && !fForce)
3159 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RM, "No file to remove specified!");
3160 return rcExit;
3161}
3162
3163static DECLCALLBACK(RTEXITCODE) gctlHandleMv(PGCTLCMDCTX pCtx, int argc, char **argv)
3164{
3165 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3166
3167 static const RTGETOPTDEF s_aOptions[] =
3168 {
3169 GCTLCMD_COMMON_OPTION_DEFS()
3170 };
3171
3172 int ch;
3173 RTGETOPTUNION ValueUnion;
3174 RTGETOPTSTATE GetState;
3175 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3176
3177 int vrc = VINF_SUCCESS;
3178
3179 bool fDryrun = false;
3180 std::vector< Utf8Str > vecSources;
3181 const char *pszDst = NULL;
3182 com::SafeArray<PathRenameFlag_T> aRenameFlags;
3183
3184 try
3185 {
3186 /** @todo Make flags configurable. */
3187 aRenameFlags.push_back(PathRenameFlag_NoReplace);
3188
3189 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3190 && RT_SUCCESS(vrc))
3191 {
3192 /* For options that require an argument, ValueUnion has received the value. */
3193 switch (ch)
3194 {
3195 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3196
3197 /** @todo Implement a --dryrun command. */
3198 /** @todo Implement rename flags. */
3199
3200 case VINF_GETOPT_NOT_OPTION:
3201 vecSources.push_back(Utf8Str(ValueUnion.psz));
3202 pszDst = ValueUnion.psz;
3203 break;
3204
3205 default:
3206 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV, ch, &ValueUnion);
3207 }
3208 }
3209 }
3210 catch (std::bad_alloc)
3211 {
3212 vrc = VERR_NO_MEMORY;
3213 }
3214
3215 if (RT_FAILURE(vrc))
3216 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize, rc=%Rrc\n", vrc);
3217
3218 size_t cSources = vecSources.size();
3219 if (!cSources)
3220 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV,
3221 "No source(s) to move specified!");
3222 if (cSources < 2)
3223 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV,
3224 "No destination specified!");
3225
3226 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3227 if (rcExit != RTEXITCODE_SUCCESS)
3228 return rcExit;
3229
3230 /* Delete last element, which now is the destination. */
3231 vecSources.pop_back();
3232 cSources = vecSources.size();
3233
3234 HRESULT rc = S_OK;
3235
3236 if (cSources > 1)
3237 {
3238 ComPtr<IGuestFsObjInfo> pFsObjInfo;
3239 rc = pCtx->pGuestSession->DirectoryQueryInfo(Bstr(pszDst).raw(), pFsObjInfo.asOutParam());
3240 if (FAILED(rc))
3241 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Destination must be a directory when specifying multiple sources\n");
3242 }
3243
3244 /*
3245 * Rename (move) the entries.
3246 */
3247 if (pCtx->cVerbose > 1)
3248 RTPrintf("Renaming %RU32 %s ...\n", cSources, cSources > 1 ? "entries" : "entry");
3249
3250 std::vector< Utf8Str >::iterator it = vecSources.begin();
3251 while ( (it != vecSources.end())
3252 && !g_fGuestCtrlCanceled)
3253 {
3254 bool fSourceIsDirectory = false;
3255 Utf8Str strCurSource = (*it);
3256
3257 /** @todo Slooooow, but works for now. */
3258 /** @todo r=bird: Need an interface for querying info on a file system
3259 * object, not just files or directories exclusively. You also may
3260 * want to take symbolic links into account somewhere along the line,
3261 * though preferrably on the guest end of things... */
3262 ComPtr<IGuestFsObjInfo> pFsObjInfo;
3263 rc = pCtx->pGuestSession->FileQueryInfo(Bstr(strCurSource).raw(), pFsObjInfo.asOutParam());
3264 if (FAILED(rc))
3265 {
3266 rc = pCtx->pGuestSession->DirectoryQueryInfo(Bstr(strCurSource).raw(), pFsObjInfo.asOutParam());
3267 fSourceIsDirectory = SUCCEEDED(rc);
3268 }
3269 if (FAILED(rc))
3270 {
3271 if (pCtx->cVerbose > 1)
3272 RTPrintf("Warning: Cannot stat for element \"%s\": No such element\n",
3273 strCurSource.c_str());
3274 it++;
3275 continue; /* Skip. */
3276 }
3277
3278 if (pCtx->cVerbose > 1)
3279 RTPrintf("Renaming %s \"%s\" to \"%s\" ...\n",
3280 fSourceIsDirectory ? "directory" : "file",
3281 strCurSource.c_str(), pszDst);
3282
3283 if (!fDryrun)
3284 {
3285 if (fSourceIsDirectory)
3286 {
3287 CHECK_ERROR_BREAK(pCtx->pGuestSession, DirectoryRename(Bstr(strCurSource).raw(),
3288 Bstr(pszDst).raw(),
3289 ComSafeArrayAsInParam(aRenameFlags)));
3290
3291 /* Break here, since it makes no sense to rename mroe than one source to
3292 * the same directory. */
3293/** @todo r=bird: You are being kind of windowsy (or just DOSish) about the 'sense' part here,
3294 * while being totaly buggy about the behavior. 'VBoxGuest guestcontrol ren dir1 dir2 dstdir' will
3295 * stop after 'dir1' and SILENTLY ignore dir2. If you tried this on Windows, you'd see an error
3296 * being displayed. If you 'man mv' on a nearby unixy system, you'd see that they've made perfect
3297 * sense out of any situation with more than one source. */
3298 it = vecSources.end();
3299 break;
3300 }
3301 else
3302 CHECK_ERROR_BREAK(pCtx->pGuestSession, FileRename(Bstr(strCurSource).raw(),
3303 Bstr(pszDst).raw(),
3304 ComSafeArrayAsInParam(aRenameFlags)));
3305 }
3306
3307 it++;
3308 }
3309
3310 if ( (it != vecSources.end())
3311 && pCtx->cVerbose > 1)
3312 {
3313 RTPrintf("Warning: Not all sources were renamed\n");
3314 }
3315
3316 return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
3317}
3318
3319static DECLCALLBACK(RTEXITCODE) gctlHandleMkTemp(PGCTLCMDCTX pCtx, int argc, char **argv)
3320{
3321 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3322
3323 static const RTGETOPTDEF s_aOptions[] =
3324 {
3325 GCTLCMD_COMMON_OPTION_DEFS()
3326 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
3327 { "--directory", 'D', RTGETOPT_REQ_NOTHING },
3328 { "--secure", 's', RTGETOPT_REQ_NOTHING },
3329 { "--tmpdir", 't', RTGETOPT_REQ_STRING }
3330 };
3331
3332 int ch;
3333 RTGETOPTUNION ValueUnion;
3334 RTGETOPTSTATE GetState;
3335 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3336
3337 Utf8Str strTemplate;
3338 uint32_t fMode = 0; /* Default mode. */
3339 bool fDirectory = false;
3340 bool fSecure = false;
3341 Utf8Str strTempDir;
3342
3343 DESTDIRMAP mapDirs;
3344
3345 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3346 {
3347 /* For options that require an argument, ValueUnion has received the value. */
3348 switch (ch)
3349 {
3350 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3351
3352 case 'm': /* Mode */
3353 fMode = ValueUnion.u32;
3354 break;
3355
3356 case 'D': /* Create directory */
3357 fDirectory = true;
3358 break;
3359
3360 case 's': /* Secure */
3361 fSecure = true;
3362 break;
3363
3364 case 't': /* Temp directory */
3365 strTempDir = ValueUnion.psz;
3366 break;
3367
3368 case VINF_GETOPT_NOT_OPTION:
3369 {
3370 if (strTemplate.isEmpty())
3371 strTemplate = ValueUnion.psz;
3372 else
3373 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
3374 "More than one template specified!\n");
3375 break;
3376 }
3377
3378 default:
3379 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP, ch, &ValueUnion);
3380 }
3381 }
3382
3383 if (strTemplate.isEmpty())
3384 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
3385 "No template specified!");
3386
3387 if (!fDirectory)
3388 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
3389 "Creating temporary files is currently not supported!");
3390
3391 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3392 if (rcExit != RTEXITCODE_SUCCESS)
3393 return rcExit;
3394
3395 /*
3396 * Create the directories.
3397 */
3398 if (pCtx->cVerbose > 1)
3399 {
3400 if (fDirectory && !strTempDir.isEmpty())
3401 RTPrintf("Creating temporary directory from template '%s' in directory '%s' ...\n",
3402 strTemplate.c_str(), strTempDir.c_str());
3403 else if (fDirectory)
3404 RTPrintf("Creating temporary directory from template '%s' in default temporary directory ...\n",
3405 strTemplate.c_str());
3406 else if (!fDirectory && !strTempDir.isEmpty())
3407 RTPrintf("Creating temporary file from template '%s' in directory '%s' ...\n",
3408 strTemplate.c_str(), strTempDir.c_str());
3409 else if (!fDirectory)
3410 RTPrintf("Creating temporary file from template '%s' in default temporary directory ...\n",
3411 strTemplate.c_str());
3412 }
3413
3414 HRESULT rc = S_OK;
3415 if (fDirectory)
3416 {
3417 Bstr directory;
3418 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreateTemp(Bstr(strTemplate).raw(),
3419 fMode, Bstr(strTempDir).raw(),
3420 fSecure,
3421 directory.asOutParam()));
3422 if (SUCCEEDED(rc))
3423 RTPrintf("Directory name: %ls\n", directory.raw());
3424 }
3425 else
3426 {
3427 // else - temporary file not yet implemented
3428 /** @todo implement temporary file creation (we fend it off above, no
3429 * worries). */
3430 rc = E_FAIL;
3431 }
3432
3433 return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
3434}
3435
3436static DECLCALLBACK(RTEXITCODE) gctlHandleStat(PGCTLCMDCTX pCtx, int argc, char **argv)
3437{
3438 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3439
3440 static const RTGETOPTDEF s_aOptions[] =
3441 {
3442 GCTLCMD_COMMON_OPTION_DEFS()
3443 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
3444 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
3445 { "--format", 'c', RTGETOPT_REQ_STRING },
3446 { "--terse", 't', RTGETOPT_REQ_NOTHING }
3447 };
3448
3449 int ch;
3450 RTGETOPTUNION ValueUnion;
3451 RTGETOPTSTATE GetState;
3452 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3453
3454 DESTDIRMAP mapObjs;
3455
3456 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3457 {
3458 /* For options that require an argument, ValueUnion has received the value. */
3459 switch (ch)
3460 {
3461 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3462
3463 case 'L': /* Dereference */
3464 case 'f': /* File-system */
3465 case 'c': /* Format */
3466 case 't': /* Terse */
3467 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
3468 "Command \"%s\" not implemented yet!", ValueUnion.psz);
3469
3470 case VINF_GETOPT_NOT_OPTION:
3471 mapObjs[ValueUnion.psz]; /* Add element to check to map. */
3472 break;
3473
3474 default:
3475 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT, ch, &ValueUnion);
3476 }
3477 }
3478
3479 size_t cObjs = mapObjs.size();
3480 if (!cObjs)
3481 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
3482 "No element(s) to check specified!");
3483
3484 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3485 if (rcExit != RTEXITCODE_SUCCESS)
3486 return rcExit;
3487
3488 HRESULT rc;
3489
3490 /*
3491 * Doing the checks.
3492 */
3493 DESTDIRMAPITER it = mapObjs.begin();
3494 while (it != mapObjs.end())
3495 {
3496 if (pCtx->cVerbose > 1)
3497 RTPrintf("Checking for element \"%s\" ...\n", it->first.c_str());
3498
3499 ComPtr<IGuestFsObjInfo> pFsObjInfo;
3500 rc = pCtx->pGuestSession->FileQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
3501 if (FAILED(rc))
3502 rc = pCtx->pGuestSession->DirectoryQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
3503
3504 if (FAILED(rc))
3505 {
3506 /* If there's at least one element which does not exist on the guest,
3507 * drop out with exitcode 1. */
3508 if (pCtx->cVerbose > 1)
3509 RTPrintf("Cannot stat for element \"%s\": No such element\n",
3510 it->first.c_str());
3511 rcExit = RTEXITCODE_FAILURE;
3512 }
3513 else
3514 {
3515 FsObjType_T objType;
3516 pFsObjInfo->COMGETTER(Type)(&objType);
3517 switch (objType)
3518 {
3519 case FsObjType_File:
3520 RTPrintf("Element \"%s\" found: Is a file\n", it->first.c_str());
3521 break;
3522
3523 case FsObjType_Directory:
3524 RTPrintf("Element \"%s\" found: Is a directory\n", it->first.c_str());
3525 break;
3526
3527 case FsObjType_Symlink:
3528 RTPrintf("Element \"%s\" found: Is a symlink\n", it->first.c_str());
3529 break;
3530
3531 default:
3532 RTPrintf("Element \"%s\" found, type unknown (%ld)\n", it->first.c_str(), objType);
3533 break;
3534 }
3535
3536 /** @todo: Show more information about this element. */
3537 }
3538
3539 it++;
3540 }
3541
3542 return rcExit;
3543}
3544
3545static DECLCALLBACK(RTEXITCODE) gctlHandleUpdateAdditions(PGCTLCMDCTX pCtx, int argc, char **argv)
3546{
3547 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3548
3549 /*
3550 * Check the syntax. We can deduce the correct syntax from the number of
3551 * arguments.
3552 */
3553 Utf8Str strSource;
3554 com::SafeArray<IN_BSTR> aArgs;
3555 bool fWaitStartOnly = false;
3556
3557 static const RTGETOPTDEF s_aOptions[] =
3558 {
3559 GCTLCMD_COMMON_OPTION_DEFS()
3560 { "--source", 's', RTGETOPT_REQ_STRING },
3561 { "--wait-start", 'w', RTGETOPT_REQ_NOTHING }
3562 };
3563
3564 int ch;
3565 RTGETOPTUNION ValueUnion;
3566 RTGETOPTSTATE GetState;
3567 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3568
3569 int vrc = VINF_SUCCESS;
3570 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3571 && RT_SUCCESS(vrc))
3572 {
3573 switch (ch)
3574 {
3575 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3576
3577 case 's':
3578 strSource = ValueUnion.psz;
3579 break;
3580
3581 case 'w':
3582 fWaitStartOnly = true;
3583 break;
3584
3585 case VINF_GETOPT_NOT_OPTION:
3586 if (aArgs.size() == 0 && strSource.isEmpty())
3587 strSource = ValueUnion.psz;
3588 else
3589 aArgs.push_back(Bstr(ValueUnion.psz).raw());
3590 break;
3591
3592 default:
3593 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEGA, ch, &ValueUnion);
3594 }
3595 }
3596
3597 if (pCtx->cVerbose > 1)
3598 RTPrintf("Updating Guest Additions ...\n");
3599
3600 HRESULT rc = S_OK;
3601 while (strSource.isEmpty())
3602 {
3603 ComPtr<ISystemProperties> pProperties;
3604 CHECK_ERROR_BREAK(pCtx->pArg->virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
3605 Bstr strISO;
3606 CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
3607 strSource = strISO;
3608 break;
3609 }
3610
3611 /* Determine source if not set yet. */
3612 if (strSource.isEmpty())
3613 {
3614 RTMsgError("No Guest Additions source found or specified, aborting\n");
3615 vrc = VERR_FILE_NOT_FOUND;
3616 }
3617 else if (!RTFileExists(strSource.c_str()))
3618 {
3619 RTMsgError("Source \"%s\" does not exist!\n", strSource.c_str());
3620 vrc = VERR_FILE_NOT_FOUND;
3621 }
3622
3623 if (RT_SUCCESS(vrc))
3624 {
3625 if (pCtx->cVerbose > 1)
3626 RTPrintf("Using source: %s\n", strSource.c_str());
3627
3628
3629 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3630 if (rcExit != RTEXITCODE_SUCCESS)
3631 return rcExit;
3632
3633
3634 com::SafeArray<AdditionsUpdateFlag_T> aUpdateFlags;
3635 if (fWaitStartOnly)
3636 {
3637 aUpdateFlags.push_back(AdditionsUpdateFlag_WaitForUpdateStartOnly);
3638 if (pCtx->cVerbose > 1)
3639 RTPrintf("Preparing and waiting for Guest Additions installer to start ...\n");
3640 }
3641
3642 ComPtr<IProgress> pProgress;
3643 CHECK_ERROR(pCtx->pGuest, UpdateGuestAdditions(Bstr(strSource).raw(),
3644 ComSafeArrayAsInParam(aArgs),
3645 /* Wait for whole update process to complete. */
3646 ComSafeArrayAsInParam(aUpdateFlags),
3647 pProgress.asOutParam()));
3648 if (FAILED(rc))
3649 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
3650 else
3651 {
3652 if (pCtx->cVerbose > 1)
3653 rc = showProgress(pProgress);
3654 else
3655 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
3656
3657 if (SUCCEEDED(rc))
3658 CHECK_PROGRESS_ERROR(pProgress, ("Guest additions update failed"));
3659 vrc = gctlPrintProgressError(pProgress);
3660 if ( RT_SUCCESS(vrc)
3661 && pCtx->cVerbose > 1)
3662 {
3663 RTPrintf("Guest Additions update successful\n");
3664 }
3665 }
3666 }
3667
3668 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3669}
3670
3671static DECLCALLBACK(RTEXITCODE) gctlHandleList(PGCTLCMDCTX pCtx, int argc, char **argv)
3672{
3673 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3674
3675 static const RTGETOPTDEF s_aOptions[] =
3676 {
3677 GCTLCMD_COMMON_OPTION_DEFS()
3678 };
3679
3680 int ch;
3681 RTGETOPTUNION ValueUnion;
3682 RTGETOPTSTATE GetState;
3683 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3684
3685 bool fSeenListArg = false;
3686 bool fListAll = false;
3687 bool fListSessions = false;
3688 bool fListProcesses = false;
3689 bool fListFiles = false;
3690
3691 int vrc = VINF_SUCCESS;
3692 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3693 && RT_SUCCESS(vrc))
3694 {
3695 switch (ch)
3696 {
3697 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3698
3699 case VINF_GETOPT_NOT_OPTION:
3700 if ( !RTStrICmp(ValueUnion.psz, "sessions")
3701 || !RTStrICmp(ValueUnion.psz, "sess"))
3702 fListSessions = true;
3703 else if ( !RTStrICmp(ValueUnion.psz, "processes")
3704 || !RTStrICmp(ValueUnion.psz, "procs"))
3705 fListSessions = fListProcesses = true; /* Showing processes implies showing sessions. */
3706 else if (!RTStrICmp(ValueUnion.psz, "files"))
3707 fListSessions = fListFiles = true; /* Showing files implies showing sessions. */
3708 else if (!RTStrICmp(ValueUnion.psz, "all"))
3709 fListAll = true;
3710 else
3711 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST,
3712 "Unknown list: '%s'", ValueUnion.psz);
3713 fSeenListArg = true;
3714 break;
3715
3716 default:
3717 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEGA, ch, &ValueUnion);
3718 }
3719 }
3720
3721 if (fSeenListArg)
3722 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST, "Missing list name");
3723 Assert(fListAll || fListSessions);
3724
3725 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3726 if (rcExit != RTEXITCODE_SUCCESS)
3727 return rcExit;
3728
3729
3730 /** @todo Do we need a machine-readable output here as well? */
3731
3732 HRESULT rc;
3733 size_t cTotalProcs = 0;
3734 size_t cTotalFiles = 0;
3735
3736 SafeIfaceArray <IGuestSession> collSessions;
3737 CHECK_ERROR(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3738 if (SUCCEEDED(rc))
3739 {
3740 size_t const cSessions = collSessions.size();
3741 if (cSessions)
3742 {
3743 RTPrintf("Active guest sessions:\n");
3744
3745 /** @todo Make this output a bit prettier. No time now. */
3746
3747 for (size_t i = 0; i < cSessions; i++)
3748 {
3749 ComPtr<IGuestSession> pCurSession = collSessions[i];
3750 if (!pCurSession.isNull())
3751 {
3752 do
3753 {
3754 ULONG uID;
3755 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Id)(&uID));
3756 Bstr strName;
3757 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Name)(strName.asOutParam()));
3758 Bstr strUser;
3759 CHECK_ERROR_BREAK(pCurSession, COMGETTER(User)(strUser.asOutParam()));
3760 GuestSessionStatus_T sessionStatus;
3761 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Status)(&sessionStatus));
3762 RTPrintf("\n\tSession #%-3zu ID=%-3RU32 User=%-16ls Status=[%s] Name=%ls",
3763 i, uID, strUser.raw(), gctlGuestSessionStatusToText(sessionStatus), strName.raw());
3764 } while (0);
3765
3766 if ( fListAll
3767 || fListProcesses)
3768 {
3769 SafeIfaceArray <IGuestProcess> collProcesses;
3770 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcesses)));
3771 for (size_t a = 0; a < collProcesses.size(); a++)
3772 {
3773 ComPtr<IGuestProcess> pCurProcess = collProcesses[a];
3774 if (!pCurProcess.isNull())
3775 {
3776 do
3777 {
3778 ULONG uPID;
3779 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(PID)(&uPID));
3780 Bstr strExecPath;
3781 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(ExecutablePath)(strExecPath.asOutParam()));
3782 ProcessStatus_T procStatus;
3783 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(Status)(&procStatus));
3784
3785 RTPrintf("\n\t\tProcess #%-03zu PID=%-6RU32 Status=[%s] Command=%ls",
3786 a, uPID, gctlProcessStatusToText(procStatus), strExecPath.raw());
3787 } while (0);
3788 }
3789 }
3790
3791 cTotalProcs += collProcesses.size();
3792 }
3793
3794 if ( fListAll
3795 || fListFiles)
3796 {
3797 SafeIfaceArray <IGuestFile> collFiles;
3798 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Files)(ComSafeArrayAsOutParam(collFiles)));
3799 for (size_t a = 0; a < collFiles.size(); a++)
3800 {
3801 ComPtr<IGuestFile> pCurFile = collFiles[a];
3802 if (!pCurFile.isNull())
3803 {
3804 do
3805 {
3806 ULONG idFile;
3807 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Id)(&idFile));
3808 Bstr strName;
3809 CHECK_ERROR_BREAK(pCurFile, COMGETTER(FileName)(strName.asOutParam()));
3810 FileStatus_T fileStatus;
3811 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Status)(&fileStatus));
3812
3813 RTPrintf("\n\t\tFile #%-03zu ID=%-6RU32 Status=[%s] Name=%ls",
3814 a, idFile, gctlFileStatusToText(fileStatus), strName.raw());
3815 } while (0);
3816 }
3817 }
3818
3819 cTotalFiles += collFiles.size();
3820 }
3821 }
3822 }
3823
3824 RTPrintf("\n\nTotal guest sessions: %zu\n", collSessions.size());
3825 if (fListAll || fListProcesses)
3826 RTPrintf("Total guest processes: %zu\n", cTotalProcs);
3827 if (fListAll || fListFiles)
3828 RTPrintf("Total guest files: %zu\n", cTotalFiles);
3829 }
3830 else
3831 RTPrintf("No active guest sessions found\n");
3832 }
3833
3834 if (FAILED(rc))
3835 rcExit = RTEXITCODE_FAILURE;
3836
3837 return rcExit;
3838}
3839
3840static DECLCALLBACK(RTEXITCODE) gctlHandleCloseProcess(PGCTLCMDCTX pCtx, int argc, char **argv)
3841{
3842 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3843
3844 static const RTGETOPTDEF s_aOptions[] =
3845 {
3846 GCTLCMD_COMMON_OPTION_DEFS()
3847 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3848 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3849 };
3850
3851 int ch;
3852 RTGETOPTUNION ValueUnion;
3853 RTGETOPTSTATE GetState;
3854 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3855
3856 std::vector < uint32_t > vecPID;
3857 ULONG ulSessionID = UINT32_MAX;
3858 Utf8Str strSessionName;
3859
3860 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3861 {
3862 /* For options that require an argument, ValueUnion has received the value. */
3863 switch (ch)
3864 {
3865 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3866
3867 case 'n': /* Session name (or pattern) */
3868 strSessionName = ValueUnion.psz;
3869 break;
3870
3871 case 'i': /* Session ID */
3872 ulSessionID = ValueUnion.u32;
3873 break;
3874
3875 case VINF_GETOPT_NOT_OPTION:
3876 {
3877 /* Treat every else specified as a PID to kill. */
3878 uint32_t uPid;
3879 int rc = RTStrToUInt32Ex(ValueUnion.psz, NULL, 0, &uPid);
3880 if ( RT_SUCCESS(rc)
3881 && rc != VWRN_TRAILING_CHARS
3882 && rc != VWRN_NUMBER_TOO_BIG
3883 && rc != VWRN_NEGATIVE_UNSIGNED)
3884 {
3885 if (uPid != 0)
3886 {
3887 try
3888 {
3889 vecPID.push_back(uPid);
3890 }
3891 catch (std::bad_alloc &)
3892 {
3893 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory");
3894 }
3895 }
3896 else
3897 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "Invalid PID value: 0");
3898 }
3899 else
3900 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
3901 "Error parsing PID value: %Rrc", rc);
3902 break;
3903 }
3904
3905 default:
3906 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, ch, &ValueUnion);
3907 }
3908 }
3909
3910 if (vecPID.empty())
3911 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
3912 "At least one PID must be specified to kill!");
3913
3914 if ( strSessionName.isEmpty()
3915 && ulSessionID == UINT32_MAX)
3916 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "No session ID specified!");
3917
3918 if ( strSessionName.isNotEmpty()
3919 && ulSessionID != UINT32_MAX)
3920 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
3921 "Either session ID or name (pattern) must be specified");
3922
3923 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3924 if (rcExit != RTEXITCODE_SUCCESS)
3925 return rcExit;
3926
3927 HRESULT rc = S_OK;
3928
3929 ComPtr<IGuestSession> pSession;
3930 ComPtr<IGuestProcess> pProcess;
3931 do
3932 {
3933 uint32_t uProcsTerminated = 0;
3934 bool fSessionFound = false;
3935
3936 SafeIfaceArray <IGuestSession> collSessions;
3937 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3938 size_t cSessions = collSessions.size();
3939
3940 uint32_t uSessionsHandled = 0;
3941 for (size_t i = 0; i < cSessions; i++)
3942 {
3943 pSession = collSessions[i];
3944 Assert(!pSession.isNull());
3945
3946 ULONG uID; /* Session ID */
3947 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3948 Bstr strName;
3949 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3950 Utf8Str strNameUtf8(strName); /* Session name */
3951 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3952 {
3953 fSessionFound = uID == ulSessionID;
3954 }
3955 else /* ... or by naming pattern. */
3956 {
3957 if (RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str()))
3958 fSessionFound = true;
3959 }
3960
3961 if (fSessionFound)
3962 {
3963 AssertStmt(!pSession.isNull(), break);
3964 uSessionsHandled++;
3965
3966 SafeIfaceArray <IGuestProcess> collProcs;
3967 CHECK_ERROR_BREAK(pSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcs)));
3968
3969 size_t cProcs = collProcs.size();
3970 for (size_t p = 0; p < cProcs; p++)
3971 {
3972 pProcess = collProcs[p];
3973 Assert(!pProcess.isNull());
3974
3975 ULONG uPID; /* Process ID */
3976 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
3977
3978 bool fProcFound = false;
3979 for (size_t a = 0; a < vecPID.size(); a++) /* Slow, but works. */
3980 {
3981 fProcFound = vecPID[a] == uPID;
3982 if (fProcFound)
3983 break;
3984 }
3985
3986 if (fProcFound)
3987 {
3988 if (pCtx->cVerbose > 1)
3989 RTPrintf("Terminating process (PID %RU32) (session ID %RU32) ...\n",
3990 uPID, uID);
3991 CHECK_ERROR_BREAK(pProcess, Terminate());
3992 uProcsTerminated++;
3993 }
3994 else
3995 {
3996 if (ulSessionID != UINT32_MAX)
3997 RTPrintf("No matching process(es) for session ID %RU32 found\n",
3998 ulSessionID);
3999 }
4000
4001 pProcess.setNull();
4002 }
4003
4004 pSession.setNull();
4005 }
4006 }
4007
4008 if (!uSessionsHandled)
4009 RTPrintf("No matching session(s) found\n");
4010
4011 if (uProcsTerminated)
4012 RTPrintf("%RU32 %s terminated\n",
4013 uProcsTerminated, uProcsTerminated == 1 ? "process" : "processes");
4014
4015 } while (0);
4016
4017 pProcess.setNull();
4018 pSession.setNull();
4019
4020 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
4021}
4022
4023
4024static DECLCALLBACK(RTEXITCODE) gctlHandleCloseSession(PGCTLCMDCTX pCtx, int argc, char **argv)
4025{
4026 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
4027
4028 enum GETOPTDEF_SESSIONCLOSE
4029 {
4030 GETOPTDEF_SESSIONCLOSE_ALL = 2000
4031 };
4032 static const RTGETOPTDEF s_aOptions[] =
4033 {
4034 GCTLCMD_COMMON_OPTION_DEFS()
4035 { "--all", GETOPTDEF_SESSIONCLOSE_ALL, RTGETOPT_REQ_NOTHING },
4036 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
4037 { "--session-name", 'n', RTGETOPT_REQ_STRING }
4038 };
4039
4040 int ch;
4041 RTGETOPTUNION ValueUnion;
4042 RTGETOPTSTATE GetState;
4043 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4044
4045 ULONG ulSessionID = UINT32_MAX;
4046 Utf8Str strSessionName;
4047
4048 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
4049 {
4050 /* For options that require an argument, ValueUnion has received the value. */
4051 switch (ch)
4052 {
4053 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
4054
4055 case 'n': /* Session name pattern */
4056 strSessionName = ValueUnion.psz;
4057 break;
4058
4059 case 'i': /* Session ID */
4060 ulSessionID = ValueUnion.u32;
4061 break;
4062
4063 case GETOPTDEF_SESSIONCLOSE_ALL:
4064 strSessionName = "*";
4065 break;
4066
4067 case VINF_GETOPT_NOT_OPTION:
4068 /** @todo Supply a CSV list of IDs or patterns to close?
4069 * break; */
4070 default:
4071 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION, ch, &ValueUnion);
4072 }
4073 }
4074
4075 if ( strSessionName.isEmpty()
4076 && ulSessionID == UINT32_MAX)
4077 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION,
4078 "No session ID specified!");
4079
4080 if ( !strSessionName.isEmpty()
4081 && ulSessionID != UINT32_MAX)
4082 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION,
4083 "Either session ID or name (pattern) must be specified");
4084
4085 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
4086 if (rcExit != RTEXITCODE_SUCCESS)
4087 return rcExit;
4088
4089 HRESULT rc = S_OK;
4090
4091 do
4092 {
4093 bool fSessionFound = false;
4094 size_t cSessionsHandled = 0;
4095
4096 SafeIfaceArray <IGuestSession> collSessions;
4097 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
4098 size_t cSessions = collSessions.size();
4099
4100 for (size_t i = 0; i < cSessions; i++)
4101 {
4102 ComPtr<IGuestSession> pSession = collSessions[i];
4103 Assert(!pSession.isNull());
4104
4105 ULONG uID; /* Session ID */
4106 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
4107 Bstr strName;
4108 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
4109 Utf8Str strNameUtf8(strName); /* Session name */
4110
4111 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
4112 {
4113 fSessionFound = uID == ulSessionID;
4114 }
4115 else /* ... or by naming pattern. */
4116 {
4117 if (RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str()))
4118 fSessionFound = true;
4119 }
4120
4121 if (fSessionFound)
4122 {
4123 cSessionsHandled++;
4124
4125 Assert(!pSession.isNull());
4126 if (pCtx->cVerbose > 1)
4127 RTPrintf("Closing guest session ID=#%RU32 \"%s\" ...\n",
4128 uID, strNameUtf8.c_str());
4129 CHECK_ERROR_BREAK(pSession, Close());
4130 if (pCtx->cVerbose > 1)
4131 RTPrintf("Guest session successfully closed\n");
4132
4133 pSession.setNull();
4134 }
4135 }
4136
4137 if (!cSessionsHandled)
4138 {
4139 RTPrintf("No guest session(s) found\n");
4140 rc = E_ABORT; /* To set exit code accordingly. */
4141 }
4142
4143 } while (0);
4144
4145 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
4146}
4147
4148
4149static DECLCALLBACK(RTEXITCODE) gctlHandleWatch(PGCTLCMDCTX pCtx, int argc, char **argv)
4150{
4151 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
4152
4153 /*
4154 * Parse arguments.
4155 */
4156 static const RTGETOPTDEF s_aOptions[] =
4157 {
4158 GCTLCMD_COMMON_OPTION_DEFS()
4159 };
4160
4161 int ch;
4162 RTGETOPTUNION ValueUnion;
4163 RTGETOPTSTATE GetState;
4164 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4165
4166 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
4167 {
4168 /* For options that require an argument, ValueUnion has received the value. */
4169 switch (ch)
4170 {
4171 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
4172
4173 case VINF_GETOPT_NOT_OPTION:
4174 default:
4175 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_WATCH, ch, &ValueUnion);
4176 }
4177 }
4178
4179 /** @todo Specify categories to watch for. */
4180 /** @todo Specify a --timeout for waiting only for a certain amount of time? */
4181
4182 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
4183 if (rcExit != RTEXITCODE_SUCCESS)
4184 return rcExit;
4185
4186 HRESULT rc;
4187
4188 try
4189 {
4190 ComObjPtr<GuestEventListenerImpl> pGuestListener;
4191 do
4192 {
4193 /* Listener creation. */
4194 pGuestListener.createObject();
4195 pGuestListener->init(new GuestEventListener());
4196
4197 /* Register for IGuest events. */
4198 ComPtr<IEventSource> es;
4199 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
4200 com::SafeArray<VBoxEventType_T> eventTypes;
4201 eventTypes.push_back(VBoxEventType_OnGuestSessionRegistered);
4202 /** @todo Also register for VBoxEventType_OnGuestUserStateChanged on demand? */
4203 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
4204 true /* Active listener */));
4205 /* Note: All other guest control events have to be registered
4206 * as their corresponding objects appear. */
4207
4208 } while (0);
4209
4210 if (pCtx->cVerbose > 1)
4211 RTPrintf("Waiting for events ...\n");
4212
4213 while (!g_fGuestCtrlCanceled)
4214 {
4215 /** @todo Timeout handling (see above)? */
4216 RTThreadSleep(10);
4217 }
4218
4219 if (pCtx->cVerbose > 1)
4220 RTPrintf("Signal caught, exiting ...\n");
4221
4222 if (!pGuestListener.isNull())
4223 {
4224 /* Guest callback unregistration. */
4225 ComPtr<IEventSource> pES;
4226 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
4227 if (!pES.isNull())
4228 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
4229 pGuestListener.setNull();
4230 }
4231 }
4232 catch (std::bad_alloc &)
4233 {
4234 rc = E_OUTOFMEMORY;
4235 }
4236
4237 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
4238}
4239
4240/**
4241 * Access the guest control store.
4242 *
4243 * @returns program exit code.
4244 * @note see the command line API description for parameters
4245 */
4246int handleGuestControl(HandlerArg *pArg)
4247{
4248 AssertPtrReturn(pArg, VERR_INVALID_POINTER);
4249
4250#ifdef DEBUG_andy_disabled
4251 if (RT_FAILURE(tstTranslatePath()))
4252 return RTEXITCODE_FAILURE;
4253#endif
4254
4255 /*
4256 * Command definitions.
4257 */
4258 static const GCTLCMDDEF s_aCmdDefs[] =
4259 {
4260 { "run", gctlHandleRun, USAGE_GSTCTRL_RUN, 0, },
4261 { "start", gctlHandleStart, USAGE_GSTCTRL_START, 0, },
4262 { "copyfrom", gctlHandleCopyFrom, USAGE_GSTCTRL_COPYFROM, 0, },
4263 { "copyto", gctlHandleCopyTo, USAGE_GSTCTRL_COPYTO, 0, },
4264
4265 { "mkdir", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4266 { "md", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4267 { "createdirectory", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4268 { "createdir", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4269
4270 { "rmdir", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
4271 { "removedir", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
4272 { "removedirectory", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
4273
4274 { "rm", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4275 { "removefile", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4276 { "erase", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4277 { "del", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4278 { "delete", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4279
4280 { "mv", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4281 { "move", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4282 { "ren", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4283 { "rename", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4284
4285 { "mktemp", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
4286 { "createtemp", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
4287 { "createtemporary", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
4288
4289 { "stat", gctlHandleStat, USAGE_GSTCTRL_STAT, 0, },
4290
4291 { "closeprocess", gctlHandleCloseProcess, USAGE_GSTCTRL_CLOSEPROCESS, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4292 { "closesession", gctlHandleCloseSession, USAGE_GSTCTRL_CLOSESESSION, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4293 { "list", gctlHandleList, USAGE_GSTCTRL_LIST, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4294 { "watch", gctlHandleWatch, USAGE_GSTCTRL_WATCH, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4295
4296 {"updateguestadditions",gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4297 { "updateadditions", gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4298 { "updatega", gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4299 };
4300
4301 /*
4302 * VBoxManage guestcontrol [common-options] <VM> [common-options] <sub-command> ...
4303 *
4304 * Parse common options and VM name until we find a sub-command. Allowing
4305 * the user to put the user and password related options before the
4306 * sub-command makes it easier to edit the command line when doing several
4307 * operations with the same guest user account. (Accidentally, it also
4308 * makes the syntax diagram shorter and easier to read.)
4309 */
4310 GCTLCMDCTX CmdCtx;
4311 RTEXITCODE rcExit = gctrCmdCtxInit(&CmdCtx, pArg);
4312 if (rcExit == RTEXITCODE_SUCCESS)
4313 {
4314 static const RTGETOPTDEF s_CommonOptions[] = { GCTLCMD_COMMON_OPTION_DEFS() };
4315
4316 int ch;
4317 RTGETOPTUNION ValueUnion;
4318 RTGETOPTSTATE GetState;
4319 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_CommonOptions, RT_ELEMENTS(s_CommonOptions), 0, 0 /* No sorting! */);
4320
4321 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
4322 {
4323 switch (ch)
4324 {
4325 GCTLCMD_COMMON_OPTION_CASES(&CmdCtx, ch, &ValueUnion);
4326
4327 case VINF_GETOPT_NOT_OPTION:
4328 /* First comes the VM name or UUID. */
4329 if (!CmdCtx.pszVmNameOrUuid)
4330 CmdCtx.pszVmNameOrUuid = ValueUnion.psz;
4331 /*
4332 * The sub-command is next. Look it up and invoke it.
4333 * Note! Currently no warnings about user/password options (like we'll do later on)
4334 * for GCTLCMDCTX_F_SESSION_ANONYMOUS commands. No reason to be too pedantic.
4335 */
4336 else
4337 {
4338 const char *pszCmd = ValueUnion.psz;
4339 uint32_t iCmd;
4340 for (iCmd = 0; iCmd < RT_ELEMENTS(s_aCmdDefs); iCmd++)
4341 if (strcmp(s_aCmdDefs[iCmd].pszName, pszCmd) == 0)
4342 {
4343 CmdCtx.pCmdDef = &s_aCmdDefs[iCmd];
4344
4345 rcExit = s_aCmdDefs[iCmd].pfnHandler(&CmdCtx, pArg->argc - GetState.iNext + 1,
4346 &pArg->argv[GetState.iNext - 1]);
4347
4348 gctlCtxTerm(&CmdCtx);
4349 return rcExit;
4350 }
4351 return errorSyntax(USAGE_GUESTCONTROL, "Unknown sub-command: '%s'", pszCmd);
4352 }
4353 break;
4354
4355 default:
4356 return errorGetOpt(USAGE_GUESTCONTROL, ch, &ValueUnion);
4357 }
4358 }
4359 if (CmdCtx.pszVmNameOrUuid)
4360 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Missing sub-command");
4361 else
4362 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Missing VM name and sub-command");
4363 }
4364 return rcExit;
4365}
4366#endif /* !VBOX_ONLY_DOCS */
4367
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