VirtualBox

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

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

VBoxManage: allow tot save the state of a VM which is already paused

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 49.8 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 35707 2011-01-25 12:53:39Z vboxsync $ */
2/** @file
3 * VBoxManage - Implementation of guestcontrol command.
4 */
5
6/*
7 * Copyright (C) 2010 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
32#include <VBox/com/VirtualBox.h>
33#include <VBox/com/EventQueue.h>
34
35#include <VBox/HostServices/GuestControlSvc.h> /* for PROC_STS_XXX */
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#ifdef USE_XPCOM_QUEUE
47# include <sys/select.h>
48# include <errno.h>
49#endif
50
51#include <signal.h>
52
53#ifdef RT_OS_DARWIN
54# include <CoreFoundation/CFRunLoop.h>
55#endif
56
57using namespace com;
58
59/**
60 * IVirtualBoxCallback implementation for handling the GuestControlCallback in
61 * relation to the "guestcontrol * wait" command.
62 */
63/** @todo */
64
65/** Set by the signal handler. */
66static volatile bool g_fGuestCtrlCanceled = false;
67
68/*
69 * Structure holding a directory entry.
70 */
71typedef struct DIRECTORYENTRY
72{
73 char *pszSourcePath;
74 char *pszDestPath;
75 RTLISTNODE Node;
76} DIRECTORYENTRY, *PDIRECTORYENTRY;
77
78#endif /* VBOX_ONLY_DOCS */
79
80void usageGuestControl(PRTSTREAM pStrm)
81{
82 RTStrmPrintf(pStrm,
83 "VBoxManage guestcontrol exec[ute] <vmname>|<uuid>\n"
84 " <path to program>\n"
85 " --username <name> --password <password>\n"
86 " [--arguments \"<arguments>\"]\n"
87 " [--environment \"<NAME>=<VALUE> [<NAME>=<VALUE>]\"]\n"
88 " [--flags <flags>] [--timeout <msec>]\n"
89 " [--verbose] [--wait-for exit,stdout,stderr||]\n"
90 /** @todo Add a "--" parameter (has to be last parameter) to directly execute
91 * stuff, e.g. "VBoxManage guestcontrol execute <VMName> --username <> ... -- /bin/rm -Rf /foo". */
92 "\n"
93 " copyto|cp <vmname>|<uuid>\n"
94 " <source on host> <destination on guest>\n"
95 " --username <name> --password <password>\n"
96 " [--dryrun] [--follow] [--recursive] [--verbose]\n"
97 "\n"
98 " createdir[ectory]|mkdir|md <vmname>|<uuid>\n"
99 " <directory to create on guest>\n"
100 " --username <name> --password <password>\n"
101 " [--parents] [--mode <mode>] [--verbose]\n"
102 "\n"
103 " updateadditions <vmname>|<uuid>\n"
104 " [--source <guest additions .ISO>] [--verbose]\n"
105 "\n");
106}
107
108#ifndef VBOX_ONLY_DOCS
109
110/**
111 * Signal handler that sets g_fGuestCtrlCanceled.
112 *
113 * This can be executed on any thread in the process, on Windows it may even be
114 * a thread dedicated to delivering this signal. Do not doing anything
115 * unnecessary here.
116 */
117static void guestCtrlSignalHandler(int iSignal)
118{
119 NOREF(iSignal);
120 ASMAtomicWriteBool(&g_fGuestCtrlCanceled, true);
121}
122
123/**
124 * Installs a custom signal handler to get notified
125 * whenever the user wants to intercept the program.
126 */
127static void ctrlSignalHandlerInstall()
128{
129 signal(SIGINT, guestCtrlSignalHandler);
130#ifdef SIGBREAK
131 signal(SIGBREAK, guestCtrlSignalHandler);
132#endif
133}
134
135/**
136 * Uninstalls a previously installed signal handler.
137 */
138static void ctrlSignalHandlerUninstall()
139{
140 signal(SIGINT, SIG_DFL);
141#ifdef SIGBREAK
142 signal(SIGBREAK, SIG_DFL);
143#endif
144}
145
146/**
147 * Translates a process status to a human readable
148 * string.
149 */
150static const char *ctrlExecGetStatus(ULONG uStatus)
151{
152 switch (uStatus)
153 {
154 case guestControl::PROC_STS_STARTED:
155 return "started";
156 case guestControl::PROC_STS_TEN:
157 return "successfully terminated";
158 case guestControl::PROC_STS_TES:
159 return "terminated by signal";
160 case guestControl::PROC_STS_TEA:
161 return "abnormally aborted";
162 case guestControl::PROC_STS_TOK:
163 return "timed out";
164 case guestControl::PROC_STS_TOA:
165 return "timed out, hanging";
166 case guestControl::PROC_STS_DWN:
167 return "killed";
168 case guestControl::PROC_STS_ERROR:
169 return "error";
170 default:
171 return "unknown";
172 }
173}
174
175static int ctrlPrintError(com::ErrorInfo &errorInfo)
176{
177 if ( errorInfo.isFullAvailable()
178 || errorInfo.isBasicAvailable())
179 {
180 /* If we got a VBOX_E_IPRT error we handle the error in a more gentle way
181 * because it contains more accurate info about what went wrong. */
182 if (errorInfo.getResultCode() == VBOX_E_IPRT_ERROR)
183 RTMsgError("%ls.", errorInfo.getText().raw());
184 else
185 {
186 RTMsgError("Error details:");
187 GluePrintErrorInfo(errorInfo);
188 }
189 return VERR_GENERAL_FAILURE; /** @todo */
190 }
191 AssertMsgFailedReturn(("Object has indicated no error!?\n"),
192 VERR_INVALID_PARAMETER);
193}
194
195static int ctrlPrintError(IUnknown *pObj, const GUID &aIID)
196{
197 com::ErrorInfo ErrInfo(pObj, aIID);
198 return ctrlPrintError(ErrInfo);
199}
200
201
202static int ctrlPrintProgressError(ComPtr<IProgress> progress)
203{
204 int rc;
205 BOOL fCanceled;
206 if ( SUCCEEDED(progress->COMGETTER(Canceled(&fCanceled)))
207 && fCanceled)
208 {
209 rc = VERR_CANCELLED;
210 }
211 else
212 {
213 com::ProgressErrorInfo ErrInfo(progress);
214 rc = ctrlPrintError(ErrInfo);
215 }
216 return rc;
217}
218
219/**
220 * Un-initializes the VM after guest control usage.
221 */
222static void ctrlUninitVM(HandlerArg *pArg)
223{
224 AssertPtrReturnVoid(pArg);
225 if (pArg->session)
226 pArg->session->UnlockMachine();
227}
228
229/**
230 * Initializes the VM, that is checks whether it's up and
231 * running, if it can be locked (shared only) and returns a
232 * valid IGuest pointer on success.
233 *
234 * @return IPRT status code.
235 * @param pArg Our command line argument structure.
236 * @param pszNameOrId The VM's name or UUID to use.
237 * @param pGuest Pointer where to store the IGuest interface.
238 */
239static int ctrlInitVM(HandlerArg *pArg, const char *pszNameOrId, ComPtr<IGuest> *pGuest)
240{
241 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
242 AssertPtrReturn(pszNameOrId, VERR_INVALID_PARAMETER);
243
244 /* Lookup VM. */
245 ComPtr<IMachine> machine;
246 /* Assume it's an UUID. */
247 HRESULT rc;
248 CHECK_ERROR(pArg->virtualBox, FindMachine(Bstr(pszNameOrId).raw(),
249 machine.asOutParam()));
250 if (FAILED(rc))
251 return VERR_NOT_FOUND;
252
253 /* Machine is running? */
254 MachineState_T machineState;
255 CHECK_ERROR_RET(machine, COMGETTER(State)(&machineState), 1);
256 if (machineState != MachineState_Running)
257 {
258 RTMsgError("Machine \"%s\" is not running (currently %s)!\n",
259 pszNameOrId, stateToName(machineState, false));
260 return VERR_VM_INVALID_VM_STATE;
261 }
262
263 do
264 {
265 /* Open a session for the VM. */
266 CHECK_ERROR_BREAK(machine, LockMachine(pArg->session, LockType_Shared));
267 /* Get the associated console. */
268 ComPtr<IConsole> console;
269 CHECK_ERROR_BREAK(pArg->session, COMGETTER(Console)(console.asOutParam()));
270 /* ... and session machine. */
271 ComPtr<IMachine> sessionMachine;
272 CHECK_ERROR_BREAK(pArg->session, COMGETTER(Machine)(sessionMachine.asOutParam()));
273 /* Get IGuest interface. */
274 CHECK_ERROR_BREAK(console, COMGETTER(Guest)(pGuest->asOutParam()));
275 } while (0);
276
277 if (FAILED(rc))
278 ctrlUninitVM(pArg);
279 return SUCCEEDED(rc) ? VINF_SUCCESS : VERR_GENERAL_FAILURE;
280}
281
282static int handleCtrlExecProgram(HandlerArg *a)
283{
284 /*
285 * Check the syntax. We can deduce the correct syntax from the number of
286 * arguments.
287 */
288 if (a->argc < 2) /* At least the command we want to execute in the guest should be present :-). */
289 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
290
291 static const RTGETOPTDEF s_aOptions[] =
292 {
293 { "--arguments", 'a', RTGETOPT_REQ_STRING },
294 { "--environment", 'e', RTGETOPT_REQ_STRING },
295 { "--flags", 'f', RTGETOPT_REQ_STRING },
296 { "--password", 'p', RTGETOPT_REQ_STRING },
297 { "--timeout", 't', RTGETOPT_REQ_UINT32 },
298 { "--username", 'u', RTGETOPT_REQ_STRING },
299 { "--verbose", 'v', RTGETOPT_REQ_NOTHING },
300 { "--wait-for", 'w', RTGETOPT_REQ_STRING }
301 };
302
303 int ch;
304 RTGETOPTUNION ValueUnion;
305 RTGETOPTSTATE GetState;
306 RTGetOptInit(&GetState, a->argc, a->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
307
308 Utf8Str Utf8Cmd;
309 uint32_t uFlags = 0;
310 /* Note: this uses IN_BSTR as it must be BSTR on COM and CBSTR on XPCOM */
311 com::SafeArray<IN_BSTR> args;
312 com::SafeArray<IN_BSTR> env;
313 Utf8Str Utf8UserName;
314 Utf8Str Utf8Password;
315 uint32_t u32TimeoutMS = 0;
316 bool fWaitForExit = false;
317 bool fWaitForStdOut = false;
318 bool fWaitForStdErr = false;
319 bool fVerbose = false;
320
321 int vrc = VINF_SUCCESS;
322 bool fUsageOK = true;
323 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
324 && RT_SUCCESS(vrc))
325 {
326 /* For options that require an argument, ValueUnion has received the value. */
327 switch (ch)
328 {
329 case 'a': /* Arguments */
330 {
331 char **papszArg;
332 int cArgs;
333
334 vrc = RTGetOptArgvFromString(&papszArg, &cArgs, ValueUnion.psz, NULL);
335 if (RT_SUCCESS(vrc))
336 {
337 for (int j = 0; j < cArgs; j++)
338 args.push_back(Bstr(papszArg[j]).raw());
339
340 RTGetOptArgvFree(papszArg);
341 }
342 break;
343 }
344
345 case 'e': /* Environment */
346 {
347 char **papszArg;
348 int cArgs;
349
350 vrc = RTGetOptArgvFromString(&papszArg, &cArgs, ValueUnion.psz, NULL);
351 if (RT_SUCCESS(vrc))
352 {
353 for (int j = 0; j < cArgs; j++)
354 env.push_back(Bstr(papszArg[j]).raw());
355
356 RTGetOptArgvFree(papszArg);
357 }
358 break;
359 }
360
361 case 'f': /* Flags */
362 /** @todo Needs a bit better processing as soon as we have more flags. */
363 /** @todo Add a hidden flag. */
364 if (!RTStrICmp(ValueUnion.psz, "ignoreorphanedprocesses"))
365 uFlags |= ExecuteProcessFlag_IgnoreOrphanedProcesses;
366 else
367 fUsageOK = false;
368 break;
369
370 case 'p': /* Password */
371 Utf8Password = ValueUnion.psz;
372 break;
373
374 case 't': /* Timeout */
375 u32TimeoutMS = ValueUnion.u32;
376 break;
377
378 case 'u': /* User name */
379 Utf8UserName = ValueUnion.psz;
380 break;
381
382 case 'v': /* Verbose */
383 fVerbose = true;
384 break;
385
386 case 'w': /* Wait for ... */
387 {
388 if (!RTStrICmp(ValueUnion.psz, "exit"))
389 fWaitForExit = true;
390 else if (!RTStrICmp(ValueUnion.psz, "stdout"))
391 {
392 fWaitForExit = true;
393 fWaitForStdOut = true;
394 }
395 else if (!RTStrICmp(ValueUnion.psz, "stderr"))
396 {
397 fWaitForExit = true;
398 fWaitForStdErr = true;
399 }
400 else
401 fUsageOK = false;
402 break;
403 }
404
405 case VINF_GETOPT_NOT_OPTION:
406 {
407 /* The actual command we want to execute on the guest. */
408 Utf8Cmd = ValueUnion.psz;
409 break;
410 }
411
412 default:
413 return RTGetOptPrintError(ch, &ValueUnion);
414 }
415 }
416
417 if (!fUsageOK)
418 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
419
420 if (Utf8Cmd.isEmpty())
421 return errorSyntax(USAGE_GUESTCONTROL,
422 "No command to execute specified!");
423
424 if (Utf8UserName.isEmpty())
425 return errorSyntax(USAGE_GUESTCONTROL,
426 "No user name specified!");
427
428 HRESULT rc = S_OK;
429 ComPtr<IGuest> guest;
430 vrc = ctrlInitVM(a, a->argv[0] /* VM Name */, &guest);
431 if (RT_SUCCESS(vrc))
432 {
433 ComPtr<IProgress> progress;
434 ULONG uPID = 0;
435
436 if (fVerbose)
437 {
438 if (u32TimeoutMS == 0)
439 RTPrintf("Waiting for guest to start process ...\n");
440 else
441 RTPrintf("Waiting for guest to start process (within %ums)\n", u32TimeoutMS);
442 }
443
444 /* Get current time stamp to later calculate rest of timeout left. */
445 uint64_t u64StartMS = RTTimeMilliTS();
446
447 /* Execute the process. */
448 rc = guest->ExecuteProcess(Bstr(Utf8Cmd).raw(), uFlags,
449 ComSafeArrayAsInParam(args),
450 ComSafeArrayAsInParam(env),
451 Bstr(Utf8UserName).raw(),
452 Bstr(Utf8Password).raw(), u32TimeoutMS,
453 &uPID, progress.asOutParam());
454 if (FAILED(rc))
455 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
456 else
457 {
458 if (fVerbose)
459 RTPrintf("Process '%s' (PID: %u) started\n", Utf8Cmd.c_str(), uPID);
460 if (fWaitForExit)
461 {
462 if (u32TimeoutMS) /* Wait with a certain timeout. */
463 {
464 /* Calculate timeout value left after process has been started. */
465 uint64_t u64Elapsed = RTTimeMilliTS() - u64StartMS;
466 /* Is timeout still bigger than current difference? */
467 if (u32TimeoutMS > u64Elapsed)
468 {
469 if (fVerbose)
470 RTPrintf("Waiting for process to exit (%ums left) ...\n", u32TimeoutMS - u64Elapsed);
471 }
472 else
473 {
474 if (fVerbose)
475 RTPrintf("No time left to wait for process!\n");
476 }
477 }
478 else if (fVerbose) /* Wait forever. */
479 RTPrintf("Waiting for process to exit ...\n");
480
481 /* Setup signal handling if cancelable. */
482 ASSERT(progress);
483 bool fCanceledAlready = false;
484 BOOL fCancelable;
485 HRESULT hrc = progress->COMGETTER(Cancelable)(&fCancelable);
486 if (FAILED(hrc))
487 fCancelable = FALSE;
488 if (fCancelable)
489 ctrlSignalHandlerInstall();
490
491 /* Wait for process to exit ... */
492 BOOL fCompleted = FALSE;
493 BOOL fCanceled = FALSE;
494 while (SUCCEEDED(progress->COMGETTER(Completed(&fCompleted))))
495 {
496 SafeArray<BYTE> aOutputData;
497 ULONG cbOutputData = 0;
498
499 /*
500 * Some data left to output?
501 */
502 if ( fWaitForStdOut
503 || fWaitForStdErr)
504 {
505 rc = guest->GetProcessOutput(uPID, 0 /* aFlags */,
506 RT_MAX(0, u32TimeoutMS - (RTTimeMilliTS() - u64StartMS)) /* Timeout in ms */,
507 _64K, ComSafeArrayAsOutParam(aOutputData));
508 if (FAILED(rc))
509 {
510 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
511 cbOutputData = 0;
512 }
513 else
514 {
515 cbOutputData = aOutputData.size();
516 if (cbOutputData > 0)
517 {
518 /* aOutputData has a platform dependent line ending, standardize on
519 * Unix style, as RTStrmWrite does the LF -> CR/LF replacement on
520 * Windows. Otherwise we end up with CR/CR/LF on Windows. */
521 ULONG cbOutputDataPrint = cbOutputData;
522 for (BYTE *s = aOutputData.raw(), *d = s;
523 s - aOutputData.raw() < (ssize_t)cbOutputData;
524 s++, d++)
525 {
526 if (*s == '\r')
527 {
528 /* skip over CR, adjust destination */
529 d--;
530 cbOutputDataPrint--;
531 }
532 else if (s != d)
533 *d = *s;
534 }
535 RTStrmWrite(g_pStdOut, aOutputData.raw(), cbOutputDataPrint);
536 }
537 }
538 }
539
540 /* No more output data left? Then wait a little while ... */
541 if (cbOutputData <= 0)
542 progress->WaitForCompletion(1 /* ms */);
543
544 /* Process async cancelation */
545 if (g_fGuestCtrlCanceled && !fCanceledAlready)
546 {
547 hrc = progress->Cancel();
548 if (SUCCEEDED(hrc))
549 fCanceledAlready = TRUE;
550 else
551 g_fGuestCtrlCanceled = false;
552 }
553
554 /* Progress canceled by Main API? */
555 if ( SUCCEEDED(progress->COMGETTER(Canceled(&fCanceled)))
556 && fCanceled)
557 {
558 break;
559 }
560
561 /* Did we run out of time? */
562 if ( u32TimeoutMS
563 && RTTimeMilliTS() - u64StartMS > u32TimeoutMS)
564 {
565 progress->Cancel();
566 break;
567 }
568 }
569
570 /* Undo signal handling */
571 if (fCancelable)
572 ctrlSignalHandlerUninstall();
573
574 if (fCanceled)
575 {
576 if (fVerbose)
577 RTPrintf("Process execution canceled!\n");
578 }
579 else if ( fCompleted
580 && SUCCEEDED(rc))
581 {
582 LONG iRc;
583 CHECK_ERROR_RET(progress, COMGETTER(ResultCode)(&iRc), rc);
584 if (FAILED(iRc))
585 {
586 vrc = ctrlPrintProgressError(progress);
587 }
588 else if (fVerbose)
589 {
590 ULONG uRetStatus, uRetExitCode, uRetFlags;
591 rc = guest->GetProcessStatus(uPID, &uRetExitCode, &uRetFlags, &uRetStatus);
592 if (SUCCEEDED(rc))
593 RTPrintf("Exit code=%u (Status=%u [%s], Flags=%u)\n", uRetExitCode, uRetStatus, ctrlExecGetStatus(uRetStatus), uRetFlags);
594 }
595 }
596 else
597 {
598 if (fVerbose)
599 RTPrintf("Process execution aborted!\n");
600 }
601 }
602 }
603 ctrlUninitVM(a);
604 }
605
606 if (RT_FAILURE(vrc))
607 rc = VBOX_E_IPRT_ERROR;
608 return SUCCEEDED(rc) ? 0 : 1;
609}
610
611/**
612 * Appends a new file/directory entry to a given list.
613 *
614 * @return IPRT status code.
615 * @param pszFileSource Full qualified source path of file to copy (optional).
616 * @param pszFileDest Full qualified destination path (optional).
617 * @param pList Copy list used for insertion.
618 */
619static int ctrlDirectoryEntryAppend(const char *pszFileSource, const char *pszFileDest,
620 PRTLISTNODE pList)
621{
622 AssertPtrReturn(pList, VERR_INVALID_POINTER);
623 AssertReturn(pszFileSource || pszFileDest, VERR_INVALID_PARAMETER);
624
625 PDIRECTORYENTRY pNode = (PDIRECTORYENTRY)RTMemAlloc(sizeof(DIRECTORYENTRY));
626 if (pNode == NULL)
627 return VERR_NO_MEMORY;
628
629 pNode->pszSourcePath = NULL;
630 pNode->pszDestPath = NULL;
631
632 if (pszFileSource)
633 {
634 pNode->pszSourcePath = RTStrDup(pszFileSource);
635 AssertPtrReturn(pNode->pszSourcePath, VERR_NO_MEMORY);
636 }
637 if (pszFileDest)
638 {
639 pNode->pszDestPath = RTStrDup(pszFileDest);
640 AssertPtrReturn(pNode->pszDestPath, VERR_NO_MEMORY);
641 }
642
643 pNode->Node.pPrev = NULL;
644 pNode->Node.pNext = NULL;
645 RTListAppend(pList, &pNode->Node);
646 return VINF_SUCCESS;
647}
648
649/**
650 * Destroys a directory list.
651 *
652 * @param pList Pointer to list to destroy.
653 */
654static void ctrlDirectoryListDestroy(PRTLISTNODE pList)
655{
656 AssertPtr(pList);
657
658 /* Destroy file list. */
659 PDIRECTORYENTRY pNode = RTListGetFirst(pList, DIRECTORYENTRY, Node);
660 while (pNode)
661 {
662 PDIRECTORYENTRY pNext = RTListNodeGetNext(&pNode->Node, DIRECTORYENTRY, Node);
663 bool fLast = RTListNodeIsLast(pList, &pNode->Node);
664
665 if (pNode->pszSourcePath)
666 RTStrFree(pNode->pszSourcePath);
667 if (pNode->pszDestPath)
668 RTStrFree(pNode->pszDestPath);
669 RTListNodeRemove(&pNode->Node);
670 RTMemFree(pNode);
671
672 if (fLast)
673 break;
674
675 pNode = pNext;
676 }
677}
678
679
680/**
681 * Reads a specified directory (recursively) based on the copy flags
682 * and appends all matching entries to the supplied list.
683 *
684 * @return IPRT status code.
685 * @param pszRootDir Directory to start with. Must end with
686 * a trailing slash and must be absolute.
687 * @param pszSubDir Sub directory part relative to the root
688 * directory; needed for recursion.
689 * @param pszFilter Search filter (e.g. *.pdf).
690 * @param pszDest Destination directory.
691 * @param uFlags Copy flags.
692 * @param pcObjects Where to store the overall objects to
693 * copy found.
694 * @param pList Pointer to the object list to use.
695 */
696static int ctrlCopyDirectoryRead(const char *pszRootDir, const char *pszSubDir,
697 const char *pszFilter, const char *pszDest,
698 uint32_t uFlags, uint32_t *pcObjects, PRTLISTNODE pList)
699{
700 AssertPtrReturn(pszRootDir, VERR_INVALID_POINTER);
701 /* Sub directory is optional. */
702 /* Filter directory is optional. */
703 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
704 AssertPtrReturn(pcObjects, VERR_INVALID_POINTER);
705 AssertPtrReturn(pList, VERR_INVALID_POINTER);
706
707 PRTDIR pDir = NULL;
708
709 int rc = VINF_SUCCESS;
710 char szCurDir[RTPATH_MAX];
711 /* Construct current path. */
712 if (RTStrPrintf(szCurDir, sizeof(szCurDir), pszRootDir))
713 {
714 if (pszSubDir != NULL)
715 rc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
716 }
717 else
718 rc = VERR_NO_MEMORY;
719
720 if (RT_SUCCESS(rc))
721 {
722 /* Open directory without a filter - RTDirOpenFiltered unfortunately
723 * cannot handle sub directories so we have to do the filtering ourselves. */
724 rc = RTDirOpen(&pDir, szCurDir);
725 for (;RT_SUCCESS(rc);)
726 {
727 RTDIRENTRY DirEntry;
728 rc = RTDirRead(pDir, &DirEntry, NULL);
729 if (RT_FAILURE(rc))
730 {
731 if (rc == VERR_NO_MORE_FILES)
732 rc = VINF_SUCCESS;
733 break;
734 }
735 switch (DirEntry.enmType)
736 {
737 case RTDIRENTRYTYPE_DIRECTORY:
738 /* Skip "." and ".." entrires. */
739 if ( !strcmp(DirEntry.szName, ".")
740 || !strcmp(DirEntry.szName, ".."))
741 {
742 break;
743 }
744 if (uFlags & CopyFileFlag_Recursive)
745 {
746 char *pszNewSub = NULL;
747 if (pszSubDir)
748 RTStrAPrintf(&pszNewSub, "%s%s/", pszSubDir, DirEntry.szName);
749 else
750 RTStrAPrintf(&pszNewSub, "%s/", DirEntry.szName);
751
752 if (pszNewSub)
753 {
754 rc = ctrlCopyDirectoryRead(pszRootDir, pszNewSub,
755 pszFilter, pszDest,
756 uFlags, pcObjects, pList);
757 RTStrFree(pszNewSub);
758 }
759 else
760 rc = VERR_NO_MEMORY;
761 }
762 break;
763
764 case RTDIRENTRYTYPE_SYMLINK:
765 if ( (uFlags & CopyFileFlag_Recursive)
766 && (uFlags & CopyFileFlag_FollowLinks))
767 {
768 /* Fall through to next case is intentional. */
769 }
770 else
771 break;
772
773 case RTDIRENTRYTYPE_FILE:
774 {
775 bool fProcess = false;
776 if (pszFilter && RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
777 fProcess = true;
778 else if (!pszFilter)
779 fProcess = true;
780
781 if (fProcess)
782 {
783 char *pszFileSource = NULL;
784 char *pszFileDest = NULL;
785 if (RTStrAPrintf(&pszFileSource, "%s%s%s",
786 pszRootDir, pszSubDir ? pszSubDir : "",
787 DirEntry.szName) >= 0)
788 {
789 if (RTStrAPrintf(&pszFileDest, "%s%s%s",
790 pszDest, pszSubDir ? pszSubDir : "",
791 DirEntry.szName) <= 0)
792 {
793 rc = VERR_NO_MEMORY;
794 }
795 }
796 else
797 rc = VERR_NO_MEMORY;
798
799 if (RT_SUCCESS(rc))
800 {
801 rc = ctrlDirectoryEntryAppend(pszFileSource, pszFileDest, pList);
802 if (RT_SUCCESS(rc))
803 *pcObjects = *pcObjects + 1;
804 }
805
806 if (pszFileSource)
807 RTStrFree(pszFileSource);
808 if (pszFileDest)
809 RTStrFree(pszFileDest);
810 }
811 }
812 break;
813
814 default:
815 break;
816 }
817 if (RT_FAILURE(rc))
818 break;
819 }
820 }
821
822 if (pDir)
823 RTDirClose(pDir);
824 return rc;
825}
826
827/**
828 * Initializes the copy process and builds up an object list
829 * with all required information to start the actual copy process.
830 *
831 * @return IPRT status code.
832 * @param pszSource Source path on host to use.
833 * @param pszDest Destination path on guest to use.
834 * @param uFlags Copy flags.
835 * @param pcObjects Where to store the count of objects to be copied.
836 * @param pList Where to store the object list.
837 */
838static int ctrlCopyInit(const char *pszSource, const char *pszDest, uint32_t uFlags,
839 uint32_t *pcObjects, PRTLISTNODE pList)
840{
841 AssertPtrReturn(pszSource, VERR_INVALID_PARAMETER);
842 AssertPtrReturn(pszDest, VERR_INVALID_PARAMETER);
843 AssertPtrReturn(pcObjects, VERR_INVALID_PARAMETER);
844 AssertPtrReturn(pList, VERR_INVALID_PARAMETER);
845
846 int rc = VINF_SUCCESS;
847 char *pszSourceAbs = RTPathAbsDup(pszSource);
848 if (pszSourceAbs)
849 {
850 if ( RTPathFilename(pszSourceAbs)
851 && RTFileExists(pszSourceAbs)) /* We have a single file ... */
852 {
853 char *pszDestAbs = RTStrDup(pszDest);
854 if (pszDestAbs)
855 {
856 /* Do we have a trailing slash for the destination?
857 * Then this is a directory ... */
858 size_t cch = strlen(pszDestAbs);
859 if ( cch > 1
860 && ( RTPATH_IS_SLASH(pszDestAbs[cch - 1])
861 || RTPATH_IS_SLASH(pszDestAbs[cch - 2])
862 )
863 )
864 {
865 rc = RTStrAAppend(&pszDestAbs, RTPathFilename(pszSourceAbs));
866 }
867 else
868 {
869 /* Since the desetination seems not to be a directory,
870 * we assume that this is the absolute path to the destination
871 * file -> nothing to do here ... */
872 }
873
874 if (RT_SUCCESS(rc))
875 {
876 RTListInit(pList);
877 rc = ctrlDirectoryEntryAppend(pszSourceAbs, pszDestAbs, pList);
878 *pcObjects = 1;
879 }
880 RTStrFree(pszDestAbs);
881 }
882 else
883 rc = VERR_NO_MEMORY;
884 }
885 else /* ... or a directory. */
886 {
887 /* Append trailing slash to absolute directory. */
888 if (RTDirExists(pszSourceAbs))
889 RTStrAAppend(&pszSourceAbs, RTPATH_SLASH_STR);
890
891 /* Extract directory filter (e.g. "*.exe"). */
892 char *pszFilter = RTPathFilename(pszSourceAbs);
893 char *pszSourceAbsRoot = RTStrDup(pszSourceAbs);
894 char *pszDestAbs = RTStrDup(pszDest);
895 if ( pszSourceAbsRoot
896 && pszDestAbs)
897 {
898 if (pszFilter)
899 {
900 RTPathStripFilename(pszSourceAbsRoot);
901 rc = RTStrAAppend(&pszSourceAbsRoot, RTPATH_SLASH_STR);
902 }
903 else
904 {
905 /*
906 * If we have more than one file to copy, make sure that we have
907 * a trailing slash so that we can construct a full path name
908 * (e.g. "foo.txt" -> "c:/foo/temp.txt") as destination.
909 */
910 size_t cch = strlen(pszSourceAbsRoot);
911 if ( cch > 1
912 && !RTPATH_IS_SLASH(pszSourceAbsRoot[cch - 1])
913 && !RTPATH_IS_SLASH(pszSourceAbsRoot[cch - 2]))
914 {
915 rc = RTStrAAppend(&pszSourceAbsRoot, RTPATH_SLASH_STR);
916 }
917 }
918
919 if (RT_SUCCESS(rc))
920 {
921 /*
922 * Make sure we have a valid destination path. All we can do
923 * here is to check whether we have a trailing slash -- the rest
924 * (i.e. path creation, rights etc.) needs to be done inside the guest.
925 */
926 size_t cch = strlen(pszDestAbs);
927 if ( cch > 1
928 && !RTPATH_IS_SLASH(pszDestAbs[cch - 1])
929 && !RTPATH_IS_SLASH(pszDestAbs[cch - 2]))
930 {
931 rc = RTStrAAppend(&pszDestAbs, RTPATH_SLASH_STR);
932 }
933 }
934
935 if (RT_SUCCESS(rc))
936 {
937 RTListInit(pList);
938 rc = ctrlCopyDirectoryRead(pszSourceAbsRoot, NULL /* Sub directory */,
939 pszFilter, pszDestAbs,
940 uFlags, pcObjects, pList);
941 if (RT_SUCCESS(rc) && *pcObjects == 0)
942 rc = VERR_NOT_FOUND;
943 }
944
945 if (pszDestAbs)
946 RTStrFree(pszDestAbs);
947 if (pszSourceAbsRoot)
948 RTStrFree(pszSourceAbsRoot);
949 }
950 else
951 rc = VERR_NO_MEMORY;
952 }
953 RTStrFree(pszSourceAbs);
954 }
955 else
956 rc = VERR_NO_MEMORY;
957 return rc;
958}
959
960/**
961 * Copys a file from host to the guest.
962 *
963 * @return IPRT status code.
964 * @param pGuest IGuest interface pointer.
965 * @param fVerbose Verbose flag.
966 * @param pszSource Source path of existing host file to copy.
967 * @param pszDest Destination path on guest to copy the file to.
968 * @param pszUserName User name on guest to use for the copy operation.
969 * @param pszPassword Password of user account.
970 * @param uFlags Copy flags.
971 */
972static int ctrlCopyFileToGuest(IGuest *pGuest, bool fVerbose, const char *pszSource, const char *pszDest,
973 const char *pszUserName, const char *pszPassword,
974 uint32_t uFlags)
975{
976 AssertPtrReturn(pszSource, VERR_INVALID_PARAMETER);
977 AssertPtrReturn(pszDest, VERR_INVALID_PARAMETER);
978 AssertPtrReturn(pszUserName, VERR_INVALID_PARAMETER);
979 AssertPtrReturn(pszPassword, VERR_INVALID_PARAMETER);
980
981 int vrc = VINF_SUCCESS;
982 ComPtr<IProgress> progress;
983 HRESULT rc = pGuest->CopyToGuest(Bstr(pszSource).raw(), Bstr(pszDest).raw(),
984 Bstr(pszUserName).raw(), Bstr(pszPassword).raw(),
985 uFlags, progress.asOutParam());
986 if (FAILED(rc))
987 vrc = ctrlPrintError(pGuest, COM_IIDOF(IGuest));
988 else
989 {
990 rc = showProgress(progress);
991 if (FAILED(rc))
992 vrc = ctrlPrintProgressError(progress);
993 }
994 return vrc;
995}
996
997static int handleCtrlCopyTo(HandlerArg *a)
998{
999 /*
1000 * Check the syntax. We can deduce the correct syntax from the number of
1001 * arguments.
1002 */
1003 if (a->argc < 3) /* At least the source + destination should be present :-). */
1004 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1005
1006 static const RTGETOPTDEF s_aOptions[] =
1007 {
1008 { "--dryrun", 'd', RTGETOPT_REQ_NOTHING },
1009 { "--follow", 'F', RTGETOPT_REQ_NOTHING },
1010 { "--password", 'p', RTGETOPT_REQ_STRING },
1011 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1012 { "--username", 'u', RTGETOPT_REQ_STRING },
1013 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1014 };
1015
1016 int ch;
1017 RTGETOPTUNION ValueUnion;
1018 RTGETOPTSTATE GetState;
1019 RTGetOptInit(&GetState, a->argc, a->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
1020
1021 Utf8Str Utf8Source;
1022 Utf8Str Utf8Dest;
1023 Utf8Str Utf8UserName;
1024 Utf8Str Utf8Password;
1025 uint32_t uFlags = CopyFileFlag_None;
1026 bool fVerbose = false;
1027 bool fCopyRecursive = false;
1028 bool fDryRun = false;
1029
1030 int vrc = VINF_SUCCESS;
1031 uint32_t uNoOptionIdx = 0;
1032 bool fUsageOK = true;
1033 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1034 && RT_SUCCESS(vrc))
1035 {
1036 /* For options that require an argument, ValueUnion has received the value. */
1037 switch (ch)
1038 {
1039 case 'd': /* Dry run */
1040 fDryRun = true;
1041 break;
1042
1043 case 'F': /* Follow symlinks */
1044 uFlags |= CopyFileFlag_FollowLinks;
1045 break;
1046
1047 case 'p': /* Password */
1048 Utf8Password = ValueUnion.psz;
1049 break;
1050
1051 case 'R': /* Recursive processing */
1052 uFlags |= CopyFileFlag_Recursive;
1053 break;
1054
1055 case 'u': /* User name */
1056 Utf8UserName = ValueUnion.psz;
1057 break;
1058
1059 case 'v': /* Verbose */
1060 fVerbose = true;
1061 break;
1062
1063 case VINF_GETOPT_NOT_OPTION:
1064 {
1065 /* Get the actual source + destination. */
1066 switch (uNoOptionIdx)
1067 {
1068 case 0:
1069 Utf8Source = ValueUnion.psz;
1070 break;
1071
1072 case 1:
1073 Utf8Dest = ValueUnion.psz;
1074 break;
1075
1076 default:
1077 break;
1078 }
1079 uNoOptionIdx++;
1080 if (uNoOptionIdx == UINT32_MAX)
1081 {
1082 RTMsgError("Too many files specified! Aborting.\n");
1083 vrc = VERR_TOO_MUCH_DATA;
1084 }
1085 break;
1086 }
1087
1088 default:
1089 return RTGetOptPrintError(ch, &ValueUnion);
1090 }
1091 }
1092
1093 if (!fUsageOK)
1094 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1095
1096 if (Utf8Source.isEmpty())
1097 return errorSyntax(USAGE_GUESTCONTROL,
1098 "No source specified!");
1099
1100 if (Utf8Dest.isEmpty())
1101 return errorSyntax(USAGE_GUESTCONTROL,
1102 "No destination specified!");
1103
1104 if (Utf8UserName.isEmpty())
1105 return errorSyntax(USAGE_GUESTCONTROL,
1106 "No user name specified!");
1107 HRESULT rc = S_OK;
1108 ComPtr<IGuest> guest;
1109 vrc = ctrlInitVM(a, a->argv[0] /* VM Name */, &guest);
1110 if (RT_SUCCESS(vrc))
1111 {
1112 if (fVerbose)
1113 {
1114 if (fDryRun)
1115 RTPrintf("Dry run - no files copied!\n");
1116 RTPrintf("Gathering file information ...\n");
1117 }
1118
1119 RTLISTNODE listToCopy;
1120 uint32_t cObjects = 0;
1121 vrc = ctrlCopyInit(Utf8Source.c_str(), Utf8Dest.c_str(), uFlags,
1122 &cObjects, &listToCopy);
1123 if (RT_FAILURE(vrc))
1124 {
1125 switch (vrc)
1126 {
1127 case VERR_NOT_FOUND:
1128 RTMsgError("No files to copy found!\n");
1129 break;
1130
1131 case VERR_FILE_NOT_FOUND:
1132 RTMsgError("Source path \"%s\" not found!\n", Utf8Source.c_str());
1133 break;
1134
1135 default:
1136 RTMsgError("Failed to initialize, rc=%Rrc\n", vrc);
1137 break;
1138 }
1139 }
1140 else
1141 {
1142 PDIRECTORYENTRY pNode;
1143 if (RT_SUCCESS(vrc))
1144 {
1145 if (fVerbose)
1146 {
1147 if (fCopyRecursive)
1148 RTPrintf("Recursively copying \"%s\" to \"%s\" (%u file(s)) ...\n",
1149 Utf8Source.c_str(), Utf8Dest.c_str(), cObjects);
1150 else
1151 RTPrintf("Copying \"%s\" to \"%s\" (%u file(s)) ...\n",
1152 Utf8Source.c_str(), Utf8Dest.c_str(), cObjects);
1153 }
1154
1155 uint32_t uCurObject = 1;
1156 RTListForEach(&listToCopy, pNode, DIRECTORYENTRY, Node)
1157 {
1158 if (!fDryRun)
1159 {
1160 if (fVerbose)
1161 RTPrintf("Copying \"%s\" to \"%s\" (%u/%u) ...\n",
1162 pNode->pszSourcePath, pNode->pszDestPath, uCurObject, cObjects);
1163 /* Finally copy the desired file (if no dry run selected). */
1164 if (!fDryRun)
1165 vrc = ctrlCopyFileToGuest(guest, fVerbose, pNode->pszSourcePath, pNode->pszDestPath,
1166 Utf8UserName.c_str(), Utf8Password.c_str(), uFlags);
1167 }
1168 if (RT_FAILURE(vrc))
1169 break;
1170 uCurObject++;
1171 }
1172 if (RT_SUCCESS(vrc) && fVerbose)
1173 RTPrintf("Copy operation successful!\n");
1174 }
1175 ctrlDirectoryListDestroy(&listToCopy);
1176 }
1177 ctrlUninitVM(a);
1178 }
1179
1180 if (RT_FAILURE(vrc))
1181 rc = VBOX_E_IPRT_ERROR;
1182 return SUCCEEDED(rc) ? 0 : 1;
1183}
1184
1185static int handleCtrlCreateDirectory(HandlerArg *a)
1186{
1187 /*
1188 * Check the syntax. We can deduce the correct syntax from the number of
1189 * arguments.
1190 */
1191 if (a->argc < 2) /* At least the directory we want to create should be present :-). */
1192 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1193
1194 static const RTGETOPTDEF s_aOptions[] =
1195 {
1196 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
1197 { "--parents", 'P', RTGETOPT_REQ_NOTHING },
1198 { "--password", 'p', RTGETOPT_REQ_STRING },
1199 { "--username", 'u', RTGETOPT_REQ_STRING },
1200 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1201 };
1202
1203 int ch;
1204 RTGETOPTUNION ValueUnion;
1205 RTGETOPTSTATE GetState;
1206 RTGetOptInit(&GetState, a->argc, a->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 1, 0);
1207
1208 Utf8Str Utf8UserName;
1209 Utf8Str Utf8Password;
1210 uint32_t uFlags = CreateDirectoryFlag_None;
1211 uint32_t uMode = 0;
1212 bool fVerbose = false;
1213
1214 RTLISTNODE listDirs;
1215 uint32_t uNumDirs = 0;
1216 RTListInit(&listDirs);
1217
1218 int vrc = VINF_SUCCESS;
1219 bool fUsageOK = true;
1220 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1221 && RT_SUCCESS(vrc))
1222 {
1223 /* For options that require an argument, ValueUnion has received the value. */
1224 switch (ch)
1225 {
1226 case 'm': /* Mode */
1227 uMode = ValueUnion.u32;
1228 break;
1229
1230 case 'P': /* Create parents */
1231 uFlags |= CreateDirectoryFlag_Parents;
1232 break;
1233
1234 case 'p': /* Password */
1235 Utf8Password = ValueUnion.psz;
1236 break;
1237
1238 case 'u': /* User name */
1239 Utf8UserName = ValueUnion.psz;
1240 break;
1241
1242 case 'v': /* Verbose */
1243 fVerbose = true;
1244 break;
1245
1246 case VINF_GETOPT_NOT_OPTION:
1247 {
1248 vrc = ctrlDirectoryEntryAppend(NULL, /* No source given */
1249 ValueUnion.psz, /* Destination */
1250 &listDirs);
1251 if (RT_SUCCESS(vrc))
1252 {
1253 uNumDirs++;
1254 if (uNumDirs == UINT32_MAX)
1255 {
1256 RTMsgError("Too many directories specified! Aborting.\n");
1257 vrc = VERR_TOO_MUCH_DATA;
1258 }
1259 }
1260 break;
1261 }
1262
1263 default:
1264 return RTGetOptPrintError(ch, &ValueUnion);
1265 }
1266 }
1267
1268 if (!fUsageOK)
1269 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1270
1271 if (!uNumDirs)
1272 return errorSyntax(USAGE_GUESTCONTROL,
1273 "No directory to create specified!");
1274
1275 if (Utf8UserName.isEmpty())
1276 return errorSyntax(USAGE_GUESTCONTROL,
1277 "No user name specified!");
1278
1279 HRESULT rc = S_OK;
1280 ComPtr<IGuest> guest;
1281 vrc = ctrlInitVM(a, a->argv[0] /* VM Name */, &guest);
1282 if (RT_SUCCESS(vrc))
1283 {
1284 if (fVerbose && uNumDirs > 1)
1285 RTPrintf("Creating %ld directories ...\n", uNumDirs);
1286
1287 PDIRECTORYENTRY pNode;
1288 RTListForEach(&listDirs, pNode, DIRECTORYENTRY, Node)
1289 {
1290 if (fVerbose)
1291 RTPrintf("Creating directory \"%s\" ...\n", pNode->pszDestPath);
1292
1293 ComPtr<IProgress> progress;
1294 rc = guest->CreateDirectory(Bstr(pNode->pszDestPath).raw(),
1295 Bstr(Utf8UserName).raw(), Bstr(Utf8Password).raw(),
1296 uMode, uFlags, progress.asOutParam());
1297 if (FAILED(rc))
1298 {
1299 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
1300 break;
1301 }
1302 }
1303 ctrlUninitVM(a);
1304 }
1305 ctrlDirectoryListDestroy(&listDirs);
1306
1307 if (RT_FAILURE(vrc))
1308 rc = VBOX_E_IPRT_ERROR;
1309 return SUCCEEDED(rc) ? 0 : 1;
1310}
1311
1312static int handleCtrlUpdateAdditions(HandlerArg *a)
1313{
1314 /*
1315 * Check the syntax. We can deduce the correct syntax from the number of
1316 * arguments.
1317 */
1318 if (a->argc < 1) /* At least the VM name should be present :-). */
1319 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1320
1321 Utf8Str Utf8Source;
1322 bool fVerbose = false;
1323
1324/** @todo r=bird: Use RTGetOpt here, no new code using strcmp-if-switching! */
1325 /* Iterate through all possible commands (if available). */
1326 bool usageOK = true;
1327 for (int i = 1; usageOK && i < a->argc; i++)
1328 {
1329 if (!strcmp(a->argv[i], "--source"))
1330 {
1331 if (i + 1 >= a->argc)
1332 usageOK = false;
1333 else
1334 {
1335 Utf8Source = a->argv[i + 1];
1336 ++i;
1337 }
1338 }
1339 else if (!strcmp(a->argv[i], "--verbose"))
1340 fVerbose = true;
1341 else
1342 return errorSyntax(USAGE_GUESTCONTROL,
1343 "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
1344 }
1345
1346 if (!usageOK)
1347 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1348
1349 HRESULT rc = S_OK;
1350 ComPtr<IGuest> guest;
1351 int vrc = ctrlInitVM(a, a->argv[0] /* VM Name */, &guest);
1352 if (RT_SUCCESS(vrc))
1353 {
1354 if (fVerbose)
1355 RTPrintf("Updating Guest Additions of machine \"%s\" ...\n", a->argv[0]);
1356
1357#ifdef DEBUG_andy
1358 if (Utf8Source.isEmpty())
1359 Utf8Source = "c:\\Downloads\\VBoxGuestAdditions-r67158.iso";
1360#endif
1361 /* Determine source if not set yet. */
1362 if (Utf8Source.isEmpty())
1363 {
1364 char strTemp[RTPATH_MAX];
1365 vrc = RTPathAppPrivateNoArch(strTemp, sizeof(strTemp));
1366 AssertRC(vrc);
1367 Utf8Str Utf8Src1 = Utf8Str(strTemp).append("/VBoxGuestAdditions.iso");
1368
1369 vrc = RTPathExecDir(strTemp, sizeof(strTemp));
1370 AssertRC(vrc);
1371 Utf8Str Utf8Src2 = Utf8Str(strTemp).append("/additions/VBoxGuestAdditions.iso");
1372
1373 /* Check the standard image locations */
1374 if (RTFileExists(Utf8Src1.c_str()))
1375 Utf8Source = Utf8Src1;
1376 else if (RTFileExists(Utf8Src2.c_str()))
1377 Utf8Source = Utf8Src2;
1378 else
1379 {
1380 RTMsgError("Source could not be determined! Please use --source to specify a valid source.\n");
1381 vrc = VERR_FILE_NOT_FOUND;
1382 }
1383 }
1384 else if (!RTFileExists(Utf8Source.c_str()))
1385 {
1386 RTMsgError("Source \"%s\" does not exist!\n", Utf8Source.c_str());
1387 vrc = VERR_FILE_NOT_FOUND;
1388 }
1389
1390 if (RT_SUCCESS(vrc))
1391 {
1392 if (fVerbose)
1393 RTPrintf("Using source: %s\n", Utf8Source.c_str());
1394
1395 ComPtr<IProgress> progress;
1396 CHECK_ERROR(guest, UpdateGuestAdditions(Bstr(Utf8Source).raw(),
1397 /* Wait for whole update process to complete. */
1398 AdditionsUpdateFlag_None,
1399 progress.asOutParam()));
1400 if (FAILED(rc))
1401 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
1402 else
1403 {
1404 rc = showProgress(progress);
1405 if (FAILED(rc))
1406 vrc = ctrlPrintProgressError(progress);
1407 else if (fVerbose)
1408 RTPrintf("Guest Additions update successful.\n");
1409 }
1410 }
1411 ctrlUninitVM(a);
1412 }
1413
1414 if (RT_FAILURE(vrc))
1415 rc = VBOX_E_IPRT_ERROR;
1416 return SUCCEEDED(rc) ? 0 : 1;
1417}
1418
1419/**
1420 * Access the guest control store.
1421 *
1422 * @returns 0 on success, 1 on failure
1423 * @note see the command line API description for parameters
1424 */
1425int handleGuestControl(HandlerArg *a)
1426{
1427 HandlerArg arg = *a;
1428 arg.argc = a->argc - 1;
1429 arg.argv = a->argv + 1;
1430
1431 if (a->argc <= 0)
1432 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1433
1434 /* switch (cmd) */
1435 if ( !RTStrICmp(a->argv[0], "exec")
1436 || !RTStrICmp(a->argv[0], "execute"))
1437 {
1438 return handleCtrlExecProgram(&arg);
1439 }
1440 else if ( !RTStrICmp(a->argv[0], "copyto")
1441 || !RTStrICmp(a->argv[0], "cp"))
1442 {
1443 return handleCtrlCopyTo(&arg);
1444 }
1445 else if ( !RTStrICmp(a->argv[0], "createdirectory")
1446 || !RTStrICmp(a->argv[0], "createdir")
1447 || !RTStrICmp(a->argv[0], "mkdir")
1448 || !RTStrICmp(a->argv[0], "md"))
1449 {
1450 return handleCtrlCreateDirectory(&arg);
1451 }
1452 else if ( !RTStrICmp(a->argv[0], "updateadditions")
1453 || !RTStrICmp(a->argv[0], "updateadds"))
1454 {
1455 return handleCtrlUpdateAdditions(&arg);
1456 }
1457
1458 /* default: */
1459 return errorSyntax(USAGE_GUESTCONTROL, "Incorrect parameters");
1460}
1461
1462#endif /* !VBOX_ONLY_DOCS */
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