VirtualBox

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

Last change on this file since 61893 was 61893, checked in by vboxsync, 8 years ago

Main: Renamed ProcessCreateFlag::NoProfile to ProcessCreateFlag::Profile.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 160.2 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 61893 2016-06-27 11:31:20Z 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;
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 int vrc = RTEXITCODE_SUCCESS;
1162 switch (enmStatus)
1163 {
1164 case ProcessStatus_TerminatedNormally:
1165 if (uExitCode == 0)
1166 return RTEXITCODE_SUCCESS;
1167 if (!fReturnExitCodes)
1168 return EXITCODEEXEC_CODE;
1169 if (uExitCode <= EXITCODEEXEC_MAPPED_RANGE)
1170 return (RTEXITCODE) (uExitCode + EXITCODEEXEC_MAPPED_DISPLACEMENT);
1171 return EXITCODEEXEC_MAPPED_BIG;
1172
1173 case ProcessStatus_TerminatedAbnormally:
1174 return EXITCODEEXEC_TERM_ABEND;
1175 case ProcessStatus_TerminatedSignal:
1176 return EXITCODEEXEC_TERM_SIGNAL;
1177
1178#if 0 /* see caller! */
1179 case ProcessStatus_TimedOutKilled:
1180 return EXITCODEEXEC_TIMEOUT;
1181 case ProcessStatus_Down:
1182 return EXITCODEEXEC_DOWN; /* Service/OS is stopping, process was killed. */
1183 case ProcessStatus_Error:
1184 return EXITCODEEXEC_FAILED;
1185
1186 /* The following is probably for detached? */
1187 case ProcessStatus_Starting:
1188 return RTEXITCODE_SUCCESS;
1189 case ProcessStatus_Started:
1190 return RTEXITCODE_SUCCESS;
1191 case ProcessStatus_Paused:
1192 return RTEXITCODE_SUCCESS;
1193 case ProcessStatus_Terminating:
1194 return RTEXITCODE_SUCCESS; /** @todo ???? */
1195#endif
1196
1197 default:
1198 AssertMsgFailed(("Unknown exit status (%u/%u) from guest process returned!\n", enmStatus, uExitCode));
1199 return RTEXITCODE_FAILURE;
1200 }
1201}
1202
1203
1204/**
1205 * Pumps guest output to the host.
1206 *
1207 * @return IPRT status code.
1208 * @param pProcess Pointer to appropriate process object.
1209 * @param hVfsIosDst Where to write the data.
1210 * @param uHandle Handle where to read the data from.
1211 * @param cMsTimeout Timeout (in ms) to wait for the operation to
1212 * complete.
1213 */
1214static int gctlRunPumpOutput(IProcess *pProcess, RTVFSIOSTREAM hVfsIosDst, ULONG uHandle, RTMSINTERVAL cMsTimeout)
1215{
1216 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
1217 Assert(hVfsIosDst != NIL_RTVFSIOSTREAM);
1218
1219 int vrc;
1220
1221 SafeArray<BYTE> aOutputData;
1222 HRESULT hrc = pProcess->Read(uHandle, _64K, RT_MAX(cMsTimeout, 1), ComSafeArrayAsOutParam(aOutputData));
1223 if (SUCCEEDED(hrc))
1224 {
1225 size_t cbOutputData = aOutputData.size();
1226 if (cbOutputData == 0)
1227 vrc = VINF_SUCCESS;
1228 else
1229 {
1230 BYTE const *pbBuf = aOutputData.raw();
1231 AssertPtr(pbBuf);
1232
1233 vrc = RTVfsIoStrmWrite(hVfsIosDst, pbBuf, cbOutputData, true /*fBlocking*/, NULL);
1234 if (RT_FAILURE(vrc))
1235 RTMsgError("Unable to write output, rc=%Rrc\n", vrc);
1236 }
1237 }
1238 else
1239 vrc = gctlPrintError(pProcess, COM_IIDOF(IProcess));
1240 return vrc;
1241}
1242
1243
1244/**
1245 * Configures a host handle for pumping guest bits.
1246 *
1247 * @returns true if enabled and we successfully configured it.
1248 * @param fEnabled Whether pumping this pipe is configured.
1249 * @param enmHandle The IPRT standard handle designation.
1250 * @param pszName The name for user messages.
1251 * @param enmTransformation The transformation to apply.
1252 * @param phVfsIos Where to return the resulting I/O stream handle.
1253 */
1254static bool gctlRunSetupHandle(bool fEnabled, RTHANDLESTD enmHandle, const char *pszName,
1255 kStreamTransform enmTransformation, PRTVFSIOSTREAM phVfsIos)
1256{
1257 if (fEnabled)
1258 {
1259 int vrc = RTVfsIoStrmFromStdHandle(enmHandle, 0, true /*fLeaveOpen*/, phVfsIos);
1260 if (RT_SUCCESS(vrc))
1261 {
1262 if (enmTransformation != kStreamTransform_None)
1263 {
1264 RTMsgWarning("Unsupported %s line ending conversion", pszName);
1265 /** @todo Implement dos2unix and unix2dos stream filters. */
1266 }
1267 return true;
1268 }
1269 RTMsgWarning("Error getting %s handle: %Rrc", pszName, vrc);
1270 }
1271 return false;
1272}
1273
1274
1275/**
1276 * Returns the remaining time (in ms) based on the start time and a set
1277 * timeout value. Returns RT_INDEFINITE_WAIT if no timeout was specified.
1278 *
1279 * @return RTMSINTERVAL Time left (in ms).
1280 * @param u64StartMs Start time (in ms).
1281 * @param cMsTimeout Timeout value (in ms).
1282 */
1283static RTMSINTERVAL gctlRunGetRemainingTime(uint64_t u64StartMs, RTMSINTERVAL cMsTimeout)
1284{
1285 if (!cMsTimeout || cMsTimeout == RT_INDEFINITE_WAIT) /* If no timeout specified, wait forever. */
1286 return RT_INDEFINITE_WAIT;
1287
1288 uint64_t u64ElapsedMs = RTTimeMilliTS() - u64StartMs;
1289 if (u64ElapsedMs >= cMsTimeout)
1290 return 0;
1291
1292 return cMsTimeout - (RTMSINTERVAL)u64ElapsedMs;
1293}
1294
1295/**
1296 * Common handler for the 'run' and 'start' commands.
1297 *
1298 * @returns Command exit code.
1299 * @param pCtx Guest session context.
1300 * @param argc The argument count.
1301 * @param argv The argument vector for this command.
1302 * @param fRunCmd Set if it's 'run' clear if 'start'.
1303 * @param fHelp The help flag for the command.
1304 */
1305static RTEXITCODE gctlHandleRunCommon(PGCTLCMDCTX pCtx, int argc, char **argv, bool fRunCmd, uint32_t fHelp)
1306{
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 size_t cOptions =
1349 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions) - (fRunCmd ? 0 : 6),
1350 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
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 AssertPtrReturn(pCtx, VERR_INVALID_POINTER);
1768
1769 int vrc = VINF_SUCCESS;
1770 try
1771 {
1772 PCOPYCONTEXT pContext = new COPYCONTEXT();
1773
1774 pContext->pCmdCtx = pCtx;
1775 pContext->fDryRun = fDryRun;
1776 pContext->fHostToGuest = fHostToGuest;
1777
1778 *ppContext = pContext;
1779 }
1780 catch (std::bad_alloc)
1781 {
1782 vrc = VERR_NO_MEMORY;
1783 }
1784
1785 return vrc;
1786}
1787
1788/**
1789 * Frees are previously allocated copy context structure.
1790 *
1791 * @param pContext Pointer to copy context to free.
1792 */
1793static void gctlCopyContextFree(PCOPYCONTEXT pContext)
1794{
1795 if (pContext)
1796 delete pContext;
1797}
1798
1799/**
1800 * Translates a source path to a destination path (can be both sides,
1801 * either host or guest). The source root is needed to determine the start
1802 * of the relative source path which also needs to present in the destination
1803 * path.
1804 *
1805 * @return IPRT status code.
1806 * @param pszSourceRoot Source root path. No trailing directory slash!
1807 * @param pszSource Actual source to transform. Must begin with
1808 * the source root path!
1809 * @param pszDest Destination path.
1810 * @param ppszTranslated Pointer to the allocated, translated destination
1811 * path. Must be free'd with RTStrFree().
1812 */
1813static int gctlCopyTranslatePath(const char *pszSourceRoot, const char *pszSource,
1814 const char *pszDest, char **ppszTranslated)
1815{
1816 AssertPtrReturn(pszSourceRoot, VERR_INVALID_POINTER);
1817 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1818 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1819 AssertPtrReturn(ppszTranslated, VERR_INVALID_POINTER);
1820#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} */
1821 AssertReturn(RTPathStartsWith(pszSource, pszSourceRoot), VERR_INVALID_PARAMETER);
1822#endif
1823
1824 /* Construct the relative dest destination path by "subtracting" the
1825 * source from the source root, e.g.
1826 *
1827 * source root path = "e:\foo\", source = "e:\foo\bar"
1828 * dest = "d:\baz\"
1829 * translated = "d:\baz\bar\"
1830 */
1831 char szTranslated[RTPATH_MAX];
1832 size_t srcOff = strlen(pszSourceRoot);
1833 AssertReturn(srcOff, VERR_INVALID_PARAMETER);
1834
1835 char *pszDestPath = RTStrDup(pszDest);
1836 AssertPtrReturn(pszDestPath, VERR_NO_MEMORY);
1837
1838 int vrc;
1839 if (!RTPathFilename(pszDestPath))
1840 {
1841 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1842 pszDestPath, &pszSource[srcOff]);
1843 }
1844 else
1845 {
1846 char *pszDestFileName = RTStrDup(RTPathFilename(pszDestPath));
1847 if (pszDestFileName)
1848 {
1849 RTPathStripFilename(pszDestPath);
1850 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1851 pszDestPath, pszDestFileName);
1852 RTStrFree(pszDestFileName);
1853 }
1854 else
1855 vrc = VERR_NO_MEMORY;
1856 }
1857 RTStrFree(pszDestPath);
1858
1859 if (RT_SUCCESS(vrc))
1860 {
1861 *ppszTranslated = RTStrDup(szTranslated);
1862#if 0
1863 RTPrintf("Root: %s, Source: %s, Dest: %s, Translated: %s\n",
1864 pszSourceRoot, pszSource, pszDest, *ppszTranslated);
1865#endif
1866 }
1867 return vrc;
1868}
1869
1870#ifdef DEBUG_andy
1871static int tstTranslatePath()
1872{
1873 RTAssertSetMayPanic(false /* Do not freak out, please. */);
1874
1875 static struct
1876 {
1877 const char *pszSourceRoot;
1878 const char *pszSource;
1879 const char *pszDest;
1880 const char *pszTranslated;
1881 int iResult;
1882 } aTests[] =
1883 {
1884 /* Invalid stuff. */
1885 { NULL, NULL, NULL, NULL, VERR_INVALID_POINTER },
1886#ifdef RT_OS_WINDOWS
1887 /* Windows paths. */
1888 { "c:\\foo", "c:\\foo\\bar.txt", "c:\\test", "c:\\test\\bar.txt", VINF_SUCCESS },
1889 { "c:\\foo", "c:\\foo\\baz\\bar.txt", "c:\\test", "c:\\test\\baz\\bar.txt", VINF_SUCCESS },
1890#else /* RT_OS_WINDOWS */
1891 { "/home/test/foo", "/home/test/foo/bar.txt", "/opt/test", "/opt/test/bar.txt", VINF_SUCCESS },
1892 { "/home/test/foo", "/home/test/foo/baz/bar.txt", "/opt/test", "/opt/test/baz/bar.txt", VINF_SUCCESS },
1893#endif /* !RT_OS_WINDOWS */
1894 /* Mixed paths*/
1895 /** @todo */
1896 { NULL }
1897 };
1898
1899 size_t iTest = 0;
1900 for (iTest; iTest < RT_ELEMENTS(aTests); iTest++)
1901 {
1902 RTPrintf("=> Test %d\n", iTest);
1903 RTPrintf("\tSourceRoot=%s, Source=%s, Dest=%s\n",
1904 aTests[iTest].pszSourceRoot, aTests[iTest].pszSource, aTests[iTest].pszDest);
1905
1906 char *pszTranslated = NULL;
1907 int iResult = gctlCopyTranslatePath(aTests[iTest].pszSourceRoot, aTests[iTest].pszSource,
1908 aTests[iTest].pszDest, &pszTranslated);
1909 if (iResult != aTests[iTest].iResult)
1910 {
1911 RTPrintf("\tReturned %Rrc, expected %Rrc\n",
1912 iResult, aTests[iTest].iResult);
1913 }
1914 else if ( pszTranslated
1915 && strcmp(pszTranslated, aTests[iTest].pszTranslated))
1916 {
1917 RTPrintf("\tReturned translated path %s, expected %s\n",
1918 pszTranslated, aTests[iTest].pszTranslated);
1919 }
1920
1921 if (pszTranslated)
1922 {
1923 RTPrintf("\tTranslated=%s\n", pszTranslated);
1924 RTStrFree(pszTranslated);
1925 }
1926 }
1927
1928 return VINF_SUCCESS; /* @todo */
1929}
1930#endif
1931
1932/**
1933 * Creates a directory on the destination, based on the current copy
1934 * context.
1935 *
1936 * @return IPRT status code.
1937 * @param pContext Pointer to current copy control context.
1938 * @param pszDir Directory to create.
1939 */
1940static int gctlCopyDirCreate(PCOPYCONTEXT pContext, const char *pszDir)
1941{
1942 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1943 AssertPtrReturn(pszDir, VERR_INVALID_POINTER);
1944
1945 bool fDirExists;
1946 int vrc = gctlCopyDirExists(pContext, pContext->fHostToGuest, pszDir, &fDirExists);
1947 if ( RT_SUCCESS(vrc)
1948 && fDirExists)
1949 {
1950 if (pContext->pCmdCtx->cVerbose)
1951 RTPrintf("Directory \"%s\" already exists\n", pszDir);
1952 return VINF_SUCCESS;
1953 }
1954
1955 /* If querying for a directory existence fails there's no point of even trying
1956 * to create such a directory. */
1957 if (RT_FAILURE(vrc))
1958 return vrc;
1959
1960 if (pContext->pCmdCtx->cVerbose)
1961 RTPrintf("Creating directory \"%s\" ...\n", pszDir);
1962
1963 if (pContext->fDryRun)
1964 return VINF_SUCCESS;
1965
1966 if (pContext->fHostToGuest) /* We want to create directories on the guest. */
1967 {
1968 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
1969 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1970 HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryCreate(Bstr(pszDir).raw(),
1971 0700, ComSafeArrayAsInParam(dirCreateFlags));
1972 if (FAILED(rc))
1973 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
1974 }
1975 else /* ... or on the host. */
1976 {
1977 vrc = RTDirCreateFullPath(pszDir, 0700);
1978 if (vrc == VERR_ALREADY_EXISTS)
1979 vrc = VINF_SUCCESS;
1980 }
1981 return vrc;
1982}
1983
1984/**
1985 * Checks whether a specific host/guest directory exists.
1986 *
1987 * @return IPRT status code.
1988 * @param pContext Pointer to current copy control context.
1989 * @param fOnGuest true if directory needs to be checked on the guest
1990 * or false if on the host.
1991 * @param pszDir Actual directory to check.
1992 * @param fExists Pointer which receives the result if the
1993 * given directory exists or not.
1994 */
1995static int gctlCopyDirExists(PCOPYCONTEXT pContext, bool fOnGuest,
1996 const char *pszDir, bool *fExists)
1997{
1998 AssertPtrReturn(pContext, false);
1999 AssertPtrReturn(pszDir, false);
2000 AssertPtrReturn(fExists, false);
2001
2002 int vrc = VINF_SUCCESS;
2003 if (fOnGuest)
2004 {
2005 BOOL fDirExists = FALSE;
2006 HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryExists(Bstr(pszDir).raw(), FALSE /*followSymlinks*/, &fDirExists);
2007 if (SUCCEEDED(rc))
2008 *fExists = fDirExists != FALSE;
2009 else
2010 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2011 }
2012 else
2013 *fExists = RTDirExists(pszDir);
2014 return vrc;
2015}
2016
2017/**
2018 * Checks whether a specific directory exists on the destination, based
2019 * on the current copy context.
2020 *
2021 * @return IPRT status code.
2022 * @param pContext Pointer to current copy control context.
2023 * @param pszDir Actual directory to check.
2024 * @param fExists Pointer which receives the result if the
2025 * given directory exists or not.
2026 */
2027static int gctlCopyDirExistsOnDest(PCOPYCONTEXT pContext, const char *pszDir,
2028 bool *fExists)
2029{
2030 return gctlCopyDirExists(pContext, pContext->fHostToGuest,
2031 pszDir, fExists);
2032}
2033
2034/**
2035 * Checks whether a specific directory exists on the source, based
2036 * on the current copy context.
2037 *
2038 * @return IPRT status code.
2039 * @param pContext Pointer to current copy control context.
2040 * @param pszDir Actual directory to check.
2041 * @param fExists Pointer which receives the result if the
2042 * given directory exists or not.
2043 */
2044static int gctlCopyDirExistsOnSource(PCOPYCONTEXT pContext, const char *pszDir,
2045 bool *fExists)
2046{
2047 return gctlCopyDirExists(pContext, !pContext->fHostToGuest,
2048 pszDir, fExists);
2049}
2050
2051/**
2052 * Checks whether a specific host/guest file exists.
2053 *
2054 * @return IPRT status code.
2055 * @param pContext Pointer to current copy control context.
2056 * @param bGuest true if file needs to be checked on the guest
2057 * or false if on the host.
2058 * @param pszFile Actual file to check.
2059 * @param fExists Pointer which receives the result if the
2060 * given file exists or not.
2061 */
2062static int gctlCopyFileExists(PCOPYCONTEXT pContext, bool bOnGuest,
2063 const char *pszFile, bool *fExists)
2064{
2065 AssertPtrReturn(pContext, false);
2066 AssertPtrReturn(pszFile, false);
2067 AssertPtrReturn(fExists, false);
2068
2069 int vrc = VINF_SUCCESS;
2070 if (bOnGuest)
2071 {
2072 BOOL fFileExists = FALSE;
2073 HRESULT rc = pContext->pCmdCtx->pGuestSession->FileExists(Bstr(pszFile).raw(), FALSE /*followSymlinks*/, &fFileExists);
2074 if (SUCCEEDED(rc))
2075 *fExists = fFileExists != FALSE;
2076 else
2077 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2078 }
2079 else
2080 *fExists = RTFileExists(pszFile);
2081 return vrc;
2082}
2083
2084/**
2085 * Checks whether a specific file exists on the destination, based on the
2086 * current copy context.
2087 *
2088 * @return IPRT status code.
2089 * @param pContext Pointer to current copy control context.
2090 * @param pszFile Actual file to check.
2091 * @param fExists Pointer which receives the result if the
2092 * given file exists or not.
2093 */
2094static int gctlCopyFileExistsOnDest(PCOPYCONTEXT pContext, const char *pszFile,
2095 bool *fExists)
2096{
2097 return gctlCopyFileExists(pContext, pContext->fHostToGuest,
2098 pszFile, fExists);
2099}
2100
2101/**
2102 * Checks whether a specific file exists on the source, based on the
2103 * current copy context.
2104 *
2105 * @return IPRT status code.
2106 * @param pContext Pointer to current copy control context.
2107 * @param pszFile Actual file to check.
2108 * @param fExists Pointer which receives the result if the
2109 * given file exists or not.
2110 */
2111static int gctlCopyFileExistsOnSource(PCOPYCONTEXT pContext, const char *pszFile,
2112 bool *fExists)
2113{
2114 return gctlCopyFileExists(pContext, !pContext->fHostToGuest,
2115 pszFile, fExists);
2116}
2117
2118/**
2119 * Copies a source file to the destination.
2120 *
2121 * @return IPRT status code.
2122 * @param pContext Pointer to current copy control context.
2123 * @param pszFileSource Source file to copy to the destination.
2124 * @param pszFileDest Name of copied file on the destination.
2125 * @param enmFlags Copy flags. No supported at the moment and
2126 * needs to be set to 0.
2127 */
2128static int gctlCopyFileToDest(PCOPYCONTEXT pContext, const char *pszFileSource,
2129 const char *pszFileDest, gctlCopyFlags enmFlags)
2130{
2131 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
2132 AssertPtrReturn(pszFileSource, VERR_INVALID_POINTER);
2133 AssertPtrReturn(pszFileDest, VERR_INVALID_POINTER);
2134 AssertReturn(enmFlags == kGctlCopyFlags_None, VERR_INVALID_PARAMETER); /* No flags supported yet. */
2135
2136 if (pContext->pCmdCtx->cVerbose)
2137 RTPrintf("Copying \"%s\" to \"%s\" ...\n", pszFileSource, pszFileDest);
2138
2139 if (pContext->fDryRun)
2140 return VINF_SUCCESS;
2141
2142 int vrc = VINF_SUCCESS;
2143 ComPtr<IProgress> pProgress;
2144 HRESULT rc;
2145 if (pContext->fHostToGuest)
2146 {
2147 SafeArray<FileCopyFlag_T> copyFlags;
2148 rc = pContext->pCmdCtx->pGuestSession->FileCopyToGuest(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
2149 ComSafeArrayAsInParam(copyFlags),
2150 pProgress.asOutParam());
2151 }
2152 else
2153 {
2154 SafeArray<FileCopyFlag_T> copyFlags;
2155 rc = pContext->pCmdCtx->pGuestSession->FileCopyFromGuest(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
2156 ComSafeArrayAsInParam(copyFlags),
2157 pProgress.asOutParam());
2158 }
2159
2160 if (FAILED(rc))
2161 {
2162 vrc = gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2163 }
2164 else
2165 {
2166 if (pContext->pCmdCtx->cVerbose)
2167 rc = showProgress(pProgress);
2168 else
2169 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
2170 if (SUCCEEDED(rc))
2171 CHECK_PROGRESS_ERROR(pProgress, ("File copy failed"));
2172 vrc = gctlPrintProgressError(pProgress);
2173 }
2174
2175 return vrc;
2176}
2177
2178/**
2179 * Copys a directory (tree) from host to the guest.
2180 *
2181 * @return IPRT status code.
2182 * @param pContext Pointer to current copy control context.
2183 * @param pszSource Source directory on the host to copy to the guest.
2184 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
2185 * @param pszDest Destination directory on the guest.
2186 * @param enmFlags Copy flags, such as recursive copying.
2187 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
2188 * is needed for recursion.
2189 */
2190static int gctlCopyDirToGuest(PCOPYCONTEXT pContext,
2191 const char *pszSource, const char *pszFilter,
2192 const char *pszDest, enum gctlCopyFlags enmFlags,
2193 const char *pszSubDir /* For recursion. */)
2194{
2195 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
2196 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
2197 /* Filter is optional. */
2198 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
2199 /* Sub directory is optional. */
2200
2201 /*
2202 * Construct current path.
2203 */
2204 char szCurDir[RTPATH_MAX];
2205 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
2206 if (RT_SUCCESS(vrc) && pszSubDir)
2207 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
2208
2209 if (pContext->pCmdCtx->cVerbose)
2210 RTPrintf("Processing host directory: %s\n", szCurDir);
2211
2212 /* Flag indicating whether the current directory was created on the
2213 * target or not. */
2214 bool fDirCreated = false;
2215
2216 /*
2217 * Open directory without a filter - RTDirOpenFiltered unfortunately
2218 * cannot handle sub directories so we have to do the filtering ourselves.
2219 */
2220 PRTDIR pDir = NULL;
2221 if (RT_SUCCESS(vrc))
2222 {
2223 vrc = RTDirOpen(&pDir, szCurDir);
2224 if (RT_FAILURE(vrc))
2225 pDir = NULL;
2226 }
2227 if (RT_SUCCESS(vrc))
2228 {
2229 /*
2230 * Enumerate the directory tree.
2231 */
2232 while (RT_SUCCESS(vrc))
2233 {
2234 RTDIRENTRY DirEntry;
2235 vrc = RTDirRead(pDir, &DirEntry, NULL);
2236 if (RT_FAILURE(vrc))
2237 {
2238 if (vrc == VERR_NO_MORE_FILES)
2239 vrc = VINF_SUCCESS;
2240 break;
2241 }
2242 /** @todo r=bird: This ain't gonna work on most UNIX file systems because
2243 * enmType is RTDIRENTRYTYPE_UNKNOWN. This is clearly documented in
2244 * RTDIRENTRY::enmType. For trunk, RTDirQueryUnknownType can be used. */
2245 switch (DirEntry.enmType)
2246 {
2247 case RTDIRENTRYTYPE_DIRECTORY:
2248 {
2249 /* Skip "." and ".." entries. */
2250 if ( !strcmp(DirEntry.szName, ".")
2251 || !strcmp(DirEntry.szName, ".."))
2252 break;
2253
2254 if (pContext->pCmdCtx->cVerbose)
2255 RTPrintf("Directory: %s\n", DirEntry.szName);
2256
2257 if (enmFlags & kGctlCopyFlags_Recursive)
2258 {
2259 char *pszNewSub = NULL;
2260 if (pszSubDir)
2261 pszNewSub = RTPathJoinA(pszSubDir, DirEntry.szName);
2262 else
2263 {
2264 pszNewSub = RTStrDup(DirEntry.szName);
2265 RTPathStripTrailingSlash(pszNewSub);
2266 }
2267
2268 if (pszNewSub)
2269 {
2270 vrc = gctlCopyDirToGuest(pContext,
2271 pszSource, pszFilter,
2272 pszDest, enmFlags, pszNewSub);
2273 RTStrFree(pszNewSub);
2274 }
2275 else
2276 vrc = VERR_NO_MEMORY;
2277 }
2278 break;
2279 }
2280
2281 case RTDIRENTRYTYPE_SYMLINK:
2282 if ( (enmFlags & kGctlCopyFlags_Recursive)
2283 && (enmFlags & kGctlCopyFlags_FollowLinks))
2284 {
2285 /* Fall through to next case is intentional. */
2286 }
2287 else
2288 break;
2289
2290 case RTDIRENTRYTYPE_FILE:
2291 {
2292 if ( pszFilter
2293 && !RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
2294 {
2295 break; /* Filter does not match. */
2296 }
2297
2298 if (pContext->pCmdCtx->cVerbose)
2299 RTPrintf("File: %s\n", DirEntry.szName);
2300
2301 if (!fDirCreated)
2302 {
2303 char *pszDestDir;
2304 vrc = gctlCopyTranslatePath(pszSource, szCurDir,
2305 pszDest, &pszDestDir);
2306 if (RT_SUCCESS(vrc))
2307 {
2308 vrc = gctlCopyDirCreate(pContext, pszDestDir);
2309 RTStrFree(pszDestDir);
2310
2311 fDirCreated = true;
2312 }
2313 }
2314
2315 if (RT_SUCCESS(vrc))
2316 {
2317 char *pszFileSource = RTPathJoinA(szCurDir, DirEntry.szName);
2318 if (pszFileSource)
2319 {
2320 char *pszFileDest;
2321 vrc = gctlCopyTranslatePath(pszSource, pszFileSource,
2322 pszDest, &pszFileDest);
2323 if (RT_SUCCESS(vrc))
2324 {
2325 vrc = gctlCopyFileToDest(pContext, pszFileSource,
2326 pszFileDest, kGctlCopyFlags_None);
2327 RTStrFree(pszFileDest);
2328 }
2329 RTStrFree(pszFileSource);
2330 }
2331 }
2332 break;
2333 }
2334
2335 default:
2336 break;
2337 }
2338 if (RT_FAILURE(vrc))
2339 break;
2340 }
2341
2342 RTDirClose(pDir);
2343 }
2344 return vrc;
2345}
2346
2347/**
2348 * Copys a directory (tree) from guest to the host.
2349 *
2350 * @return IPRT status code.
2351 * @param pContext Pointer to current copy control context.
2352 * @param pszSource Source directory on the guest to copy to the host.
2353 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
2354 * @param pszDest Destination directory on the host.
2355 * @param enmFlags Copy flags, such as recursive copying.
2356 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
2357 * is needed for recursion.
2358 */
2359static int gctlCopyDirToHost(PCOPYCONTEXT pContext,
2360 const char *pszSource, const char *pszFilter,
2361 const char *pszDest, gctlCopyFlags enmFlags,
2362 const char *pszSubDir /* For recursion. */)
2363{
2364 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
2365 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
2366 /* Filter is optional. */
2367 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
2368 /* Sub directory is optional. */
2369
2370 /*
2371 * Construct current path.
2372 */
2373 char szCurDir[RTPATH_MAX];
2374 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
2375 if (RT_SUCCESS(vrc) && pszSubDir)
2376 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
2377
2378 if (RT_FAILURE(vrc))
2379 return vrc;
2380
2381 if (pContext->pCmdCtx->cVerbose)
2382 RTPrintf("Processing guest directory: %s\n", szCurDir);
2383
2384 /* Flag indicating whether the current directory was created on the
2385 * target or not. */
2386 bool fDirCreated = false;
2387 SafeArray<DirectoryOpenFlag_T> dirOpenFlags; /* No flags supported yet. */
2388 ComPtr<IGuestDirectory> pDirectory;
2389 HRESULT rc = pContext->pCmdCtx->pGuestSession->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(),
2390 ComSafeArrayAsInParam(dirOpenFlags),
2391 pDirectory.asOutParam());
2392 if (FAILED(rc))
2393 return gctlPrintError(pContext->pCmdCtx->pGuestSession, COM_IIDOF(IGuestSession));
2394 ComPtr<IFsObjInfo> dirEntry;
2395 while (true)
2396 {
2397 rc = pDirectory->Read(dirEntry.asOutParam());
2398 if (FAILED(rc))
2399 break;
2400
2401 FsObjType_T enmType;
2402 dirEntry->COMGETTER(Type)(&enmType);
2403
2404 Bstr strName;
2405 dirEntry->COMGETTER(Name)(strName.asOutParam());
2406
2407 switch (enmType)
2408 {
2409 case FsObjType_Directory:
2410 {
2411 Assert(!strName.isEmpty());
2412
2413 /* Skip "." and ".." entries. */
2414 if ( !strName.compare(Bstr("."))
2415 || !strName.compare(Bstr("..")))
2416 break;
2417
2418 if (pContext->pCmdCtx->cVerbose)
2419 {
2420 Utf8Str strDir(strName);
2421 RTPrintf("Directory: %s\n", strDir.c_str());
2422 }
2423
2424 if (enmFlags & kGctlCopyFlags_Recursive)
2425 {
2426 Utf8Str strDir(strName);
2427 char *pszNewSub = NULL;
2428 if (pszSubDir)
2429 pszNewSub = RTPathJoinA(pszSubDir, strDir.c_str());
2430 else
2431 {
2432 pszNewSub = RTStrDup(strDir.c_str());
2433 RTPathStripTrailingSlash(pszNewSub);
2434 }
2435 if (pszNewSub)
2436 {
2437 vrc = gctlCopyDirToHost(pContext,
2438 pszSource, pszFilter,
2439 pszDest, enmFlags, pszNewSub);
2440 RTStrFree(pszNewSub);
2441 }
2442 else
2443 vrc = VERR_NO_MEMORY;
2444 }
2445 break;
2446 }
2447
2448 case FsObjType_Symlink:
2449 if ( (enmFlags & kGctlCopyFlags_Recursive)
2450 && (enmFlags & kGctlCopyFlags_FollowLinks))
2451 {
2452 /* Fall through to next case is intentional. */
2453 }
2454 else
2455 break;
2456
2457 case FsObjType_File:
2458 {
2459 Assert(!strName.isEmpty());
2460
2461 Utf8Str strFile(strName);
2462 if ( pszFilter
2463 && !RTStrSimplePatternMatch(pszFilter, strFile.c_str()))
2464 {
2465 break; /* Filter does not match. */
2466 }
2467
2468 if (pContext->pCmdCtx->cVerbose)
2469 RTPrintf("File: %s\n", strFile.c_str());
2470
2471 if (!fDirCreated)
2472 {
2473 char *pszDestDir;
2474 vrc = gctlCopyTranslatePath(pszSource, szCurDir,
2475 pszDest, &pszDestDir);
2476 if (RT_SUCCESS(vrc))
2477 {
2478 vrc = gctlCopyDirCreate(pContext, pszDestDir);
2479 RTStrFree(pszDestDir);
2480
2481 fDirCreated = true;
2482 }
2483 }
2484
2485 if (RT_SUCCESS(vrc))
2486 {
2487 char *pszFileSource = RTPathJoinA(szCurDir, strFile.c_str());
2488 if (pszFileSource)
2489 {
2490 char *pszFileDest;
2491 vrc = gctlCopyTranslatePath(pszSource, pszFileSource,
2492 pszDest, &pszFileDest);
2493 if (RT_SUCCESS(vrc))
2494 {
2495 vrc = gctlCopyFileToDest(pContext, pszFileSource,
2496 pszFileDest, kGctlCopyFlags_None);
2497 RTStrFree(pszFileDest);
2498 }
2499 RTStrFree(pszFileSource);
2500 }
2501 else
2502 vrc = VERR_NO_MEMORY;
2503 }
2504 break;
2505 }
2506
2507 default:
2508 RTPrintf("Warning: Directory entry of type %ld not handled, skipping ...\n",
2509 enmType);
2510 break;
2511 }
2512
2513 if (RT_FAILURE(vrc))
2514 break;
2515 }
2516
2517 if (RT_UNLIKELY(FAILED(rc)))
2518 {
2519 switch (rc)
2520 {
2521 case E_ABORT: /* No more directory entries left to process. */
2522 break;
2523
2524 case VBOX_E_FILE_ERROR: /* Current entry cannot be accessed to
2525 to missing rights. */
2526 {
2527 RTPrintf("Warning: Cannot access \"%s\", skipping ...\n",
2528 szCurDir);
2529 break;
2530 }
2531
2532 default:
2533 vrc = gctlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
2534 break;
2535 }
2536 }
2537
2538 HRESULT rc2 = pDirectory->Close();
2539 if (FAILED(rc2))
2540 {
2541 int vrc2 = gctlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
2542 if (RT_SUCCESS(vrc))
2543 vrc = vrc2;
2544 }
2545 else if (SUCCEEDED(rc))
2546 rc = rc2;
2547
2548 return vrc;
2549}
2550
2551/**
2552 * Copys a directory (tree) to the destination, based on the current copy
2553 * context.
2554 *
2555 * @return IPRT status code.
2556 * @param pContext Pointer to current copy control context.
2557 * @param pszSource Source directory to copy to the destination.
2558 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
2559 * @param pszDest Destination directory where to copy in the source
2560 * source directory.
2561 * @param enmFlags Copy flags, such as recursive copying.
2562 */
2563static int gctlCopyDirToDest(PCOPYCONTEXT pContext,
2564 const char *pszSource, const char *pszFilter,
2565 const char *pszDest, enum gctlCopyFlags enmFlags)
2566{
2567 if (pContext->fHostToGuest)
2568 return gctlCopyDirToGuest(pContext, pszSource, pszFilter,
2569 pszDest, enmFlags, NULL /* Sub directory, only for recursion. */);
2570 return gctlCopyDirToHost(pContext, pszSource, pszFilter,
2571 pszDest, enmFlags, NULL /* Sub directory, only for recursion. */);
2572}
2573
2574/**
2575 * Creates a source root by stripping file names or filters of the specified source.
2576 *
2577 * @return IPRT status code.
2578 * @param pszSource Source to create source root for.
2579 * @param ppszSourceRoot Pointer that receives the allocated source root. Needs
2580 * to be free'd with gctlCopyFreeSourceRoot().
2581 */
2582static int gctlCopyCreateSourceRoot(const char *pszSource, char **ppszSourceRoot)
2583{
2584 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
2585 AssertPtrReturn(ppszSourceRoot, VERR_INVALID_POINTER);
2586
2587 char *pszNewRoot = RTStrDup(pszSource);
2588 if (!pszNewRoot)
2589 return VERR_NO_MEMORY;
2590
2591 size_t lenRoot = strlen(pszNewRoot);
2592 if ( lenRoot
2593 && ( pszNewRoot[lenRoot - 1] == '/'
2594 || pszNewRoot[lenRoot - 1] == '\\')
2595 )
2596 {
2597 pszNewRoot[lenRoot - 1] = '\0';
2598 }
2599
2600 if ( lenRoot > 1
2601 && ( pszNewRoot[lenRoot - 2] == '/'
2602 || pszNewRoot[lenRoot - 2] == '\\')
2603 )
2604 {
2605 pszNewRoot[lenRoot - 2] = '\0';
2606 }
2607
2608 if (!lenRoot)
2609 {
2610 /* If there's anything (like a file name or a filter),
2611 * strip it! */
2612 RTPathStripFilename(pszNewRoot);
2613 }
2614
2615 *ppszSourceRoot = pszNewRoot;
2616
2617 return VINF_SUCCESS;
2618}
2619
2620/**
2621 * Frees a previously allocated source root.
2622 *
2623 * @return IPRT status code.
2624 * @param pszSourceRoot Source root to free.
2625 */
2626static void gctlCopyFreeSourceRoot(char *pszSourceRoot)
2627{
2628 RTStrFree(pszSourceRoot);
2629}
2630
2631static RTEXITCODE gctlHandleCopy(PGCTLCMDCTX pCtx, int argc, char **argv, bool fHostToGuest)
2632{
2633 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2634
2635 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
2636 * is much better (partly because it is much simpler of course). The main
2637 * arguments against this is that (1) all but two options conflicts with
2638 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
2639 * done windows CMD style (though not in a 100% compatible way), and (3)
2640 * that only one source is allowed - efficiently sabotaging default
2641 * wildcard expansion by a unix shell. The best solution here would be
2642 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
2643
2644 /*
2645 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
2646 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
2647 * does in here.
2648 */
2649 enum GETOPTDEF_COPY
2650 {
2651 GETOPTDEF_COPY_DRYRUN = 1000,
2652 GETOPTDEF_COPY_FOLLOW,
2653 GETOPTDEF_COPY_TARGETDIR
2654 };
2655 static const RTGETOPTDEF s_aOptions[] =
2656 {
2657 GCTLCMD_COMMON_OPTION_DEFS()
2658 { "--dryrun", GETOPTDEF_COPY_DRYRUN, RTGETOPT_REQ_NOTHING },
2659 { "--follow", GETOPTDEF_COPY_FOLLOW, RTGETOPT_REQ_NOTHING },
2660 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
2661 { "--target-directory", GETOPTDEF_COPY_TARGETDIR, RTGETOPT_REQ_STRING }
2662 };
2663
2664 int ch;
2665 RTGETOPTUNION ValueUnion;
2666 RTGETOPTSTATE GetState;
2667 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2668
2669 Utf8Str strSource;
2670 const char *pszDst = NULL;
2671 enum gctlCopyFlags enmFlags = kGctlCopyFlags_None;
2672 bool fCopyRecursive = false;
2673 bool fDryRun = false;
2674 uint32_t uUsage = fHostToGuest ? USAGE_GSTCTRL_COPYTO : USAGE_GSTCTRL_COPYFROM;
2675
2676 SOURCEVEC vecSources;
2677
2678 int vrc = VINF_SUCCESS;
2679 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2680 {
2681 /* For options that require an argument, ValueUnion has received the value. */
2682 switch (ch)
2683 {
2684 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2685
2686 case GETOPTDEF_COPY_DRYRUN:
2687 fDryRun = true;
2688 break;
2689
2690 case GETOPTDEF_COPY_FOLLOW:
2691 enmFlags = (enum gctlCopyFlags)((uint32_t)enmFlags | kGctlCopyFlags_FollowLinks);
2692 break;
2693
2694 case 'R': /* Recursive processing */
2695 enmFlags = (enum gctlCopyFlags)((uint32_t)enmFlags | kGctlCopyFlags_Recursive);
2696 break;
2697
2698 case GETOPTDEF_COPY_TARGETDIR:
2699 pszDst = ValueUnion.psz;
2700 break;
2701
2702 case VINF_GETOPT_NOT_OPTION:
2703 /* Last argument and no destination specified with
2704 * --target-directory yet? Then use the current
2705 * (= last) argument as destination. */
2706 if ( pCtx->pArg->argc == GetState.iNext
2707 && pszDst == NULL)
2708 pszDst = ValueUnion.psz;
2709 else
2710 {
2711 try
2712 { /* Save the source directory. */
2713 vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
2714 }
2715 catch (std::bad_alloc &)
2716 {
2717 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory");
2718 }
2719 }
2720 break;
2721
2722 default:
2723 return errorGetOptEx(USAGE_GUESTCONTROL, uUsage, ch, &ValueUnion);
2724 }
2725 }
2726
2727 if (!vecSources.size())
2728 return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No source(s) specified!");
2729
2730 if (pszDst == NULL)
2731 return errorSyntaxEx(USAGE_GUESTCONTROL, uUsage, "No destination specified!");
2732
2733 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
2734 if (rcExit != RTEXITCODE_SUCCESS)
2735 return rcExit;
2736
2737 /*
2738 * Done parsing arguments, do some more preparations.
2739 */
2740 if (pCtx->cVerbose)
2741 {
2742 if (fHostToGuest)
2743 RTPrintf("Copying from host to guest ...\n");
2744 else
2745 RTPrintf("Copying from guest to host ...\n");
2746 if (fDryRun)
2747 RTPrintf("Dry run - no files copied!\n");
2748 }
2749
2750 /* Create the copy context -- it contains all information
2751 * the routines need to know when handling the actual copying. */
2752 PCOPYCONTEXT pContext = NULL;
2753 vrc = gctlCopyContextCreate(pCtx, fDryRun, fHostToGuest,
2754 fHostToGuest
2755 ? "VBoxManage Guest Control - Copy to guest"
2756 : "VBoxManage Guest Control - Copy from guest", &pContext);
2757 if (RT_FAILURE(vrc))
2758 {
2759 RTMsgError("Unable to create copy context, rc=%Rrc\n", vrc);
2760 return RTEXITCODE_FAILURE;
2761 }
2762
2763/** @todo r=bird: RTPathFilename and RTPathStripFilename won't work
2764 * correctly on non-windows hosts when the guest is from the DOS world (Windows,
2765 * OS/2, DOS). The host doesn't know about DOS slashes, only UNIX slashes and
2766 * will get the wrong idea if some dilligent user does:
2767 *
2768 * copyto myfile.txt 'C:\guestfile.txt'
2769 * or
2770 * copyto myfile.txt 'D:guestfile.txt'
2771 *
2772 * @bugref{6344}
2773 */
2774 if (!RTPathFilename(pszDst))
2775 {
2776 vrc = gctlCopyDirCreate(pContext, pszDst);
2777 }
2778 else
2779 {
2780 /* We assume we got a file name as destination -- so strip
2781 * the actual file name and make sure the appropriate
2782 * directories get created. */
2783 char *pszDstDir = RTStrDup(pszDst);
2784 AssertPtr(pszDstDir);
2785 RTPathStripFilename(pszDstDir);
2786 vrc = gctlCopyDirCreate(pContext, pszDstDir);
2787 RTStrFree(pszDstDir);
2788 }
2789
2790 if (RT_SUCCESS(vrc))
2791 {
2792 /*
2793 * Here starts the actual fun!
2794 * Handle all given sources one by one.
2795 */
2796 for (unsigned long s = 0; s < vecSources.size(); s++)
2797 {
2798 char *pszSource = RTStrDup(vecSources[s].GetSource());
2799 AssertPtrBreakStmt(pszSource, vrc = VERR_NO_MEMORY);
2800 const char *pszFilter = vecSources[s].GetFilter();
2801 if (!strlen(pszFilter))
2802 pszFilter = NULL; /* If empty filter then there's no filter :-) */
2803
2804 char *pszSourceRoot;
2805 vrc = gctlCopyCreateSourceRoot(pszSource, &pszSourceRoot);
2806 if (RT_FAILURE(vrc))
2807 {
2808 RTMsgError("Unable to create source root, rc=%Rrc\n", vrc);
2809 break;
2810 }
2811
2812 if (pCtx->cVerbose)
2813 RTPrintf("Source: %s\n", pszSource);
2814
2815 /** @todo Files with filter?? */
2816 bool fSourceIsFile = false;
2817 bool fSourceExists;
2818
2819 size_t cchSource = strlen(pszSource);
2820 if ( cchSource > 1
2821 && RTPATH_IS_SLASH(pszSource[cchSource - 1]))
2822 {
2823 if (pszFilter) /* Directory with filter (so use source root w/o the actual filter). */
2824 vrc = gctlCopyDirExistsOnSource(pContext, pszSourceRoot, &fSourceExists);
2825 else /* Regular directory without filter. */
2826 vrc = gctlCopyDirExistsOnSource(pContext, pszSource, &fSourceExists);
2827
2828 if (fSourceExists)
2829 {
2830 /* Strip trailing slash from our source element so that other functions
2831 * can use this stuff properly (like RTPathStartsWith). */
2832 RTPathStripTrailingSlash(pszSource);
2833 }
2834 }
2835 else
2836 {
2837 vrc = gctlCopyFileExistsOnSource(pContext, pszSource, &fSourceExists);
2838 if ( RT_SUCCESS(vrc)
2839 && fSourceExists)
2840 {
2841 fSourceIsFile = true;
2842 }
2843 }
2844
2845 if ( RT_SUCCESS(vrc)
2846 && fSourceExists)
2847 {
2848 if (fSourceIsFile)
2849 {
2850 /* Single file. */
2851 char *pszDstFile;
2852 vrc = gctlCopyTranslatePath(pszSourceRoot, pszSource, pszDst, &pszDstFile);
2853 if (RT_SUCCESS(vrc))
2854 {
2855 vrc = gctlCopyFileToDest(pContext, pszSource, pszDstFile, kGctlCopyFlags_None);
2856 RTStrFree(pszDstFile);
2857 }
2858 else
2859 RTMsgError("Unable to translate path for \"%s\", rc=%Rrc\n", pszSource, vrc);
2860 }
2861 else
2862 {
2863 /* Directory (with filter?). */
2864 vrc = gctlCopyDirToDest(pContext, pszSource, pszFilter, pszDst, enmFlags);
2865 }
2866 }
2867
2868 gctlCopyFreeSourceRoot(pszSourceRoot);
2869
2870 if ( RT_SUCCESS(vrc)
2871 && !fSourceExists)
2872 {
2873 RTMsgError("Warning: Source \"%s\" does not exist, skipping!\n",
2874 pszSource);
2875 RTStrFree(pszSource);
2876 continue;
2877 }
2878 else if (RT_FAILURE(vrc))
2879 {
2880 RTMsgError("Error processing \"%s\", rc=%Rrc\n",
2881 pszSource, vrc);
2882 RTStrFree(pszSource);
2883 break;
2884 }
2885
2886 RTStrFree(pszSource);
2887 }
2888 }
2889
2890 gctlCopyContextFree(pContext);
2891
2892 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2893}
2894
2895static DECLCALLBACK(RTEXITCODE) gctlHandleCopyFrom(PGCTLCMDCTX pCtx, int argc, char **argv)
2896{
2897 return gctlHandleCopy(pCtx, argc, argv, false /* Guest to host */);
2898}
2899
2900static DECLCALLBACK(RTEXITCODE) gctlHandleCopyTo(PGCTLCMDCTX pCtx, int argc, char **argv)
2901{
2902 return gctlHandleCopy(pCtx, argc, argv, true /* Host to guest */);
2903}
2904
2905static DECLCALLBACK(RTEXITCODE) handleCtrtMkDir(PGCTLCMDCTX pCtx, int argc, char **argv)
2906{
2907 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2908
2909 static const RTGETOPTDEF s_aOptions[] =
2910 {
2911 GCTLCMD_COMMON_OPTION_DEFS()
2912 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2913 { "--parents", 'P', RTGETOPT_REQ_NOTHING }
2914 };
2915
2916 int ch;
2917 RTGETOPTUNION ValueUnion;
2918 RTGETOPTSTATE GetState;
2919 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2920
2921 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
2922 uint32_t fDirMode = 0; /* Default mode. */
2923 uint32_t cDirsCreated = 0;
2924 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2925
2926 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
2927 {
2928 /* For options that require an argument, ValueUnion has received the value. */
2929 switch (ch)
2930 {
2931 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
2932
2933 case 'm': /* Mode */
2934 fDirMode = ValueUnion.u32;
2935 break;
2936
2937 case 'P': /* Create parents */
2938 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
2939 break;
2940
2941 case VINF_GETOPT_NOT_OPTION:
2942 if (cDirsCreated == 0)
2943 {
2944 /*
2945 * First non-option - no more options now.
2946 */
2947 rcExit = gctlCtxPostOptionParsingInit(pCtx);
2948 if (rcExit != RTEXITCODE_SUCCESS)
2949 return rcExit;
2950 if (pCtx->cVerbose)
2951 RTPrintf("Creating %RU32 directories...\n", argc - GetState.iNext + 1);
2952 }
2953 if (g_fGuestCtrlCanceled)
2954 return RTMsgErrorExit(RTEXITCODE_FAILURE, "mkdir was interrupted by Ctrl-C (%u left)\n",
2955 argc - GetState.iNext + 1);
2956
2957 /*
2958 * Create the specified directory.
2959 *
2960 * On failure we'll change the exit status to failure and
2961 * continue with the next directory that needs creating. We do
2962 * this because we only create new things, and because this is
2963 * how /bin/mkdir works on unix.
2964 */
2965 cDirsCreated++;
2966 if (pCtx->cVerbose)
2967 RTPrintf("Creating directory \"%s\" ...\n", ValueUnion.psz);
2968 try
2969 {
2970 HRESULT rc;
2971 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreate(Bstr(ValueUnion.psz).raw(),
2972 fDirMode, ComSafeArrayAsInParam(dirCreateFlags)));
2973 if (FAILED(rc))
2974 rcExit = RTEXITCODE_FAILURE;
2975 }
2976 catch (std::bad_alloc &)
2977 {
2978 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
2979 }
2980 break;
2981
2982 default:
2983 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKDIR, ch, &ValueUnion);
2984 }
2985 }
2986
2987 if (!cDirsCreated)
2988 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKDIR, "No directory to create specified!");
2989 return rcExit;
2990}
2991
2992
2993static DECLCALLBACK(RTEXITCODE) gctlHandleRmDir(PGCTLCMDCTX pCtx, int argc, char **argv)
2994{
2995 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
2996
2997 static const RTGETOPTDEF s_aOptions[] =
2998 {
2999 GCTLCMD_COMMON_OPTION_DEFS()
3000 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
3001 };
3002
3003 int ch;
3004 RTGETOPTUNION ValueUnion;
3005 RTGETOPTSTATE GetState;
3006 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3007
3008 bool fRecursive = false;
3009 uint32_t cDirRemoved = 0;
3010 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
3011
3012 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3013 {
3014 /* For options that require an argument, ValueUnion has received the value. */
3015 switch (ch)
3016 {
3017 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3018
3019 case 'R':
3020 fRecursive = true;
3021 break;
3022
3023 case VINF_GETOPT_NOT_OPTION:
3024 {
3025 if (cDirRemoved == 0)
3026 {
3027 /*
3028 * First non-option - no more options now.
3029 */
3030 rcExit = gctlCtxPostOptionParsingInit(pCtx);
3031 if (rcExit != RTEXITCODE_SUCCESS)
3032 return rcExit;
3033 if (pCtx->cVerbose)
3034 RTPrintf("Removing %RU32 directorie%ss...\n", argc - GetState.iNext + 1, fRecursive ? "trees" : "");
3035 }
3036 if (g_fGuestCtrlCanceled)
3037 return RTMsgErrorExit(RTEXITCODE_FAILURE, "rmdir was interrupted by Ctrl-C (%u left)\n",
3038 argc - GetState.iNext + 1);
3039
3040 cDirRemoved++;
3041 HRESULT rc;
3042 if (!fRecursive)
3043 {
3044 /*
3045 * Remove exactly one directory.
3046 */
3047 if (pCtx->cVerbose)
3048 RTPrintf("Removing directory \"%s\" ...\n", ValueUnion.psz);
3049 try
3050 {
3051 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemove(Bstr(ValueUnion.psz).raw()));
3052 }
3053 catch (std::bad_alloc &)
3054 {
3055 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
3056 }
3057 }
3058 else
3059 {
3060 /*
3061 * Remove the directory and anything under it, that means files
3062 * and everything. This is in the tradition of the Windows NT
3063 * CMD.EXE "rmdir /s" operation, a tradition which jpsoft's TCC
3064 * strongly warns against (and half-ways questions the sense of).
3065 */
3066 if (pCtx->cVerbose)
3067 RTPrintf("Recursively removing directory \"%s\" ...\n", ValueUnion.psz);
3068 try
3069 {
3070 /** @todo Make flags configurable. */
3071 com::SafeArray<DirectoryRemoveRecFlag_T> aRemRecFlags;
3072 aRemRecFlags.push_back(DirectoryRemoveRecFlag_ContentAndDir);
3073
3074 ComPtr<IProgress> ptrProgress;
3075 CHECK_ERROR(pCtx->pGuestSession, DirectoryRemoveRecursive(Bstr(ValueUnion.psz).raw(),
3076 ComSafeArrayAsInParam(aRemRecFlags),
3077 ptrProgress.asOutParam()));
3078 if (SUCCEEDED(rc))
3079 {
3080 if (pCtx->cVerbose)
3081 rc = showProgress(ptrProgress);
3082 else
3083 rc = ptrProgress->WaitForCompletion(-1 /* indefinitely */);
3084 if (SUCCEEDED(rc))
3085 CHECK_PROGRESS_ERROR(ptrProgress, ("Directory deletion failed"));
3086 ptrProgress.setNull();
3087 }
3088 }
3089 catch (std::bad_alloc &)
3090 {
3091 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory during recursive rmdir\n");
3092 }
3093 }
3094
3095 /*
3096 * This command returns immediately on failure since it's destructive in nature.
3097 */
3098 if (FAILED(rc))
3099 return RTEXITCODE_FAILURE;
3100 break;
3101 }
3102
3103 default:
3104 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RMDIR, ch, &ValueUnion);
3105 }
3106 }
3107
3108 if (!cDirRemoved)
3109 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RMDIR, "No directory to remove specified!");
3110 return rcExit;
3111}
3112
3113static DECLCALLBACK(RTEXITCODE) gctlHandleRm(PGCTLCMDCTX pCtx, int argc, char **argv)
3114{
3115 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3116
3117 static const RTGETOPTDEF s_aOptions[] =
3118 {
3119 GCTLCMD_COMMON_OPTION_DEFS()
3120 { "--force", 'f', RTGETOPT_REQ_NOTHING, },
3121 };
3122
3123 int ch;
3124 RTGETOPTUNION ValueUnion;
3125 RTGETOPTSTATE GetState;
3126 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3127
3128 uint32_t cFilesDeleted = 0;
3129 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
3130 bool fForce = true;
3131
3132 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3133 {
3134 /* For options that require an argument, ValueUnion has received the value. */
3135 switch (ch)
3136 {
3137 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3138
3139 case VINF_GETOPT_NOT_OPTION:
3140 if (cFilesDeleted == 0)
3141 {
3142 /*
3143 * First non-option - no more options now.
3144 */
3145 rcExit = gctlCtxPostOptionParsingInit(pCtx);
3146 if (rcExit != RTEXITCODE_SUCCESS)
3147 return rcExit;
3148 if (pCtx->cVerbose)
3149 RTPrintf("Removing %RU32 file(s)...\n", argc - GetState.iNext + 1);
3150 }
3151 if (g_fGuestCtrlCanceled)
3152 return RTMsgErrorExit(RTEXITCODE_FAILURE, "rm was interrupted by Ctrl-C (%u left)\n",
3153 argc - GetState.iNext + 1);
3154
3155 /*
3156 * Remove the specified file.
3157 *
3158 * On failure we will by default stop, however, the force option will
3159 * by unix traditions force us to ignore errors and continue.
3160 */
3161 cFilesDeleted++;
3162 if (pCtx->cVerbose)
3163 RTPrintf("Removing file \"%s\" ...\n", ValueUnion.psz);
3164 try
3165 {
3166 /** @todo How does IGuestSession::FsObjRemove work with read-only files? Do we
3167 * need to do some chmod or whatever to better emulate the --force flag? */
3168 HRESULT rc;
3169 CHECK_ERROR(pCtx->pGuestSession, FsObjRemove(Bstr(ValueUnion.psz).raw()));
3170 if (FAILED(rc) && !fForce)
3171 return RTEXITCODE_FAILURE;
3172 }
3173 catch (std::bad_alloc &)
3174 {
3175 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory\n");
3176 }
3177 break;
3178
3179 default:
3180 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RM, ch, &ValueUnion);
3181 }
3182 }
3183
3184 if (!cFilesDeleted && !fForce)
3185 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_RM, "No file to remove specified!");
3186 return rcExit;
3187}
3188
3189static DECLCALLBACK(RTEXITCODE) gctlHandleMv(PGCTLCMDCTX pCtx, int argc, char **argv)
3190{
3191 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3192
3193 static const RTGETOPTDEF s_aOptions[] =
3194 {
3195 GCTLCMD_COMMON_OPTION_DEFS()
3196 };
3197
3198 int ch;
3199 RTGETOPTUNION ValueUnion;
3200 RTGETOPTSTATE GetState;
3201 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3202
3203 int vrc = VINF_SUCCESS;
3204
3205 bool fDryrun = false;
3206 std::vector< Utf8Str > vecSources;
3207 const char *pszDst = NULL;
3208 com::SafeArray<FsObjRenameFlag_T> aRenameFlags;
3209
3210 try
3211 {
3212 /** @todo Make flags configurable. */
3213 aRenameFlags.push_back(FsObjRenameFlag_NoReplace);
3214
3215 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3216 && RT_SUCCESS(vrc))
3217 {
3218 /* For options that require an argument, ValueUnion has received the value. */
3219 switch (ch)
3220 {
3221 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3222
3223 /** @todo Implement a --dryrun command. */
3224 /** @todo Implement rename flags. */
3225
3226 case VINF_GETOPT_NOT_OPTION:
3227 vecSources.push_back(Utf8Str(ValueUnion.psz));
3228 pszDst = ValueUnion.psz;
3229 break;
3230
3231 default:
3232 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV, ch, &ValueUnion);
3233 }
3234 }
3235 }
3236 catch (std::bad_alloc)
3237 {
3238 vrc = VERR_NO_MEMORY;
3239 }
3240
3241 if (RT_FAILURE(vrc))
3242 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize, rc=%Rrc\n", vrc);
3243
3244 size_t cSources = vecSources.size();
3245 if (!cSources)
3246 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV,
3247 "No source(s) to move specified!");
3248 if (cSources < 2)
3249 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MV,
3250 "No destination specified!");
3251
3252 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3253 if (rcExit != RTEXITCODE_SUCCESS)
3254 return rcExit;
3255
3256 /* Delete last element, which now is the destination. */
3257 vecSources.pop_back();
3258 cSources = vecSources.size();
3259
3260 HRESULT rc = S_OK;
3261
3262 if (cSources > 1)
3263 {
3264 BOOL fExists = FALSE;
3265 rc = pCtx->pGuestSession->DirectoryExists(Bstr(pszDst).raw(), FALSE /*followSymlinks*/, &fExists);
3266 if (FAILED(rc) || !fExists)
3267 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Destination must be a directory when specifying multiple sources\n");
3268 }
3269
3270 /*
3271 * Rename (move) the entries.
3272 */
3273 if (pCtx->cVerbose)
3274 RTPrintf("Renaming %RU32 %s ...\n", cSources, cSources > 1 ? "entries" : "entry");
3275
3276 std::vector< Utf8Str >::iterator it = vecSources.begin();
3277 while ( (it != vecSources.end())
3278 && !g_fGuestCtrlCanceled)
3279 {
3280 Utf8Str strCurSource = (*it);
3281
3282 ComPtr<IGuestFsObjInfo> pFsObjInfo;
3283 FsObjType_T enmObjType;
3284 rc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(strCurSource).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
3285 if (SUCCEEDED(rc))
3286 rc = pFsObjInfo->COMGETTER(Type)(&enmObjType);
3287 if (FAILED(rc))
3288 {
3289 if (pCtx->cVerbose)
3290 RTPrintf("Warning: Cannot stat for element \"%s\": No such element\n",
3291 strCurSource.c_str());
3292 ++it;
3293 continue; /* Skip. */
3294 }
3295
3296 if (pCtx->cVerbose)
3297 RTPrintf("Renaming %s \"%s\" to \"%s\" ...\n",
3298 enmObjType == FsObjType_Directory ? "directory" : "file",
3299 strCurSource.c_str(), pszDst);
3300
3301 if (!fDryrun)
3302 {
3303 if (enmObjType == FsObjType_Directory)
3304 {
3305 CHECK_ERROR_BREAK(pCtx->pGuestSession, FsObjRename(Bstr(strCurSource).raw(),
3306 Bstr(pszDst).raw(),
3307 ComSafeArrayAsInParam(aRenameFlags)));
3308
3309 /* Break here, since it makes no sense to rename mroe than one source to
3310 * the same directory. */
3311/** @todo r=bird: You are being kind of windowsy (or just DOSish) about the 'sense' part here,
3312 * while being totaly buggy about the behavior. 'VBoxGuest guestcontrol ren dir1 dir2 dstdir' will
3313 * stop after 'dir1' and SILENTLY ignore dir2. If you tried this on Windows, you'd see an error
3314 * being displayed. If you 'man mv' on a nearby unixy system, you'd see that they've made perfect
3315 * sense out of any situation with more than one source. */
3316 it = vecSources.end();
3317 break;
3318 }
3319 else
3320 CHECK_ERROR_BREAK(pCtx->pGuestSession, FsObjRename(Bstr(strCurSource).raw(),
3321 Bstr(pszDst).raw(),
3322 ComSafeArrayAsInParam(aRenameFlags)));
3323 }
3324
3325 ++it;
3326 }
3327
3328 if ( (it != vecSources.end())
3329 && pCtx->cVerbose)
3330 {
3331 RTPrintf("Warning: Not all sources were renamed\n");
3332 }
3333
3334 return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
3335}
3336
3337static DECLCALLBACK(RTEXITCODE) gctlHandleMkTemp(PGCTLCMDCTX pCtx, int argc, char **argv)
3338{
3339 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3340
3341 static const RTGETOPTDEF s_aOptions[] =
3342 {
3343 GCTLCMD_COMMON_OPTION_DEFS()
3344 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
3345 { "--directory", 'D', RTGETOPT_REQ_NOTHING },
3346 { "--secure", 's', RTGETOPT_REQ_NOTHING },
3347 { "--tmpdir", 't', RTGETOPT_REQ_STRING }
3348 };
3349
3350 int ch;
3351 RTGETOPTUNION ValueUnion;
3352 RTGETOPTSTATE GetState;
3353 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3354
3355 Utf8Str strTemplate;
3356 uint32_t fMode = 0; /* Default mode. */
3357 bool fDirectory = false;
3358 bool fSecure = false;
3359 Utf8Str strTempDir;
3360
3361 DESTDIRMAP mapDirs;
3362
3363 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3364 {
3365 /* For options that require an argument, ValueUnion has received the value. */
3366 switch (ch)
3367 {
3368 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3369
3370 case 'm': /* Mode */
3371 fMode = ValueUnion.u32;
3372 break;
3373
3374 case 'D': /* Create directory */
3375 fDirectory = true;
3376 break;
3377
3378 case 's': /* Secure */
3379 fSecure = true;
3380 break;
3381
3382 case 't': /* Temp directory */
3383 strTempDir = ValueUnion.psz;
3384 break;
3385
3386 case VINF_GETOPT_NOT_OPTION:
3387 {
3388 if (strTemplate.isEmpty())
3389 strTemplate = ValueUnion.psz;
3390 else
3391 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
3392 "More than one template specified!\n");
3393 break;
3394 }
3395
3396 default:
3397 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP, ch, &ValueUnion);
3398 }
3399 }
3400
3401 if (strTemplate.isEmpty())
3402 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
3403 "No template specified!");
3404
3405 if (!fDirectory)
3406 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_MKTEMP,
3407 "Creating temporary files is currently not supported!");
3408
3409 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3410 if (rcExit != RTEXITCODE_SUCCESS)
3411 return rcExit;
3412
3413 /*
3414 * Create the directories.
3415 */
3416 if (pCtx->cVerbose)
3417 {
3418 if (fDirectory && !strTempDir.isEmpty())
3419 RTPrintf("Creating temporary directory from template '%s' in directory '%s' ...\n",
3420 strTemplate.c_str(), strTempDir.c_str());
3421 else if (fDirectory)
3422 RTPrintf("Creating temporary directory from template '%s' in default temporary directory ...\n",
3423 strTemplate.c_str());
3424 else if (!fDirectory && !strTempDir.isEmpty())
3425 RTPrintf("Creating temporary file from template '%s' in directory '%s' ...\n",
3426 strTemplate.c_str(), strTempDir.c_str());
3427 else if (!fDirectory)
3428 RTPrintf("Creating temporary file from template '%s' in default temporary directory ...\n",
3429 strTemplate.c_str());
3430 }
3431
3432 HRESULT rc = S_OK;
3433 if (fDirectory)
3434 {
3435 Bstr directory;
3436 CHECK_ERROR(pCtx->pGuestSession, DirectoryCreateTemp(Bstr(strTemplate).raw(),
3437 fMode, Bstr(strTempDir).raw(),
3438 fSecure,
3439 directory.asOutParam()));
3440 if (SUCCEEDED(rc))
3441 RTPrintf("Directory name: %ls\n", directory.raw());
3442 }
3443 else
3444 {
3445 // else - temporary file not yet implemented
3446 /** @todo implement temporary file creation (we fend it off above, no
3447 * worries). */
3448 rc = E_FAIL;
3449 }
3450
3451 return FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
3452}
3453
3454static DECLCALLBACK(RTEXITCODE) gctlHandleStat(PGCTLCMDCTX pCtx, int argc, char **argv)
3455{
3456 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3457
3458 static const RTGETOPTDEF s_aOptions[] =
3459 {
3460 GCTLCMD_COMMON_OPTION_DEFS()
3461 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
3462 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
3463 { "--format", 'c', RTGETOPT_REQ_STRING },
3464 { "--terse", 't', RTGETOPT_REQ_NOTHING }
3465 };
3466
3467 int ch;
3468 RTGETOPTUNION ValueUnion;
3469 RTGETOPTSTATE GetState;
3470 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3471
3472 DESTDIRMAP mapObjs;
3473
3474 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3475 {
3476 /* For options that require an argument, ValueUnion has received the value. */
3477 switch (ch)
3478 {
3479 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3480
3481 case 'L': /* Dereference */
3482 case 'f': /* File-system */
3483 case 'c': /* Format */
3484 case 't': /* Terse */
3485 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
3486 "Command \"%s\" not implemented yet!", ValueUnion.psz);
3487
3488 case VINF_GETOPT_NOT_OPTION:
3489 mapObjs[ValueUnion.psz]; /* Add element to check to map. */
3490 break;
3491
3492 default:
3493 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT, ch, &ValueUnion);
3494 }
3495 }
3496
3497 size_t cObjs = mapObjs.size();
3498 if (!cObjs)
3499 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_STAT,
3500 "No element(s) to check specified!");
3501
3502 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3503 if (rcExit != RTEXITCODE_SUCCESS)
3504 return rcExit;
3505
3506 HRESULT rc;
3507
3508 /*
3509 * Doing the checks.
3510 */
3511 DESTDIRMAPITER it = mapObjs.begin();
3512 while (it != mapObjs.end())
3513 {
3514 if (pCtx->cVerbose)
3515 RTPrintf("Checking for element \"%s\" ...\n", it->first.c_str());
3516
3517 ComPtr<IGuestFsObjInfo> pFsObjInfo;
3518 rc = pCtx->pGuestSession->FsObjQueryInfo(Bstr(it->first).raw(), FALSE /*followSymlinks*/, pFsObjInfo.asOutParam());
3519 if (FAILED(rc))
3520 {
3521 /* If there's at least one element which does not exist on the guest,
3522 * drop out with exitcode 1. */
3523 if (pCtx->cVerbose)
3524 RTPrintf("Cannot stat for element \"%s\": No such element\n",
3525 it->first.c_str());
3526 rcExit = RTEXITCODE_FAILURE;
3527 }
3528 else
3529 {
3530 FsObjType_T objType;
3531 pFsObjInfo->COMGETTER(Type)(&objType); /** @todo What about error checking? */
3532 switch (objType)
3533 {
3534 case FsObjType_File:
3535 RTPrintf("Element \"%s\" found: Is a file\n", it->first.c_str());
3536 break;
3537
3538 case FsObjType_Directory:
3539 RTPrintf("Element \"%s\" found: Is a directory\n", it->first.c_str());
3540 break;
3541
3542 case FsObjType_Symlink:
3543 RTPrintf("Element \"%s\" found: Is a symlink\n", it->first.c_str());
3544 break;
3545
3546 default:
3547 RTPrintf("Element \"%s\" found, type unknown (%ld)\n", it->first.c_str(), objType);
3548 break;
3549 }
3550
3551 /** @todo: Show more information about this element. */
3552 }
3553
3554 ++it;
3555 }
3556
3557 return rcExit;
3558}
3559
3560static DECLCALLBACK(RTEXITCODE) gctlHandleUpdateAdditions(PGCTLCMDCTX pCtx, int argc, char **argv)
3561{
3562 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3563
3564 /*
3565 * Check the syntax. We can deduce the correct syntax from the number of
3566 * arguments.
3567 */
3568 Utf8Str strSource;
3569 com::SafeArray<IN_BSTR> aArgs;
3570 bool fWaitStartOnly = false;
3571
3572 static const RTGETOPTDEF s_aOptions[] =
3573 {
3574 GCTLCMD_COMMON_OPTION_DEFS()
3575 { "--source", 's', RTGETOPT_REQ_STRING },
3576 { "--wait-start", 'w', RTGETOPT_REQ_NOTHING }
3577 };
3578
3579 int ch;
3580 RTGETOPTUNION ValueUnion;
3581 RTGETOPTSTATE GetState;
3582 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3583
3584 int vrc = VINF_SUCCESS;
3585 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3586 && RT_SUCCESS(vrc))
3587 {
3588 switch (ch)
3589 {
3590 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3591
3592 case 's':
3593 strSource = ValueUnion.psz;
3594 break;
3595
3596 case 'w':
3597 fWaitStartOnly = true;
3598 break;
3599
3600 case VINF_GETOPT_NOT_OPTION:
3601 if (aArgs.size() == 0 && strSource.isEmpty())
3602 strSource = ValueUnion.psz;
3603 else
3604 aArgs.push_back(Bstr(ValueUnion.psz).raw());
3605 break;
3606
3607 default:
3608 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEGA, ch, &ValueUnion);
3609 }
3610 }
3611
3612 if (pCtx->cVerbose)
3613 RTPrintf("Updating Guest Additions ...\n");
3614
3615 HRESULT rc = S_OK;
3616 while (strSource.isEmpty())
3617 {
3618 ComPtr<ISystemProperties> pProperties;
3619 CHECK_ERROR_BREAK(pCtx->pArg->virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
3620 Bstr strISO;
3621 CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
3622 strSource = strISO;
3623 break;
3624 }
3625
3626 /* Determine source if not set yet. */
3627 if (strSource.isEmpty())
3628 {
3629 RTMsgError("No Guest Additions source found or specified, aborting\n");
3630 vrc = VERR_FILE_NOT_FOUND;
3631 }
3632 else if (!RTFileExists(strSource.c_str()))
3633 {
3634 RTMsgError("Source \"%s\" does not exist!\n", strSource.c_str());
3635 vrc = VERR_FILE_NOT_FOUND;
3636 }
3637
3638 if (RT_SUCCESS(vrc))
3639 {
3640 if (pCtx->cVerbose)
3641 RTPrintf("Using source: %s\n", strSource.c_str());
3642
3643
3644 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3645 if (rcExit != RTEXITCODE_SUCCESS)
3646 return rcExit;
3647
3648
3649 com::SafeArray<AdditionsUpdateFlag_T> aUpdateFlags;
3650 if (fWaitStartOnly)
3651 {
3652 aUpdateFlags.push_back(AdditionsUpdateFlag_WaitForUpdateStartOnly);
3653 if (pCtx->cVerbose)
3654 RTPrintf("Preparing and waiting for Guest Additions installer to start ...\n");
3655 }
3656
3657 ComPtr<IProgress> pProgress;
3658 CHECK_ERROR(pCtx->pGuest, UpdateGuestAdditions(Bstr(strSource).raw(),
3659 ComSafeArrayAsInParam(aArgs),
3660 /* Wait for whole update process to complete. */
3661 ComSafeArrayAsInParam(aUpdateFlags),
3662 pProgress.asOutParam()));
3663 if (FAILED(rc))
3664 vrc = gctlPrintError(pCtx->pGuest, COM_IIDOF(IGuest));
3665 else
3666 {
3667 if (pCtx->cVerbose)
3668 rc = showProgress(pProgress);
3669 else
3670 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
3671
3672 if (SUCCEEDED(rc))
3673 CHECK_PROGRESS_ERROR(pProgress, ("Guest additions update failed"));
3674 vrc = gctlPrintProgressError(pProgress);
3675 if ( RT_SUCCESS(vrc)
3676 && pCtx->cVerbose)
3677 {
3678 RTPrintf("Guest Additions update successful\n");
3679 }
3680 }
3681 }
3682
3683 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
3684}
3685
3686static DECLCALLBACK(RTEXITCODE) gctlHandleList(PGCTLCMDCTX pCtx, int argc, char **argv)
3687{
3688 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3689
3690 static const RTGETOPTDEF s_aOptions[] =
3691 {
3692 GCTLCMD_COMMON_OPTION_DEFS()
3693 };
3694
3695 int ch;
3696 RTGETOPTUNION ValueUnion;
3697 RTGETOPTSTATE GetState;
3698 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3699
3700 bool fSeenListArg = false;
3701 bool fListAll = false;
3702 bool fListSessions = false;
3703 bool fListProcesses = false;
3704 bool fListFiles = false;
3705
3706 int vrc = VINF_SUCCESS;
3707 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
3708 && RT_SUCCESS(vrc))
3709 {
3710 switch (ch)
3711 {
3712 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3713
3714 case VINF_GETOPT_NOT_OPTION:
3715 if ( !RTStrICmp(ValueUnion.psz, "sessions")
3716 || !RTStrICmp(ValueUnion.psz, "sess"))
3717 fListSessions = true;
3718 else if ( !RTStrICmp(ValueUnion.psz, "processes")
3719 || !RTStrICmp(ValueUnion.psz, "procs"))
3720 fListSessions = fListProcesses = true; /* Showing processes implies showing sessions. */
3721 else if (!RTStrICmp(ValueUnion.psz, "files"))
3722 fListSessions = fListFiles = true; /* Showing files implies showing sessions. */
3723 else if (!RTStrICmp(ValueUnion.psz, "all"))
3724 fListAll = true;
3725 else
3726 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST,
3727 "Unknown list: '%s'", ValueUnion.psz);
3728 fSeenListArg = true;
3729 break;
3730
3731 default:
3732 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_UPDATEGA, ch, &ValueUnion);
3733 }
3734 }
3735
3736 if (!fSeenListArg)
3737 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_LIST, "Missing list name");
3738 Assert(fListAll || fListSessions);
3739
3740 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3741 if (rcExit != RTEXITCODE_SUCCESS)
3742 return rcExit;
3743
3744
3745 /** @todo Do we need a machine-readable output here as well? */
3746
3747 HRESULT rc;
3748 size_t cTotalProcs = 0;
3749 size_t cTotalFiles = 0;
3750
3751 SafeIfaceArray <IGuestSession> collSessions;
3752 CHECK_ERROR(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3753 if (SUCCEEDED(rc))
3754 {
3755 size_t const cSessions = collSessions.size();
3756 if (cSessions)
3757 {
3758 RTPrintf("Active guest sessions:\n");
3759
3760 /** @todo Make this output a bit prettier. No time now. */
3761
3762 for (size_t i = 0; i < cSessions; i++)
3763 {
3764 ComPtr<IGuestSession> pCurSession = collSessions[i];
3765 if (!pCurSession.isNull())
3766 {
3767 do
3768 {
3769 ULONG uID;
3770 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Id)(&uID));
3771 Bstr strName;
3772 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Name)(strName.asOutParam()));
3773 Bstr strUser;
3774 CHECK_ERROR_BREAK(pCurSession, COMGETTER(User)(strUser.asOutParam()));
3775 GuestSessionStatus_T sessionStatus;
3776 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Status)(&sessionStatus));
3777 RTPrintf("\n\tSession #%-3zu ID=%-3RU32 User=%-16ls Status=[%s] Name=%ls",
3778 i, uID, strUser.raw(), gctlGuestSessionStatusToText(sessionStatus), strName.raw());
3779 } while (0);
3780
3781 if ( fListAll
3782 || fListProcesses)
3783 {
3784 SafeIfaceArray <IGuestProcess> collProcesses;
3785 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcesses)));
3786 for (size_t a = 0; a < collProcesses.size(); a++)
3787 {
3788 ComPtr<IGuestProcess> pCurProcess = collProcesses[a];
3789 if (!pCurProcess.isNull())
3790 {
3791 do
3792 {
3793 ULONG uPID;
3794 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(PID)(&uPID));
3795 Bstr strExecPath;
3796 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(ExecutablePath)(strExecPath.asOutParam()));
3797 ProcessStatus_T procStatus;
3798 CHECK_ERROR_BREAK(pCurProcess, COMGETTER(Status)(&procStatus));
3799
3800 RTPrintf("\n\t\tProcess #%-03zu PID=%-6RU32 Status=[%s] Command=%ls",
3801 a, uPID, gctlProcessStatusToText(procStatus), strExecPath.raw());
3802 } while (0);
3803 }
3804 }
3805
3806 cTotalProcs += collProcesses.size();
3807 }
3808
3809 if ( fListAll
3810 || fListFiles)
3811 {
3812 SafeIfaceArray <IGuestFile> collFiles;
3813 CHECK_ERROR_BREAK(pCurSession, COMGETTER(Files)(ComSafeArrayAsOutParam(collFiles)));
3814 for (size_t a = 0; a < collFiles.size(); a++)
3815 {
3816 ComPtr<IGuestFile> pCurFile = collFiles[a];
3817 if (!pCurFile.isNull())
3818 {
3819 do
3820 {
3821 ULONG idFile;
3822 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Id)(&idFile));
3823 Bstr strName;
3824 CHECK_ERROR_BREAK(pCurFile, COMGETTER(FileName)(strName.asOutParam()));
3825 FileStatus_T fileStatus;
3826 CHECK_ERROR_BREAK(pCurFile, COMGETTER(Status)(&fileStatus));
3827
3828 RTPrintf("\n\t\tFile #%-03zu ID=%-6RU32 Status=[%s] Name=%ls",
3829 a, idFile, gctlFileStatusToText(fileStatus), strName.raw());
3830 } while (0);
3831 }
3832 }
3833
3834 cTotalFiles += collFiles.size();
3835 }
3836 }
3837 }
3838
3839 RTPrintf("\n\nTotal guest sessions: %zu\n", collSessions.size());
3840 if (fListAll || fListProcesses)
3841 RTPrintf("Total guest processes: %zu\n", cTotalProcs);
3842 if (fListAll || fListFiles)
3843 RTPrintf("Total guest files: %zu\n", cTotalFiles);
3844 }
3845 else
3846 RTPrintf("No active guest sessions found\n");
3847 }
3848
3849 if (FAILED(rc))
3850 rcExit = RTEXITCODE_FAILURE;
3851
3852 return rcExit;
3853}
3854
3855static DECLCALLBACK(RTEXITCODE) gctlHandleCloseProcess(PGCTLCMDCTX pCtx, int argc, char **argv)
3856{
3857 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
3858
3859 static const RTGETOPTDEF s_aOptions[] =
3860 {
3861 GCTLCMD_COMMON_OPTION_DEFS()
3862 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
3863 { "--session-name", 'n', RTGETOPT_REQ_STRING }
3864 };
3865
3866 int ch;
3867 RTGETOPTUNION ValueUnion;
3868 RTGETOPTSTATE GetState;
3869 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
3870
3871 std::vector < uint32_t > vecPID;
3872 ULONG ulSessionID = UINT32_MAX;
3873 Utf8Str strSessionName;
3874
3875 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
3876 {
3877 /* For options that require an argument, ValueUnion has received the value. */
3878 switch (ch)
3879 {
3880 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
3881
3882 case 'n': /* Session name (or pattern) */
3883 strSessionName = ValueUnion.psz;
3884 break;
3885
3886 case 'i': /* Session ID */
3887 ulSessionID = ValueUnion.u32;
3888 break;
3889
3890 case VINF_GETOPT_NOT_OPTION:
3891 {
3892 /* Treat every else specified as a PID to kill. */
3893 uint32_t uPid;
3894 int rc = RTStrToUInt32Ex(ValueUnion.psz, NULL, 0, &uPid);
3895 if ( RT_SUCCESS(rc)
3896 && rc != VWRN_TRAILING_CHARS
3897 && rc != VWRN_NUMBER_TOO_BIG
3898 && rc != VWRN_NEGATIVE_UNSIGNED)
3899 {
3900 if (uPid != 0)
3901 {
3902 try
3903 {
3904 vecPID.push_back(uPid);
3905 }
3906 catch (std::bad_alloc &)
3907 {
3908 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Out of memory");
3909 }
3910 }
3911 else
3912 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "Invalid PID value: 0");
3913 }
3914 else
3915 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
3916 "Error parsing PID value: %Rrc", rc);
3917 break;
3918 }
3919
3920 default:
3921 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, ch, &ValueUnion);
3922 }
3923 }
3924
3925 if (vecPID.empty())
3926 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
3927 "At least one PID must be specified to kill!");
3928
3929 if ( strSessionName.isEmpty()
3930 && ulSessionID == UINT32_MAX)
3931 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS, "No session ID specified!");
3932
3933 if ( strSessionName.isNotEmpty()
3934 && ulSessionID != UINT32_MAX)
3935 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSEPROCESS,
3936 "Either session ID or name (pattern) must be specified");
3937
3938 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
3939 if (rcExit != RTEXITCODE_SUCCESS)
3940 return rcExit;
3941
3942 HRESULT rc = S_OK;
3943
3944 ComPtr<IGuestSession> pSession;
3945 ComPtr<IGuestProcess> pProcess;
3946 do
3947 {
3948 uint32_t uProcsTerminated = 0;
3949 bool fSessionFound = false;
3950
3951 SafeIfaceArray <IGuestSession> collSessions;
3952 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
3953 size_t cSessions = collSessions.size();
3954
3955 uint32_t uSessionsHandled = 0;
3956 for (size_t i = 0; i < cSessions; i++)
3957 {
3958 pSession = collSessions[i];
3959 Assert(!pSession.isNull());
3960
3961 ULONG uID; /* Session ID */
3962 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
3963 Bstr strName;
3964 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
3965 Utf8Str strNameUtf8(strName); /* Session name */
3966 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
3967 {
3968 fSessionFound = uID == ulSessionID;
3969 }
3970 else /* ... or by naming pattern. */
3971 {
3972 if (RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str()))
3973 fSessionFound = true;
3974 }
3975
3976 if (fSessionFound)
3977 {
3978 AssertStmt(!pSession.isNull(), break);
3979 uSessionsHandled++;
3980
3981 SafeIfaceArray <IGuestProcess> collProcs;
3982 CHECK_ERROR_BREAK(pSession, COMGETTER(Processes)(ComSafeArrayAsOutParam(collProcs)));
3983
3984 size_t cProcs = collProcs.size();
3985 for (size_t p = 0; p < cProcs; p++)
3986 {
3987 pProcess = collProcs[p];
3988 Assert(!pProcess.isNull());
3989
3990 ULONG uPID; /* Process ID */
3991 CHECK_ERROR_BREAK(pProcess, COMGETTER(PID)(&uPID));
3992
3993 bool fProcFound = false;
3994 for (size_t a = 0; a < vecPID.size(); a++) /* Slow, but works. */
3995 {
3996 fProcFound = vecPID[a] == uPID;
3997 if (fProcFound)
3998 break;
3999 }
4000
4001 if (fProcFound)
4002 {
4003 if (pCtx->cVerbose)
4004 RTPrintf("Terminating process (PID %RU32) (session ID %RU32) ...\n",
4005 uPID, uID);
4006 CHECK_ERROR_BREAK(pProcess, Terminate());
4007 uProcsTerminated++;
4008 }
4009 else
4010 {
4011 if (ulSessionID != UINT32_MAX)
4012 RTPrintf("No matching process(es) for session ID %RU32 found\n",
4013 ulSessionID);
4014 }
4015
4016 pProcess.setNull();
4017 }
4018
4019 pSession.setNull();
4020 }
4021 }
4022
4023 if (!uSessionsHandled)
4024 RTPrintf("No matching session(s) found\n");
4025
4026 if (uProcsTerminated)
4027 RTPrintf("%RU32 %s terminated\n",
4028 uProcsTerminated, uProcsTerminated == 1 ? "process" : "processes");
4029
4030 } while (0);
4031
4032 pProcess.setNull();
4033 pSession.setNull();
4034
4035 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
4036}
4037
4038
4039static DECLCALLBACK(RTEXITCODE) gctlHandleCloseSession(PGCTLCMDCTX pCtx, int argc, char **argv)
4040{
4041 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
4042
4043 enum GETOPTDEF_SESSIONCLOSE
4044 {
4045 GETOPTDEF_SESSIONCLOSE_ALL = 2000
4046 };
4047 static const RTGETOPTDEF s_aOptions[] =
4048 {
4049 GCTLCMD_COMMON_OPTION_DEFS()
4050 { "--all", GETOPTDEF_SESSIONCLOSE_ALL, RTGETOPT_REQ_NOTHING },
4051 { "--session-id", 'i', RTGETOPT_REQ_UINT32 },
4052 { "--session-name", 'n', RTGETOPT_REQ_STRING }
4053 };
4054
4055 int ch;
4056 RTGETOPTUNION ValueUnion;
4057 RTGETOPTSTATE GetState;
4058 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4059
4060 ULONG ulSessionID = UINT32_MAX;
4061 Utf8Str strSessionName;
4062
4063 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
4064 {
4065 /* For options that require an argument, ValueUnion has received the value. */
4066 switch (ch)
4067 {
4068 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
4069
4070 case 'n': /* Session name pattern */
4071 strSessionName = ValueUnion.psz;
4072 break;
4073
4074 case 'i': /* Session ID */
4075 ulSessionID = ValueUnion.u32;
4076 break;
4077
4078 case GETOPTDEF_SESSIONCLOSE_ALL:
4079 strSessionName = "*";
4080 break;
4081
4082 case VINF_GETOPT_NOT_OPTION:
4083 /** @todo Supply a CSV list of IDs or patterns to close?
4084 * break; */
4085 default:
4086 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION, ch, &ValueUnion);
4087 }
4088 }
4089
4090 if ( strSessionName.isEmpty()
4091 && ulSessionID == UINT32_MAX)
4092 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION,
4093 "No session ID specified!");
4094
4095 if ( !strSessionName.isEmpty()
4096 && ulSessionID != UINT32_MAX)
4097 return errorSyntaxEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_CLOSESESSION,
4098 "Either session ID or name (pattern) must be specified");
4099
4100 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
4101 if (rcExit != RTEXITCODE_SUCCESS)
4102 return rcExit;
4103
4104 HRESULT rc = S_OK;
4105
4106 do
4107 {
4108 bool fSessionFound = false;
4109 size_t cSessionsHandled = 0;
4110
4111 SafeIfaceArray <IGuestSession> collSessions;
4112 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(Sessions)(ComSafeArrayAsOutParam(collSessions)));
4113 size_t cSessions = collSessions.size();
4114
4115 for (size_t i = 0; i < cSessions; i++)
4116 {
4117 ComPtr<IGuestSession> pSession = collSessions[i];
4118 Assert(!pSession.isNull());
4119
4120 ULONG uID; /* Session ID */
4121 CHECK_ERROR_BREAK(pSession, COMGETTER(Id)(&uID));
4122 Bstr strName;
4123 CHECK_ERROR_BREAK(pSession, COMGETTER(Name)(strName.asOutParam()));
4124 Utf8Str strNameUtf8(strName); /* Session name */
4125
4126 if (strSessionName.isEmpty()) /* Search by ID. Slow lookup. */
4127 {
4128 fSessionFound = uID == ulSessionID;
4129 }
4130 else /* ... or by naming pattern. */
4131 {
4132 if (RTStrSimplePatternMatch(strSessionName.c_str(), strNameUtf8.c_str()))
4133 fSessionFound = true;
4134 }
4135
4136 if (fSessionFound)
4137 {
4138 cSessionsHandled++;
4139
4140 Assert(!pSession.isNull());
4141 if (pCtx->cVerbose)
4142 RTPrintf("Closing guest session ID=#%RU32 \"%s\" ...\n",
4143 uID, strNameUtf8.c_str());
4144 CHECK_ERROR_BREAK(pSession, Close());
4145 if (pCtx->cVerbose)
4146 RTPrintf("Guest session successfully closed\n");
4147
4148 pSession.setNull();
4149 }
4150 }
4151
4152 if (!cSessionsHandled)
4153 {
4154 RTPrintf("No guest session(s) found\n");
4155 rc = E_ABORT; /* To set exit code accordingly. */
4156 }
4157
4158 } while (0);
4159
4160 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
4161}
4162
4163
4164static DECLCALLBACK(RTEXITCODE) gctlHandleWatch(PGCTLCMDCTX pCtx, int argc, char **argv)
4165{
4166 AssertPtrReturn(pCtx, RTEXITCODE_FAILURE);
4167
4168 /*
4169 * Parse arguments.
4170 */
4171 static const RTGETOPTDEF s_aOptions[] =
4172 {
4173 GCTLCMD_COMMON_OPTION_DEFS()
4174 };
4175
4176 int ch;
4177 RTGETOPTUNION ValueUnion;
4178 RTGETOPTSTATE GetState;
4179 RTGetOptInit(&GetState, argc, argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, RTGETOPTINIT_FLAGS_OPTS_FIRST);
4180
4181 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
4182 {
4183 /* For options that require an argument, ValueUnion has received the value. */
4184 switch (ch)
4185 {
4186 GCTLCMD_COMMON_OPTION_CASES(pCtx, ch, &ValueUnion);
4187
4188 case VINF_GETOPT_NOT_OPTION:
4189 default:
4190 return errorGetOptEx(USAGE_GUESTCONTROL, USAGE_GSTCTRL_WATCH, ch, &ValueUnion);
4191 }
4192 }
4193
4194 /** @todo Specify categories to watch for. */
4195 /** @todo Specify a --timeout for waiting only for a certain amount of time? */
4196
4197 RTEXITCODE rcExit = gctlCtxPostOptionParsingInit(pCtx);
4198 if (rcExit != RTEXITCODE_SUCCESS)
4199 return rcExit;
4200
4201 HRESULT rc;
4202
4203 try
4204 {
4205 ComObjPtr<GuestEventListenerImpl> pGuestListener;
4206 do
4207 {
4208 /* Listener creation. */
4209 pGuestListener.createObject();
4210 pGuestListener->init(new GuestEventListener());
4211
4212 /* Register for IGuest events. */
4213 ComPtr<IEventSource> es;
4214 CHECK_ERROR_BREAK(pCtx->pGuest, COMGETTER(EventSource)(es.asOutParam()));
4215 com::SafeArray<VBoxEventType_T> eventTypes;
4216 eventTypes.push_back(VBoxEventType_OnGuestSessionRegistered);
4217 /** @todo Also register for VBoxEventType_OnGuestUserStateChanged on demand? */
4218 CHECK_ERROR_BREAK(es, RegisterListener(pGuestListener, ComSafeArrayAsInParam(eventTypes),
4219 true /* Active listener */));
4220 /* Note: All other guest control events have to be registered
4221 * as their corresponding objects appear. */
4222
4223 } while (0);
4224
4225 if (pCtx->cVerbose)
4226 RTPrintf("Waiting for events ...\n");
4227
4228 while (!g_fGuestCtrlCanceled)
4229 {
4230 /** @todo Timeout handling (see above)? */
4231 RTThreadSleep(10);
4232 }
4233
4234 if (pCtx->cVerbose)
4235 RTPrintf("Signal caught, exiting ...\n");
4236
4237 if (!pGuestListener.isNull())
4238 {
4239 /* Guest callback unregistration. */
4240 ComPtr<IEventSource> pES;
4241 CHECK_ERROR(pCtx->pGuest, COMGETTER(EventSource)(pES.asOutParam()));
4242 if (!pES.isNull())
4243 CHECK_ERROR(pES, UnregisterListener(pGuestListener));
4244 pGuestListener.setNull();
4245 }
4246 }
4247 catch (std::bad_alloc &)
4248 {
4249 rc = E_OUTOFMEMORY;
4250 }
4251
4252 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
4253}
4254
4255/**
4256 * Access the guest control store.
4257 *
4258 * @returns program exit code.
4259 * @note see the command line API description for parameters
4260 */
4261RTEXITCODE handleGuestControl(HandlerArg *pArg)
4262{
4263 AssertPtr(pArg);
4264
4265#ifdef DEBUG_andy_disabled
4266 if (RT_FAILURE(tstTranslatePath()))
4267 return RTEXITCODE_FAILURE;
4268#endif
4269
4270 /*
4271 * Command definitions.
4272 */
4273 static const GCTLCMDDEF s_aCmdDefs[] =
4274 {
4275 { "run", gctlHandleRun, USAGE_GSTCTRL_RUN, 0, },
4276 { "start", gctlHandleStart, USAGE_GSTCTRL_START, 0, },
4277 { "copyfrom", gctlHandleCopyFrom, USAGE_GSTCTRL_COPYFROM, 0, },
4278 { "copyto", gctlHandleCopyTo, USAGE_GSTCTRL_COPYTO, 0, },
4279
4280 { "mkdir", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4281 { "md", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4282 { "createdirectory", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4283 { "createdir", handleCtrtMkDir, USAGE_GSTCTRL_MKDIR, 0, },
4284
4285 { "rmdir", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
4286 { "removedir", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
4287 { "removedirectory", gctlHandleRmDir, USAGE_GSTCTRL_RMDIR, 0, },
4288
4289 { "rm", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4290 { "removefile", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4291 { "erase", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4292 { "del", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4293 { "delete", gctlHandleRm, USAGE_GSTCTRL_RM, 0, },
4294
4295 { "mv", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4296 { "move", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4297 { "ren", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4298 { "rename", gctlHandleMv, USAGE_GSTCTRL_MV, 0, },
4299
4300 { "mktemp", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
4301 { "createtemp", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
4302 { "createtemporary", gctlHandleMkTemp, USAGE_GSTCTRL_MKTEMP, 0, },
4303
4304 { "stat", gctlHandleStat, USAGE_GSTCTRL_STAT, 0, },
4305
4306 { "closeprocess", gctlHandleCloseProcess, USAGE_GSTCTRL_CLOSEPROCESS, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4307 { "closesession", gctlHandleCloseSession, USAGE_GSTCTRL_CLOSESESSION, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4308 { "list", gctlHandleList, USAGE_GSTCTRL_LIST, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4309 { "watch", gctlHandleWatch, USAGE_GSTCTRL_WATCH, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4310
4311 {"updateguestadditions",gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4312 { "updateadditions", gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4313 { "updatega", gctlHandleUpdateAdditions, USAGE_GSTCTRL_UPDATEGA, GCTLCMDCTX_F_SESSION_ANONYMOUS | GCTLCMDCTX_F_NO_SIGNAL_HANDLER, },
4314 };
4315
4316 /*
4317 * VBoxManage guestcontrol [common-options] <VM> [common-options] <sub-command> ...
4318 *
4319 * Parse common options and VM name until we find a sub-command. Allowing
4320 * the user to put the user and password related options before the
4321 * sub-command makes it easier to edit the command line when doing several
4322 * operations with the same guest user account. (Accidentally, it also
4323 * makes the syntax diagram shorter and easier to read.)
4324 */
4325 GCTLCMDCTX CmdCtx;
4326 RTEXITCODE rcExit = gctrCmdCtxInit(&CmdCtx, pArg);
4327 if (rcExit == RTEXITCODE_SUCCESS)
4328 {
4329 static const RTGETOPTDEF s_CommonOptions[] = { GCTLCMD_COMMON_OPTION_DEFS() };
4330
4331 int ch;
4332 RTGETOPTUNION ValueUnion;
4333 RTGETOPTSTATE GetState;
4334 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_CommonOptions, RT_ELEMENTS(s_CommonOptions), 0, 0 /* No sorting! */);
4335
4336 while ((ch = RTGetOpt(&GetState, &ValueUnion)) != 0)
4337 {
4338 switch (ch)
4339 {
4340 GCTLCMD_COMMON_OPTION_CASES(&CmdCtx, ch, &ValueUnion);
4341
4342 case VINF_GETOPT_NOT_OPTION:
4343 /* First comes the VM name or UUID. */
4344 if (!CmdCtx.pszVmNameOrUuid)
4345 CmdCtx.pszVmNameOrUuid = ValueUnion.psz;
4346 /*
4347 * The sub-command is next. Look it up and invoke it.
4348 * Note! Currently no warnings about user/password options (like we'll do later on)
4349 * for GCTLCMDCTX_F_SESSION_ANONYMOUS commands. No reason to be too pedantic.
4350 */
4351 else
4352 {
4353 const char *pszCmd = ValueUnion.psz;
4354 uint32_t iCmd;
4355 for (iCmd = 0; iCmd < RT_ELEMENTS(s_aCmdDefs); iCmd++)
4356 if (strcmp(s_aCmdDefs[iCmd].pszName, pszCmd) == 0)
4357 {
4358 CmdCtx.pCmdDef = &s_aCmdDefs[iCmd];
4359
4360 rcExit = s_aCmdDefs[iCmd].pfnHandler(&CmdCtx, pArg->argc - GetState.iNext + 1,
4361 &pArg->argv[GetState.iNext - 1]);
4362
4363 gctlCtxTerm(&CmdCtx);
4364 return rcExit;
4365 }
4366 return errorSyntax(USAGE_GUESTCONTROL, "Unknown sub-command: '%s'", pszCmd);
4367 }
4368 break;
4369
4370 default:
4371 return errorGetOpt(USAGE_GUESTCONTROL, ch, &ValueUnion);
4372 }
4373 }
4374 if (CmdCtx.pszVmNameOrUuid)
4375 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Missing sub-command");
4376 else
4377 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Missing VM name and sub-command");
4378 }
4379 return rcExit;
4380}
4381#endif /* !VBOX_ONLY_DOCS */
4382
Note: See TracBrowser for help on using the repository browser.

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