VirtualBox

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

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

GuestControl: Bugfixes, logging.

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

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