VirtualBox

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

Last change on this file since 42808 was 42808, checked in by vboxsync, 13 years ago

Guest Control 2.0: Update.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 86.8 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 42808 2012-08-14 14:01:11Z 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#ifdef DEBUG
810 if (fVerbose)
811 RTPrintf("rc=%Rrc, waitResult=%ld\n", rc, waitResult);
812#endif
813 switch (waitResult)
814 {
815 case ProcessWaitResult_Start:
816 {
817 if (fVerbose)
818 {
819 ULONG uPID = 0;
820 rc = pProcess->COMGETTER(PID)(&uPID);
821 if (FAILED(rc))
822 {
823 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
824 return RTEXITCODE_FAILURE;
825 }
826 RTPrintf("Process '%s' (PID: %u) started\n", strCmd.c_str(), uPID);
827 }
828 break;
829 }
830 case ProcessWaitResult_StdOut:
831 fReadStdOut = true;
832 break;
833 case ProcessWaitResult_StdErr:
834 fReadStdErr = true;
835 break;
836 case ProcessWaitResult_Terminate:
837 /* Process terminated, we're done */
838 fCompleted = true;
839 break;
840 case ProcessWaitResult_Any:
841 fReadStdOut = fReadStdErr = true;
842 break;
843 default:
844 /* Ignore all other results, let the timeout expire */;
845 break;
846 }
847
848 if (fReadStdOut) /* Do we need to fetch stdout data? */
849 {
850 vrc = ctrlExecPrintOutput(pProcess, g_pStdOut, 1 /* StdOut */);
851 fReadStdOut = false;
852 }
853
854 if (fReadStdErr) /* Do we need to fetch stdout data? */
855 {
856 vrc = ctrlExecPrintOutput(pProcess, g_pStdErr, 2 /* StdErr */);
857 fReadStdErr = false;
858 }
859
860 if (RT_FAILURE(vrc))
861 break;
862
863 } /* while */
864
865 /* Report status back to the user. */
866 if (fCompleted)
867 {
868 ProcessStatus_T status;
869 rc = pProcess->COMGETTER(Status)(&status);
870 if (FAILED(rc))
871 {
872 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
873 return RTEXITCODE_FAILURE;
874 }
875 LONG exitCode;
876 rc = pProcess->COMGETTER(ExitCode)(&exitCode);
877 if (FAILED(rc))
878 {
879 ctrlPrintError(pProcess, COM_IIDOF(IProcess));
880 return RTEXITCODE_FAILURE;
881 }
882 if (fVerbose)
883 RTPrintf("Exit code=%u (Status=%u [%s])\n", exitCode, status, ctrlExecProcessStatusToText(status));
884 return ctrlExecProcessStatusToExitCode(status, exitCode);
885 }
886 else
887 {
888 if (fVerbose)
889 RTPrintf("Process execution aborted!\n");
890 return EXITCODEEXEC_TERM_ABEND;
891 }
892 }
893
894 return RT_FAILURE(vrc) || FAILED(rc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
895}
896
897/**
898 * Creates a copy context structure which then can be used with various
899 * guest control copy functions. Needs to be free'd with ctrlCopyContextFree().
900 *
901 * @return IPRT status code.
902 * @param pGuest Pointer to IGuest interface to use.
903 * @param fVerbose Flag indicating if we want to run in verbose mode.
904 * @param fDryRun Flag indicating if we want to run a dry run only.
905 * @param fHostToGuest Flag indicating if we want to copy from host to guest
906 * or vice versa.
907 * @param strUsername Username of account to use on the guest side.
908 * @param strPassword Password of account to use.
909 * @param strDomain Domain of account to use.
910 * @param strSessionName Session name (only for identification purposes).
911 * @param ppContext Pointer which receives the allocated copy context.
912 */
913static int ctrlCopyContextCreate(IGuest *pGuest, bool fVerbose, bool fDryRun,
914 bool fHostToGuest, const Utf8Str &strUsername,
915 const Utf8Str &strPassword, const Utf8Str &strDomain,
916 const Utf8Str &strSessionName,
917 PCOPYCONTEXT *ppContext)
918{
919 AssertPtrReturn(pGuest, VERR_INVALID_POINTER);
920
921 PCOPYCONTEXT pContext = new COPYCONTEXT();
922 AssertPtrReturn(pContext, VERR_NO_MEMORY); /**< @todo r=klaus cannot happen with new */
923 ComPtr<IGuestSession> pGuestSession;
924 HRESULT rc = pGuest->CreateSession(Bstr(strUsername).raw(),
925 Bstr(strPassword).raw(),
926 Bstr(strDomain).raw(),
927 Bstr(strSessionName).raw(),
928 pGuestSession.asOutParam());
929 if (FAILED(rc))
930 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
931
932 pContext->fVerbose = fVerbose;
933 pContext->fDryRun = fDryRun;
934 pContext->fHostToGuest = fHostToGuest;
935 pContext->pGuestSession = pGuestSession;
936
937 *ppContext = pContext;
938
939 return VINF_SUCCESS;
940}
941
942/**
943 * Frees are previously allocated copy context structure.
944 *
945 * @param pContext Pointer to copy context to free.
946 */
947static void ctrlCopyContextFree(PCOPYCONTEXT pContext)
948{
949 if (pContext)
950 {
951 if (pContext->pGuestSession)
952 pContext->pGuestSession->Close();
953 delete pContext;
954 }
955}
956
957/**
958 * Translates a source path to a destination path (can be both sides,
959 * either host or guest). The source root is needed to determine the start
960 * of the relative source path which also needs to present in the destination
961 * path.
962 *
963 * @return IPRT status code.
964 * @param pszSourceRoot Source root path. No trailing directory slash!
965 * @param pszSource Actual source to transform. Must begin with
966 * the source root path!
967 * @param pszDest Destination path.
968 * @param ppszTranslated Pointer to the allocated, translated destination
969 * path. Must be free'd with RTStrFree().
970 */
971static int ctrlCopyTranslatePath(const char *pszSourceRoot, const char *pszSource,
972 const char *pszDest, char **ppszTranslated)
973{
974 AssertPtrReturn(pszSourceRoot, VERR_INVALID_POINTER);
975 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
976 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
977 AssertPtrReturn(ppszTranslated, VERR_INVALID_POINTER);
978 AssertReturn(RTPathStartsWith(pszSource, pszSourceRoot), VERR_INVALID_PARAMETER);
979
980 /* Construct the relative dest destination path by "subtracting" the
981 * source from the source root, e.g.
982 *
983 * source root path = "e:\foo\", source = "e:\foo\bar"
984 * dest = "d:\baz\"
985 * translated = "d:\baz\bar\"
986 */
987 char szTranslated[RTPATH_MAX];
988 size_t srcOff = strlen(pszSourceRoot);
989 AssertReturn(srcOff, VERR_INVALID_PARAMETER);
990
991 char *pszDestPath = RTStrDup(pszDest);
992 AssertPtrReturn(pszDestPath, VERR_NO_MEMORY);
993
994 int vrc;
995 if (!RTPathFilename(pszDestPath))
996 {
997 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
998 pszDestPath, &pszSource[srcOff]);
999 }
1000 else
1001 {
1002 char *pszDestFileName = RTStrDup(RTPathFilename(pszDestPath));
1003 if (pszDestFileName)
1004 {
1005 RTPathStripFilename(pszDestPath);
1006 vrc = RTPathJoin(szTranslated, sizeof(szTranslated),
1007 pszDestPath, pszDestFileName);
1008 RTStrFree(pszDestFileName);
1009 }
1010 else
1011 vrc = VERR_NO_MEMORY;
1012 }
1013 RTStrFree(pszDestPath);
1014
1015 if (RT_SUCCESS(vrc))
1016 {
1017 *ppszTranslated = RTStrDup(szTranslated);
1018#if 0
1019 RTPrintf("Root: %s, Source: %s, Dest: %s, Translated: %s\n",
1020 pszSourceRoot, pszSource, pszDest, *ppszTranslated);
1021#endif
1022 }
1023 return vrc;
1024}
1025
1026#ifdef DEBUG_andy
1027static int tstTranslatePath()
1028{
1029 RTAssertSetMayPanic(false /* Do not freak out, please. */);
1030
1031 static struct
1032 {
1033 const char *pszSourceRoot;
1034 const char *pszSource;
1035 const char *pszDest;
1036 const char *pszTranslated;
1037 int iResult;
1038 } aTests[] =
1039 {
1040 /* Invalid stuff. */
1041 { NULL, NULL, NULL, NULL, VERR_INVALID_POINTER },
1042#ifdef RT_OS_WINDOWS
1043 /* Windows paths. */
1044 { "c:\\foo", "c:\\foo\\bar.txt", "c:\\test", "c:\\test\\bar.txt", VINF_SUCCESS },
1045 { "c:\\foo", "c:\\foo\\baz\\bar.txt", "c:\\test", "c:\\test\\baz\\bar.txt", VINF_SUCCESS },
1046#else /* RT_OS_WINDOWS */
1047 { "/home/test/foo", "/home/test/foo/bar.txt", "/opt/test", "/opt/test/bar.txt", VINF_SUCCESS },
1048 { "/home/test/foo", "/home/test/foo/baz/bar.txt", "/opt/test", "/opt/test/baz/bar.txt", VINF_SUCCESS },
1049#endif /* !RT_OS_WINDOWS */
1050 /* Mixed paths*/
1051 /** @todo */
1052 { NULL }
1053 };
1054
1055 size_t iTest = 0;
1056 for (iTest; iTest < RT_ELEMENTS(aTests); iTest++)
1057 {
1058 RTPrintf("=> Test %d\n", iTest);
1059 RTPrintf("\tSourceRoot=%s, Source=%s, Dest=%s\n",
1060 aTests[iTest].pszSourceRoot, aTests[iTest].pszSource, aTests[iTest].pszDest);
1061
1062 char *pszTranslated = NULL;
1063 int iResult = ctrlCopyTranslatePath(aTests[iTest].pszSourceRoot, aTests[iTest].pszSource,
1064 aTests[iTest].pszDest, &pszTranslated);
1065 if (iResult != aTests[iTest].iResult)
1066 {
1067 RTPrintf("\tReturned %Rrc, expected %Rrc\n",
1068 iResult, aTests[iTest].iResult);
1069 }
1070 else if ( pszTranslated
1071 && strcmp(pszTranslated, aTests[iTest].pszTranslated))
1072 {
1073 RTPrintf("\tReturned translated path %s, expected %s\n",
1074 pszTranslated, aTests[iTest].pszTranslated);
1075 }
1076
1077 if (pszTranslated)
1078 {
1079 RTPrintf("\tTranslated=%s\n", pszTranslated);
1080 RTStrFree(pszTranslated);
1081 }
1082 }
1083
1084 return VINF_SUCCESS; /* @todo */
1085}
1086#endif
1087
1088/**
1089 * Creates a directory on the destination, based on the current copy
1090 * context.
1091 *
1092 * @return IPRT status code.
1093 * @param pContext Pointer to current copy control context.
1094 * @param pszDir Directory to create.
1095 */
1096static int ctrlCopyDirCreate(PCOPYCONTEXT pContext, const char *pszDir)
1097{
1098 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1099 AssertPtrReturn(pszDir, VERR_INVALID_POINTER);
1100
1101 bool fDirExists;
1102 int vrc = ctrlCopyDirExists(pContext, pContext->fHostToGuest, pszDir, &fDirExists);
1103 if ( RT_SUCCESS(vrc)
1104 && fDirExists)
1105 {
1106 if (pContext->fVerbose)
1107 RTPrintf("Directory \"%s\" already exists\n", pszDir);
1108 return VINF_SUCCESS;
1109 }
1110
1111 /* If querying for a directory existence fails there's no point of even trying
1112 * to create such a directory. */
1113 if (RT_FAILURE(vrc))
1114 return vrc;
1115
1116 if (pContext->fVerbose)
1117 RTPrintf("Creating directory \"%s\" ...\n", pszDir);
1118
1119 if (pContext->fDryRun)
1120 return VINF_SUCCESS;
1121
1122 if (pContext->fHostToGuest) /* We want to create directories on the guest. */
1123 {
1124 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
1125 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
1126 HRESULT rc = pContext->pGuestSession->DirectoryCreate(Bstr(pszDir).raw(),
1127 0700, ComSafeArrayAsInParam(dirCreateFlags));
1128 if (FAILED(rc))
1129 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1130 }
1131 else /* ... or on the host. */
1132 {
1133 vrc = RTDirCreateFullPath(pszDir, 0700);
1134 if (vrc == VERR_ALREADY_EXISTS)
1135 vrc = VINF_SUCCESS;
1136 }
1137 return vrc;
1138}
1139
1140/**
1141 * Checks whether a specific host/guest directory exists.
1142 *
1143 * @return IPRT status code.
1144 * @param pContext Pointer to current copy control context.
1145 * @param bGuest true if directory needs to be checked on the guest
1146 * or false if on the host.
1147 * @param pszDir Actual directory to check.
1148 * @param fExists Pointer which receives the result if the
1149 * given directory exists or not.
1150 */
1151static int ctrlCopyDirExists(PCOPYCONTEXT pContext, bool bGuest,
1152 const char *pszDir, bool *fExists)
1153{
1154 AssertPtrReturn(pContext, false);
1155 AssertPtrReturn(pszDir, false);
1156 AssertPtrReturn(fExists, false);
1157
1158 int vrc = VINF_SUCCESS;
1159 if (bGuest)
1160 {
1161 BOOL fDirExists = FALSE;
1162 HRESULT rc = pContext->pGuestSession->DirectoryExists(Bstr(pszDir).raw(), &fDirExists);
1163 if (FAILED(rc))
1164 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1165 else
1166 *fExists = fDirExists ? true : false;
1167 }
1168 else
1169 *fExists = RTDirExists(pszDir);
1170 return vrc;
1171}
1172
1173/**
1174 * Checks whether a specific directory exists on the destination, based
1175 * on the current copy context.
1176 *
1177 * @return IPRT status code.
1178 * @param pContext Pointer to current copy control context.
1179 * @param pszDir Actual directory to check.
1180 * @param fExists Pointer which receives the result if the
1181 * given directory exists or not.
1182 */
1183static int ctrlCopyDirExistsOnDest(PCOPYCONTEXT pContext, const char *pszDir,
1184 bool *fExists)
1185{
1186 return ctrlCopyDirExists(pContext, pContext->fHostToGuest,
1187 pszDir, fExists);
1188}
1189
1190/**
1191 * Checks whether a specific directory exists on the source, based
1192 * on the current copy context.
1193 *
1194 * @return IPRT status code.
1195 * @param pContext Pointer to current copy control context.
1196 * @param pszDir Actual directory to check.
1197 * @param fExists Pointer which receives the result if the
1198 * given directory exists or not.
1199 */
1200static int ctrlCopyDirExistsOnSource(PCOPYCONTEXT pContext, const char *pszDir,
1201 bool *fExists)
1202{
1203 return ctrlCopyDirExists(pContext, !pContext->fHostToGuest,
1204 pszDir, fExists);
1205}
1206
1207/**
1208 * Checks whether a specific host/guest file exists.
1209 *
1210 * @return IPRT status code.
1211 * @param pContext Pointer to current copy control context.
1212 * @param bGuest true if file needs to be checked on the guest
1213 * or false if on the host.
1214 * @param pszFile Actual file to check.
1215 * @param fExists Pointer which receives the result if the
1216 * given file exists or not.
1217 */
1218static int ctrlCopyFileExists(PCOPYCONTEXT pContext, bool bOnGuest,
1219 const char *pszFile, bool *fExists)
1220{
1221 AssertPtrReturn(pContext, false);
1222 AssertPtrReturn(pszFile, false);
1223 AssertPtrReturn(fExists, false);
1224
1225 int vrc = VINF_SUCCESS;
1226 if (bOnGuest)
1227 {
1228 BOOL fFileExists = FALSE;
1229 HRESULT rc = pContext->pGuestSession->FileExists(Bstr(pszFile).raw(), &fFileExists);
1230 if (FAILED(rc))
1231 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1232 else
1233 *fExists = fFileExists ? true : false;
1234 }
1235 else
1236 *fExists = RTFileExists(pszFile);
1237 return vrc;
1238}
1239
1240/**
1241 * Checks whether a specific file exists on the destination, based on the
1242 * current copy context.
1243 *
1244 * @return IPRT status code.
1245 * @param pContext Pointer to current copy control context.
1246 * @param pszFile Actual file to check.
1247 * @param fExists Pointer which receives the result if the
1248 * given file exists or not.
1249 */
1250static int ctrlCopyFileExistsOnDest(PCOPYCONTEXT pContext, const char *pszFile,
1251 bool *fExists)
1252{
1253 return ctrlCopyFileExists(pContext, pContext->fHostToGuest,
1254 pszFile, fExists);
1255}
1256
1257/**
1258 * Checks whether a specific file exists on the source, based on the
1259 * current copy context.
1260 *
1261 * @return IPRT status code.
1262 * @param pContext Pointer to current copy control context.
1263 * @param pszFile Actual file to check.
1264 * @param fExists Pointer which receives the result if the
1265 * given file exists or not.
1266 */
1267static int ctrlCopyFileExistsOnSource(PCOPYCONTEXT pContext, const char *pszFile,
1268 bool *fExists)
1269{
1270 return ctrlCopyFileExists(pContext, !pContext->fHostToGuest,
1271 pszFile, fExists);
1272}
1273
1274/**
1275 * Copies a source file to the destination.
1276 *
1277 * @return IPRT status code.
1278 * @param pContext Pointer to current copy control context.
1279 * @param pszFileSource Source file to copy to the destination.
1280 * @param pszFileDest Name of copied file on the destination.
1281 * @param fFlags Copy flags. No supported at the moment and needs
1282 * to be set to 0.
1283 */
1284static int ctrlCopyFileToDest(PCOPYCONTEXT pContext, const char *pszFileSource,
1285 const char *pszFileDest, uint32_t fFlags)
1286{
1287 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1288 AssertPtrReturn(pszFileSource, VERR_INVALID_POINTER);
1289 AssertPtrReturn(pszFileDest, VERR_INVALID_POINTER);
1290 AssertReturn(!fFlags, VERR_INVALID_POINTER); /* No flags supported yet. */
1291
1292 if (pContext->fVerbose)
1293 RTPrintf("Copying \"%s\" to \"%s\" ...\n",
1294 pszFileSource, pszFileDest);
1295
1296 if (pContext->fDryRun)
1297 return VINF_SUCCESS;
1298
1299 int vrc = VINF_SUCCESS;
1300 ComPtr<IProgress> pProgress;
1301 HRESULT rc;
1302 if (pContext->fHostToGuest)
1303 {
1304 SafeArray<CopyFileFlag_T> copyFlags;
1305 rc = pContext->pGuestSession->CopyTo(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
1306 ComSafeArrayAsInParam(copyFlags),
1307
1308 pProgress.asOutParam());
1309 }
1310 else
1311 {
1312 SafeArray<CopyFileFlag_T> copyFlags;
1313 rc = pContext->pGuestSession->CopyFrom(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
1314 ComSafeArrayAsInParam(copyFlags),
1315 pProgress.asOutParam());
1316 }
1317
1318 if (FAILED(rc))
1319 {
1320 vrc = ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1321 }
1322 else
1323 {
1324 if (pContext->fVerbose)
1325 rc = showProgress(pProgress);
1326 else
1327 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
1328 if (SUCCEEDED(rc))
1329 CHECK_PROGRESS_ERROR(pProgress, ("File copy failed"));
1330 vrc = ctrlPrintProgressError(pProgress);
1331 }
1332
1333 return vrc;
1334}
1335
1336/**
1337 * Copys a directory (tree) from host to the guest.
1338 *
1339 * @return IPRT status code.
1340 * @param pContext Pointer to current copy control context.
1341 * @param pszSource Source directory on the host to copy to the guest.
1342 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
1343 * @param pszDest Destination directory on the guest.
1344 * @param fFlags Copy flags, such as recursive copying.
1345 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
1346 * is needed for recursion.
1347 */
1348static int ctrlCopyDirToGuest(PCOPYCONTEXT pContext,
1349 const char *pszSource, const char *pszFilter,
1350 const char *pszDest, uint32_t fFlags,
1351 const char *pszSubDir /* For recursion. */)
1352{
1353 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1354 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1355 /* Filter is optional. */
1356 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1357 /* Sub directory is optional. */
1358
1359 /*
1360 * Construct current path.
1361 */
1362 char szCurDir[RTPATH_MAX];
1363 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
1364 if (RT_SUCCESS(vrc) && pszSubDir)
1365 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
1366
1367 if (pContext->fVerbose)
1368 RTPrintf("Processing host directory: %s\n", szCurDir);
1369
1370 /* Flag indicating whether the current directory was created on the
1371 * target or not. */
1372 bool fDirCreated = false;
1373
1374 /*
1375 * Open directory without a filter - RTDirOpenFiltered unfortunately
1376 * cannot handle sub directories so we have to do the filtering ourselves.
1377 */
1378 PRTDIR pDir = NULL;
1379 if (RT_SUCCESS(vrc))
1380 {
1381 vrc = RTDirOpen(&pDir, szCurDir);
1382 if (RT_FAILURE(vrc))
1383 pDir = NULL;
1384 }
1385 if (RT_SUCCESS(vrc))
1386 {
1387 /*
1388 * Enumerate the directory tree.
1389 */
1390 while (RT_SUCCESS(vrc))
1391 {
1392 RTDIRENTRY DirEntry;
1393 vrc = RTDirRead(pDir, &DirEntry, NULL);
1394 if (RT_FAILURE(vrc))
1395 {
1396 if (vrc == VERR_NO_MORE_FILES)
1397 vrc = VINF_SUCCESS;
1398 break;
1399 }
1400 switch (DirEntry.enmType)
1401 {
1402 case RTDIRENTRYTYPE_DIRECTORY:
1403 {
1404 /* Skip "." and ".." entries. */
1405 if ( !strcmp(DirEntry.szName, ".")
1406 || !strcmp(DirEntry.szName, ".."))
1407 break;
1408
1409 if (pContext->fVerbose)
1410 RTPrintf("Directory: %s\n", DirEntry.szName);
1411
1412 if (fFlags & CopyFileFlag_Recursive)
1413 {
1414 char *pszNewSub = NULL;
1415 if (pszSubDir)
1416 pszNewSub = RTPathJoinA(pszSubDir, DirEntry.szName);
1417 else
1418 {
1419 pszNewSub = RTStrDup(DirEntry.szName);
1420 RTPathStripTrailingSlash(pszNewSub);
1421 }
1422
1423 if (pszNewSub)
1424 {
1425 vrc = ctrlCopyDirToGuest(pContext,
1426 pszSource, pszFilter,
1427 pszDest, fFlags, pszNewSub);
1428 RTStrFree(pszNewSub);
1429 }
1430 else
1431 vrc = VERR_NO_MEMORY;
1432 }
1433 break;
1434 }
1435
1436 case RTDIRENTRYTYPE_SYMLINK:
1437 if ( (fFlags & CopyFileFlag_Recursive)
1438 && (fFlags & CopyFileFlag_FollowLinks))
1439 {
1440 /* Fall through to next case is intentional. */
1441 }
1442 else
1443 break;
1444
1445 case RTDIRENTRYTYPE_FILE:
1446 {
1447 if ( pszFilter
1448 && !RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
1449 {
1450 break; /* Filter does not match. */
1451 }
1452
1453 if (pContext->fVerbose)
1454 RTPrintf("File: %s\n", DirEntry.szName);
1455
1456 if (!fDirCreated)
1457 {
1458 char *pszDestDir;
1459 vrc = ctrlCopyTranslatePath(pszSource, szCurDir,
1460 pszDest, &pszDestDir);
1461 if (RT_SUCCESS(vrc))
1462 {
1463 vrc = ctrlCopyDirCreate(pContext, pszDestDir);
1464 RTStrFree(pszDestDir);
1465
1466 fDirCreated = true;
1467 }
1468 }
1469
1470 if (RT_SUCCESS(vrc))
1471 {
1472 char *pszFileSource = RTPathJoinA(szCurDir, DirEntry.szName);
1473 if (pszFileSource)
1474 {
1475 char *pszFileDest;
1476 vrc = ctrlCopyTranslatePath(pszSource, pszFileSource,
1477 pszDest, &pszFileDest);
1478 if (RT_SUCCESS(vrc))
1479 {
1480 vrc = ctrlCopyFileToDest(pContext, pszFileSource,
1481 pszFileDest, 0 /* Flags */);
1482 RTStrFree(pszFileDest);
1483 }
1484 RTStrFree(pszFileSource);
1485 }
1486 }
1487 break;
1488 }
1489
1490 default:
1491 break;
1492 }
1493 if (RT_FAILURE(vrc))
1494 break;
1495 }
1496
1497 RTDirClose(pDir);
1498 }
1499 return vrc;
1500}
1501
1502/**
1503 * Copys a directory (tree) from guest to the host.
1504 *
1505 * @return IPRT status code.
1506 * @param pContext Pointer to current copy control context.
1507 * @param pszSource Source directory on the guest to copy to the host.
1508 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
1509 * @param pszDest Destination directory on the host.
1510 * @param fFlags Copy flags, such as recursive copying.
1511 * @param pszSubDir Current sub directory to handle. Needs to NULL and only
1512 * is needed for recursion.
1513 */
1514static int ctrlCopyDirToHost(PCOPYCONTEXT pContext,
1515 const char *pszSource, const char *pszFilter,
1516 const char *pszDest, uint32_t fFlags,
1517 const char *pszSubDir /* For recursion. */)
1518{
1519 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1520 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1521 /* Filter is optional. */
1522 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1523 /* Sub directory is optional. */
1524
1525 /*
1526 * Construct current path.
1527 */
1528 char szCurDir[RTPATH_MAX];
1529 int vrc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
1530 if (RT_SUCCESS(vrc) && pszSubDir)
1531 vrc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
1532
1533 if (RT_FAILURE(vrc))
1534 return vrc;
1535
1536 if (pContext->fVerbose)
1537 RTPrintf("Processing guest directory: %s\n", szCurDir);
1538
1539 /* Flag indicating whether the current directory was created on the
1540 * target or not. */
1541 bool fDirCreated = false;
1542 SafeArray<DirectoryOpenFlag_T> dirOpenFlags; /* No flags supported yet. */
1543 ComPtr<IGuestDirectory> pDirectory;
1544 HRESULT rc = pContext->pGuestSession->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(),
1545 ComSafeArrayAsInParam(dirOpenFlags),
1546 pDirectory.asOutParam());
1547 if (FAILED(rc))
1548 return ctrlPrintError(pContext->pGuestSession, COM_IIDOF(IGuestSession));
1549 ComPtr<IFsObjInfo> dirEntry;
1550 while (true)
1551 {
1552 rc = pDirectory->Read(dirEntry.asOutParam());
1553 if (FAILED(rc))
1554 break;
1555
1556 FsObjType_T enmType;
1557 dirEntry->COMGETTER(Type)(&enmType);
1558
1559 Bstr strName;
1560 dirEntry->COMGETTER(Name)(strName.asOutParam());
1561
1562 switch (enmType)
1563 {
1564 case FsObjType_Directory:
1565 {
1566 Assert(!strName.isEmpty());
1567
1568 /* Skip "." and ".." entries. */
1569 if ( !strName.compare(Bstr("."))
1570 || !strName.compare(Bstr("..")))
1571 break;
1572
1573 if (pContext->fVerbose)
1574 {
1575 Utf8Str strDir(strName);
1576 RTPrintf("Directory: %s\n", strDir.c_str());
1577 }
1578
1579 if (fFlags & CopyFileFlag_Recursive)
1580 {
1581 Utf8Str strDir(strName);
1582 char *pszNewSub = NULL;
1583 if (pszSubDir)
1584 pszNewSub = RTPathJoinA(pszSubDir, strDir.c_str());
1585 else
1586 {
1587 pszNewSub = RTStrDup(strDir.c_str());
1588 RTPathStripTrailingSlash(pszNewSub);
1589 }
1590 if (pszNewSub)
1591 {
1592 vrc = ctrlCopyDirToHost(pContext,
1593 pszSource, pszFilter,
1594 pszDest, fFlags, pszNewSub);
1595 RTStrFree(pszNewSub);
1596 }
1597 else
1598 vrc = VERR_NO_MEMORY;
1599 }
1600 break;
1601 }
1602
1603 case FsObjType_Symlink:
1604 if ( (fFlags & CopyFileFlag_Recursive)
1605 && (fFlags & CopyFileFlag_FollowLinks))
1606 {
1607 /* Fall through to next case is intentional. */
1608 }
1609 else
1610 break;
1611
1612 case FsObjType_File:
1613 {
1614 Assert(!strName.isEmpty());
1615
1616 Utf8Str strFile(strName);
1617 if ( pszFilter
1618 && !RTStrSimplePatternMatch(pszFilter, strFile.c_str()))
1619 {
1620 break; /* Filter does not match. */
1621 }
1622
1623 if (pContext->fVerbose)
1624 RTPrintf("File: %s\n", strFile.c_str());
1625
1626 if (!fDirCreated)
1627 {
1628 char *pszDestDir;
1629 vrc = ctrlCopyTranslatePath(pszSource, szCurDir,
1630 pszDest, &pszDestDir);
1631 if (RT_SUCCESS(vrc))
1632 {
1633 vrc = ctrlCopyDirCreate(pContext, pszDestDir);
1634 RTStrFree(pszDestDir);
1635
1636 fDirCreated = true;
1637 }
1638 }
1639
1640 if (RT_SUCCESS(vrc))
1641 {
1642 char *pszFileSource = RTPathJoinA(szCurDir, strFile.c_str());
1643 if (pszFileSource)
1644 {
1645 char *pszFileDest;
1646 vrc = ctrlCopyTranslatePath(pszSource, pszFileSource,
1647 pszDest, &pszFileDest);
1648 if (RT_SUCCESS(vrc))
1649 {
1650 vrc = ctrlCopyFileToDest(pContext, pszFileSource,
1651 pszFileDest, 0 /* Flags */);
1652 RTStrFree(pszFileDest);
1653 }
1654 RTStrFree(pszFileSource);
1655 }
1656 else
1657 vrc = VERR_NO_MEMORY;
1658 }
1659 break;
1660 }
1661
1662 default:
1663 RTPrintf("Warning: Directory entry of type %ld not handled, skipping ...\n",
1664 enmType);
1665 break;
1666 }
1667
1668 if (RT_FAILURE(vrc))
1669 break;
1670 }
1671
1672 if (RT_UNLIKELY(FAILED(rc)))
1673 {
1674 switch (rc)
1675 {
1676 case E_ABORT: /* No more directory entries left to process. */
1677 break;
1678
1679 case VBOX_E_FILE_ERROR: /* Current entry cannot be accessed to
1680 to missing rights. */
1681 {
1682 RTPrintf("Warning: Cannot access \"%s\", skipping ...\n",
1683 szCurDir);
1684 break;
1685 }
1686
1687 default:
1688 vrc = ctrlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
1689 break;
1690 }
1691 }
1692
1693 HRESULT rc2 = pDirectory->Close();
1694 if (FAILED(rc2))
1695 {
1696 int vrc2 = ctrlPrintError(pDirectory, COM_IIDOF(IGuestDirectory));
1697 if (RT_SUCCESS(vrc))
1698 vrc = vrc2;
1699 }
1700 else if (SUCCEEDED(rc))
1701 rc = rc2;
1702
1703 return vrc;
1704}
1705
1706/**
1707 * Copys a directory (tree) to the destination, based on the current copy
1708 * context.
1709 *
1710 * @return IPRT status code.
1711 * @param pContext Pointer to current copy control context.
1712 * @param pszSource Source directory to copy to the destination.
1713 * @param pszFilter DOS-style wildcard filter (?, *). Optional.
1714 * @param pszDest Destination directory where to copy in the source
1715 * source directory.
1716 * @param fFlags Copy flags, such as recursive copying.
1717 */
1718static int ctrlCopyDirToDest(PCOPYCONTEXT pContext,
1719 const char *pszSource, const char *pszFilter,
1720 const char *pszDest, uint32_t fFlags)
1721{
1722 if (pContext->fHostToGuest)
1723 return ctrlCopyDirToGuest(pContext, pszSource, pszFilter,
1724 pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
1725 return ctrlCopyDirToHost(pContext, pszSource, pszFilter,
1726 pszDest, fFlags, NULL /* Sub directory, only for recursion. */);
1727}
1728
1729/**
1730 * Creates a source root by stripping file names or filters of the specified source.
1731 *
1732 * @return IPRT status code.
1733 * @param pszSource Source to create source root for.
1734 * @param ppszSourceRoot Pointer that receives the allocated source root. Needs
1735 * to be free'd with ctrlCopyFreeSourceRoot().
1736 */
1737static int ctrlCopyCreateSourceRoot(const char *pszSource, char **ppszSourceRoot)
1738{
1739 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1740 AssertPtrReturn(ppszSourceRoot, VERR_INVALID_POINTER);
1741
1742 char *pszNewRoot = RTStrDup(pszSource);
1743 AssertPtrReturn(pszNewRoot, VERR_NO_MEMORY);
1744
1745 size_t lenRoot = strlen(pszNewRoot);
1746 if ( lenRoot
1747 && pszNewRoot[lenRoot - 1] == '/'
1748 && pszNewRoot[lenRoot - 1] == '\\'
1749 && lenRoot > 1
1750 && pszNewRoot[lenRoot - 2] == '/'
1751 && pszNewRoot[lenRoot - 2] == '\\')
1752 {
1753 *ppszSourceRoot = pszNewRoot;
1754 if (lenRoot > 1)
1755 *ppszSourceRoot[lenRoot - 2] = '\0';
1756 *ppszSourceRoot[lenRoot - 1] = '\0';
1757 }
1758 else
1759 {
1760 /* If there's anything (like a file name or a filter),
1761 * strip it! */
1762 RTPathStripFilename(pszNewRoot);
1763 *ppszSourceRoot = pszNewRoot;
1764 }
1765
1766 return VINF_SUCCESS;
1767}
1768
1769/**
1770 * Frees a previously allocated source root.
1771 *
1772 * @return IPRT status code.
1773 * @param pszSourceRoot Source root to free.
1774 */
1775static void ctrlCopyFreeSourceRoot(char *pszSourceRoot)
1776{
1777 RTStrFree(pszSourceRoot);
1778}
1779
1780static int handleCtrlCopy(ComPtr<IGuest> guest, HandlerArg *pArg,
1781 bool fHostToGuest)
1782{
1783 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1784
1785 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
1786 * is much better (partly because it is much simpler of course). The main
1787 * arguments against this is that (1) all but two options conflicts with
1788 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
1789 * done windows CMD style (though not in a 100% compatible way), and (3)
1790 * that only one source is allowed - efficiently sabotaging default
1791 * wildcard expansion by a unix shell. The best solution here would be
1792 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
1793
1794 /*
1795 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1796 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1797 * does in here.
1798 */
1799 static const RTGETOPTDEF s_aOptions[] =
1800 {
1801 { "--dryrun", GETOPTDEF_COPY_DRYRUN, RTGETOPT_REQ_NOTHING },
1802 { "--follow", GETOPTDEF_COPY_FOLLOW, RTGETOPT_REQ_NOTHING },
1803 { "--username", 'u', RTGETOPT_REQ_STRING },
1804 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
1805 { "--password", GETOPTDEF_COPY_PASSWORD, RTGETOPT_REQ_STRING },
1806 { "--domain", 'd', RTGETOPT_REQ_STRING },
1807 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1808 { "--target-directory", GETOPTDEF_COPY_TARGETDIR, RTGETOPT_REQ_STRING },
1809 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1810 };
1811
1812 int ch;
1813 RTGETOPTUNION ValueUnion;
1814 RTGETOPTSTATE GetState;
1815 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1816 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1817
1818 Utf8Str strSource;
1819 Utf8Str strDest;
1820 Utf8Str strUsername;
1821 Utf8Str strPassword;
1822 Utf8Str strDomain;
1823 uint32_t fFlags = CopyFileFlag_None;
1824 bool fVerbose = false;
1825 bool fCopyRecursive = false;
1826 bool fDryRun = false;
1827
1828 SOURCEVEC vecSources;
1829
1830 int vrc = VINF_SUCCESS;
1831 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1832 {
1833 /* For options that require an argument, ValueUnion has received the value. */
1834 switch (ch)
1835 {
1836 case GETOPTDEF_COPY_DRYRUN:
1837 fDryRun = true;
1838 break;
1839
1840 case GETOPTDEF_COPY_FOLLOW:
1841 fFlags |= CopyFileFlag_FollowLinks;
1842 break;
1843
1844 case 'u': /* User name */
1845 strUsername = ValueUnion.psz;
1846 break;
1847
1848 case GETOPTDEF_COPY_PASSWORD: /* Password */
1849 strPassword = ValueUnion.psz;
1850 break;
1851
1852 case 'p': /* Password file */
1853 {
1854 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
1855 if (rcExit != RTEXITCODE_SUCCESS)
1856 return rcExit;
1857 break;
1858 }
1859
1860 case 'd': /* domain */
1861 strDomain = ValueUnion.psz;
1862 break;
1863
1864 case 'R': /* Recursive processing */
1865 fFlags |= CopyFileFlag_Recursive;
1866 break;
1867
1868 case GETOPTDEF_COPY_TARGETDIR:
1869 strDest = ValueUnion.psz;
1870 break;
1871
1872 case 'v': /* Verbose */
1873 fVerbose = true;
1874 break;
1875
1876 case VINF_GETOPT_NOT_OPTION:
1877 {
1878 /* Last argument and no destination specified with
1879 * --target-directory yet? Then use the current
1880 * (= last) argument as destination. */
1881 if ( pArg->argc == GetState.iNext
1882 && strDest.isEmpty())
1883 {
1884 strDest = ValueUnion.psz;
1885 }
1886 else
1887 {
1888 /* Save the source directory. */
1889 vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
1890 }
1891 break;
1892 }
1893
1894 default:
1895 return RTGetOptPrintError(ch, &ValueUnion);
1896 }
1897 }
1898
1899 if (!vecSources.size())
1900 return errorSyntax(USAGE_GUESTCONTROL,
1901 "No source(s) specified!");
1902
1903 if (strDest.isEmpty())
1904 return errorSyntax(USAGE_GUESTCONTROL,
1905 "No destination specified!");
1906
1907 if (strUsername.isEmpty())
1908 return errorSyntax(USAGE_GUESTCONTROL,
1909 "No user name specified!");
1910
1911 /*
1912 * Done parsing arguments, do some more preparations.
1913 */
1914 if (fVerbose)
1915 {
1916 if (fHostToGuest)
1917 RTPrintf("Copying from host to guest ...\n");
1918 else
1919 RTPrintf("Copying from guest to host ...\n");
1920 if (fDryRun)
1921 RTPrintf("Dry run - no files copied!\n");
1922 }
1923
1924 /* Create the copy context -- it contains all information
1925 * the routines need to know when handling the actual copying. */
1926 PCOPYCONTEXT pContext;
1927 vrc = ctrlCopyContextCreate(guest, fVerbose, fDryRun, fHostToGuest,
1928 strUsername, strPassword, strDomain,
1929 "VBoxManage Guest Control Copy", &pContext);
1930 if (RT_FAILURE(vrc))
1931 {
1932 RTMsgError("Unable to create copy context, rc=%Rrc\n", vrc);
1933 return RTEXITCODE_FAILURE;
1934 }
1935
1936 /* If the destination is a path, (try to) create it. */
1937 const char *pszDest = strDest.c_str();
1938 if (!RTPathFilename(pszDest))
1939 {
1940 vrc = ctrlCopyDirCreate(pContext, pszDest);
1941 }
1942 else
1943 {
1944 /* We assume we got a file name as destination -- so strip
1945 * the actual file name and make sure the appropriate
1946 * directories get created. */
1947 char *pszDestDir = RTStrDup(pszDest);
1948 AssertPtr(pszDestDir);
1949 RTPathStripFilename(pszDestDir);
1950 vrc = ctrlCopyDirCreate(pContext, pszDestDir);
1951 RTStrFree(pszDestDir);
1952 }
1953
1954 if (RT_SUCCESS(vrc))
1955 {
1956 /*
1957 * Here starts the actual fun!
1958 * Handle all given sources one by one.
1959 */
1960 for (unsigned long s = 0; s < vecSources.size(); s++)
1961 {
1962 char *pszSource = RTStrDup(vecSources[s].GetSource());
1963 AssertPtrBreakStmt(pszSource, vrc = VERR_NO_MEMORY);
1964 const char *pszFilter = vecSources[s].GetFilter();
1965 if (!strlen(pszFilter))
1966 pszFilter = NULL; /* If empty filter then there's no filter :-) */
1967
1968 char *pszSourceRoot;
1969 vrc = ctrlCopyCreateSourceRoot(pszSource, &pszSourceRoot);
1970 if (RT_FAILURE(vrc))
1971 {
1972 RTMsgError("Unable to create source root, rc=%Rrc\n", vrc);
1973 break;
1974 }
1975
1976 if (fVerbose)
1977 RTPrintf("Source: %s\n", pszSource);
1978
1979 /** @todo Files with filter?? */
1980 bool fSourceIsFile = false;
1981 bool fSourceExists;
1982
1983 size_t cchSource = strlen(pszSource);
1984 if ( cchSource > 1
1985 && RTPATH_IS_SLASH(pszSource[cchSource - 1]))
1986 {
1987 if (pszFilter) /* Directory with filter (so use source root w/o the actual filter). */
1988 vrc = ctrlCopyDirExistsOnSource(pContext, pszSourceRoot, &fSourceExists);
1989 else /* Regular directory without filter. */
1990 vrc = ctrlCopyDirExistsOnSource(pContext, pszSource, &fSourceExists);
1991
1992 if (fSourceExists)
1993 {
1994 /* Strip trailing slash from our source element so that other functions
1995 * can use this stuff properly (like RTPathStartsWith). */
1996 RTPathStripTrailingSlash(pszSource);
1997 }
1998 }
1999 else
2000 {
2001 vrc = ctrlCopyFileExistsOnSource(pContext, pszSource, &fSourceExists);
2002 if ( RT_SUCCESS(vrc)
2003 && fSourceExists)
2004 {
2005 fSourceIsFile = true;
2006 }
2007 }
2008
2009 if ( RT_SUCCESS(vrc)
2010 && fSourceExists)
2011 {
2012 if (fSourceIsFile)
2013 {
2014 /* Single file. */
2015 char *pszDestFile;
2016 vrc = ctrlCopyTranslatePath(pszSourceRoot, pszSource,
2017 strDest.c_str(), &pszDestFile);
2018 if (RT_SUCCESS(vrc))
2019 {
2020 vrc = ctrlCopyFileToDest(pContext, pszSource,
2021 pszDestFile, 0 /* Flags */);
2022 RTStrFree(pszDestFile);
2023 }
2024 else
2025 RTMsgError("Unable to translate path for \"%s\", rc=%Rrc\n",
2026 pszSource, vrc);
2027 }
2028 else
2029 {
2030 /* Directory (with filter?). */
2031 vrc = ctrlCopyDirToDest(pContext, pszSource, pszFilter,
2032 strDest.c_str(), fFlags);
2033 }
2034 }
2035
2036 ctrlCopyFreeSourceRoot(pszSourceRoot);
2037
2038 if ( RT_SUCCESS(vrc)
2039 && !fSourceExists)
2040 {
2041 RTMsgError("Warning: Source \"%s\" does not exist, skipping!\n",
2042 pszSource);
2043 RTStrFree(pszSource);
2044 continue;
2045 }
2046 else if (RT_FAILURE(vrc))
2047 {
2048 RTMsgError("Error processing \"%s\", rc=%Rrc\n",
2049 pszSource, vrc);
2050 RTStrFree(pszSource);
2051 break;
2052 }
2053
2054 RTStrFree(pszSource);
2055 }
2056 }
2057
2058 ctrlCopyContextFree(pContext);
2059
2060 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2061}
2062
2063static int handleCtrlCreateDirectory(ComPtr<IGuest> pGuest, HandlerArg *pArg)
2064{
2065 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2066
2067 /*
2068 * Parse arguments.
2069 *
2070 * Note! No direct returns here, everyone must go thru the cleanup at the
2071 * end of this function.
2072 */
2073 static const RTGETOPTDEF s_aOptions[] =
2074 {
2075 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
2076 { "--parents", 'P', RTGETOPT_REQ_NOTHING },
2077 { "--username", 'u', RTGETOPT_REQ_STRING },
2078 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
2079 { "--password", GETOPTDEF_MKDIR_PASSWORD, RTGETOPT_REQ_STRING },
2080 { "--domain", 'd', RTGETOPT_REQ_STRING },
2081 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2082 };
2083
2084 int ch;
2085 RTGETOPTUNION ValueUnion;
2086 RTGETOPTSTATE GetState;
2087 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
2088 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2089
2090 Utf8Str strUsername;
2091 Utf8Str strPassword;
2092 Utf8Str strDomain;
2093 SafeArray<DirectoryCreateFlag_T> dirCreateFlags;
2094 uint32_t fDirMode = 0; /* Default mode. */
2095 bool fVerbose = false;
2096
2097 DESTDIRMAP mapDirs;
2098
2099 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2100 {
2101 /* For options that require an argument, ValueUnion has received the value. */
2102 switch (ch)
2103 {
2104 case 'm': /* Mode */
2105 fDirMode = ValueUnion.u32;
2106 break;
2107
2108 case 'P': /* Create parents */
2109 dirCreateFlags.push_back(DirectoryCreateFlag_Parents);
2110 break;
2111
2112 case 'u': /* User name */
2113 strUsername = ValueUnion.psz;
2114 break;
2115
2116 case GETOPTDEF_MKDIR_PASSWORD: /* Password */
2117 strPassword = ValueUnion.psz;
2118 break;
2119
2120 case 'p': /* Password file */
2121 {
2122 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
2123 if (rcExit != RTEXITCODE_SUCCESS)
2124 return rcExit;
2125 break;
2126 }
2127
2128 case 'd': /* domain */
2129 strDomain = ValueUnion.psz;
2130 break;
2131
2132 case 'v': /* Verbose */
2133 fVerbose = true;
2134 break;
2135
2136 case VINF_GETOPT_NOT_OPTION:
2137 {
2138 mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
2139 break;
2140 }
2141
2142 default:
2143 return RTGetOptPrintError(ch, &ValueUnion);
2144 }
2145 }
2146
2147 uint32_t cDirs = mapDirs.size();
2148 if (!cDirs)
2149 return errorSyntax(USAGE_GUESTCONTROL, "No directory to create specified!");
2150
2151 if (strUsername.isEmpty())
2152 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
2153
2154 /*
2155 * Create the directories.
2156 */
2157 HRESULT hrc = S_OK;
2158 if (fVerbose && cDirs)
2159 RTPrintf("Creating %u directories ...\n", cDirs);
2160
2161 ComPtr<IGuestSession> pGuestSession;
2162 hrc = pGuest->CreateSession(Bstr(strUsername).raw(),
2163 Bstr(strPassword).raw(),
2164 Bstr(strDomain).raw(),
2165 Bstr("VBoxManage Guest Control MkDir").raw(),
2166 pGuestSession.asOutParam());
2167 if (FAILED(hrc))
2168 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
2169
2170 DESTDIRMAPITER it = mapDirs.begin();
2171 while (it != mapDirs.end())
2172 {
2173 if (fVerbose)
2174 RTPrintf("Creating directory \"%s\" ...\n", it->first.c_str());
2175
2176 hrc = pGuestSession->DirectoryCreate(Bstr(it->first).raw(), fDirMode, ComSafeArrayAsInParam(dirCreateFlags));
2177 if (FAILED(hrc))
2178 {
2179 ctrlPrintError(pGuest, COM_IIDOF(IGuestSession)); /* Return code ignored, save original rc. */
2180 break;
2181 }
2182
2183 it++;
2184 }
2185
2186 if (!pGuestSession.isNull())
2187 pGuestSession->Close();
2188
2189 return FAILED(hrc) ? RTEXITCODE_FAILURE : RTEXITCODE_SUCCESS;
2190}
2191
2192static int handleCtrlStat(ComPtr<IGuest> pGuest, HandlerArg *pArg)
2193{
2194 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2195
2196 static const RTGETOPTDEF s_aOptions[] =
2197 {
2198 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
2199 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
2200 { "--format", 'c', RTGETOPT_REQ_STRING },
2201 { "--username", 'u', RTGETOPT_REQ_STRING },
2202 { "--passwordfile", 'p', RTGETOPT_REQ_STRING },
2203 { "--password", GETOPTDEF_STAT_PASSWORD, RTGETOPT_REQ_STRING },
2204 { "--domain", 'd', RTGETOPT_REQ_STRING },
2205 { "--terse", 't', RTGETOPT_REQ_NOTHING },
2206 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2207 };
2208
2209 int ch;
2210 RTGETOPTUNION ValueUnion;
2211 RTGETOPTSTATE GetState;
2212 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
2213 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
2214
2215 Utf8Str strUsername;
2216 Utf8Str strPassword;
2217 Utf8Str strDomain;
2218
2219 bool fVerbose = false;
2220 DESTDIRMAP mapObjs;
2221
2222 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
2223 {
2224 /* For options that require an argument, ValueUnion has received the value. */
2225 switch (ch)
2226 {
2227 case 'u': /* User name */
2228 strUsername = ValueUnion.psz;
2229 break;
2230
2231 case GETOPTDEF_STAT_PASSWORD: /* Password */
2232 strPassword = ValueUnion.psz;
2233 break;
2234
2235 case 'p': /* Password file */
2236 {
2237 RTEXITCODE rcExit = readPasswordFile(ValueUnion.psz, &strPassword);
2238 if (rcExit != RTEXITCODE_SUCCESS)
2239 return rcExit;
2240 break;
2241 }
2242
2243 case 'd': /* domain */
2244 strDomain = ValueUnion.psz;
2245 break;
2246
2247 case 'L': /* Dereference */
2248 case 'f': /* File-system */
2249 case 'c': /* Format */
2250 case 't': /* Terse */
2251 return errorSyntax(USAGE_GUESTCONTROL, "Command \"%s\" not implemented yet!",
2252 ValueUnion.psz);
2253 break; /* Never reached. */
2254
2255 case 'v': /* Verbose */
2256 fVerbose = true;
2257 break;
2258
2259 case VINF_GETOPT_NOT_OPTION:
2260 {
2261 mapObjs[ValueUnion.psz]; /* Add element to check to map. */
2262 break;
2263 }
2264
2265 default:
2266 return RTGetOptPrintError(ch, &ValueUnion);
2267 }
2268 }
2269
2270 uint32_t cObjs = mapObjs.size();
2271 if (!cObjs)
2272 return errorSyntax(USAGE_GUESTCONTROL, "No element(s) to check specified!");
2273
2274 if (strUsername.isEmpty())
2275 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
2276
2277 ComPtr<IGuestSession> pGuestSession;
2278 HRESULT hrc = pGuest->CreateSession(Bstr(strUsername).raw(),
2279 Bstr(strPassword).raw(),
2280 Bstr(strDomain).raw(),
2281 Bstr("VBoxManage Guest Control Stat").raw(),
2282 pGuestSession.asOutParam());
2283 if (FAILED(hrc))
2284 return ctrlPrintError(pGuest, COM_IIDOF(IGuest));
2285
2286 /*
2287 * Create the directories.
2288 */
2289 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
2290 DESTDIRMAPITER it = mapObjs.begin();
2291 while (it != mapObjs.end())
2292 {
2293 if (fVerbose)
2294 RTPrintf("Checking for element \"%s\" ...\n", it->first.c_str());
2295
2296 ComPtr<IGuestFsObjInfo> pFsObjInfo;
2297 hrc = pGuestSession->FileQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
2298 if (FAILED(hrc))
2299 hrc = pGuestSession->DirectoryQueryInfo(Bstr(it->first).raw(), pFsObjInfo.asOutParam());
2300
2301 if (FAILED(hrc))
2302 {
2303 /* If there's at least one element which does not exist on the guest,
2304 * drop out with exitcode 1. */
2305 if (fVerbose)
2306 RTPrintf("Cannot stat for element \"%s\": No such element\n",
2307 it->first.c_str());
2308 rcExit = RTEXITCODE_FAILURE;
2309 }
2310 else
2311 {
2312 FsObjType_T objType;
2313 hrc = pFsObjInfo->COMGETTER(Type)(&objType);
2314 if (FAILED(hrc))
2315 return ctrlPrintError(pGuest, COM_IIDOF(IGuestFsObjInfo));
2316 switch (objType)
2317 {
2318 case FsObjType_File:
2319 RTPrintf("Element \"%s\" found: Is a file\n", it->first.c_str());
2320 break;
2321
2322 case FsObjType_Directory:
2323 RTPrintf("Element \"%s\" found: Is a directory\n", it->first.c_str());
2324 break;
2325
2326 case FsObjType_Symlink:
2327 RTPrintf("Element \"%s\" found: Is a symlink\n", it->first.c_str());
2328 break;
2329
2330 default:
2331 RTPrintf("Element \"%s\" found, type unknown (%ld)\n", it->first.c_str(), objType);
2332 break;
2333 }
2334
2335 /** @todo: Show more information about this element. */
2336 }
2337
2338 it++;
2339 }
2340
2341 if (!pGuestSession.isNull())
2342 pGuestSession->Close();
2343
2344 return rcExit;
2345}
2346
2347static int handleCtrlUpdateAdditions(ComPtr<IGuest> guest, HandlerArg *pArg)
2348{
2349 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2350
2351 /*
2352 * Check the syntax. We can deduce the correct syntax from the number of
2353 * arguments.
2354 */
2355 Utf8Str strSource;
2356 bool fVerbose = false;
2357
2358 static const RTGETOPTDEF s_aOptions[] =
2359 {
2360 { "--source", 's', RTGETOPT_REQ_STRING },
2361 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
2362 };
2363
2364 int ch;
2365 RTGETOPTUNION ValueUnion;
2366 RTGETOPTSTATE GetState;
2367 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, 0);
2368
2369 int vrc = VINF_SUCCESS;
2370 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
2371 && RT_SUCCESS(vrc))
2372 {
2373 switch (ch)
2374 {
2375 case 's':
2376 strSource = ValueUnion.psz;
2377 break;
2378
2379 case 'v':
2380 fVerbose = true;
2381 break;
2382
2383 default:
2384 return RTGetOptPrintError(ch, &ValueUnion);
2385 }
2386 }
2387
2388 if (fVerbose)
2389 RTPrintf("Updating Guest Additions ...\n");
2390
2391#ifdef DEBUG_andy
2392 if (strSource.isEmpty())
2393 strSource = "c:\\Downloads\\VBoxGuestAdditions-r67158.iso";
2394#endif
2395
2396 /* Determine source if not set yet. */
2397 if (strSource.isEmpty())
2398 {
2399 char strTemp[RTPATH_MAX];
2400 vrc = RTPathAppPrivateNoArch(strTemp, sizeof(strTemp));
2401 AssertRC(vrc);
2402 Utf8Str strSrc1 = Utf8Str(strTemp).append("/VBoxGuestAdditions.iso");
2403
2404 vrc = RTPathExecDir(strTemp, sizeof(strTemp));
2405 AssertRC(vrc);
2406 Utf8Str strSrc2 = Utf8Str(strTemp).append("/additions/VBoxGuestAdditions.iso");
2407
2408 /* Check the standard image locations */
2409 if (RTFileExists(strSrc1.c_str()))
2410 strSource = strSrc1;
2411 else if (RTFileExists(strSrc2.c_str()))
2412 strSource = strSrc2;
2413 else
2414 {
2415 RTMsgError("Source could not be determined! Please use --source to specify a valid source\n");
2416 vrc = VERR_FILE_NOT_FOUND;
2417 }
2418 }
2419 else if (!RTFileExists(strSource.c_str()))
2420 {
2421 RTMsgError("Source \"%s\" does not exist!\n", strSource.c_str());
2422 vrc = VERR_FILE_NOT_FOUND;
2423 }
2424
2425 if (RT_SUCCESS(vrc))
2426 {
2427 if (fVerbose)
2428 RTPrintf("Using source: %s\n", strSource.c_str());
2429
2430 HRESULT rc = S_OK;
2431 ComPtr<IProgress> pProgress;
2432
2433 SafeArray<AdditionsUpdateFlag_T> updateFlags;
2434 CHECK_ERROR(guest, UpdateGuestAdditions(Bstr(strSource).raw(),
2435 /* Wait for whole update process to complete. */
2436 ComSafeArrayAsInParam(updateFlags),
2437 pProgress.asOutParam()));
2438 if (FAILED(rc))
2439 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
2440 else
2441 {
2442 if (fVerbose)
2443 rc = showProgress(pProgress);
2444 else
2445 rc = pProgress->WaitForCompletion(-1 /* No timeout */);
2446
2447 if (SUCCEEDED(rc))
2448 CHECK_PROGRESS_ERROR(pProgress, ("Guest additions update failed"));
2449 vrc = ctrlPrintProgressError(pProgress);
2450 if ( RT_SUCCESS(vrc)
2451 && fVerbose)
2452 {
2453 RTPrintf("Guest Additions update successful\n");
2454 }
2455 }
2456 }
2457
2458 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2459}
2460
2461/**
2462 * Access the guest control store.
2463 *
2464 * @returns program exit code.
2465 * @note see the command line API description for parameters
2466 */
2467int handleGuestControl(HandlerArg *pArg)
2468{
2469 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2470
2471#ifdef DEBUG_andy_disabled
2472 if (RT_FAILURE(tstTranslatePath()))
2473 return RTEXITCODE_FAILURE;
2474#endif
2475
2476 HandlerArg arg = *pArg;
2477 arg.argc = pArg->argc - 2; /* Skip VM name and sub command. */
2478 arg.argv = pArg->argv + 2; /* Same here. */
2479
2480 ComPtr<IGuest> guest;
2481 int vrc = ctrlInitVM(pArg, pArg->argv[0] /* VM Name */, &guest);
2482 if (RT_SUCCESS(vrc))
2483 {
2484 int rcExit;
2485 if (pArg->argc < 2)
2486 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No sub command specified!");
2487 else if ( !strcmp(pArg->argv[1], "exec")
2488 || !strcmp(pArg->argv[1], "execute"))
2489 rcExit = handleCtrlExecProgram(guest, &arg);
2490 else if (!strcmp(pArg->argv[1], "copyfrom"))
2491 rcExit = handleCtrlCopy(guest, &arg, false /* Guest to host */);
2492 else if ( !strcmp(pArg->argv[1], "copyto")
2493 || !strcmp(pArg->argv[1], "cp"))
2494 rcExit = handleCtrlCopy(guest, &arg, true /* Host to guest */);
2495 else if ( !strcmp(pArg->argv[1], "createdirectory")
2496 || !strcmp(pArg->argv[1], "createdir")
2497 || !strcmp(pArg->argv[1], "mkdir")
2498 || !strcmp(pArg->argv[1], "md"))
2499 rcExit = handleCtrlCreateDirectory(guest, &arg);
2500 else if ( !strcmp(pArg->argv[1], "stat"))
2501 rcExit = handleCtrlStat(guest, &arg);
2502 else if ( !strcmp(pArg->argv[1], "updateadditions")
2503 || !strcmp(pArg->argv[1], "updateadds"))
2504 rcExit = handleCtrlUpdateAdditions(guest, &arg);
2505 else
2506 rcExit = errorSyntax(USAGE_GUESTCONTROL, "Unknown sub command '%s' specified!", pArg->argv[1]);
2507
2508 ctrlUninitVM(pArg);
2509 return rcExit;
2510 }
2511 return RTEXITCODE_FAILURE;
2512}
2513
2514#endif /* !VBOX_ONLY_DOCS */
2515
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