VirtualBox

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

Last change on this file since 37608 was 37447, checked in by vboxsync, 14 years ago

GuestCtrl/Execute: Added NoProfile flag for executing processes without loading the user's profile.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 65.5 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 37447 2011-06-14 15:46:03Z 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
71/**
72 * An entry for a source element, including an optional filter.
73 */
74typedef struct SOURCEFILEENTRY
75{
76 SOURCEFILEENTRY(const char *pszSource, const char *pszFilter)
77 : mSource(pszSource),
78 mFilter(pszFilter) {}
79 SOURCEFILEENTRY(const char *pszSource)
80 : mSource(pszSource)
81 {
82 if ( !RTFileExists(pszSource)
83 && !RTDirExists(pszSource))
84 {
85 /* No file and no directory -- maybe a filter? */
86 if (NULL != strpbrk(RTPathFilename(pszSource), "*?"))
87 {
88 /* Yep, get the actual filter part. */
89 mFilter = RTPathFilename(pszSource);
90 /* Remove the filter from actual sourcec directory name. */
91 RTPathStripFilename(mSource.mutableRaw());
92 mSource.jolt();
93 }
94 }
95 }
96 Utf8Str mSource;
97 Utf8Str mFilter;
98} SOURCEFILEENTRY, *PSOURCEFILEENTRY;
99typedef std::vector<SOURCEFILEENTRY> SOURCEVEC, *PSOURCEVEC;
100
101/**
102 * An entry for an element which needs to be copied to the guest.
103 */
104typedef struct DESTFILEENTRY
105{
106 DESTFILEENTRY(Utf8Str strFileName) : mFileName(strFileName) {}
107 Utf8Str mFileName;
108} DESTFILEENTRY, *PDESTFILEENTRY;
109/*
110 * Map for holding destination entires, whereas the key is the destination
111 * directory and the mapped value is a vector holding all elements for this directoy.
112 */
113typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> > DESTDIRMAP, *PDESTDIRMAP;
114typedef std::map< Utf8Str, std::vector<DESTFILEENTRY> >::iterator DESTDIRMAPITER, *PDESTDIRMAPITER;
115
116/**
117 * Special exit codes for returning errors/information of a
118 * started guest process to the command line VBoxManage was started from.
119 * Useful for e.g. scripting.
120 *
121 * @note These are frozen as of 4.1.0.
122 */
123enum EXITCODEEXEC
124{
125 EXITCODEEXEC_SUCCESS = RTEXITCODE_SUCCESS,
126 /* Process exited normally but with an exit code <> 0. */
127 EXITCODEEXEC_CODE = 16,
128 EXITCODEEXEC_FAILED = 17,
129 EXITCODEEXEC_TERM_SIGNAL = 18,
130 EXITCODEEXEC_TERM_ABEND = 19,
131 EXITCODEEXEC_TIMEOUT = 20,
132 EXITCODEEXEC_DOWN = 21,
133 EXITCODEEXEC_CANCELED = 22
134};
135
136/**
137 * RTGetOpt-IDs for the guest execution control command line.
138 */
139enum GETOPTDEF_EXEC
140{
141 GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES = 1000,
142 GETOPTDEF_EXEC_NO_PROFILE,
143 GETOPTDEF_EXEC_OUTPUTFORMAT,
144 GETOPTDEF_EXEC_DOS2UNIX,
145 GETOPTDEF_EXEC_UNIX2DOS,
146 GETOPTDEF_EXEC_WAITFOREXIT,
147 GETOPTDEF_EXEC_WAITFORSTDOUT,
148 GETOPTDEF_EXEC_WAITFORSTDERR
149};
150
151enum GETOPTDEF_COPYFROM
152{
153 GETOPTDEF_COPYFROM_DRYRUN = 1000,
154 GETOPTDEF_COPYFROM_FOLLOW,
155 GETOPTDEF_COPYFROM_PASSWORD,
156 GETOPTDEF_COPYFROM_TARGETDIR,
157 GETOPTDEF_COPYFROM_USERNAME
158};
159
160enum GETOPTDEF_COPYTO
161{
162 GETOPTDEF_COPYTO_DRYRUN = 1000,
163 GETOPTDEF_COPYTO_FOLLOW,
164 GETOPTDEF_COPYTO_PASSWORD,
165 GETOPTDEF_COPYTO_TARGETDIR,
166 GETOPTDEF_COPYTO_USERNAME
167};
168
169enum OUTPUTTYPE
170{
171 OUTPUTTYPE_UNDEFINED = 0,
172 OUTPUTTYPE_DOS2UNIX = 10,
173 OUTPUTTYPE_UNIX2DOS = 20
174};
175
176#endif /* VBOX_ONLY_DOCS */
177
178void usageGuestControl(PRTSTREAM pStrm)
179{
180 RTStrmPrintf(pStrm,
181 "VBoxManage guestcontrol <vmname>|<uuid>\n"
182 " exec[ute]\n"
183 " --image <path to program>\n"
184 " --username <name> --password <password>\n"
185 " [--dos2unix]\n"
186 " [--environment \"<NAME>=<VALUE> [<NAME>=<VALUE>]\"]\n"
187 " [--timeout <msec>] [--unix2dos] [--verbose]\n"
188 " [--wait-exit] [--wait-stdout] [--wait-stdout]\n"
189 //" [--output-format=<dos>|<unix>]\n"
190 " [--output-type=<binary>|<text>]\n"
191 " [-- [<argument1>] ... [<argumentN>]\n"
192 /** @todo Add a "--" parameter (has to be last parameter) to directly execute
193 * stuff, e.g. "VBoxManage guestcontrol execute <VMName> --username <> ... -- /bin/rm -Rf /foo". */
194 "\n"
195 " copyfrom\n"
196 " <source on guest> <destination on host>\n"
197 " --username <name> --password <password>\n"
198 " [--dryrun] [--follow] [--recursive] [--verbose]\n"
199 "\n"
200 " copyto|cp\n"
201 " <source on host> <destination on guest>\n"
202 " --username <name> --password <password>\n"
203 " [--dryrun] [--follow] [--recursive] [--verbose]\n"
204 "\n"
205 " createdir[ectory]|mkdir|md\n"
206 " <directory to create on guest>\n"
207 " --username <name> --password <password>\n"
208 " [--parents] [--mode <mode>] [--verbose]\n"
209 "\n"
210 " updateadditions\n"
211 " [--source <guest additions .ISO>] [--verbose]\n"
212 "\n");
213}
214
215#ifndef VBOX_ONLY_DOCS
216
217/**
218 * Signal handler that sets g_fGuestCtrlCanceled.
219 *
220 * This can be executed on any thread in the process, on Windows it may even be
221 * a thread dedicated to delivering this signal. Do not doing anything
222 * unnecessary here.
223 */
224static void guestCtrlSignalHandler(int iSignal)
225{
226 NOREF(iSignal);
227 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
228}
229
230/**
231 * Installs a custom signal handler to get notified
232 * whenever the user wants to intercept the program.
233 */
234static void ctrlSignalHandlerInstall()
235{
236 signal(SIGINT, guestCtrlSignalHandler);
237#ifdef SIGBREAK
238 signal(SIGBREAK, guestCtrlSignalHandler);
239#endif
240}
241
242/**
243 * Uninstalls a previously installed signal handler.
244 */
245static void ctrlSignalHandlerUninstall()
246{
247 signal(SIGINT, SIG_DFL);
248#ifdef SIGBREAK
249 signal(SIGBREAK, SIG_DFL);
250#endif
251}
252
253/**
254 * Translates a process status to a human readable
255 * string.
256 */
257static const char *ctrlExecProcessStatusToText(ExecuteProcessStatus_T enmStatus)
258{
259 switch (enmStatus)
260 {
261 case ExecuteProcessStatus_Started:
262 return "started";
263 case ExecuteProcessStatus_TerminatedNormally:
264 return "successfully terminated";
265 case ExecuteProcessStatus_TerminatedSignal:
266 return "terminated by signal";
267 case ExecuteProcessStatus_TerminatedAbnormally:
268 return "abnormally aborted";
269 case ExecuteProcessStatus_TimedOutKilled:
270 return "timed out";
271 case ExecuteProcessStatus_TimedOutAbnormally:
272 return "timed out, hanging";
273 case ExecuteProcessStatus_Down:
274 return "killed";
275 case ExecuteProcessStatus_Error:
276 return "error";
277 default:
278 break;
279 }
280 return "unknown";
281}
282
283static int ctrlExecProcessStatusToExitCode(ExecuteProcessStatus_T enmStatus, ULONG uExitCode)
284{
285 int rc = EXITCODEEXEC_SUCCESS;
286 switch (enmStatus)
287 {
288 case ExecuteProcessStatus_Started:
289 rc = EXITCODEEXEC_SUCCESS;
290 break;
291 case ExecuteProcessStatus_TerminatedNormally:
292 rc = !uExitCode ? EXITCODEEXEC_SUCCESS : EXITCODEEXEC_CODE;
293 break;
294 case ExecuteProcessStatus_TerminatedSignal:
295 rc = EXITCODEEXEC_TERM_SIGNAL;
296 break;
297 case ExecuteProcessStatus_TerminatedAbnormally:
298 rc = EXITCODEEXEC_TERM_ABEND;
299 break;
300 case ExecuteProcessStatus_TimedOutKilled:
301 rc = EXITCODEEXEC_TIMEOUT;
302 break;
303 case ExecuteProcessStatus_TimedOutAbnormally:
304 rc = EXITCODEEXEC_TIMEOUT;
305 break;
306 case ExecuteProcessStatus_Down:
307 /* Service/OS is stopping, process was killed, so
308 * not exactly an error of the started process ... */
309 rc = EXITCODEEXEC_DOWN;
310 break;
311 case ExecuteProcessStatus_Error:
312 rc = EXITCODEEXEC_FAILED;
313 break;
314 default:
315 AssertMsgFailed(("Unknown exit code (%u) from guest process returned!\n", enmStatus));
316 break;
317 }
318 return rc;
319}
320
321static int ctrlPrintError(com::ErrorInfo &errorInfo)
322{
323 if ( errorInfo.isFullAvailable()
324 || errorInfo.isBasicAvailable())
325 {
326 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
327 * because it contains more accurate info about what went wrong. */
328 if (errorInfo.getResultCode() == VBOX_E_IPRT_ERROR)
329 RTMsgError("%ls.", errorInfo.getText().raw());
330 else
331 {
332 RTMsgError("Error details:");
333 GluePrintErrorInfo(errorInfo);
334 }
335 return VERR_GENERAL_FAILURE; /** @todo */
336 }
337 AssertMsgFailedReturn(("Object has indicated no error!?\n"),
338 VERR_INVALID_PARAMETER);
339}
340
341static int ctrlPrintError(IUnknown *pObj, const GUID &aIID)
342{
343 com::ErrorInfo ErrInfo(pObj, aIID);
344 return ctrlPrintError(ErrInfo);
345}
346
347static int ctrlPrintProgressError(ComPtr<IProgress> progress)
348{
349 int rc;
350 BOOL fCanceled;
351 if ( SUCCEEDED(progress->COMGETTER(Canceled(&fCanceled)))
352 && fCanceled)
353 {
354 rc = VERR_CANCELLED;
355 }
356 else
357 {
358 com::ProgressErrorInfo ErrInfo(progress);
359 rc = ctrlPrintError(ErrInfo);
360 }
361 return rc;
362}
363
364/**
365 * Un-initializes the VM after guest control usage.
366 */
367static void ctrlUninitVM(HandlerArg *pArg)
368{
369 AssertPtrReturnVoid(pArg);
370 if (pArg->session)
371 pArg->session->UnlockMachine();
372}
373
374/**
375 * Initializes the VM for IGuest operations.
376 *
377 * That is, checks whether it's up and running, if it can be locked (shared
378 * only) and returns a valid IGuest pointer on success.
379 *
380 * @return IPRT status code.
381 * @param pArg Our command line argument structure.
382 * @param pszNameOrId The VM's name or UUID.
383 * @param pGuest Where to return the IGuest interface pointer.
384 */
385static int ctrlInitVM(HandlerArg *pArg, const char *pszNameOrId, ComPtr<IGuest> *pGuest)
386{
387 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
388 AssertPtrReturn(pszNameOrId, VERR_INVALID_PARAMETER);
389
390 /* Lookup VM. */
391 ComPtr<IMachine> machine;
392 /* Assume it's an UUID. */
393 HRESULT rc;
394 CHECK_ERROR(pArg->virtualBox, FindMachine(Bstr(pszNameOrId).raw(),
395 machine.asOutParam()));
396 if (FAILED(rc))
397 return VERR_NOT_FOUND;
398
399 /* Machine is running? */
400 MachineState_T machineState;
401 CHECK_ERROR_RET(machine, COMGETTER(State)(&machineState), 1);
402 if (machineState != MachineState_Running)
403 {
404 RTMsgError("Machine \"%s\" is not running (currently %s)!\n",
405 pszNameOrId, machineStateToName(machineState, false));
406 return VERR_VM_INVALID_VM_STATE;
407 }
408
409 do
410 {
411 /* Open a session for the VM. */
412 CHECK_ERROR_BREAK(machine, LockMachine(pArg->session, LockType_Shared));
413 /* Get the associated console. */
414 ComPtr<IConsole> console;
415 CHECK_ERROR_BREAK(pArg->session, COMGETTER(Console)(console.asOutParam()));
416 /* ... and session machine. */
417 ComPtr<IMachine> sessionMachine;
418 CHECK_ERROR_BREAK(pArg->session, COMGETTER(Machine)(sessionMachine.asOutParam()));
419 /* Get IGuest interface. */
420 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(pGuest->asOutParam()));
421 } while (0);
422
423 if (FAILED(rc))
424 ctrlUninitVM(pArg);
425 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
426}
427
428/* <Missing docuemntation> */
429static int handleCtrlExecProgram(ComPtr<IGuest> guest, HandlerArg *pArg)
430{
431 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
432
433 /*
434 * Parse arguments.
435 */
436 if (pArg->argc < 2) /* At least the command we want to execute in the guest should be present :-). */
437 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
438
439 static const RTGETOPTDEF s_aOptions[] =
440 {
441 { "--dos2unix", GETOPTDEF_EXEC_DOS2UNIX, RTGETOPT_REQ_NOTHING },
442 { "--environment", 'e', RTGETOPT_REQ_STRING },
443 { "--flags", 'f', RTGETOPT_REQ_STRING },
444 { "--ignore-operhaned-processes", GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES, RTGETOPT_REQ_NOTHING },
445 { "--image", 'i', RTGETOPT_REQ_STRING },
446 { "--no-profile", GETOPTDEF_EXEC_NO_PROFILE, RTGETOPT_REQ_NOTHING },
447 { "--password", 'p', RTGETOPT_REQ_STRING },
448 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
449 { "--unix2dos", GETOPTDEF_EXEC_UNIX2DOS, RTGETOPT_REQ_NOTHING },
450 { "--username", 'u', RTGETOPT_REQ_STRING },
451 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
452 { "--wait-exit", GETOPTDEF_EXEC_WAITFOREXIT, RTGETOPT_REQ_NOTHING },
453 { "--wait-stdout", GETOPTDEF_EXEC_WAITFORSTDOUT, RTGETOPT_REQ_NOTHING },
454 { "--wait-stderr", GETOPTDEF_EXEC_WAITFORSTDERR, RTGETOPT_REQ_NOTHING }
455 };
456
457 int ch;
458 RTGETOPTUNION ValueUnion;
459 RTGETOPTSTATE GetState;
460 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, 0);
461
462 Utf8Str Utf8Cmd;
463 uint32_t fExecFlags = ExecuteProcessFlag_None;
464 uint32_t fOutputFlags = ProcessOutputFlag_None;
465 com::SafeArray<IN_BSTR> args;
466 com::SafeArray<IN_BSTR> env;
467 Utf8Str Utf8UserName;
468 Utf8Str Utf8Password;
469 uint32_t cMsTimeout = 0;
470 OUTPUTTYPE eOutputType = OUTPUTTYPE_UNDEFINED;
471 bool fOutputBinary = false;
472 bool fWaitForExit = false;
473 bool fWaitForStdOut = false;
474 bool fVerbose = false;
475
476 int vrc = VINF_SUCCESS;
477 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
478 && RT_SUCCESS(vrc))
479 {
480 /* For options that require an argument, ValueUnion has received the value. */
481 switch (ch)
482 {
483 case GETOPTDEF_EXEC_DOS2UNIX:
484 if (eOutputType != OUTPUTTYPE_UNDEFINED)
485 return errorSyntax(USAGE_GUESTCONTROL, "More than one output type (dos2unix/unix2dos) specified!");
486 eOutputType = OUTPUTTYPE_DOS2UNIX;
487 break;
488
489 case 'e': /* Environment */
490 {
491 char **papszArg;
492 int cArgs;
493
494 vrc = RTGetOptArgvFromString(&papszArg, &cArgs, ValueUnion.psz, NULL);
495 if (RT_FAILURE(vrc))
496 return errorSyntax(USAGE_GUESTCONTROL, "Failed to parse environment value, rc=%Rrc", vrc);
497 for (int j = 0; j < cArgs; j++)
498 env.push_back(Bstr(papszArg[j]).raw());
499
500 RTGetOptArgvFree(papszArg);
501 break;
502 }
503
504 case GETOPTDEF_EXEC_IGNOREORPHANEDPROCESSES:
505 fExecFlags |= ExecuteProcessFlag_IgnoreOrphanedProcesses;
506 break;
507
508 case GETOPTDEF_EXEC_NO_PROFILE:
509 fExecFlags |= ExecuteProcessFlag_NoProfile;
510 break;
511
512 case 'i':
513 Utf8Cmd = ValueUnion.psz;
514 break;
515
516 /** @todo Add a hidden flag. */
517
518 case 'p': /* Password */
519 Utf8Password = ValueUnion.psz;
520 break;
521
522 case 't': /* Timeout */
523 cMsTimeout = ValueUnion.u32;
524 break;
525
526 case GETOPTDEF_EXEC_UNIX2DOS:
527 if (eOutputType != OUTPUTTYPE_UNDEFINED)
528 return errorSyntax(USAGE_GUESTCONTROL, "More than one output type (dos2unix/unix2dos) specified!");
529 eOutputType = OUTPUTTYPE_UNIX2DOS;
530 break;
531
532 case 'u': /* User name */
533 Utf8UserName = ValueUnion.psz;
534 break;
535
536 case 'v': /* Verbose */
537 fVerbose = true;
538 break;
539
540 case GETOPTDEF_EXEC_WAITFOREXIT:
541 fWaitForExit = true;
542 break;
543
544 case GETOPTDEF_EXEC_WAITFORSTDOUT:
545 fWaitForExit = true;
546 fWaitForStdOut = true;
547 break;
548
549 case GETOPTDEF_EXEC_WAITFORSTDERR:
550 fWaitForExit = (fOutputFlags |= ProcessOutputFlag_StdErr) ? true : false;
551 break;
552
553 case VINF_GETOPT_NOT_OPTION:
554 {
555 if (args.size() == 0 && Utf8Cmd.isEmpty())
556 Utf8Cmd = ValueUnion.psz;
557 else
558 args.push_back(Bstr(ValueUnion.psz).raw());
559 break;
560 }
561
562 default:
563 return RTGetOptPrintError(ch, &ValueUnion);
564 }
565 }
566
567 if (Utf8Cmd.isEmpty())
568 return errorSyntax(USAGE_GUESTCONTROL, "No command to execute specified!");
569
570 if (Utf8UserName.isEmpty())
571 return errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
572
573 /*
574 * <missing comment indicating that we're done parsing args and started doing something else>
575 */
576 HRESULT rc = S_OK;
577 if (fVerbose)
578 {
579 if (cMsTimeout == 0)
580 RTPrintf("Waiting for guest to start process ...\n");
581 else
582 RTPrintf("Waiting for guest to start process (within %ums)\n", cMsTimeout);
583 }
584
585 /* Get current time stamp to later calculate rest of timeout left. */
586 uint64_t u64StartMS = RTTimeMilliTS();
587
588 /* Execute the process. */
589 int rcProc = RTEXITCODE_FAILURE;
590 ComPtr<IProgress> progress;
591 ULONG uPID = 0;
592 rc = guest->ExecuteProcess(Bstr(Utf8Cmd).raw(),
593 fExecFlags,
594 ComSafeArrayAsInParam(args),
595 ComSafeArrayAsInParam(env),
596 Bstr(Utf8UserName).raw(),
597 Bstr(Utf8Password).raw(),
598 cMsTimeout,
599 &uPID,
600 progress.asOutParam());
601 if (FAILED(rc))
602 return ctrlPrintError(guest, COM_IIDOF(IGuest));
603
604 if (fVerbose)
605 RTPrintf("Process '%s' (PID: %u) started\n", Utf8Cmd.c_str(), uPID);
606 if (fWaitForExit)
607 {
608 if (fVerbose)
609 {
610 if (cMsTimeout) /* Wait with a certain timeout. */
611 {
612 /* Calculate timeout value left after process has been started. */
613 uint64_t u64Elapsed = RTTimeMilliTS() - u64StartMS;
614 /* Is timeout still bigger than current difference? */
615 if (cMsTimeout > u64Elapsed)
616 RTPrintf("Waiting for process to exit (%ums left) ...\n", cMsTimeout - u64Elapsed);
617 else
618 RTPrintf("No time left to wait for process!\n"); /** @todo a bit misleading ... */
619 }
620 else /* Wait forever. */
621 RTPrintf("Waiting for process to exit ...\n");
622 }
623
624 /* Setup signal handling if cancelable. */
625 ASSERT(progress);
626 bool fCanceledAlready = false;
627 BOOL fCancelable;
628 HRESULT hrc = progress->COMGETTER(Cancelable)(&fCancelable);
629 if (FAILED(hrc))
630 fCancelable = FALSE;
631 if (fCancelable)
632 ctrlSignalHandlerInstall();
633
634 /* Wait for process to exit ... */
635 BOOL fCompleted = FALSE;
636 BOOL fCanceled = FALSE;
637 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
638 {
639 SafeArray<BYTE> aOutputData;
640 ULONG cbOutputData = 0;
641
642 /*
643 * Some data left to output?
644 */
645 if (fOutputFlags || fWaitForStdOut)
646 {
647 /** @todo r=bird: The timeout argument is bogus in several
648 * ways:
649 * 1. RT_MAX will evaluate the arguments twice, which may
650 * result in different values because RTTimeMilliTS()
651 * returns a higher value the 2nd time. Worst case:
652 * Imagine when RT_MAX calculates the remaining time
653 * out (first expansion) there is say 60 ms left. Then
654 * we're preempted and rescheduled after, say, 120 ms.
655 * We call RTTimeMilliTS() again and ends up with a
656 * value -60 ms, which translate to a UINT32_MAX - 59
657 * ms timeout.
658 *
659 * 2. When the period expires, we will wait forever since
660 * both 0 and -1 mean indefinite timeout with this API,
661 * at least that's one way of reading the main code.
662 *
663 * 3. There is a signed/unsigned ambiguity in the
664 * RT_MAX expression. The left hand side is signed
665 * integer (0), the right side is unsigned 64-bit. From
666 * what I can tell, the compiler will treat this as
667 * unsigned 64-bit and never return 0.
668 */
669 rc = guest->GetProcessOutput(uPID, fOutputFlags,
670 RT_MAX(0, cMsTimeout - (RTTimeMilliTS() - u64StartMS)) /* Timeout in ms */,
671 _64K, ComSafeArrayAsOutParam(aOutputData));
672 if (FAILED(rc))
673 {
674 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
675 cbOutputData = 0;
676 }
677 else
678 {
679 cbOutputData = aOutputData.size();
680 if (cbOutputData > 0)
681 {
682 /** @todo r=bird: Use a VFS I/O stream filter for doing this, it's a
683 * generic problem and the new VFS APIs will handle it more
684 * transparently. (requires writing dos2unix/unix2dos filters ofc) */
685 if (eOutputType != OUTPUTTYPE_UNDEFINED)
686 {
687 /*
688 * If aOutputData is text data from the guest process' stdout or stderr,
689 * it has a platform dependent line ending. So standardize on
690 * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
691 * Windows. Otherwise we end up with CR/CR/LF on Windows.
692 */
693 ULONG cbOutputDataPrint = cbOutputData;
694 for (BYTE *s = aOutputData.raw(), *d = s;
695 s - aOutputData.raw() < (ssize_t)cbOutputData;
696 s++, d++)
697 {
698 if (*s == '\r')
699 {
700 /* skip over CR, adjust destination */
701 d--;
702 cbOutputDataPrint--;
703 }
704 else if (s != d)
705 *d = *s;
706 }
707 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputDataPrint);
708 }
709 else /* Just dump all data as we got it ... */
710 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputData);
711 }
712 }
713 }
714
715 /* No more output data left? */
716 if (cbOutputData <= 0)
717 {
718 /* Only break out from process handling loop if we processed (displayed)
719 * all output data or if there simply never was output data and the process
720 * has been marked as complete. */
721 if (fCompleted)
722 break;
723 }
724
725 /* Process async cancelation */
726 if (g_fGuestCtrlCanceled && !fCanceledAlready)
727 {
728 hrc = progress->Cancel();
729 if (SUCCEEDED(hrc))
730 fCanceledAlready = TRUE;
731 else
732 g_fGuestCtrlCanceled = false;
733 }
734
735 /* Progress canceled by Main API? */
736 if ( SUCCEEDED(progress->COMGETTER(Canceled(&fCanceled)))
737 && fCanceled)
738 break;
739
740 /* Did we run out of time? */
741 if ( cMsTimeout
742 && RTTimeMilliTS() - u64StartMS > cMsTimeout)
743 {
744 progress->Cancel();
745 break;
746 }
747 } /* while */
748
749 /* Undo signal handling */
750 if (fCancelable)
751 ctrlSignalHandlerUninstall();
752
753 /* Report status back to the user. */
754 if (fCanceled)
755 {
756 if (fVerbose)
757 RTPrintf("Process execution canceled!\n");
758 rcProc = EXITCODEEXEC_CANCELED;
759 }
760 else if ( fCompleted
761 && SUCCEEDED(rc)) /* The GetProcessOutput rc. */
762 {
763 LONG iRc;
764 CHECK_ERROR_RET(progress, COMGETTER(ResultCode)(&iRc), rc);
765 if (FAILED(iRc))
766 vrc = ctrlPrintProgressError(progress);
767 else
768 {
769 ExecuteProcessStatus_T retStatus;
770 ULONG uRetExitCode, uRetFlags;
771 rc = guest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &retStatus);
772 if (SUCCEEDED(rc) && fVerbose)
773 RTPrintf("Exit code=%u (Status=%u [%s], Flags=%u)\n", uRetExitCode, retStatus, ctrlExecProcessStatusToText(retStatus), uRetFlags);
774 rcProc = ctrlExecProcessStatusToExitCode(retStatus, uRetExitCode);
775 }
776 }
777 else
778 {
779 if (fVerbose)
780 RTPrintf("Process execution aborted!\n");
781 rcProc = EXITCODEEXEC_TERM_ABEND;
782 }
783 }
784
785 if (RT_FAILURE(vrc) || FAILED(rc))
786 return RTEXITCODE_FAILURE;
787 return rcProc;
788}
789
790/** @todo Clean up too long parameter list -> move guest specific stuff into own struct etc! */
791static int ctrlCopyDirectoryReadGuest(IGuest *pGuest,
792 const char *pszUsername, const char *pszPassword,
793 const char *pszRootDir, const char *pszSubDir,
794 const char *pszFilter, const char *pszDest,
795 uint32_t fFlags, uint32_t *pcObjects, DESTDIRMAP &dirMap)
796{
797 AssertPtrReturn(pszRootDir, VERR_INVALID_POINTER);
798 /* Sub directory is optional. */
799 /* Filter directory is optional. */
800 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
801 AssertPtrReturn(pcObjects, VERR_INVALID_POINTER);
802
803 /*
804 * Construct current path.
805 */
806 char szCurDir[RTPATH_MAX];
807 int rc = RTStrCopy(szCurDir, sizeof(szCurDir), pszRootDir);
808 if (RT_SUCCESS(rc) && pszSubDir != NULL)
809 rc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
810
811 if (RT_SUCCESS(rc))
812 {
813 ULONG uDirHandle;
814 HRESULT hr = pGuest->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(), fFlags,
815 Bstr(pszUsername).raw(), Bstr(pszPassword).raw(), &uDirHandle);
816 if (FAILED(hr))
817 rc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
818 else
819 {
820 ComPtr <IGuestDirEntry> dirEntry;
821 while (SUCCEEDED(hr = pGuest->DirectoryRead(uDirHandle, dirEntry.asOutParam())))
822 {
823 GuestDirEntryType_T enmType;
824 dirEntry->COMGETTER(Type)(&enmType);
825
826 Bstr strName;
827 dirEntry->COMGETTER(Name)(strName.asOutParam());
828
829 switch (enmType)
830 {
831 case GuestDirEntryType_Directory:
832 {
833 /* Skip "." and ".." entries. */
834 if ( !strName.compare(Bstr("."))
835 || !strName.compare(Bstr("..")))
836 break;
837
838 const char *pszName = Utf8Str(strName).c_str();
839 if (fFlags & CopyFileFlag_Recursive)
840 {
841 char *pszNewSub = NULL;
842 if (pszSubDir)
843 RTStrAPrintf(&pszNewSub, "%s/%s", pszSubDir, pszName);
844 else
845 RTStrAPrintf(&pszNewSub, "%s", pszName);
846
847 if (pszNewSub)
848 {
849 dirMap[pszNewSub];
850
851 rc = ctrlCopyDirectoryReadGuest(pGuest, pszUsername, pszPassword,
852 pszRootDir, pszNewSub,
853 pszFilter, pszDest,
854 fFlags, pcObjects, dirMap);
855 RTStrFree(pszNewSub);
856 }
857 else
858 rc = VERR_NO_MEMORY;
859 }
860 break;
861 }
862
863 case GuestDirEntryType_Symlink:
864 if ( (fFlags & CopyFileFlag_Recursive)
865 && (fFlags & CopyFileFlag_FollowLinks))
866 {
867 /* Fall through to next case is intentional. */
868 }
869 else
870 break;
871
872 case GuestDirEntryType_File:
873 {
874 const char *pszName = Utf8Str(strName).c_str();
875 if ( !pszFilter
876 || RTStrSimplePatternMatch(pszFilter, pszName))
877 {
878 dirMap[pszSubDir].push_back(DESTFILEENTRY(pszName));
879 *pcObjects += 1;
880 }
881 break;
882 }
883
884 default:
885 break;
886 }
887 }
888
889 hr = pGuest->DirectoryClose(uDirHandle);
890 if (FAILED(rc))
891 rc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
892 }
893 }
894 return rc;
895}
896
897/**
898 * Reads a specified directory (recursively) based on the copy flags
899 * and appends all matching entries to the supplied list.
900 *
901 * @return IPRT status code.
902 * @param pszRootDir Directory to start with. Must end with
903 * a trailing slash and must be absolute.
904 * @param pszSubDir Sub directory part relative to the root
905 * directory; needed for recursion.
906 * @param pszFilter Search filter (e.g. *.pdf).
907 * @param pszDest Destination directory.
908 * @param fFlags Copy flags.
909 * @param pcObjects Where to store the overall objects to
910 * copy found.
911 * @param dirMap Reference to destination directory map to store found
912 * directories (primary key) + files (secondary key, vector).
913 */
914static int ctrlCopyDirectoryReadHost(const char *pszRootDir, const char *pszSubDir,
915 const char *pszFilter, const char *pszDest,
916 uint32_t fFlags, uint32_t *pcObjects, DESTDIRMAP &dirMap)
917{
918 AssertPtrReturn(pszRootDir, VERR_INVALID_POINTER);
919 /* Sub directory is optional. */
920 /* Filter directory is optional. */
921 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
922 AssertPtrReturn(pcObjects, VERR_INVALID_POINTER);
923
924 /*
925 * Construct current path.
926 */
927 char szCurDir[RTPATH_MAX];
928 int rc = RTStrCopy(szCurDir, sizeof(szCurDir), pszRootDir);
929 if (RT_SUCCESS(rc) && pszSubDir != NULL)
930 rc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
931
932 /*
933 * Open directory without a filter - RTDirOpenFiltered unfortunately
934 * cannot handle sub directories so we have to do the filtering ourselves.
935 */
936 PRTDIR pDir = NULL;
937 if (RT_SUCCESS(rc))
938 {
939 rc = RTDirOpen(&pDir, szCurDir);
940 if (RT_FAILURE(rc))
941 pDir = NULL;
942 }
943 if (RT_SUCCESS(rc))
944 {
945 /*
946 * Enumerate the directory tree.
947 */
948 while (RT_SUCCESS(rc))
949 {
950 RTDIRENTRY DirEntry;
951 rc = RTDirRead(pDir, &DirEntry, NULL);
952 if (RT_FAILURE(rc))
953 {
954 if (rc == VERR_NO_MORE_FILES)
955 rc = VINF_SUCCESS;
956 break;
957 }
958 switch (DirEntry.enmType)
959 {
960 case RTDIRENTRYTYPE_DIRECTORY:
961 {
962 /* Skip "." and ".." entries. */
963 if ( !strcmp(DirEntry.szName, ".")
964 || !strcmp(DirEntry.szName, ".."))
965 break;
966
967 if (fFlags & CopyFileFlag_Recursive)
968 {
969 char *pszNewSub = NULL;
970 if (pszSubDir)
971 RTStrAPrintf(&pszNewSub, "%s/%s", pszSubDir, DirEntry.szName);
972 else
973 RTStrAPrintf(&pszNewSub, "%s", DirEntry.szName);
974
975 if (pszNewSub)
976 {
977 dirMap[pszNewSub];
978
979 rc = ctrlCopyDirectoryReadHost(pszRootDir, pszNewSub,
980 pszFilter, pszDest,
981 fFlags, pcObjects, dirMap);
982 RTStrFree(pszNewSub);
983 }
984 else
985 rc = VERR_NO_MEMORY;
986 }
987 break;
988 }
989
990 case RTDIRENTRYTYPE_SYMLINK:
991 if ( (fFlags & CopyFileFlag_Recursive)
992 && (fFlags & CopyFileFlag_FollowLinks))
993 {
994 /* Fall through to next case is intentional. */
995 }
996 else
997 break;
998
999 case RTDIRENTRYTYPE_FILE:
1000 {
1001 if ( !pszFilter
1002 || RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
1003 {
1004 dirMap[pszSubDir].push_back(DESTFILEENTRY(Utf8Str(DirEntry.szName)));
1005 *pcObjects += 1;
1006 }
1007 break;
1008 }
1009
1010 default:
1011 break;
1012 }
1013 if (RT_FAILURE(rc))
1014 break;
1015 }
1016
1017 RTDirClose(pDir);
1018 }
1019 return rc;
1020}
1021
1022/**
1023 * Constructs a destinations map from a source entry and a destination root.
1024 *
1025 * @return IPRT status code.
1026 * @param fHostToGuest
1027 * @param sourceEntry Reference to a specified source entry to use.
1028 * @param fFlags Copy file flags. Needed for recursive directory parsing.
1029 * @param pszDestRoot Pointer to destination root. This can be used to add one or
1030 * more directories to the actual destination path.
1031 * @param mapDest Reference to the destination map for storing the actual result.
1032 * @param pcObjects Pointer to a total object (file) count to copy.
1033 */
1034static int ctrlCopyConstructDestinationsForGuest(SOURCEFILEENTRY &sourceEntry, uint32_t fFlags,
1035 const char *pszDestRoot, DESTDIRMAP &mapDest,
1036 uint32_t *pcObjects)
1037{
1038 int rc = VINF_SUCCESS;
1039 const char *pszSource = sourceEntry.mSource.c_str();
1040
1041 if ( RTPathFilename(pszSource)
1042 && RTFileExists(pszSource))
1043 {
1044 /* Source is a single file. */
1045 char *pszFileName = RTPathFilename(pszSource);
1046 mapDest[Utf8Str(pszDestRoot)].push_back(DESTFILEENTRY(pszFileName));
1047
1048 *pcObjects++;
1049 }
1050 else
1051 {
1052 /* Source is either a directory or a filter (e.g. *.dll). */
1053 rc = ctrlCopyDirectoryReadHost(pszSource,
1054 NULL /* pszSubDir */,
1055 sourceEntry.mFilter.isEmpty() ? NULL : sourceEntry.mFilter.c_str(),
1056 pszDestRoot, fFlags, pcObjects, mapDest);
1057 }
1058 return rc;
1059}
1060
1061static int ctrlCopyConstructDestinationsForHost(IGuest *pGuest,
1062 const char *pszUsername, const char *pszPassword,
1063 SOURCEFILEENTRY &sourceEntry, uint32_t fFlags,
1064 const char *pszDestRoot, DESTDIRMAP &mapDest,
1065 uint32_t *pcObjects)
1066{
1067 int rc = VINF_SUCCESS;
1068 const char *pszSource = sourceEntry.mSource.c_str();
1069
1070 BOOL fExists = FALSE;
1071 HRESULT hr = pGuest->FileExists(Bstr(pszSource).raw(),
1072 Bstr(pszUsername).raw(), Bstr(pszPassword).raw(), &fExists);
1073 if (FAILED(rc))
1074 rc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
1075 else
1076 {
1077 if (fExists)
1078 {
1079 /* Source is a single file. */
1080 char *pszFileName = RTPathFilename(pszSource);
1081 mapDest[Utf8Str(pszDestRoot)].push_back(DESTFILEENTRY(pszFileName));
1082
1083 *pcObjects++;
1084 }
1085 else
1086 {
1087 /* Source is either a directory or a filter (e.g. *.dll). */
1088 rc = ctrlCopyDirectoryReadGuest(pGuest, pszUsername, pszPassword,
1089 pszSource, NULL /* pszSubDir */,
1090 sourceEntry.mFilter.isEmpty() ? NULL : sourceEntry.mFilter.c_str(),
1091 pszDestRoot, fFlags, pcObjects, mapDest);
1092 }
1093 }
1094 return rc;
1095}
1096
1097/**
1098 * Determines the destination root for a specified source entry.
1099 *
1100 * @return IPRT status code.
1101 * @param ppszDestRoot Receives pointer of allocated destination root. Must be
1102 * free'd with ctrlCopyFreeDestinationRoot().
1103 * @param sourceEntry Source entry to determine the destination root for.
1104 * @param pszDest Original destination string to use.
1105 */
1106static int ctrlCopyAllocDestinationRoot(char **ppszDestRoot, SOURCEFILEENTRY &sourceEntry, const char *pszDest)
1107{
1108 AssertPtrReturn(ppszDestRoot, VERR_INVALID_POINTER);
1109 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1110
1111 int rc = VINF_SUCCESS;
1112
1113 /*
1114 * If a source filter is set (e.g. *.dll) use the original
1115 * destination as our final root, because we want to copy all filtered
1116 * files directly into the original root (and its sub directories if apply).
1117 */
1118 char *pszDestRoot;
1119 if (!sourceEntry.mFilter.isEmpty())
1120 pszDestRoot = RTStrDup(pszDest);
1121 else
1122 {
1123 /*
1124 * However, if no source filter is set we want to also copy the original
1125 * source directory to our destination so that source "c:\foo", dest "c:\temp"
1126 * becomes "c:\temp\foo".
1127 */
1128 int iLen = RTStrAPrintf(&pszDestRoot, "%s/%s",
1129 pszDest, RTPathFilename(sourceEntry.mSource.c_str()));
1130 if (!iLen)
1131 rc = VERR_NO_MEMORY;
1132 }
1133
1134 if (RT_SUCCESS(rc))
1135 *ppszDestRoot = pszDestRoot;
1136 return rc;
1137}
1138
1139/**
1140 * Frees a formerly allocated destination root.
1141 *
1142 * @param pszDestRoot Pointer to destination root to free.
1143 */
1144static void ctrlCopyFreeDestinationRoot(char *pszDestRoot)
1145{
1146 RTStrFree(pszDestRoot);
1147}
1148
1149/**
1150 * Prepares the destination directory hirarchy on the guest side by creating the directories
1151 * and sets the appropriate access rights.
1152 *
1153 * @return IPRT status code.
1154 * @param pGuest IGuest interface pointer.
1155 * @param fHostToGuest
1156 * @param itDest Destination map iterator to process.
1157 * @param pszDestRoot Destination root to use.
1158 * @param pszUsername Username to use.
1159 * @param pszPassword Password to use.
1160 */
1161static int ctrlCopyPrepareDestDirectory(IGuest *pGuest, bool fHostToGuest,
1162 DESTDIRMAPITER itDest, const char *pszDestRoot,
1163 const char *pszUsername, const char *pszPassword)
1164{
1165 AssertPtrReturn(pGuest, VERR_INVALID_POINTER);
1166 AssertPtrReturn(pszDestRoot, VERR_INVALID_POINTER);
1167 AssertPtrReturn(pszUsername, VERR_INVALID_POINTER);
1168 AssertPtrReturn(pszPassword, VERR_INVALID_POINTER);
1169
1170 char *pszDestFinal = NULL;
1171 int rc = VINF_SUCCESS;
1172
1173 /* Create root directory (= empty name) and skip the rest for
1174 * this round. */
1175 if (itDest->first.isEmpty())
1176 {
1177 pszDestFinal = RTStrDup(pszDestRoot);
1178 if (!pszDestFinal)
1179 rc = VERR_NO_MEMORY;
1180 }
1181 else /* Create sub-directories, also empty ones. */
1182 {
1183 if (!RTStrAPrintf(&pszDestFinal, "%s/%s", pszDestRoot, itDest->first.c_str()))
1184 rc = VERR_NO_MEMORY;
1185 }
1186
1187 if (RT_SUCCESS(rc) && pszDestFinal)
1188 {
1189 if (fHostToGuest) /* We want to create directories on the guest. */
1190 {
1191 HRESULT hrc = pGuest->DirectoryCreate(Bstr(pszDestFinal).raw(),
1192 Bstr(pszUsername).raw(), Bstr(pszPassword).raw(),
1193 700, DirectoryCreateFlag_Parents);
1194 if (FAILED(hrc))
1195 rc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
1196 }
1197 else /* ... or on the host. */
1198 {
1199 rc = RTDirCreate(pszDestFinal, 700);
1200 }
1201 RTStrFree(pszDestFinal);
1202 }
1203 return rc;
1204}
1205
1206/**
1207 * Copys a file from host to the guest.
1208 *
1209 * @return IPRT status code.
1210 * @param pGuest IGuest interface pointer.
1211 * @param pszSource Source path of existing host file to copy to the guest.
1212 * @param pszDest Destination path on guest to copy the file to.
1213 * @param pszUserName User name on guest to use for the copy operation.
1214 * @param pszPassword Password of user account.
1215 * @param fFlags Copy flags.
1216 */
1217static int ctrlCopyFileToGuest(IGuest *pGuest, const char *pszSource, const char *pszDest,
1218 const char *pszUserName, const char *pszPassword,
1219 uint32_t fFlags)
1220{
1221 AssertPtrReturn(pGuest, VERR_INVALID_POINTER);
1222 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1223 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1224 AssertPtrReturn(pszUserName, VERR_INVALID_POINTER);
1225 AssertPtrReturn(pszPassword, VERR_INVALID_POINTER);
1226
1227 int vrc = VINF_SUCCESS;
1228 ComPtr<IProgress> progress;
1229 HRESULT rc = pGuest->CopyToGuest(Bstr(pszSource).raw(), Bstr(pszDest).raw(),
1230 Bstr(pszUserName).raw(), Bstr(pszPassword).raw(),
1231 fFlags, progress.asOutParam());
1232 if (FAILED(rc))
1233 vrc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
1234 else
1235 {
1236 rc = showProgress(progress);
1237 if (FAILED(rc))
1238 vrc = ctrlPrintProgressError(progress);
1239 }
1240 return vrc;
1241}
1242
1243/**
1244 * Copys a file from guest to the host.
1245 *
1246 * @return IPRT status code.
1247 * @param pGuest IGuest interface pointer.
1248 * @param pszSource Source path of existing guest file to copy to the host.
1249 * @param pszDest Destination path/file on host to copy the file to.
1250 * @param pszUserName User name on guest to use for the copy operation.
1251 * @param pszPassword Password of user account.
1252 * @param fFlags Copy flags.
1253 */
1254static int ctrlCopyFileToHost(IGuest *pGuest, const char *pszSource, const char *pszDest,
1255 const char *pszUserName, const char *pszPassword,
1256 uint32_t fFlags)
1257{
1258 AssertPtrReturn(pGuest, VERR_INVALID_POINTER);
1259 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1260 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1261 AssertPtrReturn(pszUserName, VERR_INVALID_POINTER);
1262 AssertPtrReturn(pszPassword, VERR_INVALID_POINTER);
1263
1264 int vrc = VINF_SUCCESS;
1265 ComPtr<IProgress> progress;
1266 HRESULT rc = pGuest->CopyFromGuest(Bstr(pszSource).raw(), Bstr(pszDest).raw(),
1267 Bstr(pszUserName).raw(), Bstr(pszPassword).raw(),
1268 fFlags, progress.asOutParam());
1269 if (FAILED(rc))
1270 vrc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
1271 else
1272 {
1273 rc = showProgress(progress);
1274 if (FAILED(rc))
1275 vrc = ctrlPrintProgressError(progress);
1276 }
1277 return vrc;
1278}
1279
1280static int ctrlCopyToDestDirectory(IGuest *pGuest, bool fVerbose, bool fDryRun, bool fHostToGuest, DESTDIRMAPITER itDest, const char *pszDestRoot,
1281 SOURCEFILEENTRY &sourceEntry, uint32_t uFlags, const char *pszUsername, const char *pszPassword)
1282{
1283 AssertPtrReturn(pGuest, VERR_INVALID_POINTER);
1284 AssertPtrReturn(pszDestRoot, VERR_INVALID_POINTER);
1285 AssertPtrReturn(pszUsername, VERR_INVALID_POINTER);
1286 AssertPtrReturn(pszPassword, VERR_INVALID_POINTER);
1287
1288 int rc = VINF_SUCCESS;
1289 for (unsigned long l = 0; l < itDest->second.size(); l++)
1290 {
1291 int iLen;
1292 char *pszSource;
1293 if (itDest->first.isEmpty())
1294 iLen = RTStrAPrintf(&pszSource, "%s/%s", sourceEntry.mSource.c_str(),
1295 itDest->second[l].mFileName.c_str());
1296 else
1297 iLen = RTStrAPrintf(&pszSource, "%s/%s/%s", sourceEntry.mSource.c_str(),
1298 itDest->first.c_str(), itDest->second[l].mFileName.c_str());
1299 if (!iLen)
1300 {
1301 rc = VERR_NO_MEMORY;
1302 break;
1303 }
1304
1305 char *pszDest;
1306 if (itDest->first.isEmpty())
1307 iLen = RTStrAPrintf(&pszDest, "%s/%s", pszDestRoot,
1308 itDest->second[l].mFileName.c_str());
1309 else
1310 iLen = RTStrAPrintf(&pszDest, "%s/%s/%s", pszDestRoot, itDest->first.c_str(),
1311 itDest->second[l].mFileName.c_str());
1312 if (!iLen)
1313 {
1314 rc = VERR_NO_MEMORY;
1315 RTStrFree(pszSource);
1316 break;
1317 }
1318
1319 if (fVerbose)
1320 RTPrintf("\"%s\" -> \"%s\"\n", pszSource, pszDest);
1321
1322 /* Finally copy the desired file (if no dry run selected). */
1323 if (!fDryRun)
1324 {
1325 if (fHostToGuest)
1326 rc = ctrlCopyFileToGuest(pGuest, pszSource, pszDest,
1327 pszUsername, pszPassword, uFlags);
1328 else
1329 rc = ctrlCopyFileToHost(pGuest, pszSource, pszDest,
1330 pszUsername, pszPassword, uFlags);
1331 }
1332 RTStrFree(pszSource);
1333 RTStrFree(pszDest);
1334 }
1335 return rc;
1336}
1337
1338static int handleCtrlCopyTo(ComPtr<IGuest> guest, HandlerArg *pArg,
1339 bool fHostToGuest)
1340{
1341 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1342
1343 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
1344 * is much better (partly because it is much simpler of course). The main
1345 * arguments against this is that (1) all but two options conflicts with
1346 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
1347 * done windows CMD style (though not in a 100% compatible way), and (3)
1348 * that only one source is allowed - efficiently sabotaging default
1349 * wildcard expansion by a unix shell. The best solution here would be
1350 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
1351
1352 /*
1353 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1354 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1355 * does in here.
1356 */
1357
1358 static const RTGETOPTDEF s_aOptions[] =
1359 {
1360 { "--dryrun", GETOPTDEF_COPYTO_DRYRUN, RTGETOPT_REQ_NOTHING },
1361 { "--follow", GETOPTDEF_COPYTO_FOLLOW, RTGETOPT_REQ_NOTHING },
1362 { "--password", GETOPTDEF_COPYTO_PASSWORD, RTGETOPT_REQ_STRING },
1363 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1364 { "--target-directory", GETOPTDEF_COPYTO_TARGETDIR, RTGETOPT_REQ_STRING },
1365 { "--username", GETOPTDEF_COPYTO_USERNAME, RTGETOPT_REQ_STRING },
1366 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1367 };
1368
1369 int ch;
1370 RTGETOPTUNION ValueUnion;
1371 RTGETOPTSTATE GetState;
1372 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1373 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1374
1375 Utf8Str Utf8Source;
1376 Utf8Str Utf8Dest;
1377 Utf8Str Utf8UserName;
1378 Utf8Str Utf8Password;
1379 uint32_t fFlags = CopyFileFlag_None;
1380 bool fVerbose = false;
1381 bool fCopyRecursive = false;
1382 bool fDryRun = false;
1383
1384 SOURCEVEC vecSources;
1385
1386 int vrc = VINF_SUCCESS;
1387 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1388 {
1389 /* For options that require an argument, ValueUnion has received the value. */
1390 switch (ch)
1391 {
1392 case GETOPTDEF_COPYTO_DRYRUN:
1393 fDryRun = true;
1394 break;
1395
1396 case GETOPTDEF_COPYTO_FOLLOW:
1397 fFlags |= CopyFileFlag_FollowLinks;
1398 break;
1399
1400 case GETOPTDEF_COPYTO_PASSWORD:
1401 Utf8Password = ValueUnion.psz;
1402 break;
1403
1404 case 'R': /* Recursive processing */
1405 fFlags |= CopyFileFlag_Recursive;
1406 break;
1407
1408 case GETOPTDEF_COPYTO_TARGETDIR:
1409 Utf8Dest = ValueUnion.psz;
1410 break;
1411
1412 case GETOPTDEF_COPYTO_USERNAME:
1413 Utf8UserName = ValueUnion.psz;
1414 break;
1415
1416 case 'v': /* Verbose */
1417 fVerbose = true;
1418 break;
1419
1420 case VINF_GETOPT_NOT_OPTION:
1421 {
1422 /* Last argument and no destination specified with
1423 * --target-directory yet? Then use the current argument
1424 * as destination. */
1425 if ( pArg->argc == GetState.iNext
1426 && Utf8Dest.isEmpty())
1427 {
1428 Utf8Dest = ValueUnion.psz;
1429 }
1430 else
1431 {
1432 /* Save the source directory. */
1433 vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
1434 }
1435 break;
1436 }
1437
1438 default:
1439 return RTGetOptPrintError(ch, &ValueUnion);
1440 }
1441 }
1442
1443 if (!vecSources.size())
1444 return errorSyntax(USAGE_GUESTCONTROL,
1445 "No source(s) specified!");
1446
1447 if (Utf8Dest.isEmpty())
1448 return errorSyntax(USAGE_GUESTCONTROL,
1449 "No destination specified!");
1450
1451 if (Utf8UserName.isEmpty())
1452 return errorSyntax(USAGE_GUESTCONTROL,
1453 "No user name specified!");
1454
1455 /*
1456 * Done parsing arguments, do some more preparations.
1457 */
1458 if (fVerbose)
1459 {
1460 if (fHostToGuest)
1461 RTPrintf("Copying from host to guest ...\n");
1462 else
1463 RTPrintf("Copying from guest to host ...\n");
1464 if (fDryRun)
1465 RTPrintf("Dry run - no files copied!\n");
1466 }
1467
1468 /* Strip traling slash from destination path. */
1469 RTPathStripTrailingSlash(Utf8Dest.mutableRaw());
1470 Utf8Dest.jolt();
1471
1472 /*
1473 * Here starts the actual fun!
1474 */
1475 for (unsigned long s = 0; s < vecSources.size(); s++)
1476 {
1477 uint32_t cObjects = 0;
1478 DESTDIRMAP mapDest;
1479
1480 char *pszDestRoot;
1481 vrc = ctrlCopyAllocDestinationRoot(&pszDestRoot, vecSources[s], Utf8Dest.c_str());
1482 if (RT_SUCCESS(vrc))
1483 {
1484 if (fHostToGuest)
1485 vrc = ctrlCopyConstructDestinationsForGuest(vecSources[s], fFlags, pszDestRoot,
1486 mapDest, &cObjects);
1487 else
1488 vrc = ctrlCopyConstructDestinationsForHost(guest, Utf8UserName.c_str(), Utf8Password.c_str(),
1489 vecSources[s], fFlags, pszDestRoot,
1490 mapDest, &cObjects);
1491 if (RT_FAILURE(vrc))
1492 {
1493 if ( fVerbose
1494 && vrc == VERR_FILE_NOT_FOUND)
1495 {
1496 RTPrintf("Warning: Source \"%s\" does not exist, skipping!\n",
1497 vecSources[s].mSource.c_str());
1498 }
1499 }
1500 else
1501 {
1502 /*
1503 * Prepare directory structure of each destination directory.
1504 */
1505 DESTDIRMAPITER itDest;
1506 ComPtr<IProgress> progress;
1507 for (itDest = mapDest.begin(); itDest != mapDest.end(); itDest++)
1508 {
1509 if (!fDryRun)
1510 vrc = ctrlCopyPrepareDestDirectory(guest, fHostToGuest, itDest, pszDestRoot,
1511 Utf8UserName.c_str(), Utf8Password.c_str());
1512 if (RT_FAILURE(vrc))
1513 break;
1514 }
1515
1516 if (fVerbose)
1517 {
1518 if (!cObjects)
1519 RTPrintf("Warning: Source \"%s\" has no (matching) files to copy, skipping!\n",
1520 vecSources[s].mSource.c_str());
1521 else
1522 RTPrintf("Copying \"%s\" (%u files) ...\n",
1523 vecSources[s].mSource.c_str(), cObjects);
1524 }
1525
1526 /*
1527 * Copy files of each destination root directory to the guest.
1528 */
1529 for (itDest = mapDest.begin(); itDest != mapDest.end(); itDest++)
1530 {
1531 if (fVerbose && itDest->second.size())
1532 {
1533 if (itDest->first.isEmpty())
1534 RTPrintf("Copying %u files ...\n", itDest->second.size());
1535 else
1536 RTPrintf("Copying directory \"%s\" (%u files) ...\n",
1537 itDest->first.c_str(), itDest->second.size());
1538 }
1539
1540 vrc = ctrlCopyToDestDirectory(guest, fVerbose, fDryRun, fHostToGuest, itDest, pszDestRoot,
1541 vecSources[s], fFlags, Utf8UserName.c_str(), Utf8Password.c_str());
1542 if (RT_FAILURE(vrc))
1543 break;
1544 }
1545 }
1546 ctrlCopyFreeDestinationRoot(pszDestRoot);
1547 }
1548 }
1549
1550 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1551}
1552
1553static int handleCtrlCreateDirectory(ComPtr<IGuest> guest, HandlerArg *pArg)
1554{
1555 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1556
1557 /*
1558 * Parse arguments.
1559 *
1560 * Note! No direct returns here, everyone must go thru the cleanup at the
1561 * end of this function.
1562 */
1563 static const RTGETOPTDEF s_aOptions[] =
1564 {
1565 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
1566 { "--parents", 'P', RTGETOPT_REQ_NOTHING },
1567 { "--password", 'p', RTGETOPT_REQ_STRING },
1568 { "--username", 'u', RTGETOPT_REQ_STRING },
1569 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1570 };
1571
1572 int ch;
1573 RTGETOPTUNION ValueUnion;
1574 RTGETOPTSTATE GetState;
1575 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1576 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1577
1578 Utf8Str Utf8UserName;
1579 Utf8Str Utf8Password;
1580 uint32_t fFlags = DirectoryCreateFlag_None;
1581 uint32_t fDirMode = 0; /* Default mode. */
1582 bool fVerbose = false;
1583
1584 DESTDIRMAP mapDirs;
1585
1586 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1587 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1588 && rcExit == RTEXITCODE_SUCCESS)
1589 {
1590 /* For options that require an argument, ValueUnion has received the value. */
1591 switch (ch)
1592 {
1593 case 'm': /* Mode */
1594 fDirMode = ValueUnion.u32;
1595 break;
1596
1597 case 'P': /* Create parents */
1598 fFlags |= DirectoryCreateFlag_Parents;
1599 break;
1600
1601 case 'p': /* Password */
1602 Utf8Password = ValueUnion.psz;
1603 break;
1604
1605 case 'u': /* User name */
1606 Utf8UserName = ValueUnion.psz;
1607 break;
1608
1609 case 'v': /* Verbose */
1610 fVerbose = true;
1611 break;
1612
1613 case VINF_GETOPT_NOT_OPTION:
1614 {
1615 mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
1616 break;
1617 }
1618
1619 default:
1620 rcExit = RTGetOptPrintError(ch, &ValueUnion);
1621 break;
1622 }
1623 }
1624
1625 uint32_t cDirs = mapDirs.size();
1626 if (rcExit == RTEXITCODE_SUCCESS && !cDirs)
1627 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No directory to create specified!");
1628
1629 if (rcExit == RTEXITCODE_SUCCESS && Utf8UserName.isEmpty())
1630 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
1631
1632 if (rcExit == RTEXITCODE_SUCCESS)
1633 {
1634 /*
1635 * Create the directories.
1636 */
1637 HRESULT hrc = S_OK;
1638 if (fVerbose && cDirs)
1639 RTPrintf("Creating %u directories ...\n", cDirs);
1640
1641 DESTDIRMAPITER it = mapDirs.begin();
1642 while (it != mapDirs.end())
1643 {
1644 if (fVerbose)
1645 RTPrintf("Creating directory \"%s\" ...\n", it->first.c_str());
1646
1647 hrc = guest->DirectoryCreate(Bstr(it->first).raw(),
1648 Bstr(Utf8UserName).raw(), Bstr(Utf8Password).raw(),
1649 fDirMode, fFlags);
1650 if (FAILED(hrc))
1651 {
1652 ctrlPrintError(guest, COM_IIDOF(IGuest)); /* Return code ignored, save original rc. */
1653 break;
1654 }
1655
1656 it++;
1657 }
1658
1659 if (FAILED(hrc))
1660 rcExit = RTEXITCODE_FAILURE;
1661 }
1662
1663 return rcExit;
1664}
1665
1666static int handleCtrlUpdateAdditions(ComPtr<IGuest> guest, HandlerArg *pArg)
1667{
1668 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1669
1670 /*
1671 * Check the syntax. We can deduce the correct syntax from the number of
1672 * arguments.
1673 */
1674 Utf8Str Utf8Source;
1675 bool fVerbose = false;
1676
1677 static const RTGETOPTDEF s_aOptions[] =
1678 {
1679 { "--source", 's', RTGETOPT_REQ_STRING },
1680 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1681 };
1682
1683 int ch;
1684 RTGETOPTUNION ValueUnion;
1685 RTGETOPTSTATE GetState;
1686 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, 0);
1687
1688 int vrc = VINF_SUCCESS;
1689 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1690 && RT_SUCCESS(vrc))
1691 {
1692 switch (ch)
1693 {
1694 case 's':
1695 Utf8Source = ValueUnion.psz;
1696 break;
1697
1698 case 'v':
1699 fVerbose = true;
1700 break;
1701
1702 default:
1703 return RTGetOptPrintError(ch, &ValueUnion);
1704 }
1705 }
1706
1707 if (fVerbose)
1708 RTPrintf("Updating Guest Additions ...\n");
1709
1710#ifdef DEBUG_andy
1711 if (Utf8Source.isEmpty())
1712 Utf8Source = "c:\\Downloads\\VBoxGuestAdditions-r67158.iso";
1713#endif
1714
1715 /* Determine source if not set yet. */
1716 if (Utf8Source.isEmpty())
1717 {
1718 char strTemp[RTPATH_MAX];
1719 vrc = RTPathAppPrivateNoArch(strTemp, sizeof(strTemp));
1720 AssertRC(vrc);
1721 Utf8Str Utf8Src1 = Utf8Str(strTemp).append("/VBoxGuestAdditions.iso");
1722
1723 vrc = RTPathExecDir(strTemp, sizeof(strTemp));
1724 AssertRC(vrc);
1725 Utf8Str Utf8Src2 = Utf8Str(strTemp).append("/additions/VBoxGuestAdditions.iso");
1726
1727 /* Check the standard image locations */
1728 if (RTFileExists(Utf8Src1.c_str()))
1729 Utf8Source = Utf8Src1;
1730 else if (RTFileExists(Utf8Src2.c_str()))
1731 Utf8Source = Utf8Src2;
1732 else
1733 {
1734 RTMsgError("Source could not be determined! Please use --source to specify a valid source.\n");
1735 vrc = VERR_FILE_NOT_FOUND;
1736 }
1737 }
1738 else if (!RTFileExists(Utf8Source.c_str()))
1739 {
1740 RTMsgError("Source \"%s\" does not exist!\n", Utf8Source.c_str());
1741 vrc = VERR_FILE_NOT_FOUND;
1742 }
1743
1744 if (RT_SUCCESS(vrc))
1745 {
1746 if (fVerbose)
1747 RTPrintf("Using source: %s\n", Utf8Source.c_str());
1748
1749 HRESULT rc = S_OK;
1750 ComPtr<IProgress> progress;
1751 CHECK_ERROR(guest, UpdateGuestAdditions(Bstr(Utf8Source).raw(),
1752 /* Wait for whole update process to complete. */
1753 AdditionsUpdateFlag_None,
1754 progress.asOutParam()));
1755 if (FAILED(rc))
1756 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
1757 else
1758 {
1759 rc = showProgress(progress);
1760 if (FAILED(rc))
1761 vrc = ctrlPrintProgressError(progress);
1762 else if (fVerbose)
1763 RTPrintf("Guest Additions update successful.\n");
1764 }
1765 }
1766
1767 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1768}
1769
1770/**
1771 * Access the guest control store.
1772 *
1773 * @returns program exit code.
1774 * @note see the command line API description for parameters
1775 */
1776int handleGuestControl(HandlerArg *pArg)
1777{
1778 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1779
1780 HandlerArg arg = *pArg;
1781 arg.argc = pArg->argc - 2; /* Skip VM name and sub command. */
1782 arg.argv = pArg->argv + 2; /* Same here. */
1783
1784 ComPtr<IGuest> guest;
1785 int vrc = ctrlInitVM(pArg, pArg->argv[0] /* VM Name */, &guest);
1786 if (RT_SUCCESS(vrc))
1787 {
1788 int rcExit;
1789 if ( !strcmp(pArg->argv[1], "exec")
1790 || !strcmp(pArg->argv[1], "execute"))
1791 {
1792 rcExit = handleCtrlExecProgram(guest, &arg);
1793 }
1794 else if (!strcmp(pArg->argv[1], "copyfrom"))
1795 {
1796 rcExit = handleCtrlCopyTo(guest, &arg,
1797 false /* Guest to host */);
1798 }
1799 else if ( !strcmp(pArg->argv[1], "copyto")
1800 || !strcmp(pArg->argv[1], "cp"))
1801 {
1802 rcExit = handleCtrlCopyTo(guest, &arg,
1803 true /* Host to guest */);
1804 }
1805 else if ( !strcmp(pArg->argv[1], "createdirectory")
1806 || !strcmp(pArg->argv[1], "createdir")
1807 || !strcmp(pArg->argv[1], "mkdir")
1808 || !strcmp(pArg->argv[1], "md"))
1809 {
1810 rcExit = handleCtrlCreateDirectory(guest, &arg);
1811 }
1812 else if ( !strcmp(pArg->argv[1], "updateadditions")
1813 || !strcmp(pArg->argv[1], "updateadds"))
1814 {
1815 rcExit = handleCtrlUpdateAdditions(guest, &arg);
1816 }
1817 else
1818 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No sub command specified!");
1819
1820 ctrlUninitVM(pArg);
1821 return rcExit;
1822 }
1823 return RTEXITCODE_FAILURE;
1824}
1825
1826#endif /* !VBOX_ONLY_DOCS */
1827
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