VirtualBox

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

Last change on this file since 42976 was 42969, checked in by vboxsync, 12 years ago

VBoxManage/GuestCtrl: Further checks not needed anymore.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 92.5 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 42969 2012-08-24 08:35:47Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010-2012 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
24#ifndef VBOX_ONLY_DOCS
25
26#include <VBox/com/com.h>
27#include <VBox/com/string.h>
28#include <VBox/com/array.h>
29#include <VBox/com/ErrorInfo.h>
30#include <VBox/com/errorprint.h>
31#include <VBox/com/VirtualBox.h>
32#include <VBox/com/EventQueue.h>
33
34#include <VBox/err.h>
35#include <VBox/log.h>
36
37#include <iprt/asm.h>
38#include <iprt/dir.h>
39#include <iprt/file.h>
40#include <iprt/isofs.h>
41#include <iprt/getopt.h>
42#include <iprt/list.h>
43#include <iprt/path.h>
44#include <iprt/thread.h>
45
46#include <map>
47#include <vector>
48
49#ifdef USE_XPCOM_QUEUE
50# include <sys/select.h>
51# include <errno.h>
52#endif
53
54#include <signal.h>
55
56#ifdef RT_OS_DARWIN
57# include <CoreFoundation/CFRunLoop.h>
58#endif
59
60using namespace com;
61
62/**
63 * IVirtualBoxCallback implementation for handling the GuestControlCallback in
64 * relation to the "guestcontrol * wait" command.
65 */
66/** @todo */
67
68/** Set by the signal handler. */
69static volatile bool g_fGuestCtrlCanceled = false;
70
71typedef struct COPYCONTEXT
72{
73 COPYCONTEXT() : fVerbose(false), fDryRun(false), fHostToGuest(false)
74 {
75 }
76
77 ComPtr<IGuestSession> pGuestSession;
78 bool fVerbose;
79 bool fDryRun;
80 bool fHostToGuest;
81} COPYCONTEXT, *PCOPYCONTEXT;
82
83/**
84 * An entry for a source element, including an optional DOS-like wildcard (*,?).
85 */
86class SOURCEFILEENTRY
87{
88 public:
89
90 SOURCEFILEENTRY(const char *pszSource, const char *pszFilter)
91 : mSource(pszSource),
92 mFilter(pszFilter) {}
93
94 SOURCEFILEENTRY(const char *pszSource)
95 : mSource(pszSource)
96 {
97 Parse(pszSource);
98 }
99
100 const char* GetSource() const
101 {
102 return mSource.c_str();
103 }
104
105 const char* GetFilter() const
106 {
107 return mFilter.c_str();
108 }
109
110 private:
111
112 int Parse(const char *pszPath)
113 {
114 AssertPtrReturn(pszPath, VERR_INVALID_POINTER);
115
116 if ( !RTFileExists(pszPath)
117 && !RTDirExists(pszPath))
118 {
119 /* No file and no directory -- maybe a filter? */
120 char *pszFilename = RTPathFilename(pszPath);
121 if ( pszFilename
122 && strpbrk(pszFilename, "*?"))
123 {
124 /* Yep, get the actual filter part. */
125 mFilter = RTPathFilename(pszPath);
126 /* Remove the filter from actual sourcec directory name. */
127 RTPathStripFilename(mSource.mutableRaw());
128 mSource.jolt();
129 }
130 }
131
132 return VINF_SUCCESS; /* @todo */
133 }
134
135 private:
136
137 Utf8Str mSource;
138 Utf8Str mFilter;
139};
140typedef std::vector<SOURCEFILEENTRY> SOURCEVEC, *PSOURCEVEC;
141
142/**
143 * An entry for an element which needs to be copied/created to/on the guest.
144 */
145typedef struct DESTFILEENTRY
146{
147 DESTFILEENTRY(Utf8Str strFileName) : mFileName(strFileName) {}
148 Utf8Str mFileName;
149} DESTFILEENTRY, *PDESTFILEENTRY;
150/*
151 * Map for holding destination entires, whereas the key is the destination
152 * directory and the mapped value is a vector holding all elements for this directoy.
153 */
154typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> > DESTDIRMAP, *PDESTDIRMAP;
155typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> >::iterator DESTDIRMAPITER, *PDESTDIRMAPITER;
156
157/**
158 * Special exit codes for returning errors/information of a
159 * started guest process to the command line VBoxManage was started from.
160 * Useful for e.g. scripting.
161 *
162 * @note These are frozen as of 4.1.0.
163 */
164enum EXITCODEEXEC
165{
166 EXITCODEEXEC_SUCCESS = RTEXITCODE_SUCCESS,
167 /* Process exited normally but with an exit code <> 0. */
168 EXITCODEEXEC_CODE = 16,
169 EXITCODEEXEC_FAILED = 17,
170 EXITCODEEXEC_TERM_SIGNAL = 18,
171 EXITCODEEXEC_TERM_ABEND = 19,
172 EXITCODEEXEC_TIMEOUT = 20,
173 EXITCODEEXEC_DOWN = 21,
174 EXITCODEEXEC_CANCELED = 22
175};
176
177/**
178 * RTGetOpt-IDs for the guest execution control command line.
179 */
180enum GETOPTDEF_EXEC
181{
182 GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES = 1000,
183 GETOPTDEF_EXEC_NO_PROFILE,
184 GETOPTDEF_EXEC_OUTPUTFORMAT,
185 GETOPTDEF_EXEC_DOS2UNIX,
186 GETOPTDEF_EXEC_UNIX2DOS,
187 GETOPTDEF_EXEC_PASSWORD,
188 GETOPTDEF_EXEC_WAITFOREXIT,
189 GETOPTDEF_EXEC_WAITFORSTDOUT,
190 GETOPTDEF_EXEC_WAITFORSTDERR
191};
192
193enum GETOPTDEF_COPY
194{
195 GETOPTDEF_COPY_DRYRUN = 1000,
196 GETOPTDEF_COPY_FOLLOW,
197 GETOPTDEF_COPY_PASSWORD,
198 GETOPTDEF_COPY_TARGETDIR
199};
200
201enum GETOPTDEF_MKDIR
202{
203 GETOPTDEF_MKDIR_PASSWORD = 1000
204};
205
206enum GETOPTDEF_STAT
207{
208 GETOPTDEF_STAT_PASSWORD = 1000
209};
210
211enum OUTPUTTYPE
212{
213 OUTPUTTYPE_UNDEFINED = 0,
214 OUTPUTTYPE_DOS2UNIX = 10,
215 OUTPUTTYPE_UNIX2DOS = 20
216};
217
218static int ctrlCopyDirExists(PCOPYCONTEXT pContext, bool bGuest, const char *pszDir, bool *fExists);
219
220#endif /* VBOX_ONLY_DOCS */
221
222void usageGuestControl(PRTSTREAM pStrm, const char *pcszSep1, const char *pcszSep2)
223{
224 RTStrmPrintf(pStrm,
225 "%s guestcontrol %s <vmname>|<uuid>\n"
226 " exec[ute]\n"
227 " --image <path to program> --username <name>\n"
228 " [--passwordfile <file> | --password <password>]\n"
229 " [--domain <domain>] [--verbose] [--timeout <msec>]\n"
230 " [--environment \"<NAME>=<VALUE> [<NAME>=<VALUE>]\"]\n"
231 " [--wait-exit] [--wait-stdout] [--wait-stderr]\n"
232 " [--dos2unix] [--unix2dos]\n"
233 " [-- [<argument1>] ... [<argumentN>]]\n"
234 /** @todo Add a "--" parameter (has to be last parameter) to directly execute
235 * stuff, e.g. "VBoxManage guestcontrol execute <VMName> --username <> ... -- /bin/rm -Rf /foo". */
236 "\n"
237 " copyfrom\n"
238 " <guest source> <host dest> --username <name>\n"
239 " [--passwordfile <file> | --password <password>]\n"
240 " [--domain <domain>] [--verbose]\n"
241 " [--dryrun] [--follow] [--recursive]\n"
242 "\n"
243 " copyto|cp\n"
244 " <host source> <guest dest> --username <name>\n"
245 " [--passwordfile <file> | --password <password>]\n"
246 " [--domain <domain>] [--verbose]\n"
247 " [--dryrun] [--follow] [--recursive]\n"
248 "\n"
249 " createdir[ectory]|mkdir|md\n"
250 " <guest directory>... --username <name>\n"
251 " [--passwordfile <file> | --password <password>]\n"
252 " [--domain <domain>] [--verbose]\n"
253 " [--parents] [--mode <mode>]\n"
254 "\n"
255 " stat\n"
256 " <file>... --username <name>\n"
257 " [--passwordfile <file> | --password <password>]\n"
258 " [--domain <domain>] [--verbose]\n"
259 "\n"
260 " updateadditions\n"
261 " [--source <guest additions .ISO>] [--verbose]\n"
262 "\n", pcszSep1, pcszSep2);
263}
264
265#ifndef VBOX_ONLY_DOCS
266
267/**
268 * Signal handler that sets g_fGuestCtrlCanceled.
269 *
270 * This can be executed on any thread in the process, on Windows it may even be
271 * a thread dedicated to delivering this signal. Do not doing anything
272 * unnecessary here.
273 */
274static void guestCtrlSignalHandler(int iSignal)
275{
276 NOREF(iSignal);
277 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
278}
279
280/**
281 * Installs a custom signal handler to get notified
282 * whenever the user wants to intercept the program.
283 */
284static void ctrlSignalHandlerInstall()
285{
286 signal(SIGINT, guestCtrlSignalHandler);
287#ifdef SIGBREAK
288 signal(SIGBREAK, guestCtrlSignalHandler);
289#endif
290}
291
292/**
293 * Uninstalls a previously installed signal handler.
294 */
295static void ctrlSignalHandlerUninstall()
296{
297 signal(SIGINT, SIG_DFL);
298#ifdef SIGBREAK
299 signal(SIGBREAK, SIG_DFL);
300#endif
301}
302
303/**
304 * Translates a process status to a human readable
305 * string.
306 */
307static const char *ctrlExecProcessStatusToText(ProcessStatus_T enmStatus)
308{
309 switch (enmStatus)
310 {
311 case ProcessStatus_Starting:
312 return "starting";
313 case ProcessStatus_Started:
314 return "started";
315 case ProcessStatus_Paused:
316 return "paused";
317 case ProcessStatus_Terminating:
318 return "terminating";
319 case ProcessStatus_TerminatedNormally:
320 return "successfully terminated";
321 case ProcessStatus_TerminatedSignal:
322 return "terminated by signal";
323 case ProcessStatus_TerminatedAbnormally:
324 return "abnormally aborted";
325 case ProcessStatus_TimedOutKilled:
326 return "timed out";
327 case ProcessStatus_TimedOutAbnormally:
328 return "timed out, hanging";
329 case ProcessStatus_Down:
330 return "killed";
331 case ProcessStatus_Error:
332 return "error";
333 default:
334 break;
335 }
336 return "unknown";
337}
338
339static int ctrlExecProcessStatusToExitCode(ProcessStatus_T enmStatus, ULONG uExitCode)
340{
341 int vrc = EXITCODEEXEC_SUCCESS;
342 switch (enmStatus)
343 {
344 case ProcessStatus_Starting:
345 vrc = EXITCODEEXEC_SUCCESS;
346 break;
347 case ProcessStatus_Started:
348 vrc = EXITCODEEXEC_SUCCESS;
349 break;
350 case ProcessStatus_Paused:
351 vrc = EXITCODEEXEC_SUCCESS;
352 break;
353 case ProcessStatus_Terminating:
354 vrc = EXITCODEEXEC_SUCCESS;
355 break;
356 case ProcessStatus_TerminatedNormally:
357 vrc = !uExitCode ? EXITCODEEXEC_SUCCESS : EXITCODEEXEC_CODE;
358 break;
359 case ProcessStatus_TerminatedSignal:
360 vrc = EXITCODEEXEC_TERM_SIGNAL;
361 break;
362 case ProcessStatus_TerminatedAbnormally:
363 vrc = EXITCODEEXEC_TERM_ABEND;
364 break;
365 case ProcessStatus_TimedOutKilled:
366 vrc = EXITCODEEXEC_TIMEOUT;
367 break;
368 case ProcessStatus_TimedOutAbnormally:
369 vrc = EXITCODEEXEC_TIMEOUT;
370 break;
371 case ProcessStatus_Down:
372 /* Service/OS is stopping, process was killed, so
373 * not exactly an error of the started process ... */
374 vrc = EXITCODEEXEC_DOWN;
375 break;
376 case ProcessStatus_Error:
377 vrc = EXITCODEEXEC_FAILED;
378 break;
379 default:
380 AssertMsgFailed(("Unknown exit code (%u) from guest process returned!\n", enmStatus));
381 break;
382 }
383 return vrc;
384}
385
386static int ctrlPrintError(com::ErrorInfo &errorInfo)
387{
388 if ( errorInfo.isFullAvailable()
389 || errorInfo.isBasicAvailable())
390 {
391 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
392 * because it contains more accurate info about what went wrong. */
393 if (errorInfo.getResultCode() == VBOX_E_IPRT_ERROR)
394 RTMsgError("%ls.", errorInfo.getText().raw());
395 else
396 {
397 RTMsgError("Error details:");
398 GluePrintErrorInfo(errorInfo);
399 }
400 return VERR_GENERAL_FAILURE; /** @todo */
401 }
402 AssertMsgFailedReturn(("Object has indicated no error (%Rhrc)!?\n", errorInfo.getResultCode()),
403 VERR_INVALID_PARAMETER);
404}
405
406static int ctrlPrintError(IUnknown *pObj, const GUID &aIID)
407{
408 com::ErrorInfo ErrInfo(pObj, aIID);
409 return ctrlPrintError(ErrInfo);
410}
411
412static int ctrlPrintProgressError(ComPtr<IProgress> pProgress)
413{
414 int vrc = VINF_SUCCESS;
415 HRESULT rc;
416
417 do
418 {
419 BOOL fCanceled;
420 CHECK_ERROR_BREAK(pProgress, COMGETTER(Canceled)(&fCanceled));
421 if (!fCanceled)
422 {
423 LONG rcProc;
424 CHECK_ERROR_BREAK(pProgress, COMGETTER(ResultCode)(&rcProc));
425 if (FAILED(rcProc))
426 {
427 com::ProgressErrorInfo ErrInfo(pProgress);
428 vrc = ctrlPrintError(ErrInfo);
429 }
430 }
431
432 } while(0);
433
434 if (FAILED(rc))
435 AssertMsgStmt(NULL, ("Could not lookup progress information\n"), vrc = VERR_COM_UNEXPECTED);
436
437 return vrc;
438}
439
440/**
441 * Un-initializes the VM after guest control usage.
442 */
443static void ctrlUninitVM(HandlerArg *pArg)
444{
445 AssertPtrReturnVoid(pArg);
446 if (pArg->session)
447 pArg->session->UnlockMachine();
448}
449
450/**
451 * Initializes the VM for IGuest operations.
452 *
453 * That is, checks whether it's up and running, if it can be locked (shared
454 * only) and returns a valid IGuest pointer on success.
455 *
456 * @return IPRT status code.
457 * @param pArg Our command line argument structure.
458 * @param pszNameOrId The VM's name or UUID.
459 * @param pGuest Where to return the IGuest interface pointer.
460 */
461static int ctrlInitVM(HandlerArg *pArg, const char *pszNameOrId, ComPtr<IGuest> *pGuest)
462{
463 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
464 AssertPtrReturn(pszNameOrId, VERR_INVALID_PARAMETER);
465
466 /* Lookup VM. */
467 ComPtr<IMachine> machine;
468 /* Assume it's an UUID. */
469 HRESULT rc;
470 CHECK_ERROR(pArg->virtualBox, FindMachine(Bstr(pszNameOrId).raw(),
471 machine.asOutParam()));
472 if (FAILED(rc))
473 return VERR_NOT_FOUND;
474
475 /* Machine is running? */
476 MachineState_T machineState;
477 CHECK_ERROR_RET(machine, COMGETTER(State)(&machineState), 1);
478 if (machineState != MachineState_Running)
479 {
480 RTMsgError("Machine \"%s\" is not running (currently %s)!\n",
481 pszNameOrId, machineStateToName(machineState, false));
482 return VERR_VM_INVALID_VM_STATE;
483 }
484
485 do
486 {
487 /* Open a session for the VM. */
488 CHECK_ERROR_BREAK(machine, LockMachine(pArg->session, LockType_Shared));
489 /* Get the associated console. */
490 ComPtr<IConsole> console;
491 CHECK_ERROR_BREAK(pArg->session, COMGETTER(Console)(console.asOutParam()));
492 /* ... and session machine. */
493 ComPtr<IMachine> sessionMachine;
494 CHECK_ERROR_BREAK(pArg->session, COMGETTER(Machine)(sessionMachine.asOutParam()));
495 /* Get IGuest interface. */
496 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(pGuest->asOutParam()));
497 } while (0);
498
499 if (FAILED(rc))
500 ctrlUninitVM(pArg);
501 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
502}
503
504/**
505 * Prints the desired guest output to a stream.
506 *
507 * @return IPRT status code.
508 * @param pProcess Pointer to appropriate process object.
509 * @param pStrmOutput Where to write the data.
510 * @param hStream Where to read the data from.
511 */
512static int ctrlExecPrintOutput(IProcess *pProcess, PRTSTREAM pStrmOutput,
513 ULONG uHandle)
514{
515 AssertPtrReturn(pProcess, VERR_INVALID_POINTER);
516 AssertPtrReturn(pStrmOutput, VERR_INVALID_POINTER);
517
518 int vrc = VINF_SUCCESS;
519
520 SafeArray<BYTE> aOutputData;
521 HRESULT rc = pProcess->Read(uHandle, _64K, 30 * 1000 /* 30s timeout. */,
522 ComSafeArrayAsOutParam(aOutputData));
523 if (FAILED(rc))
524 vrc = ctrlPrintError(pProcess, COM_IIDOF(IProcess));
525 else
526 {
527 /** @todo implement the dos2unix/unix2dos conversions */
528 vrc = RTStrmWrite(pStrmOutput, aOutputData.raw(), aOutputData.size());
529 if (RT_FAILURE(vrc))
530 RTMsgError("Unable to write output, rc=%Rrc\n", vrc);
531 }
532
533 return vrc;
534}
535
536/**
537 * Returns the remaining time (in ms) based on the start time and a set
538 * timeout value. Returns RT_INDEFINITE_WAIT if no timeout was specified.
539 *
540 * @return RTMSINTERVAL Time left (in ms).
541 * @param u64StartMs Start time (in ms).
542 * @param cMsTimeout Timeout value (in ms).
543 */
544inline RTMSINTERVAL ctrlExecGetRemainingTime(uint64_t u64StartMs, RTMSINTERVAL cMsTimeout)
545{
546 if (!cMsTimeout || cMsTimeout == RT_INDEFINITE_WAIT) /* If no timeout specified, wait forever. */
547 return RT_INDEFINITE_WAIT;
548
549 uint32_t u64ElapsedMs = RTTimeMilliTS() - u64StartMs;
550 if (u64ElapsedMs >= cMsTimeout)
551 return 0;
552
553 return cMsTimeout - u64ElapsedMs;
554}
555
556/* <Missing documentation> */
557static int handleCtrlExecProgram(ComPtr<IGuest> pGuest, HandlerArg *pArg)
558{
559 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
560
561 /*
562 * Parse arguments.
563 */
564 static const RTGETOPTDEF s_aOptions[] =
565 {
566 { "--dos2unix", GETOPTDEF_EXEC_DOS2UNIX, RTGETOPT_REQ_NOTHING },
567 { "--environment", 'e', RTGETOPT_REQ_STRING },
568 { "--flags", 'f', RTGETOPT_REQ_STRING },
569 { "--ignore-operhaned-processes", GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES, RTGETOPT_REQ_NOTHING },
570 { "--image", 'i', RTGETOPT_REQ_STRING },
571 { "--no-profile", GETOPTDEF_EXEC_NO_PROFILE, RTGETOPT_REQ_NOTHING },
572 { "--username", 'u', RTGETOPT_REQ_STRING },
573 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
574 { "--password", GETOPTDEF_EXEC_PASSWORD, RTGETOPT_REQ_STRING },
575 { "--domain", 'd', RTGETOPT_REQ_STRING },
576 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
577 { "--unix2dos", GETOPTDEF_EXEC_UNIX2DOS, RTGETOPT_REQ_NOTHING },
578 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
579 { "--wait-exit", GETOPTDEF_EXEC_WAITFOREXIT, RTGETOPT_REQ_NOTHING },
580 { "--wait-stdout", GETOPTDEF_EXEC_WAITFORSTDOUT, RTGETOPT_REQ_NOTHING },
581 { "--wait-stderr", GETOPTDEF_EXEC_WAITFORSTDERR, RTGETOPT_REQ_NOTHING }
582 };
583
584 int ch;
585 RTGETOPTUNION ValueUnion;
586 RTGETOPTSTATE GetState;
587 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, 0);
588
589 Utf8Str strCmd;
590 com::SafeArray<ProcessCreateFlag_T> aCreateFlags;
591 com::SafeArray<ProcessWaitForFlag_T> aWaitFlags;
592 com::SafeArray<IN_BSTR> args;
593 com::SafeArray<IN_BSTR> env;
594 Utf8Str strUsername;
595 Utf8Str strPassword;
596 Utf8Str strDomain;
597 RTMSINTERVAL cMsTimeout = 0;
598 OUTPUTTYPE eOutputType = OUTPUTTYPE_UNDEFINED;
599 bool fWaitForExit = false;
600 bool fVerbose = false;
601 int vrc = VINF_SUCCESS;
602
603 /* Wait for process start in any case. This is useful for scripting VBoxManage
604 * when relying on its overall exit code. */
605 aWaitFlags.push_back(ProcessWaitForFlag_Start);
606
607 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
608 && RT_SUCCESS(vrc))
609 {
610 /* For options that require an argument, ValueUnion has received the value. */
611 switch (ch)
612 {
613 case GETOPTDEF_EXEC_DOS2UNIX:
614 if (eOutputType != OUTPUTTYPE_UNDEFINED)
615 return errorSyntax(USAGE_GUESTCONTROL, "More than one output type (dos2unix/unix2dos) specified!");
616 eOutputType = OUTPUTTYPE_DOS2UNIX;
617 break;
618
619 case 'e': /* Environment */
620 {
621 char **papszArg;
622 int cArgs;
623
624 vrc = RTGetOptArgvFromString(&papszArg, &cArgs, ValueUnion.psz, NULL);
625 if (RT_FAILURE(vrc))
626 return errorSyntax(USAGE_GUESTCONTROL, "Failed to parse environment value, rc=%Rrc", vrc);
627 for (int j = 0; j < cArgs; j++)
628 env.push_back(Bstr(papszArg[j]).raw());
629
630 RTGetOptArgvFree(papszArg);
631 break;
632 }
633
634 case GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES:
635 aCreateFlags.push_back(ProcessCreateFlag_IgnoreOrphanedProcesses);
636 break;
637
638 case GETOPTDEF_EXEC_NO_PROFILE:
639 aCreateFlags.push_back(ProcessCreateFlag_NoProfile);
640 break;
641
642 case 'i':
643 strCmd = ValueUnion.psz;
644 break;
645
646 /** @todo Add a hidden flag. */
647
648 case 'u': /* User name */
649 strUsername = ValueUnion.psz;
650 break;
651
652 case GETOPTDEF_EXEC_PASSWORD: /* Password */
653 strPassword = ValueUnion.psz;
654 break;
655
656 case 'p': /* Password file */
657 {
658 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
659 if (rcExit != RTEXITCODE_SUCCESS)
660 return rcExit;
661 break;
662 }
663
664 case 'd': /* domain */
665 strDomain = ValueUnion.psz;
666 break;
667
668 case 't': /* Timeout */
669 cMsTimeout = ValueUnion.u32;
670 break;
671
672 case GETOPTDEF_EXEC_UNIX2DOS:
673 if (eOutputType != OUTPUTTYPE_UNDEFINED)
674 return errorSyntax(USAGE_GUESTCONTROL, "More than one output type (dos2unix/unix2dos) specified!");
675 eOutputType = OUTPUTTYPE_UNIX2DOS;
676 break;
677
678 case 'v': /* Verbose */
679 fVerbose = true;
680 break;
681
682 case GETOPTDEF_EXEC_WAITFOREXIT:
683 aWaitFlags.push_back(ProcessWaitForFlag_Terminate);
684 fWaitForExit = true;
685 break;
686
687 case GETOPTDEF_EXEC_WAITFORSTDOUT:
688 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdOut);
689 aWaitFlags.push_back(ProcessWaitForFlag_StdOut);
690 fWaitForExit = true;
691 break;
692
693 case GETOPTDEF_EXEC_WAITFORSTDERR:
694 aCreateFlags.push_back(ProcessCreateFlag_WaitForStdErr);
695 aWaitFlags.push_back(ProcessWaitForFlag_StdErr);
696 fWaitForExit = true;
697 break;
698
699 case VINF_GETOPT_NOT_OPTION:
700 {
701 if (args.size() == 0 && strCmd.isEmpty())
702 strCmd = ValueUnion.psz;
703 else
704 args.push_back(Bstr(ValueUnion.psz).raw());
705 break;
706 }
707
708 default:
709 return RTGetOptPrintError(ch, &ValueUnion);
710 }
711 }
712
713 if (strCmd.isEmpty())
714 return errorSyntax(USAGE_GUESTCONTROL, "No command to execute specified!");
715
716 if (strUsername.isEmpty())
717 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
718
719 /* Any output conversion not supported yet! */
720 if (eOutputType != OUTPUTTYPE_UNDEFINED)
721 return errorSyntax(USAGE_GUESTCONTROL, "Output conversion not implemented yet!");
722
723 /*
724 * Start with the real work.
725 */
726 HRESULT rc = S_OK;
727 if (fVerbose)
728 {
729 if (cMsTimeout == 0)
730 RTPrintf("Waiting for guest to start process ...\n");
731 else
732 RTPrintf("Waiting for guest to start process (within %ums)\n", cMsTimeout);
733 }
734
735 ComPtr<IGuestSession> pGuestSession;
736 rc = pGuest->CreateSession(Bstr(strUsername).raw(),
737 Bstr(strPassword).raw(),
738 Bstr(strDomain).raw(),
739 Bstr("VBoxManage Guest Control Exec").raw(),
740 pGuestSession.asOutParam());
741 if (FAILED(rc))
742 {
743 ctrlPrintError(pGuest, COM_IIDOF(IGuest));
744 return RTEXITCODE_FAILURE;
745 }
746
747 /* Get current time stamp to later calculate rest of timeout left. */
748 uint64_t u64StartMS = RTTimeMilliTS();
749
750 /*
751 * Execute the process.
752 */
753 ComPtr<IGuestProcess> pProcess;
754 rc = pGuestSession->ProcessCreate(Bstr(strCmd).raw(),
755 ComSafeArrayAsInParam(args),
756 ComSafeArrayAsInParam(env),
757 ComSafeArrayAsInParam(aCreateFlags),
758 cMsTimeout,
759 pProcess.asOutParam());
760 if (FAILED(rc))
761 {
762 ctrlPrintError(pGuestSession, COM_IIDOF(IGuestSession));
763 return RTEXITCODE_FAILURE;
764 }
765
766 if (fWaitForExit)
767 {
768 if (fVerbose)
769 {
770 if (cMsTimeout) /* Wait with a certain timeout. */
771 {
772 /* Calculate timeout value left after process has been started. */
773 uint64_t u64Elapsed = RTTimeMilliTS() - u64StartMS;
774 /* Is timeout still bigger than current difference? */
775 if (cMsTimeout > u64Elapsed)
776 RTPrintf("Waiting for process to exit (%ums left) ...\n", cMsTimeout - u64Elapsed);
777 else
778 RTPrintf("No time left to wait for process!\n"); /** @todo a bit misleading ... */
779 }
780 else /* Wait forever. */
781 RTPrintf("Waiting for process to exit ...\n");
782 }
783
784 /** @todo does this need signal handling? there's no progress object etc etc */
785
786 vrc = RTStrmSetMode(g_pStdOut, 1 /* Binary mode */, -1 /* Code set, unchanged */);
787 if (RT_FAILURE(vrc))
788 RTMsgError("Unable to set stdout's binary mode, rc=%Rrc\n", vrc);
789 vrc = RTStrmSetMode(g_pStdErr, 1 /* Binary mode */, -1 /* Code set, unchanged */);
790 if (RT_FAILURE(vrc))
791 RTMsgError("Unable to set stderr's binary mode, rc=%Rrc\n", vrc);
792
793 /* Wait for process to exit ... */
794 RTMSINTERVAL cMsTimeLeft = 1;
795 bool fReadStdOut, fReadStdErr;
796 fReadStdOut = fReadStdErr = false;
797 bool fCompleted = false;
798 while (!fCompleted && cMsTimeLeft != 0)
799 {
800 cMsTimeLeft = ctrlExecGetRemainingTime(u64StartMS, cMsTimeout);
801 ProcessWaitResult_T waitResult;
802 rc = pProcess->WaitForArray(ComSafeArrayAsInParam(aWaitFlags), cMsTimeLeft, &waitResult);
803 if (FAILED(rc))
804 {
805 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
806 return RTEXITCODE_FAILURE;
807 }
808
809 switch (waitResult)
810 {
811 case ProcessWaitResult_Start:
812 {
813 if (fVerbose)
814 {
815 ULONG uPID = 0;
816 rc = pProcess->COMGETTER(PID)(&uPID);
817 if (FAILED(rc))
818 {
819 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
820 return RTEXITCODE_FAILURE;
821 }
822 RTPrintf("Process '%s' (PID: %u) started\n", strCmd.c_str(), uPID);
823 }
824 break;
825 }
826 case ProcessWaitResult_StdOut:
827 fReadStdOut = true;
828 break;
829 case ProcessWaitResult_StdErr:
830 fReadStdErr = true;
831 break;
832 case ProcessWaitResult_Terminate:
833 /* Process terminated, we're done */
834 fCompleted = true;
835 break;
836 case ProcessWaitResult_WaitFlagNotSupported:
837 {
838 /* The guest does not support waiting for stdout/err, so
839 * yield to reduce the CPU load due to busy waiting. */
840 RTThreadYield(); /* Optional, don't check rc. */
841
842 /* Try both, stdout + stderr. */
843 fReadStdOut = fReadStdErr = true;
844 break;
845 }
846 default:
847 /* Ignore all other results, let the timeout expire */;
848 break;
849 }
850
851 if (fReadStdOut) /* Do we need to fetch stdout data? */
852 {
853 vrc = ctrlExecPrintOutput(pProcess, g_pStdOut, 1 /* StdOut */);
854 fReadStdOut = false;
855 }
856
857 if (fReadStdErr) /* Do we need to fetch stdout data? */
858 {
859 vrc = ctrlExecPrintOutput(pProcess, g_pStdErr, 2 /* StdErr */);
860 fReadStdErr = false;
861 }
862
863 if (RT_FAILURE(vrc))
864 break;
865
866 } /* while */
867
868 /* Report status back to the user. */
869 if (fCompleted)
870 {
871 ProcessStatus_T status;
872 rc = pProcess->COMGETTER(Status)(&status);
873 if (FAILED(rc))
874 {
875 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
876 return RTEXITCODE_FAILURE;
877 }
878 LONG exitCode;
879 rc = pProcess->COMGETTER(ExitCode)(&exitCode);
880 if (FAILED(rc))
881 {
882 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
883 return RTEXITCODE_FAILURE;
884 }
885 if (fVerbose)
886 RTPrintf("Exit code=%u (Status=%u [%s])\n", exitCode, status, ctrlExecProcessStatusToText(status));
887 return ctrlExecProcessStatusToExitCode(status, exitCode);
888 }
889 else
890 {
891 if (fVerbose)
892 RTPrintf("Process execution aborted!\n");
893 return EXITCODEEXEC_TERM_ABEND;
894 }
895 }
896
897 return RT_FAILURE(vrc) || FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
898}
899
900/**
901 * Creates a copy context structure which then can be used with various
902 * guest control copy functions. Needs to be free'd with ctrlCopyContextFree().
903 *
904 * @return IPRT status code.
905 * @param pGuest Pointer to IGuest interface to use.
906 * @param fVerbose Flag indicating if we want to run in verbose mode.
907 * @param fDryRun Flag indicating if we want to run a dry run only.
908 * @param fHostToGuest Flag indicating if we want to copy from host to guest
909 * or vice versa.
910 * @param strUsername Username of account to use on the guest side.
911 * @param strPassword Password of account to use.
912 * @param strDomain Domain of account to use.
913 * @param strSessionName Session name (only for identification purposes).
914 * @param ppContext Pointer which receives the allocated copy context.
915 */
916static int ctrlCopyContextCreate(IGuest *pGuest, bool fVerbose, bool fDryRun,
917 bool fHostToGuest, const Utf8Str &strUsername,
918 const Utf8Str &strPassword, const Utf8Str &strDomain,
919 const Utf8Str &strSessionName,
920 PCOPYCONTEXT *ppContext)
921{
922 AssertPtrReturn(pGuest, VERR_INVALID_POINTER);
923
924 PCOPYCONTEXT pContext = new COPYCONTEXT();
925 AssertPtrReturn(pContext, VERR_NO_MEMORY); /**< @todo r=klaus cannot happen with new */
926 ComPtr<IGuestSession> pGuestSession;
927 HRESULT rc = pGuest->CreateSession(Bstr(strUsername).raw(),
928 Bstr(strPassword).raw(),
929 Bstr(strDomain).raw(),
930 Bstr(strSessionName).raw(),
931 pGuestSession.asOutParam());
932 if (FAILED(rc))
933 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
934
935 pContext->fVerbose = fVerbose;
936 pContext->fDryRun = fDryRun;
937 pContext->fHostToGuest = fHostToGuest;
938 pContext->pGuestSession = pGuestSession;
939
940 *ppContext = pContext;
941
942 return VINF_SUCCESS;
943}
944
945/**
946 * Frees are previously allocated copy context structure.
947 *
948 * @param pContext Pointer to copy context to free.
949 */
950static void ctrlCopyContextFree(PCOPYCONTEXT pContext)
951{
952 if (pContext)
953 {
954 if (pContext->pGuestSession)
955 pContext->pGuestSession->Close();
956 delete pContext;
957 }
958}
959
960/**
961 * Translates a source path to a destination path (can be both sides,
962 * either host or guest). The source root is needed to determine the start
963 * of the relative source path which also needs to present in the destination
964 * path.
965 *
966 * @return IPRT status code.
967 * @param pszSourceRoot Source root path. No trailing directory slash!
968 * @param pszSource Actual source to transform. Must begin with
969 * the source root path!
970 * @param pszDest Destination path.
971 * @param ppszTranslated Pointer to the allocated, translated destination
972 * path. Must be free'd with RTStrFree().
973 */
974static int ctrlCopyTranslatePath(const char *pszSourceRoot, const char *pszSource,
975 const char *pszDest, char **ppszTranslated)
976{
977 AssertPtrReturn(pszSourceRoot, VERR_INVALID_POINTER);
978 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
979 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
980 AssertPtrReturn(ppszTranslated, VERR_INVALID_POINTER);
981 AssertReturn(RTPathStartsWith(pszSource, pszSourceRoot), VERR_INVALID_PARAMETER);
982
983 /* Construct the relative dest destination path by "subtracting" the
984 * source from the source root, e.g.
985 *
986 * source root path = "e:\foo\", source = "e:\foo\bar"
987 * dest = "d:\baz\"
988 * translated = "d:\baz\bar\"
989 */
990 char szTranslated[RTPATH_MAX];
991 size_t srcOff = strlen(pszSourceRoot);
992 AssertReturn(srcOff, VERR_INVALID_PARAMETER);
993
994 char *pszDestPath = RTStrDup(pszDest);
995 AssertPtrReturn(pszDestPath, VERR_NO_MEMORY);
996
997 int vrc;
998 if (!RTPathFilename(pszDestPath))
999 {
1000 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1001 pszDestPath, &pszSource[srcOff]);
1002 }
1003 else
1004 {
1005 char *pszDestFileName = RTStrDup(RTPathFilename(pszDestPath));
1006 if (pszDestFileName)
1007 {
1008 RTPathStripFilename(pszDestPath);
1009 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1010 pszDestPath, pszDestFileName);
1011 RTStrFree(pszDestFileName);
1012 }
1013 else
1014 vrc = VERR_NO_MEMORY;
1015 }
1016 RTStrFree(pszDestPath);
1017
1018 if (RT_SUCCESS(vrc))
1019 {
1020 *ppszTranslated = RTStrDup(szTranslated);
1021#if 0
1022 RTPrintf("Root: %s, Source: %s, Dest: %s, Translated: %s\n",
1023 pszSourceRoot, pszSource, pszDest, *ppszTranslated);
1024#endif
1025 }
1026 return vrc;
1027}
1028
1029#ifdef DEBUG_andy
1030static int tstTranslatePath()
1031{
1032 RTAssertSetMayPanic(false /* Do not freak out, please. */);
1033
1034 static struct
1035 {
1036 const char *pszSourceRoot;
1037 const char *pszSource;
1038 const char *pszDest;
1039 const char *pszTranslated;
1040 int iResult;
1041 } aTests[] =
1042 {
1043 /* Invalid stuff. */
1044 { NULL, NULL, NULL, NULL, VERR_INVALID_POINTER },
1045#ifdef RT_OS_WINDOWS
1046 /* Windows paths. */
1047 { "c:\\foo", "c:\\foo\\bar.txt", "c:\\test", "c:\\test\\bar.txt", VINF_SUCCESS },
1048 { "c:\\foo", "c:\\foo\\baz\\bar.txt", "c:\\test", "c:\\test\\baz\\bar.txt", VINF_SUCCESS },
1049#else /* RT_OS_WINDOWS */
1050 { "/home/test/foo", "/home/test/foo/bar.txt", "/opt/test", "/opt/test/bar.txt", VINF_SUCCESS },
1051 { "/home/test/foo", "/home/test/foo/baz/bar.txt", "/opt/test", "/opt/test/baz/bar.txt", VINF_SUCCESS },
1052#endif /* !RT_OS_WINDOWS */
1053 /* Mixed paths*/
1054 /** @todo */
1055 { NULL }
1056 };
1057
1058 size_t iTest = 0;
1059 for (iTest; iTest < RT_ELEMENTS(aTests); iTest++)
1060 {
1061 RTPrintf("=> Test %d\n", iTest);
1062 RTPrintf("\tSourceRoot=%s, Source=%s, Dest=%s\n",
1063 aTests[iTest].pszSourceRoot, aTests[iTest].pszSource, aTests[iTest].pszDest);
1064
1065 char *pszTranslated = NULL;
1066 int iResult = ctrlCopyTranslatePath(aTests[iTest].pszSourceRoot, aTests[iTest].pszSource,
1067 aTests[iTest].pszDest, &pszTranslated);
1068 if (iResult != aTests[iTest].iResult)
1069 {
1070 RTPrintf("\tReturned %Rrc, expected %Rrc\n",
1071 iResult, aTests[iTest].iResult);
1072 }
1073 else if ( pszTranslated
1074 && strcmp(pszTranslated, aTests[iTest].pszTranslated))
1075 {
1076 RTPrintf("\tReturned translated path %s, expected %s\n",
1077 pszTranslated, aTests[iTest].pszTranslated);
1078 }
1079
1080 if (pszTranslated)
1081 {
1082 RTPrintf("\tTranslated=%s\n", pszTranslated);
1083 RTStrFree(pszTranslated);
1084 }
1085 }
1086
1087 return VINF_SUCCESS; /* @todo */
1088}
1089#endif
1090
1091/**
1092 * Creates a directory on the destination, based on the current copy
1093 * context.
1094 *
1095 * @return IPRT status code.
1096 * @param pContext Pointer to current copy control context.
1097 * @param pszDir Directory to create.
1098 */
1099static int ctrlCopyDirCreate(PCOPYCONTEXT pContext, const char *pszDir)
1100{
1101 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1102 AssertPtrReturn(pszDir, VERR_INVALID_POINTER);
1103
1104 bool fDirExists;
1105 int vrc = ctrlCopyDirExists(pContext, pContext->fHostToGuest, pszDir, &fDirExists);
1106 if ( RT_SUCCESS(vrc)
1107 && fDirExists)
1108 {
1109 if (pContext->fVerbose)
1110 RTPrintf("Directory \"%s\" already exists\n", pszDir);
1111 return VINF_SUCCESS;
1112 }
1113
1114 /* If querying for a directory existence fails there's no point of even trying
1115 * to create such a directory. */
1116 if (RT_FAILURE(vrc))
1117 return vrc;
1118
1119 if (pContext->fVerbose)
1120 RTPrintf("Creating directory \"%s\" ...\n", pszDir);
1121
1122 if (pContext->fDryRun)
1123 return VINF_SUCCESS;
1124
1125 if (pContext->fHostToGuest) /* We want to create directories on the guest. */
1126 {
1127 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
1128 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1129 HRESULT rc = pContext->pGuestSession->DirectoryCreate(Bstr(pszDir).raw(),
1130 0700, ComSafeArrayAsInParam(dirCreateFlags));
1131 if (FAILED(rc))
1132 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1133 }
1134 else /* ... or on the host. */
1135 {
1136 vrc = RTDirCreateFullPath(pszDir, 0700);
1137 if (vrc == VERR_ALREADY_EXISTS)
1138 vrc = VINF_SUCCESS;
1139 }
1140 return vrc;
1141}
1142
1143/**
1144 * Checks whether a specific host/guest directory exists.
1145 *
1146 * @return IPRT status code.
1147 * @param pContext Pointer to current copy control context.
1148 * @param bGuest true if directory needs to be checked on the guest
1149 * or false if on the host.
1150 * @param pszDir Actual directory to check.
1151 * @param fExists Pointer which receives the result if the
1152 * given directory exists or not.
1153 */
1154static int ctrlCopyDirExists(PCOPYCONTEXT pContext, bool bGuest,
1155 const char *pszDir, bool *fExists)
1156{
1157 AssertPtrReturn(pContext, false);
1158 AssertPtrReturn(pszDir, false);
1159 AssertPtrReturn(fExists, false);
1160
1161 int vrc = VINF_SUCCESS;
1162 if (bGuest)
1163 {
1164 BOOL fDirExists = FALSE;
1165 HRESULT rc = pContext->pGuestSession->DirectoryExists(Bstr(pszDir).raw(), &fDirExists);
1166 if (FAILED(rc))
1167 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1168 else
1169 *fExists = fDirExists ? true : false;
1170 }
1171 else
1172 *fExists = RTDirExists(pszDir);
1173 return vrc;
1174}
1175
1176/**
1177 * Checks whether a specific directory exists on the destination, based
1178 * on the current copy context.
1179 *
1180 * @return IPRT status code.
1181 * @param pContext Pointer to current copy control context.
1182 * @param pszDir Actual directory to check.
1183 * @param fExists Pointer which receives the result if the
1184 * given directory exists or not.
1185 */
1186static int ctrlCopyDirExistsOnDest(PCOPYCONTEXT pContext, const char *pszDir,
1187 bool *fExists)
1188{
1189 return ctrlCopyDirExists(pContext, pContext->fHostToGuest,
1190 pszDir, fExists);
1191}
1192
1193/**
1194 * Checks whether a specific directory exists on the source, based
1195 * on the current copy context.
1196 *
1197 * @return IPRT status code.
1198 * @param pContext Pointer to current copy control context.
1199 * @param pszDir Actual directory to check.
1200 * @param fExists Pointer which receives the result if the
1201 * given directory exists or not.
1202 */
1203static int ctrlCopyDirExistsOnSource(PCOPYCONTEXT pContext, const char *pszDir,
1204 bool *fExists)
1205{
1206 return ctrlCopyDirExists(pContext, !pContext->fHostToGuest,
1207 pszDir, fExists);
1208}
1209
1210/**
1211 * Checks whether a specific host/guest file exists.
1212 *
1213 * @return IPRT status code.
1214 * @param pContext Pointer to current copy control context.
1215 * @param bGuest true if file needs to be checked on the guest
1216 * or false if on the host.
1217 * @param pszFile Actual file to check.
1218 * @param fExists Pointer which receives the result if the
1219 * given file exists or not.
1220 */
1221static int ctrlCopyFileExists(PCOPYCONTEXT pContext, bool bOnGuest,
1222 const char *pszFile, bool *fExists)
1223{
1224 AssertPtrReturn(pContext, false);
1225 AssertPtrReturn(pszFile, false);
1226 AssertPtrReturn(fExists, false);
1227
1228 int vrc = VINF_SUCCESS;
1229 if (bOnGuest)
1230 {
1231 BOOL fFileExists = FALSE;
1232 HRESULT rc = pContext->pGuestSession->FileExists(Bstr(pszFile).raw(), &fFileExists);
1233 if (FAILED(rc))
1234 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1235 else
1236 *fExists = fFileExists ? true : false;
1237 }
1238 else
1239 *fExists = RTFileExists(pszFile);
1240 return vrc;
1241}
1242
1243/**
1244 * Checks whether a specific file exists on the destination, based on the
1245 * current copy context.
1246 *
1247 * @return IPRT status code.
1248 * @param pContext Pointer to current copy control context.
1249 * @param pszFile Actual file to check.
1250 * @param fExists Pointer which receives the result if the
1251 * given file exists or not.
1252 */
1253static int ctrlCopyFileExistsOnDest(PCOPYCONTEXT pContext, const char *pszFile,
1254 bool *fExists)
1255{
1256 return ctrlCopyFileExists(pContext, pContext->fHostToGuest,
1257 pszFile, fExists);
1258}
1259
1260/**
1261 * Checks whether a specific file exists on the source, based on the
1262 * current copy context.
1263 *
1264 * @return IPRT status code.
1265 * @param pContext Pointer to current copy control context.
1266 * @param pszFile Actual file to check.
1267 * @param fExists Pointer which receives the result if the
1268 * given file exists or not.
1269 */
1270static int ctrlCopyFileExistsOnSource(PCOPYCONTEXT pContext, const char *pszFile,
1271 bool *fExists)
1272{
1273 return ctrlCopyFileExists(pContext, !pContext->fHostToGuest,
1274 pszFile, fExists);
1275}
1276
1277/**
1278 * Copies a source file to the destination.
1279 *
1280 * @return IPRT status code.
1281 * @param pContext Pointer to current copy control context.
1282 * @param pszFileSource Source file to copy to the destination.
1283 * @param pszFileDest Name of copied file on the destination.
1284 * @param fFlags Copy flags. No supported at the moment and needs
1285 * to be set to 0.
1286 */
1287static int ctrlCopyFileToDest(PCOPYCONTEXT pContext, const char *pszFileSource,
1288 const char *pszFileDest, uint32_t fFlags)
1289{
1290 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1291 AssertPtrReturn(pszFileSource, VERR_INVALID_POINTER);
1292 AssertPtrReturn(pszFileDest, VERR_INVALID_POINTER);
1293 AssertReturn(!fFlags, VERR_INVALID_POINTER); /* No flags supported yet. */
1294
1295 if (pContext->fVerbose)
1296 RTPrintf("Copying \"%s\" to \"%s\" ...\n",
1297 pszFileSource, pszFileDest);
1298
1299 if (pContext->fDryRun)
1300 return VINF_SUCCESS;
1301
1302 int vrc = VINF_SUCCESS;
1303 ComPtr<IProgress> pProgress;
1304 HRESULT rc;
1305 if (pContext->fHostToGuest)
1306 {
1307 SafeArray<CopyFileFlag_T> copyFlags;
1308 rc = pContext->pGuestSession->CopyTo(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
1309 ComSafeArrayAsInParam(copyFlags),
1310
1311 pProgress.asOutParam());
1312 }
1313 else
1314 {
1315 SafeArray<CopyFileFlag_T> copyFlags;
1316 rc = pContext->pGuestSession->CopyFrom(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
1317 ComSafeArrayAsInParam(copyFlags),
1318 pProgress.asOutParam());
1319 }
1320
1321 if (FAILED(rc))
1322 {
1323 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1324 }
1325 else
1326 {
1327 if (pContext->fVerbose)
1328 rc = showProgress(pProgress);
1329 else
1330 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
1331 if (SUCCEEDED(rc))
1332 CHECK_PROGRESS_ERROR(pProgress, ("File copy failed"));
1333 vrc = ctrlPrintProgressError(pProgress);
1334 }
1335
1336 return vrc;
1337}
1338
1339/**
1340 * Copys a directory (tree) from host to the guest.
1341 *
1342 * @return IPRT status code.
1343 * @param pContext Pointer to current copy control context.
1344 * @param pszSource Source directory on the host to copy to the guest.
1345 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
1346 * @param pszDest Destination directory on the guest.
1347 * @param fFlags Copy flags, such as recursive copying.
1348 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
1349 * is needed for recursion.
1350 */
1351static int ctrlCopyDirToGuest(PCOPYCONTEXT pContext,
1352 const char *pszSource, const char *pszFilter,
1353 const char *pszDest, uint32_t fFlags,
1354 const char *pszSubDir /* For recursion. */)
1355{
1356 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1357 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1358 /* Filter is optional. */
1359 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1360 /* Sub directory is optional. */
1361
1362 /*
1363 * Construct current path.
1364 */
1365 char szCurDir[RTPATH_MAX];
1366 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
1367 if (RT_SUCCESS(vrc) && pszSubDir)
1368 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
1369
1370 if (pContext->fVerbose)
1371 RTPrintf("Processing host directory: %s\n", szCurDir);
1372
1373 /* Flag indicating whether the current directory was created on the
1374 * target or not. */
1375 bool fDirCreated = false;
1376
1377 /*
1378 * Open directory without a filter - RTDirOpenFiltered unfortunately
1379 * cannot handle sub directories so we have to do the filtering ourselves.
1380 */
1381 PRTDIR pDir = NULL;
1382 if (RT_SUCCESS(vrc))
1383 {
1384 vrc = RTDirOpen(&pDir, szCurDir);
1385 if (RT_FAILURE(vrc))
1386 pDir = NULL;
1387 }
1388 if (RT_SUCCESS(vrc))
1389 {
1390 /*
1391 * Enumerate the directory tree.
1392 */
1393 while (RT_SUCCESS(vrc))
1394 {
1395 RTDIRENTRY DirEntry;
1396 vrc = RTDirRead(pDir, &DirEntry, NULL);
1397 if (RT_FAILURE(vrc))
1398 {
1399 if (vrc == VERR_NO_MORE_FILES)
1400 vrc = VINF_SUCCESS;
1401 break;
1402 }
1403 switch (DirEntry.enmType)
1404 {
1405 case RTDIRENTRYTYPE_DIRECTORY:
1406 {
1407 /* Skip "." and ".." entries. */
1408 if ( !strcmp(DirEntry.szName, ".")
1409 || !strcmp(DirEntry.szName, ".."))
1410 break;
1411
1412 if (pContext->fVerbose)
1413 RTPrintf("Directory: %s\n", DirEntry.szName);
1414
1415 if (fFlags & CopyFileFlag_Recursive)
1416 {
1417 char *pszNewSub = NULL;
1418 if (pszSubDir)
1419 pszNewSub = RTPathJoinA(pszSubDir, DirEntry.szName);
1420 else
1421 {
1422 pszNewSub = RTStrDup(DirEntry.szName);
1423 RTPathStripTrailingSlash(pszNewSub);
1424 }
1425
1426 if (pszNewSub)
1427 {
1428 vrc = ctrlCopyDirToGuest(pContext,
1429 pszSource, pszFilter,
1430 pszDest, fFlags, pszNewSub);
1431 RTStrFree(pszNewSub);
1432 }
1433 else
1434 vrc = VERR_NO_MEMORY;
1435 }
1436 break;
1437 }
1438
1439 case RTDIRENTRYTYPE_SYMLINK:
1440 if ( (fFlags & CopyFileFlag_Recursive)
1441 && (fFlags & CopyFileFlag_FollowLinks))
1442 {
1443 /* Fall through to next case is intentional. */
1444 }
1445 else
1446 break;
1447
1448 case RTDIRENTRYTYPE_FILE:
1449 {
1450 if ( pszFilter
1451 && !RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
1452 {
1453 break; /* Filter does not match. */
1454 }
1455
1456 if (pContext->fVerbose)
1457 RTPrintf("File: %s\n", DirEntry.szName);
1458
1459 if (!fDirCreated)
1460 {
1461 char *pszDestDir;
1462 vrc = ctrlCopyTranslatePath(pszSource, szCurDir,
1463 pszDest, &pszDestDir);
1464 if (RT_SUCCESS(vrc))
1465 {
1466 vrc = ctrlCopyDirCreate(pContext, pszDestDir);
1467 RTStrFree(pszDestDir);
1468
1469 fDirCreated = true;
1470 }
1471 }
1472
1473 if (RT_SUCCESS(vrc))
1474 {
1475 char *pszFileSource = RTPathJoinA(szCurDir, DirEntry.szName);
1476 if (pszFileSource)
1477 {
1478 char *pszFileDest;
1479 vrc = ctrlCopyTranslatePath(pszSource, pszFileSource,
1480 pszDest, &pszFileDest);
1481 if (RT_SUCCESS(vrc))
1482 {
1483 vrc = ctrlCopyFileToDest(pContext, pszFileSource,
1484 pszFileDest, 0 /* Flags */);
1485 RTStrFree(pszFileDest);
1486 }
1487 RTStrFree(pszFileSource);
1488 }
1489 }
1490 break;
1491 }
1492
1493 default:
1494 break;
1495 }
1496 if (RT_FAILURE(vrc))
1497 break;
1498 }
1499
1500 RTDirClose(pDir);
1501 }
1502 return vrc;
1503}
1504
1505/**
1506 * Copys a directory (tree) from guest to the host.
1507 *
1508 * @return IPRT status code.
1509 * @param pContext Pointer to current copy control context.
1510 * @param pszSource Source directory on the guest to copy to the host.
1511 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
1512 * @param pszDest Destination directory on the host.
1513 * @param fFlags Copy flags, such as recursive copying.
1514 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
1515 * is needed for recursion.
1516 */
1517static int ctrlCopyDirToHost(PCOPYCONTEXT pContext,
1518 const char *pszSource, const char *pszFilter,
1519 const char *pszDest, uint32_t fFlags,
1520 const char *pszSubDir /* For recursion. */)
1521{
1522 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1523 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1524 /* Filter is optional. */
1525 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1526 /* Sub directory is optional. */
1527
1528 /*
1529 * Construct current path.
1530 */
1531 char szCurDir[RTPATH_MAX];
1532 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
1533 if (RT_SUCCESS(vrc) && pszSubDir)
1534 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
1535
1536 if (RT_FAILURE(vrc))
1537 return vrc;
1538
1539 if (pContext->fVerbose)
1540 RTPrintf("Processing guest directory: %s\n", szCurDir);
1541
1542 /* Flag indicating whether the current directory was created on the
1543 * target or not. */
1544 bool fDirCreated = false;
1545 SafeArray<DirectoryOpenFlag_T> dirOpenFlags; /* No flags supported yet. */
1546 ComPtr<IGuestDirectory> pDirectory;
1547 HRESULT rc = pContext->pGuestSession->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(),
1548 ComSafeArrayAsInParam(dirOpenFlags),
1549 pDirectory.asOutParam());
1550 if (FAILED(rc))
1551 return ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1552 ComPtr<IFsObjInfo> dirEntry;
1553 while (true)
1554 {
1555 rc = pDirectory->Read(dirEntry.asOutParam());
1556 if (FAILED(rc))
1557 break;
1558
1559 FsObjType_T enmType;
1560 dirEntry->COMGETTER(Type)(&enmType);
1561
1562 Bstr strName;
1563 dirEntry->COMGETTER(Name)(strName.asOutParam());
1564
1565 switch (enmType)
1566 {
1567 case FsObjType_Directory:
1568 {
1569 Assert(!strName.isEmpty());
1570
1571 /* Skip "." and ".." entries. */
1572 if ( !strName.compare(Bstr("."))
1573 || !strName.compare(Bstr("..")))
1574 break;
1575
1576 if (pContext->fVerbose)
1577 {
1578 Utf8Str strDir(strName);
1579 RTPrintf("Directory: %s\n", strDir.c_str());
1580 }
1581
1582 if (fFlags & CopyFileFlag_Recursive)
1583 {
1584 Utf8Str strDir(strName);
1585 char *pszNewSub = NULL;
1586 if (pszSubDir)
1587 pszNewSub = RTPathJoinA(pszSubDir, strDir.c_str());
1588 else
1589 {
1590 pszNewSub = RTStrDup(strDir.c_str());
1591 RTPathStripTrailingSlash(pszNewSub);
1592 }
1593 if (pszNewSub)
1594 {
1595 vrc = ctrlCopyDirToHost(pContext,
1596 pszSource, pszFilter,
1597 pszDest, fFlags, pszNewSub);
1598 RTStrFree(pszNewSub);
1599 }
1600 else
1601 vrc = VERR_NO_MEMORY;
1602 }
1603 break;
1604 }
1605
1606 case FsObjType_Symlink:
1607 if ( (fFlags & CopyFileFlag_Recursive)
1608 && (fFlags & CopyFileFlag_FollowLinks))
1609 {
1610 /* Fall through to next case is intentional. */
1611 }
1612 else
1613 break;
1614
1615 case FsObjType_File:
1616 {
1617 Assert(!strName.isEmpty());
1618
1619 Utf8Str strFile(strName);
1620 if ( pszFilter
1621 && !RTStrSimplePatternMatch(pszFilter, strFile.c_str()))
1622 {
1623 break; /* Filter does not match. */
1624 }
1625
1626 if (pContext->fVerbose)
1627 RTPrintf("File: %s\n", strFile.c_str());
1628
1629 if (!fDirCreated)
1630 {
1631 char *pszDestDir;
1632 vrc = ctrlCopyTranslatePath(pszSource, szCurDir,
1633 pszDest, &pszDestDir);
1634 if (RT_SUCCESS(vrc))
1635 {
1636 vrc = ctrlCopyDirCreate(pContext, pszDestDir);
1637 RTStrFree(pszDestDir);
1638
1639 fDirCreated = true;
1640 }
1641 }
1642
1643 if (RT_SUCCESS(vrc))
1644 {
1645 char *pszFileSource = RTPathJoinA(szCurDir, strFile.c_str());
1646 if (pszFileSource)
1647 {
1648 char *pszFileDest;
1649 vrc = ctrlCopyTranslatePath(pszSource, pszFileSource,
1650 pszDest, &pszFileDest);
1651 if (RT_SUCCESS(vrc))
1652 {
1653 vrc = ctrlCopyFileToDest(pContext, pszFileSource,
1654 pszFileDest, 0 /* Flags */);
1655 RTStrFree(pszFileDest);
1656 }
1657 RTStrFree(pszFileSource);
1658 }
1659 else
1660 vrc = VERR_NO_MEMORY;
1661 }
1662 break;
1663 }
1664
1665 default:
1666 RTPrintf("Warning: Directory entry of type %ld not handled, skipping ...\n",
1667 enmType);
1668 break;
1669 }
1670
1671 if (RT_FAILURE(vrc))
1672 break;
1673 }
1674
1675 if (RT_UNLIKELY(FAILED(rc)))
1676 {
1677 switch (rc)
1678 {
1679 case E_ABORT: /* No more directory entries left to process. */
1680 break;
1681
1682 case VBOX_E_FILE_ERROR: /* Current entry cannot be accessed to
1683 to missing rights. */
1684 {
1685 RTPrintf("Warning: Cannot access \"%s\", skipping ...\n",
1686 szCurDir);
1687 break;
1688 }
1689
1690 default:
1691 vrc = ctrlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
1692 break;
1693 }
1694 }
1695
1696 HRESULT rc2 = pDirectory->Close();
1697 if (FAILED(rc2))
1698 {
1699 int vrc2 = ctrlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
1700 if (RT_SUCCESS(vrc))
1701 vrc = vrc2;
1702 }
1703 else if (SUCCEEDED(rc))
1704 rc = rc2;
1705
1706 return vrc;
1707}
1708
1709/**
1710 * Copys a directory (tree) to the destination, based on the current copy
1711 * context.
1712 *
1713 * @return IPRT status code.
1714 * @param pContext Pointer to current copy control context.
1715 * @param pszSource Source directory to copy to the destination.
1716 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
1717 * @param pszDest Destination directory where to copy in the source
1718 * source directory.
1719 * @param fFlags Copy flags, such as recursive copying.
1720 */
1721static int ctrlCopyDirToDest(PCOPYCONTEXT pContext,
1722 const char *pszSource, const char *pszFilter,
1723 const char *pszDest, uint32_t fFlags)
1724{
1725 if (pContext->fHostToGuest)
1726 return ctrlCopyDirToGuest(pContext, pszSource, pszFilter,
1727 pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
1728 return ctrlCopyDirToHost(pContext, pszSource, pszFilter,
1729 pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
1730}
1731
1732/**
1733 * Creates a source root by stripping file names or filters of the specified source.
1734 *
1735 * @return IPRT status code.
1736 * @param pszSource Source to create source root for.
1737 * @param ppszSourceRoot Pointer that receives the allocated source root. Needs
1738 * to be free'd with ctrlCopyFreeSourceRoot().
1739 */
1740static int ctrlCopyCreateSourceRoot(const char *pszSource, char **ppszSourceRoot)
1741{
1742 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1743 AssertPtrReturn(ppszSourceRoot, VERR_INVALID_POINTER);
1744
1745 char *pszNewRoot = RTStrDup(pszSource);
1746 AssertPtrReturn(pszNewRoot, VERR_NO_MEMORY);
1747
1748 size_t lenRoot = strlen(pszNewRoot);
1749 if ( lenRoot
1750 && pszNewRoot[lenRoot - 1] == '/'
1751 && pszNewRoot[lenRoot - 1] == '\\'
1752 && lenRoot > 1
1753 && pszNewRoot[lenRoot - 2] == '/'
1754 && pszNewRoot[lenRoot - 2] == '\\')
1755 {
1756 *ppszSourceRoot = pszNewRoot;
1757 if (lenRoot > 1)
1758 *ppszSourceRoot[lenRoot - 2] = '\0';
1759 *ppszSourceRoot[lenRoot - 1] = '\0';
1760 }
1761 else
1762 {
1763 /* If there's anything (like a file name or a filter),
1764 * strip it! */
1765 RTPathStripFilename(pszNewRoot);
1766 *ppszSourceRoot = pszNewRoot;
1767 }
1768
1769 return VINF_SUCCESS;
1770}
1771
1772/**
1773 * Frees a previously allocated source root.
1774 *
1775 * @return IPRT status code.
1776 * @param pszSourceRoot Source root to free.
1777 */
1778static void ctrlCopyFreeSourceRoot(char *pszSourceRoot)
1779{
1780 RTStrFree(pszSourceRoot);
1781}
1782
1783static int handleCtrlCopy(ComPtr<IGuest> guest, HandlerArg *pArg,
1784 bool fHostToGuest)
1785{
1786 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1787
1788 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
1789 * is much better (partly because it is much simpler of course). The main
1790 * arguments against this is that (1) all but two options conflicts with
1791 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
1792 * done windows CMD style (though not in a 100% compatible way), and (3)
1793 * that only one source is allowed - efficiently sabotaging default
1794 * wildcard expansion by a unix shell. The best solution here would be
1795 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
1796
1797 /*
1798 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1799 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1800 * does in here.
1801 */
1802 static const RTGETOPTDEF s_aOptions[] =
1803 {
1804 { "--dryrun", GETOPTDEF_COPY_DRYRUN, RTGETOPT_REQ_NOTHING },
1805 { "--follow", GETOPTDEF_COPY_FOLLOW, RTGETOPT_REQ_NOTHING },
1806 { "--username", 'u', RTGETOPT_REQ_STRING },
1807 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
1808 { "--password", GETOPTDEF_COPY_PASSWORD, RTGETOPT_REQ_STRING },
1809 { "--domain", 'd', RTGETOPT_REQ_STRING },
1810 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1811 { "--target-directory", GETOPTDEF_COPY_TARGETDIR, RTGETOPT_REQ_STRING },
1812 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1813 };
1814
1815 int ch;
1816 RTGETOPTUNION ValueUnion;
1817 RTGETOPTSTATE GetState;
1818 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1819 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1820
1821 Utf8Str strSource;
1822 Utf8Str strDest;
1823 Utf8Str strUsername;
1824 Utf8Str strPassword;
1825 Utf8Str strDomain;
1826 uint32_t fFlags = CopyFileFlag_None;
1827 bool fVerbose = false;
1828 bool fCopyRecursive = false;
1829 bool fDryRun = false;
1830
1831 SOURCEVEC vecSources;
1832
1833 int vrc = VINF_SUCCESS;
1834 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1835 {
1836 /* For options that require an argument, ValueUnion has received the value. */
1837 switch (ch)
1838 {
1839 case GETOPTDEF_COPY_DRYRUN:
1840 fDryRun = true;
1841 break;
1842
1843 case GETOPTDEF_COPY_FOLLOW:
1844 fFlags |= CopyFileFlag_FollowLinks;
1845 break;
1846
1847 case 'u': /* User name */
1848 strUsername = ValueUnion.psz;
1849 break;
1850
1851 case GETOPTDEF_COPY_PASSWORD: /* Password */
1852 strPassword = ValueUnion.psz;
1853 break;
1854
1855 case 'p': /* Password file */
1856 {
1857 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
1858 if (rcExit != RTEXITCODE_SUCCESS)
1859 return rcExit;
1860 break;
1861 }
1862
1863 case 'd': /* domain */
1864 strDomain = ValueUnion.psz;
1865 break;
1866
1867 case 'R': /* Recursive processing */
1868 fFlags |= CopyFileFlag_Recursive;
1869 break;
1870
1871 case GETOPTDEF_COPY_TARGETDIR:
1872 strDest = ValueUnion.psz;
1873 break;
1874
1875 case 'v': /* Verbose */
1876 fVerbose = true;
1877 break;
1878
1879 case VINF_GETOPT_NOT_OPTION:
1880 {
1881 /* Last argument and no destination specified with
1882 * --target-directory yet? Then use the current
1883 * (= last) argument as destination. */
1884 if ( pArg->argc == GetState.iNext
1885 && strDest.isEmpty())
1886 {
1887 strDest = ValueUnion.psz;
1888 }
1889 else
1890 {
1891 /* Save the source directory. */
1892 vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
1893 }
1894 break;
1895 }
1896
1897 default:
1898 return RTGetOptPrintError(ch, &ValueUnion);
1899 }
1900 }
1901
1902 if (!vecSources.size())
1903 return errorSyntax(USAGE_GUESTCONTROL,
1904 "No source(s) specified!");
1905
1906 if (strDest.isEmpty())
1907 return errorSyntax(USAGE_GUESTCONTROL,
1908 "No destination specified!");
1909
1910 if (strUsername.isEmpty())
1911 return errorSyntax(USAGE_GUESTCONTROL,
1912 "No user name specified!");
1913
1914 /*
1915 * Done parsing arguments, do some more preparations.
1916 */
1917 if (fVerbose)
1918 {
1919 if (fHostToGuest)
1920 RTPrintf("Copying from host to guest ...\n");
1921 else
1922 RTPrintf("Copying from guest to host ...\n");
1923 if (fDryRun)
1924 RTPrintf("Dry run - no files copied!\n");
1925 }
1926
1927 /* Create the copy context -- it contains all information
1928 * the routines need to know when handling the actual copying. */
1929 PCOPYCONTEXT pContext;
1930 vrc = ctrlCopyContextCreate(guest, fVerbose, fDryRun, fHostToGuest,
1931 strUsername, strPassword, strDomain,
1932 "VBoxManage Guest Control Copy", &pContext);
1933 if (RT_FAILURE(vrc))
1934 {
1935 RTMsgError("Unable to create copy context, rc=%Rrc\n", vrc);
1936 return RTEXITCODE_FAILURE;
1937 }
1938
1939 /* If the destination is a path, (try to) create it. */
1940 const char *pszDest = strDest.c_str();
1941 if (!RTPathFilename(pszDest))
1942 {
1943 vrc = ctrlCopyDirCreate(pContext, pszDest);
1944 }
1945 else
1946 {
1947 /* We assume we got a file name as destination -- so strip
1948 * the actual file name and make sure the appropriate
1949 * directories get created. */
1950 char *pszDestDir = RTStrDup(pszDest);
1951 AssertPtr(pszDestDir);
1952 RTPathStripFilename(pszDestDir);
1953 vrc = ctrlCopyDirCreate(pContext, pszDestDir);
1954 RTStrFree(pszDestDir);
1955 }
1956
1957 if (RT_SUCCESS(vrc))
1958 {
1959 /*
1960 * Here starts the actual fun!
1961 * Handle all given sources one by one.
1962 */
1963 for (unsigned long s = 0; s < vecSources.size(); s++)
1964 {
1965 char *pszSource = RTStrDup(vecSources[s].GetSource());
1966 AssertPtrBreakStmt(pszSource, vrc = VERR_NO_MEMORY);
1967 const char *pszFilter = vecSources[s].GetFilter();
1968 if (!strlen(pszFilter))
1969 pszFilter = NULL; /* If empty filter then there's no filter :-) */
1970
1971 char *pszSourceRoot;
1972 vrc = ctrlCopyCreateSourceRoot(pszSource, &pszSourceRoot);
1973 if (RT_FAILURE(vrc))
1974 {
1975 RTMsgError("Unable to create source root, rc=%Rrc\n", vrc);
1976 break;
1977 }
1978
1979 if (fVerbose)
1980 RTPrintf("Source: %s\n", pszSource);
1981
1982 /** @todo Files with filter?? */
1983 bool fSourceIsFile = false;
1984 bool fSourceExists;
1985
1986 size_t cchSource = strlen(pszSource);
1987 if ( cchSource > 1
1988 && RTPATH_IS_SLASH(pszSource[cchSource - 1]))
1989 {
1990 if (pszFilter) /* Directory with filter (so use source root w/o the actual filter). */
1991 vrc = ctrlCopyDirExistsOnSource(pContext, pszSourceRoot, &fSourceExists);
1992 else /* Regular directory without filter. */
1993 vrc = ctrlCopyDirExistsOnSource(pContext, pszSource, &fSourceExists);
1994
1995 if (fSourceExists)
1996 {
1997 /* Strip trailing slash from our source element so that other functions
1998 * can use this stuff properly (like RTPathStartsWith). */
1999 RTPathStripTrailingSlash(pszSource);
2000 }
2001 }
2002 else
2003 {
2004 vrc = ctrlCopyFileExistsOnSource(pContext, pszSource, &fSourceExists);
2005 if ( RT_SUCCESS(vrc)
2006 && fSourceExists)
2007 {
2008 fSourceIsFile = true;
2009 }
2010 }
2011
2012 if ( RT_SUCCESS(vrc)
2013 && fSourceExists)
2014 {
2015 if (fSourceIsFile)
2016 {
2017 /* Single file. */
2018 char *pszDestFile;
2019 vrc = ctrlCopyTranslatePath(pszSourceRoot, pszSource,
2020 strDest.c_str(), &pszDestFile);
2021 if (RT_SUCCESS(vrc))
2022 {
2023 vrc = ctrlCopyFileToDest(pContext, pszSource,
2024 pszDestFile, 0 /* Flags */);
2025 RTStrFree(pszDestFile);
2026 }
2027 else
2028 RTMsgError("Unable to translate path for \"%s\", rc=%Rrc\n",
2029 pszSource, vrc);
2030 }
2031 else
2032 {
2033 /* Directory (with filter?). */
2034 vrc = ctrlCopyDirToDest(pContext, pszSource, pszFilter,
2035 strDest.c_str(), fFlags);
2036 }
2037 }
2038
2039 ctrlCopyFreeSourceRoot(pszSourceRoot);
2040
2041 if ( RT_SUCCESS(vrc)
2042 && !fSourceExists)
2043 {
2044 RTMsgError("Warning: Source \"%s\" does not exist, skipping!\n",
2045 pszSource);
2046 RTStrFree(pszSource);
2047 continue;
2048 }
2049 else if (RT_FAILURE(vrc))
2050 {
2051 RTMsgError("Error processing \"%s\", rc=%Rrc\n",
2052 pszSource, vrc);
2053 RTStrFree(pszSource);
2054 break;
2055 }
2056
2057 RTStrFree(pszSource);
2058 }
2059 }
2060
2061 ctrlCopyContextFree(pContext);
2062
2063 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2064}
2065
2066static int handleCtrlCreateDirectory(ComPtr<IGuest> pGuest, HandlerArg *pArg)
2067{
2068 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2069
2070 /*
2071 * Parse arguments.
2072 *
2073 * Note! No direct returns here, everyone must go thru the cleanup at the
2074 * end of this function.
2075 */
2076 static const RTGETOPTDEF s_aOptions[] =
2077 {
2078 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2079 { "--parents", 'P', RTGETOPT_REQ_NOTHING },
2080 { "--username", 'u', RTGETOPT_REQ_STRING },
2081 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
2082 { "--password", GETOPTDEF_MKDIR_PASSWORD, RTGETOPT_REQ_STRING },
2083 { "--domain", 'd', RTGETOPT_REQ_STRING },
2084 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2085 };
2086
2087 int ch;
2088 RTGETOPTUNION ValueUnion;
2089 RTGETOPTSTATE GetState;
2090 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
2091 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2092
2093 Utf8Str strUsername;
2094 Utf8Str strPassword;
2095 Utf8Str strDomain;
2096 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
2097 uint32_t fDirMode = 0; /* Default mode. */
2098 bool fVerbose = false;
2099
2100 DESTDIRMAP mapDirs;
2101
2102 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2103 {
2104 /* For options that require an argument, ValueUnion has received the value. */
2105 switch (ch)
2106 {
2107 case 'm': /* Mode */
2108 fDirMode = ValueUnion.u32;
2109 break;
2110
2111 case 'P': /* Create parents */
2112 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
2113 break;
2114
2115 case 'u': /* User name */
2116 strUsername = ValueUnion.psz;
2117 break;
2118
2119 case GETOPTDEF_MKDIR_PASSWORD: /* Password */
2120 strPassword = ValueUnion.psz;
2121 break;
2122
2123 case 'p': /* Password file */
2124 {
2125 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
2126 if (rcExit != RTEXITCODE_SUCCESS)
2127 return rcExit;
2128 break;
2129 }
2130
2131 case 'd': /* domain */
2132 strDomain = ValueUnion.psz;
2133 break;
2134
2135 case 'v': /* Verbose */
2136 fVerbose = true;
2137 break;
2138
2139 case VINF_GETOPT_NOT_OPTION:
2140 {
2141 mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
2142 break;
2143 }
2144
2145 default:
2146 return RTGetOptPrintError(ch, &ValueUnion);
2147 }
2148 }
2149
2150 uint32_t cDirs = mapDirs.size();
2151 if (!cDirs)
2152 return errorSyntax(USAGE_GUESTCONTROL, "No directory to create specified!");
2153
2154 if (strUsername.isEmpty())
2155 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
2156
2157 /*
2158 * Create the directories.
2159 */
2160 HRESULT hrc = S_OK;
2161 if (fVerbose && cDirs)
2162 RTPrintf("Creating %u directories ...\n", cDirs);
2163
2164 ComPtr<IGuestSession> pGuestSession;
2165 hrc = pGuest->CreateSession(Bstr(strUsername).raw(),
2166 Bstr(strPassword).raw(),
2167 Bstr(strDomain).raw(),
2168 Bstr("VBoxManage Guest Control MkDir").raw(),
2169 pGuestSession.asOutParam());
2170 if (FAILED(hrc))
2171 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
2172
2173 DESTDIRMAPITER it = mapDirs.begin();
2174 while (it != mapDirs.end())
2175 {
2176 if (fVerbose)
2177 RTPrintf("Creating directory \"%s\" ...\n", it->first.c_str());
2178
2179 hrc = pGuestSession->DirectoryCreate(Bstr(it->first).raw(), fDirMode, ComSafeArrayAsInParam(dirCreateFlags));
2180 if (FAILED(hrc))
2181 {
2182 ctrlPrintError(pGuest, COM_IIDOF(IGuestSession)); /* Return code ignored, save original rc. */
2183 break;
2184 }
2185
2186 it++;
2187 }
2188
2189 if (!pGuestSession.isNull())
2190 pGuestSession->Close();
2191
2192 return FAILED(hrc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2193}
2194
2195static int handleCtrlCreateTemp(ComPtr<IGuest> pGuest, HandlerArg *pArg)
2196{
2197 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2198
2199 /*
2200 * Parse arguments.
2201 *
2202 * Note! No direct returns here, everyone must go thru the cleanup at the
2203 * end of this function.
2204 */
2205 static const RTGETOPTDEF s_aOptions[] =
2206 {
2207 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2208 { "--directory", 'D', RTGETOPT_REQ_NOTHING },
2209 { "--secure", 's', RTGETOPT_REQ_NOTHING },
2210 { "--tmpdir", 't', RTGETOPT_REQ_STRING },
2211 { "--username", 'u', RTGETOPT_REQ_STRING },
2212 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
2213 { "--password", GETOPTDEF_MKDIR_PASSWORD, RTGETOPT_REQ_STRING },
2214 { "--domain", 'd', RTGETOPT_REQ_STRING },
2215 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2216 };
2217
2218 int ch;
2219 RTGETOPTUNION ValueUnion;
2220 RTGETOPTSTATE GetState;
2221 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
2222 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2223
2224 Utf8Str strUsername;
2225 Utf8Str strPassword;
2226 Utf8Str strDomain;
2227 Utf8Str strTemplate;
2228 uint32_t fMode = 0; /* Default mode. */
2229 bool fDirectory = false;
2230 bool fSecure = false;
2231 Utf8Str strTempDir;
2232 bool fVerbose = false;
2233
2234 DESTDIRMAP mapDirs;
2235
2236 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2237 {
2238 /* For options that require an argument, ValueUnion has received the value. */
2239 switch (ch)
2240 {
2241 case 'm': /* Mode */
2242 fMode = ValueUnion.u32;
2243 break;
2244
2245 case 'D': /* Create directory */
2246 fDirectory = true;
2247 break;
2248
2249 case 's': /* Secure */
2250 fSecure = true;
2251 break;
2252
2253 case 't': /* Temp directory */
2254 strTempDir = ValueUnion.psz;
2255 break;
2256
2257 case 'u': /* User name */
2258 strUsername = ValueUnion.psz;
2259 break;
2260
2261 case GETOPTDEF_MKDIR_PASSWORD: /* Password */
2262 strPassword = ValueUnion.psz;
2263 break;
2264
2265 case 'p': /* Password file */
2266 {
2267 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
2268 if (rcExit != RTEXITCODE_SUCCESS)
2269 return rcExit;
2270 break;
2271 }
2272
2273 case 'd': /* domain */
2274 strDomain = ValueUnion.psz;
2275 break;
2276
2277 case 'v': /* Verbose */
2278 fVerbose = true;
2279 break;
2280
2281 case VINF_GETOPT_NOT_OPTION:
2282 {
2283 if (strTemplate.isEmpty())
2284 strTemplate = ValueUnion.psz;
2285 else
2286 return errorSyntax(USAGE_GUESTCONTROL,
2287 "More than one template specified!\n");
2288 break;
2289 }
2290
2291 default:
2292 return RTGetOptPrintError(ch, &ValueUnion);
2293 }
2294 }
2295
2296 if (strTemplate.isEmpty())
2297 return errorSyntax(USAGE_GUESTCONTROL, "No template specified!");
2298
2299 if (strUsername.isEmpty())
2300 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
2301
2302 if (!fDirectory)
2303 return errorSyntax(USAGE_GUESTCONTROL, "Creating temporary files is currently not supported!");
2304
2305 /*
2306 * Create the directories.
2307 */
2308 HRESULT hrc = S_OK;
2309 if (fVerbose)
2310 {
2311 if (fDirectory && !strTempDir.isEmpty())
2312 RTPrintf("Creating temporary directory from template '%s' in directory '%s' ...\n",
2313 strTemplate.c_str(), strTempDir.c_str());
2314 else if (fDirectory)
2315 RTPrintf("Creating temporary directory from template '%s' in default temporary directory ...\n",
2316 strTemplate.c_str());
2317 else if (!fDirectory && !strTempDir.isEmpty())
2318 RTPrintf("Creating temporary file from template '%s' in directory '%s' ...\n",
2319 strTemplate.c_str(), strTempDir.c_str());
2320 else if (!fDirectory)
2321 RTPrintf("Creating temporary file from template '%s' in default temporary directory ...\n",
2322 strTemplate.c_str());
2323 }
2324
2325 ComPtr<IGuestSession> pGuestSession;
2326 hrc = pGuest->CreateSession(Bstr(strUsername).raw(),
2327 Bstr(strPassword).raw(),
2328 Bstr(strDomain).raw(),
2329 Bstr("VBoxManage Guest Control MkTemp").raw(),
2330 pGuestSession.asOutParam());
2331 if (FAILED(hrc))
2332 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
2333
2334 if (fDirectory)
2335 {
2336 Bstr directory;
2337 hrc = pGuestSession->DirectoryCreateTemp(Bstr(strTemplate).raw(),
2338 fMode, Bstr(strTempDir).raw(),
2339 fSecure,
2340 directory.asOutParam());
2341 if (SUCCEEDED(hrc))
2342 RTPrintf("Directory name: %ls\n", directory.raw());
2343 }
2344 // else - temporary file not yet implemented
2345 if (FAILED(hrc))
2346 ctrlPrintError(pGuest, COM_IIDOF(IGuestSession)); /* Return code ignored, save original rc. */
2347
2348 if (!pGuestSession.isNull())
2349 pGuestSession->Close();
2350
2351 return FAILED(hrc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2352}
2353
2354static int handleCtrlStat(ComPtr<IGuest> pGuest, HandlerArg *pArg)
2355{
2356 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2357
2358 static const RTGETOPTDEF s_aOptions[] =
2359 {
2360 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
2361 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
2362 { "--format", 'c', RTGETOPT_REQ_STRING },
2363 { "--username", 'u', RTGETOPT_REQ_STRING },
2364 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
2365 { "--password", GETOPTDEF_STAT_PASSWORD, RTGETOPT_REQ_STRING },
2366 { "--domain", 'd', RTGETOPT_REQ_STRING },
2367 { "--terse", 't', RTGETOPT_REQ_NOTHING },
2368 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2369 };
2370
2371 int ch;
2372 RTGETOPTUNION ValueUnion;
2373 RTGETOPTSTATE GetState;
2374 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
2375 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2376
2377 Utf8Str strUsername;
2378 Utf8Str strPassword;
2379 Utf8Str strDomain;
2380
2381 bool fVerbose = false;
2382 DESTDIRMAP mapObjs;
2383
2384 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2385 {
2386 /* For options that require an argument, ValueUnion has received the value. */
2387 switch (ch)
2388 {
2389 case 'u': /* User name */
2390 strUsername = ValueUnion.psz;
2391 break;
2392
2393 case GETOPTDEF_STAT_PASSWORD: /* Password */
2394 strPassword = ValueUnion.psz;
2395 break;
2396
2397 case 'p': /* Password file */
2398 {
2399 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
2400 if (rcExit != RTEXITCODE_SUCCESS)
2401 return rcExit;
2402 break;
2403 }
2404
2405 case 'd': /* domain */
2406 strDomain = ValueUnion.psz;
2407 break;
2408
2409 case 'L': /* Dereference */
2410 case 'f': /* File-system */
2411 case 'c': /* Format */
2412 case 't': /* Terse */
2413 return errorSyntax(USAGE_GUESTCONTROL, "Command \"%s\" not implemented yet!",
2414 ValueUnion.psz);
2415 break; /* Never reached. */
2416
2417 case 'v': /* Verbose */
2418 fVerbose = true;
2419 break;
2420
2421 case VINF_GETOPT_NOT_OPTION:
2422 {
2423 mapObjs[ValueUnion.psz]; /* Add element to check to map. */
2424 break;
2425 }
2426
2427 default:
2428 return RTGetOptPrintError(ch, &ValueUnion);
2429 }
2430 }
2431
2432 uint32_t cObjs = mapObjs.size();
2433 if (!cObjs)
2434 return errorSyntax(USAGE_GUESTCONTROL, "No element(s) to check specified!");
2435
2436 if (strUsername.isEmpty())
2437 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
2438
2439 ComPtr<IGuestSession> pGuestSession;
2440 HRESULT hrc = pGuest->CreateSession(Bstr(strUsername).raw(),
2441 Bstr(strPassword).raw(),
2442 Bstr(strDomain).raw(),
2443 Bstr("VBoxManage Guest Control Stat").raw(),
2444 pGuestSession.asOutParam());
2445 if (FAILED(hrc))
2446 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
2447
2448 /*
2449 * Create the directories.
2450 */
2451 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2452 DESTDIRMAPITER it = mapObjs.begin();
2453 while (it != mapObjs.end())
2454 {
2455 if (fVerbose)
2456 RTPrintf("Checking for element \"%s\" ...\n", it->first.c_str());
2457
2458 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2459 hrc = pGuestSession->FileQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
2460 if (FAILED(hrc))
2461 hrc = pGuestSession->DirectoryQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
2462
2463 if (FAILED(hrc))
2464 {
2465 /* If there's at least one element which does not exist on the guest,
2466 * drop out with exitcode 1. */
2467 if (fVerbose)
2468 RTPrintf("Cannot stat for element \"%s\": No such element\n",
2469 it->first.c_str());
2470 rcExit = RTEXITCODE_FAILURE;
2471 }
2472 else
2473 {
2474 FsObjType_T objType;
2475 hrc = pFsObjInfo->COMGETTER(Type)(&objType);
2476 if (FAILED(hrc))
2477 return ctrlPrintError(pGuest, COM_IIDOF(IGuestFsObjInfo));
2478 switch (objType)
2479 {
2480 case FsObjType_File:
2481 RTPrintf("Element \"%s\" found: Is a file\n", it->first.c_str());
2482 break;
2483
2484 case FsObjType_Directory:
2485 RTPrintf("Element \"%s\" found: Is a directory\n", it->first.c_str());
2486 break;
2487
2488 case FsObjType_Symlink:
2489 RTPrintf("Element \"%s\" found: Is a symlink\n", it->first.c_str());
2490 break;
2491
2492 default:
2493 RTPrintf("Element \"%s\" found, type unknown (%ld)\n", it->first.c_str(), objType);
2494 break;
2495 }
2496
2497 /** @todo: Show more information about this element. */
2498 }
2499
2500 it++;
2501 }
2502
2503 if (!pGuestSession.isNull())
2504 pGuestSession->Close();
2505
2506 return rcExit;
2507}
2508
2509static int handleCtrlUpdateAdditions(ComPtr<IGuest> guest, HandlerArg *pArg)
2510{
2511 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2512
2513 /*
2514 * Check the syntax. We can deduce the correct syntax from the number of
2515 * arguments.
2516 */
2517 Utf8Str strSource;
2518 bool fVerbose = false;
2519
2520 static const RTGETOPTDEF s_aOptions[] =
2521 {
2522 { "--source", 's', RTGETOPT_REQ_STRING },
2523 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2524 };
2525
2526 int ch;
2527 RTGETOPTUNION ValueUnion;
2528 RTGETOPTSTATE GetState;
2529 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, 0);
2530
2531 int vrc = VINF_SUCCESS;
2532 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2533 && RT_SUCCESS(vrc))
2534 {
2535 switch (ch)
2536 {
2537 case 's':
2538 strSource = ValueUnion.psz;
2539 break;
2540
2541 case 'v':
2542 fVerbose = true;
2543 break;
2544
2545 default:
2546 return RTGetOptPrintError(ch, &ValueUnion);
2547 }
2548 }
2549
2550 if (fVerbose)
2551 RTPrintf("Updating Guest Additions ...\n");
2552
2553 HRESULT rc = S_OK;
2554 while (strSource.isEmpty())
2555 {
2556 ComPtr<ISystemProperties> pProperties;
2557 CHECK_ERROR_BREAK(pArg->virtualBox, COMGETTER(SystemProperties)(pProperties.asOutParam()));
2558 Bstr strISO;
2559 CHECK_ERROR_BREAK(pProperties, COMGETTER(DefaultAdditionsISO)(strISO.asOutParam()));
2560 strSource = strISO;
2561 break;
2562 }
2563
2564 /* Determine source if not set yet. */
2565 if (strSource.isEmpty())
2566 {
2567 RTMsgError("No Guest Additions source found or specified, aborting\n");
2568 vrc = VERR_FILE_NOT_FOUND;
2569 }
2570 else if (!RTFileExists(strSource.c_str()))
2571 {
2572 RTMsgError("Source \"%s\" does not exist!\n", strSource.c_str());
2573 vrc = VERR_FILE_NOT_FOUND;
2574 }
2575
2576 if (RT_SUCCESS(vrc))
2577 {
2578 if (fVerbose)
2579 RTPrintf("Using source: %s\n", strSource.c_str());
2580
2581 ComPtr<IProgress> pProgress;
2582
2583 SafeArray<AdditionsUpdateFlag_T> updateFlags; /* No flags set. */
2584 CHECK_ERROR(guest, UpdateGuestAdditions(Bstr(strSource).raw(),
2585 /* Wait for whole update process to complete. */
2586 ComSafeArrayAsInParam(updateFlags),
2587 pProgress.asOutParam()));
2588 if (FAILED(rc))
2589 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
2590 else
2591 {
2592 if (fVerbose)
2593 rc = showProgress(pProgress);
2594 else
2595 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
2596
2597 if (SUCCEEDED(rc))
2598 CHECK_PROGRESS_ERROR(pProgress, ("Guest additions update failed"));
2599 vrc = ctrlPrintProgressError(pProgress);
2600 if ( RT_SUCCESS(vrc)
2601 && fVerbose)
2602 {
2603 RTPrintf("Guest Additions update successful\n");
2604 }
2605 }
2606 }
2607
2608 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2609}
2610
2611/**
2612 * Access the guest control store.
2613 *
2614 * @returns program exit code.
2615 * @note see the command line API description for parameters
2616 */
2617int handleGuestControl(HandlerArg *pArg)
2618{
2619 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2620
2621#ifdef DEBUG_andy_disabled
2622 if (RT_FAILURE(tstTranslatePath()))
2623 return RTEXITCODE_FAILURE;
2624#endif
2625
2626 HandlerArg arg = *pArg;
2627 arg.argc = pArg->argc - 2; /* Skip VM name and sub command. */
2628 arg.argv = pArg->argv + 2; /* Same here. */
2629
2630 ComPtr<IGuest> guest;
2631 int vrc = ctrlInitVM(pArg, pArg->argv[0] /* VM Name */, &guest);
2632 if (RT_SUCCESS(vrc))
2633 {
2634 int rcExit;
2635 if (pArg->argc < 2)
2636 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No sub command specified!");
2637 else if ( !strcmp(pArg->argv[1], "exec")
2638 || !strcmp(pArg->argv[1], "execute"))
2639 rcExit = handleCtrlExecProgram(guest, &arg);
2640 else if (!strcmp(pArg->argv[1], "copyfrom"))
2641 rcExit = handleCtrlCopy(guest, &arg, false /* Guest to host */);
2642 else if ( !strcmp(pArg->argv[1], "copyto")
2643 || !strcmp(pArg->argv[1], "cp"))
2644 rcExit = handleCtrlCopy(guest, &arg, true /* Host to guest */);
2645 else if ( !strcmp(pArg->argv[1], "createdirectory")
2646 || !strcmp(pArg->argv[1], "createdir")
2647 || !strcmp(pArg->argv[1], "mkdir")
2648 || !strcmp(pArg->argv[1], "md"))
2649 rcExit = handleCtrlCreateDirectory(guest, &arg);
2650 else if ( !strcmp(pArg->argv[1], "createtemporary")
2651 || !strcmp(pArg->argv[1], "createtemp")
2652 || !strcmp(pArg->argv[1], "mktemp"))
2653 rcExit = handleCtrlCreateTemp(guest, &arg);
2654 else if ( !strcmp(pArg->argv[1], "stat"))
2655 rcExit = handleCtrlStat(guest, &arg);
2656 else if ( !strcmp(pArg->argv[1], "updateadditions")
2657 || !strcmp(pArg->argv[1], "updateadds"))
2658 rcExit = handleCtrlUpdateAdditions(guest, &arg);
2659 else
2660 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Unknown sub command '%s' specified!", pArg->argv[1]);
2661
2662 ctrlUninitVM(pArg);
2663 return rcExit;
2664 }
2665 return RTEXITCODE_FAILURE;
2666}
2667
2668#endif /* !VBOX_ONLY_DOCS */
2669
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