VirtualBox

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

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

GuestCtrl: More code for guest session infrastructure handling (untested, work in progress).

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