VirtualBox

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

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

Main/IGuest::UpdateGuestAdditions: Implemented support for passing optional command line arguments to the performing installer on the guest (untested).

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