VirtualBox

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

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

GuestCtrl: Update.

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

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