VirtualBox

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

Last change on this file since 63300 was 63300, checked in by vboxsync, 9 years ago

VBoxManage: warnings

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

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