VirtualBox

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

Last change on this file since 38537 was 38525, checked in by vboxsync, 13 years ago

FE/CLI: use CHECK_PROGRESS_ERROR

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 72.3 KB
Line 
1/* $Id: VBoxManageGuestCtrl.cpp 38525 2011-08-25 11:40:58Z 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 * Translates a source path to a destintation path (can be both sides,
862 * either host or guest). The source root is needed to determine the start
863 * of the relative source path which also needs to present in the destination
864 * path.
865 *
866 * @return IPRT status code.
867 * @param pszSourceRoot Source root path.
868 * @param pszSource Actual source to transform. Must begin with
869 * the source root path!
870 * @param pszDest Destination path.
871 * @param ppszTranslated Pointer to the allocated, translated destination
872 * path. Must be free'd with RTStrFree().
873 */
874static int ctrlCopyTranslatePath(const char *pszSourceRoot, const char *pszSource,
875 const char *pszDest, char **ppszTranslated)
876{
877 AssertPtrReturn(pszSourceRoot, VERR_INVALID_POINTER);
878 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
879 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
880 AssertPtrReturn(ppszTranslated, VERR_INVALID_POINTER);
881
882 /* Source path must contain the source root! */
883 if (!RTPathStartsWith(pszSource, pszSourceRoot))
884 return VERR_INVALID_PARAMETER;
885
886 /* Construct the relative dest destination path by "subtracting" the
887 * source from the source root, e.g.
888 *
889 * source root path = "e:\foo\", source = "e:\foo\bar"
890 * dest = "d:\baz\"
891 * translated = "d:\baz\bar\"
892 */
893
894 size_t lenRoot = strlen(pszSourceRoot);
895 AssertReturn(lenRoot, VERR_INVALID_PARAMETER);
896 char *pszTranslated = RTStrDup(pszDest);
897 AssertReturn(pszTranslated, VERR_NO_MEMORY);
898 int vrc = RTStrAAppend(&pszTranslated, &pszSource[lenRoot]);
899 if (RT_FAILURE(vrc))
900 return vrc;
901
902 *ppszTranslated = pszTranslated;
903
904 return vrc;
905}
906
907#ifdef DEBUG_andy
908static void tstTranslatePath()
909{
910 static struct
911 {
912 const char *pszSourceRoot;
913 const char *pszSource;
914 const char *pszDest;
915 const char *pszTranslated;
916 int iResult;
917 } aTests[] =
918 {
919 /* Invalid stuff. */
920 { NULL, NULL, NULL, NULL, VERR_INVALID_POINTER },
921 /* Windows paths. */
922 { "c:\\foo", "c:\\foo\\bar.txt", "c:\\test", "c:\\test\\bar.txt", VINF_SUCCESS },
923 { "c:\\foo", "c:\\foo\\baz\\bar.txt", "c:\\test", "c:\\test\\baz\\bar.txt", VINF_SUCCESS }
924 /* UNIX-like paths. */
925 /* Mixed paths*/
926 /** @todo */
927 };
928
929 int iTest = 0;
930 for (iTest; iTest < RT_ELEMENTS(aTests); iTest++)
931 {
932 RTPrintf("=> Test %d\n", iTest);
933 RTPrintf("\tSourceRoot=%s, Source=%s, Dest=%s\n",
934 aTests[iTest].pszSourceRoot, aTests[iTest].pszSource, aTests[iTest].pszDest);
935
936 char *pszTranslated = NULL;
937 int iResult = ctrlCopyTranslatePath(aTests[iTest].pszSourceRoot, aTests[iTest].pszSource,
938 aTests[iTest].pszDest, &pszTranslated);
939 if (iResult != aTests[iTest].iResult)
940 {
941 RTPrintf("\tReturned %Rrc, expected %Rrc\n",
942 iResult, aTests[iTest].iResult);
943 }
944 else if ( pszTranslated
945 && strcmp(pszTranslated, aTests[iTest].pszTranslated))
946 {
947 RTPrintf("\tReturned translated path %s, expected %s\n",
948 pszTranslated, aTests[iTest].pszTranslated);
949 }
950
951 if (pszTranslated)
952 {
953 RTPrintf("\tTranslated=%s\n", pszTranslated);
954 RTStrFree(pszTranslated);
955 }
956 }
957}
958#endif
959
960static int ctrlCopyDirCreate(PCOPYCONTEXT pContext, const char *pszDir)
961{
962 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
963 AssertPtrReturn(pszDir, VERR_INVALID_POINTER);
964
965 int rc = VINF_SUCCESS;
966 if (pContext->fHostToGuest) /* We want to create directories on the guest. */
967 {
968 HRESULT hrc = pContext->pGuest->DirectoryCreate(Bstr(pszDir).raw(),
969 Bstr(pContext->pszUsername).raw(), Bstr(pContext->pszPassword).raw(),
970 700, DirectoryCreateFlag_Parents);
971 if (FAILED(hrc))
972 rc = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
973 }
974 else /* ... or on the host. */
975 {
976 rc = RTDirCreate(pszDir, 700);
977 if (rc == VERR_ALREADY_EXISTS)
978 rc = VINF_SUCCESS;
979 }
980 return rc;
981}
982
983static int ctrlCopyDirExists(PCOPYCONTEXT pContext, bool bGuest,
984 const char *pszDir, bool *fExists)
985{
986 AssertPtrReturn(pContext, false);
987 AssertPtrReturn(pszDir, false);
988 AssertPtrReturn(fExists, false);
989
990 int rc = VINF_SUCCESS;
991 if (bGuest)
992 {
993 BOOL fDirExists = FALSE;
994 /** @todo Replace with DirectoryExists as soon as API is in place. */
995 HRESULT hr = pContext->pGuest->FileExists(Bstr(pszDir).raw(),
996 Bstr(pContext->pszUsername).raw(),
997 Bstr(pContext->pszPassword).raw(), &fDirExists);
998 if (FAILED(hr))
999 rc = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
1000 else
1001 *fExists = fDirExists ? true : false;
1002 }
1003 else
1004 *fExists = RTDirExists(pszDir);
1005 return rc;
1006}
1007
1008static int ctrlCopyDirExistsOnDest(PCOPYCONTEXT pContext, const char *pszDir,
1009 bool *fExists)
1010{
1011 return ctrlCopyDirExists(pContext, pContext->fHostToGuest,
1012 pszDir, fExists);
1013}
1014
1015static int ctrlCopyDirExistsOnSource(PCOPYCONTEXT pContext, const char *pszDir,
1016 bool *fExists)
1017{
1018 return ctrlCopyDirExists(pContext, !pContext->fHostToGuest,
1019 pszDir, fExists);
1020}
1021
1022static int ctrlCopyFileExists(PCOPYCONTEXT pContext, bool bOnGuest,
1023 const char *pszFile, bool *fExists)
1024{
1025 AssertPtrReturn(pContext, false);
1026 AssertPtrReturn(pszFile, false);
1027 AssertPtrReturn(fExists, false);
1028
1029 int rc = VINF_SUCCESS;
1030 if (bOnGuest)
1031 {
1032 BOOL fFileExists = FALSE;
1033 HRESULT hr = pContext->pGuest->FileExists(Bstr(pszFile).raw(),
1034 Bstr(pContext->pszUsername).raw(),
1035 Bstr(pContext->pszPassword).raw(), &fFileExists);
1036 if (FAILED(hr))
1037 rc = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
1038 else
1039 *fExists = fFileExists ? true : false;
1040 }
1041 else
1042 *fExists = RTFileExists(pszFile);
1043 return rc;
1044}
1045
1046static int ctrlCopyFileExistsOnDest(PCOPYCONTEXT pContext, const char *pszFile,
1047 bool *fExists)
1048{
1049 return ctrlCopyFileExists(pContext, pContext->fHostToGuest,
1050 pszFile, fExists);
1051}
1052
1053static int ctrlCopyFileExistsOnSource(PCOPYCONTEXT pContext, const char *pszFile,
1054 bool *fExists)
1055{
1056 return ctrlCopyFileExists(pContext, !pContext->fHostToGuest,
1057 pszFile, fExists);
1058}
1059
1060static int ctrlCopyFileToTarget(PCOPYCONTEXT pContext, const char *pszFileSource,
1061 const char *pszFileDest, uint32_t fFlags)
1062{
1063 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1064 AssertPtrReturn(pszFileSource, VERR_INVALID_POINTER);
1065 AssertPtrReturn(pszFileDest, VERR_INVALID_POINTER);
1066
1067 if (pContext->fVerbose)
1068 {
1069 RTPrintf("Copying \"%s\" to \"%s\" ...\n",
1070 pszFileSource, pszFileDest);
1071 }
1072
1073 int vrc = VINF_SUCCESS;
1074 ComPtr<IProgress> progress;
1075 HRESULT rc;
1076 if (pContext->fHostToGuest)
1077 {
1078 rc = pContext->pGuest->CopyToGuest(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
1079 Bstr(pContext->pszUsername).raw(), Bstr(pContext->pszPassword).raw(),
1080 fFlags, progress.asOutParam());
1081 }
1082 else
1083 {
1084 rc = pContext->pGuest->CopyFromGuest(Bstr(pszFileSource).raw(), Bstr(pszFileDest).raw(),
1085 Bstr(pContext->pszUsername).raw(), Bstr(pContext->pszPassword).raw(),
1086 fFlags, progress.asOutParam());
1087 }
1088
1089 if (FAILED(rc))
1090 vrc = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
1091 else
1092 {
1093 rc = showProgress(progress);
1094 CHECK_PROGRESS_ERROR(progress, ("File copy failed"));
1095 }
1096
1097 return vrc;
1098}
1099
1100static int ctrlCopyDirToGuest(PCOPYCONTEXT pContext,
1101 const char *pszSource, const char *pszFilter,
1102 const char *pszDest, uint32_t fFlags,
1103 const char *pszSubDir /* For recursion */)
1104{
1105 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1106 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1107 /* Filter is optional. */
1108 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1109 /* Sub directory is optional. */
1110
1111 /*
1112 * Construct current path.
1113 */
1114 char szCurDir[RTPATH_MAX];
1115 int rc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
1116 if (RT_SUCCESS(rc) && pszSubDir)
1117 rc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
1118
1119 /* Flag indicating whether the current directory was created on the
1120 * target or not. */
1121 bool fDirCreated = false;
1122
1123 /*
1124 * Open directory without a filter - RTDirOpenFiltered unfortunately
1125 * cannot handle sub directories so we have to do the filtering ourselves.
1126 */
1127 PRTDIR pDir = NULL;
1128 if (RT_SUCCESS(rc))
1129 {
1130 rc = RTDirOpen(&pDir, szCurDir);
1131 if (RT_FAILURE(rc))
1132 pDir = NULL;
1133 }
1134 if (RT_SUCCESS(rc))
1135 {
1136 /*
1137 * Enumerate the directory tree.
1138 */
1139 while (RT_SUCCESS(rc))
1140 {
1141 RTDIRENTRY DirEntry;
1142 rc = RTDirRead(pDir, &DirEntry, NULL);
1143 if (RT_FAILURE(rc))
1144 {
1145 if (rc == VERR_NO_MORE_FILES)
1146 rc = VINF_SUCCESS;
1147 break;
1148 }
1149 switch (DirEntry.enmType)
1150 {
1151 case RTDIRENTRYTYPE_DIRECTORY:
1152 {
1153 /* Skip "." and ".." entries. */
1154 if ( !strcmp(DirEntry.szName, ".")
1155 || !strcmp(DirEntry.szName, ".."))
1156 break;
1157
1158 if (fFlags & CopyFileFlag_Recursive)
1159 {
1160 char *pszNewSub = NULL;
1161 if (pszSubDir)
1162 RTStrAPrintf(&pszNewSub, "%s/%s", pszSubDir, DirEntry.szName);
1163 else
1164 RTStrAPrintf(&pszNewSub, "%s", DirEntry.szName);
1165
1166 if (pszNewSub)
1167 {
1168 rc = ctrlCopyDirToGuest(pContext,
1169 pszSource, pszFilter,
1170 pszDest, fFlags, pszNewSub);
1171 RTStrFree(pszNewSub);
1172 }
1173 else
1174 rc = VERR_NO_MEMORY;
1175 }
1176 break;
1177 }
1178
1179 case RTDIRENTRYTYPE_SYMLINK:
1180 if ( (fFlags & CopyFileFlag_Recursive)
1181 && (fFlags & CopyFileFlag_FollowLinks))
1182 {
1183 /* Fall through to next case is intentional. */
1184 }
1185 else
1186 break;
1187
1188 case RTDIRENTRYTYPE_FILE:
1189 {
1190 if ( !pszFilter
1191 || RTStrSimplePatternMatch(pszFilter, DirEntry.szName))
1192 {
1193 if (!fDirCreated)
1194 {
1195 char *pszDestDir;
1196 rc = ctrlCopyTranslatePath(pszSource, szCurDir,
1197 pszDest, &pszDestDir);
1198 if (RT_SUCCESS(rc))
1199 {
1200 rc = ctrlCopyDirCreate(pContext, pszDestDir);
1201 RTStrFree(pszDestDir);
1202
1203 fDirCreated = true;
1204 }
1205 }
1206
1207 if (RT_SUCCESS(rc))
1208 {
1209 char *pszFileSource;
1210 if (RTStrAPrintf(&pszFileSource, "%s/%s",
1211 szCurDir, DirEntry.szName))
1212 {
1213 char *pszFileDest;
1214 rc = ctrlCopyTranslatePath(pszSource, pszFileSource,
1215 pszDest, &pszFileDest);
1216 if (RT_SUCCESS(rc))
1217 {
1218 rc = ctrlCopyFileToTarget(pContext, pszFileSource,
1219 pszFileDest, 0 /* Flags? */);
1220 RTStrFree(pszFileDest);
1221 }
1222 RTStrFree(pszFileSource);
1223 }
1224 }
1225 }
1226 break;
1227 }
1228
1229 default:
1230 break;
1231 }
1232 if (RT_FAILURE(rc))
1233 break;
1234 }
1235
1236 RTDirClose(pDir);
1237 }
1238 return rc;
1239}
1240
1241static int ctrlCopyDirToHost(PCOPYCONTEXT pContext,
1242 const char *pszSource, const char *pszFilter,
1243 const char *pszDest, uint32_t fFlags,
1244 const char *pszSubDir /* For recursion */)
1245{
1246 AssertPtrReturn(pContext, VERR_INVALID_POINTER);
1247 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1248 /* Filter is optional. */
1249 AssertPtrReturn(pszDest, VERR_INVALID_POINTER);
1250 /* Sub directory is optional. */
1251
1252 /*
1253 * Construct current path.
1254 */
1255 char szCurDir[RTPATH_MAX];
1256 int rc = RTStrCopy(szCurDir, sizeof(szCurDir), pszSource);
1257 if (RT_SUCCESS(rc) && pszSubDir)
1258 rc = RTPathAppend(szCurDir, sizeof(szCurDir), pszSubDir);
1259
1260 if (RT_FAILURE(rc))
1261 return rc;
1262
1263 /* Flag indicating whether the current directory was created on the
1264 * target or not. */
1265 bool fDirCreated = false;
1266
1267 ULONG uDirHandle;
1268 HRESULT hr = pContext->pGuest->DirectoryOpen(Bstr(szCurDir).raw(), Bstr(pszFilter).raw(),
1269 DirectoryOpenFlag_None /* No flags supported yet. */,
1270 Bstr(pContext->pszUsername).raw(), Bstr(pContext->pszPassword).raw(),
1271 &uDirHandle);
1272 if (FAILED(hr))
1273 rc = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
1274 else
1275 {
1276 ComPtr <IGuestDirEntry> dirEntry;
1277 while (SUCCEEDED(hr = pContext->pGuest->DirectoryRead(uDirHandle, dirEntry.asOutParam())))
1278 {
1279 GuestDirEntryType_T enmType;
1280 dirEntry->COMGETTER(Type)(&enmType);
1281
1282 Bstr strName;
1283 dirEntry->COMGETTER(Name)(strName.asOutParam());
1284
1285 switch (enmType)
1286 {
1287 case GuestDirEntryType_Directory:
1288 {
1289 /* Skip "." and ".." entries. */
1290 if ( !strName.compare(Bstr("."))
1291 || !strName.compare(Bstr("..")))
1292 break;
1293
1294 if (fFlags & CopyFileFlag_Recursive)
1295 {
1296 Utf8Str strDir(strName);
1297 char *pszNewSub = NULL;
1298 if (pszSubDir)
1299 RTStrAPrintf(&pszNewSub, "%s/%s", pszSubDir, strDir.c_str());
1300 else
1301 RTStrAPrintf(&pszNewSub, "%s", strDir.c_str());
1302
1303 if (pszNewSub)
1304 {
1305 rc = ctrlCopyDirToHost(pContext,
1306 pszSource, pszFilter,
1307 pszDest, fFlags, pszNewSub);
1308 RTStrFree(pszNewSub);
1309 }
1310 else
1311 rc = VERR_NO_MEMORY;
1312 }
1313 break;
1314 }
1315
1316 case GuestDirEntryType_Symlink:
1317 if ( (fFlags & CopyFileFlag_Recursive)
1318 && (fFlags & CopyFileFlag_FollowLinks))
1319 {
1320 /* Fall through to next case is intentional. */
1321 }
1322 else
1323 break;
1324
1325 case GuestDirEntryType_File:
1326 {
1327 Utf8Str strFile(strName);
1328 if ( !pszFilter
1329 || RTStrSimplePatternMatch(pszFilter, strFile.c_str()))
1330 {
1331 if (!fDirCreated)
1332 {
1333 char *pszDestDir;
1334 rc = ctrlCopyTranslatePath(pszSource, szCurDir,
1335 pszDest, &pszDestDir);
1336 if (RT_SUCCESS(rc))
1337 {
1338 rc = ctrlCopyDirCreate(pContext, pszDestDir);
1339 RTStrFree(pszDestDir);
1340
1341 fDirCreated = true;
1342 }
1343 }
1344
1345 if (RT_SUCCESS(rc))
1346 {
1347 char *pszFileSource;
1348 if (RTStrAPrintf(&pszFileSource, "%s/%s",
1349 szCurDir, strFile.c_str()))
1350 {
1351 char *pszFileDest;
1352 rc = ctrlCopyTranslatePath(pszSource, pszFileSource,
1353 pszDest, &pszFileDest);
1354 if (RT_SUCCESS(rc))
1355 {
1356 rc = ctrlCopyFileToTarget(pContext, pszFileSource,
1357 pszFileDest, 0 /* Flags? */);
1358 RTStrFree(pszFileDest);
1359 }
1360 RTStrFree(pszFileSource);
1361 }
1362 else
1363 rc = VERR_NO_MEMORY;
1364 }
1365 }
1366 break;
1367 }
1368
1369 default:
1370 break;
1371 }
1372
1373 if (RT_FAILURE(rc))
1374 break;
1375 }
1376
1377 if (FAILED(hr))
1378 {
1379 if (hr != E_ABORT)
1380 rc = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
1381 }
1382
1383 HRESULT hr2 = pContext->pGuest->DirectoryClose(uDirHandle);
1384 if (FAILED(hr2))
1385 {
1386 int rc2 = ctrlPrintError(pContext->pGuest, COM_IIDOF(IGuest));
1387 if (RT_SUCCESS(rc))
1388 rc = rc2;
1389 }
1390 else if (SUCCEEDED(hr))
1391 hr = hr2;
1392 }
1393
1394 return rc;
1395}
1396
1397static int ctrlCopyDirToTarget(PCOPYCONTEXT pContext,
1398 const char *pszSource, const char *pszFilter,
1399 const char *pszDest, uint32_t fFlags,
1400 const char *pszSubDir /* For recursion */)
1401{
1402 if (pContext->fHostToGuest)
1403 return ctrlCopyDirToGuest(pContext, pszSource, pszFilter,
1404 pszDest, fFlags, pszSubDir);
1405 return ctrlCopyDirToHost(pContext, pszSource, pszFilter,
1406 pszDest, fFlags, pszSubDir);
1407}
1408
1409static int ctrlCopyCreateSourceRoot(const char *pszSource, char **ppszSourceRoot)
1410{
1411 AssertPtrReturn(pszSource, VERR_INVALID_POINTER);
1412 AssertPtrReturn(ppszSourceRoot, VERR_INVALID_POINTER);
1413
1414 char *pszNewRoot = RTStrDup(pszSource);
1415 AssertPtrReturn(pszNewRoot, VERR_NO_MEMORY);
1416
1417 size_t lenRoot = strlen(pszNewRoot);
1418 if ( lenRoot
1419 && pszNewRoot[lenRoot - 1] == '/'
1420 && pszNewRoot[lenRoot - 1] == '\\'
1421 && lenRoot > 1
1422 && pszNewRoot[lenRoot - 2] == '/'
1423 && pszNewRoot[lenRoot - 2] == '\\')
1424 {
1425 *ppszSourceRoot = pszNewRoot;
1426 if (lenRoot > 1)
1427 *ppszSourceRoot[lenRoot - 2] = '\0';
1428 *ppszSourceRoot[lenRoot - 1] = '\0';
1429 }
1430 else
1431 {
1432 /* If there's anything (like a file name or a filter),
1433 * strip it! */
1434 RTPathStripFilename(pszNewRoot);
1435 *ppszSourceRoot = pszNewRoot;
1436 }
1437
1438 return VINF_SUCCESS;
1439}
1440
1441static void ctrlCopyFreeSourceRoot(char *pszSourceRoot)
1442{
1443 RTStrFree(pszSourceRoot);
1444}
1445
1446static int handleCtrlCopyTo(ComPtr<IGuest> guest, HandlerArg *pArg,
1447 bool fHostToGuest)
1448{
1449 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1450
1451 /** @todo r=bird: This command isn't very unix friendly in general. mkdir
1452 * is much better (partly because it is much simpler of course). The main
1453 * arguments against this is that (1) all but two options conflicts with
1454 * what 'man cp' tells me on a GNU/Linux system, (2) wildchar matching is
1455 * done windows CMD style (though not in a 100% compatible way), and (3)
1456 * that only one source is allowed - efficiently sabotaging default
1457 * wildcard expansion by a unix shell. The best solution here would be
1458 * two different variant, one windowsy (xcopy) and one unixy (gnu cp). */
1459
1460 /*
1461 * IGuest::CopyToGuest is kept as simple as possible to let the developer choose
1462 * what and how to implement the file enumeration/recursive lookup, like VBoxManage
1463 * does in here.
1464 */
1465
1466#ifdef DEBUG_andy
1467 tstTranslatePath();
1468 return VINF_SUCCESS;
1469#endif
1470
1471 static const RTGETOPTDEF s_aOptions[] =
1472 {
1473 { "--dryrun", GETOPTDEF_COPYTO_DRYRUN, RTGETOPT_REQ_NOTHING },
1474 { "--follow", GETOPTDEF_COPYTO_FOLLOW, RTGETOPT_REQ_NOTHING },
1475 { "--password", GETOPTDEF_COPYTO_PASSWORD, RTGETOPT_REQ_STRING },
1476 { "--recursive", 'R', RTGETOPT_REQ_NOTHING },
1477 { "--target-directory", GETOPTDEF_COPYTO_TARGETDIR, RTGETOPT_REQ_STRING },
1478 { "--username", GETOPTDEF_COPYTO_USERNAME, RTGETOPT_REQ_STRING },
1479 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1480 };
1481
1482 int ch;
1483 RTGETOPTUNION ValueUnion;
1484 RTGETOPTSTATE GetState;
1485 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1486 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1487
1488 Utf8Str Utf8Source;
1489 Utf8Str Utf8Dest;
1490 Utf8Str Utf8UserName;
1491 Utf8Str Utf8Password;
1492 uint32_t fFlags = CopyFileFlag_None;
1493 bool fVerbose = false;
1494 bool fCopyRecursive = false;
1495 bool fDryRun = false;
1496
1497 SOURCEVEC vecSources;
1498
1499 int vrc = VINF_SUCCESS;
1500 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1501 {
1502 /* For options that require an argument, ValueUnion has received the value. */
1503 switch (ch)
1504 {
1505 case GETOPTDEF_COPYTO_DRYRUN:
1506 fDryRun = true;
1507 break;
1508
1509 case GETOPTDEF_COPYTO_FOLLOW:
1510 fFlags |= CopyFileFlag_FollowLinks;
1511 break;
1512
1513 case GETOPTDEF_COPYTO_PASSWORD:
1514 Utf8Password = ValueUnion.psz;
1515 break;
1516
1517 case 'R': /* Recursive processing */
1518 fFlags |= CopyFileFlag_Recursive;
1519 break;
1520
1521 case GETOPTDEF_COPYTO_TARGETDIR:
1522 Utf8Dest = ValueUnion.psz;
1523 break;
1524
1525 case GETOPTDEF_COPYTO_USERNAME:
1526 Utf8UserName = ValueUnion.psz;
1527 break;
1528
1529 case 'v': /* Verbose */
1530 fVerbose = true;
1531 break;
1532
1533 case VINF_GETOPT_NOT_OPTION:
1534 {
1535 /* Last argument and no destination specified with
1536 * --target-directory yet? Then use the current argument
1537 * as destination. */
1538 if ( pArg->argc == GetState.iNext
1539 && Utf8Dest.isEmpty())
1540 {
1541 Utf8Dest = ValueUnion.psz;
1542 }
1543 else
1544 {
1545 /* Save the source directory. */
1546 vecSources.push_back(SOURCEFILEENTRY(ValueUnion.psz));
1547 }
1548 break;
1549 }
1550
1551 default:
1552 return RTGetOptPrintError(ch, &ValueUnion);
1553 }
1554 }
1555
1556 if (!vecSources.size())
1557 return errorSyntax(USAGE_GUESTCONTROL,
1558 "No source(s) specified!");
1559
1560 if (Utf8Dest.isEmpty())
1561 return errorSyntax(USAGE_GUESTCONTROL,
1562 "No destination specified!");
1563
1564 if (Utf8UserName.isEmpty())
1565 return errorSyntax(USAGE_GUESTCONTROL,
1566 "No user name specified!");
1567
1568 /*
1569 * Done parsing arguments, do some more preparations.
1570 */
1571 if (fVerbose)
1572 {
1573 if (fHostToGuest)
1574 RTPrintf("Copying from host to guest ...\n");
1575 else
1576 RTPrintf("Copying from guest to host ...\n");
1577 if (fDryRun)
1578 RTPrintf("Dry run - no files copied!\n");
1579 }
1580
1581 /* Create the copy context -- it contains all information
1582 * the routines need to know when handling the actual copying. */
1583 PCOPYCONTEXT pContext;
1584 vrc = ctrlCopyContextCreate(guest, fVerbose, fHostToGuest,
1585 Utf8UserName.c_str(), Utf8Password.c_str(),
1586 &pContext);
1587 if (RT_FAILURE(vrc))
1588 {
1589 RTMsgError("Unable to create copy context, rc=%Rrc\n", vrc);
1590 return RTEXITCODE_FAILURE;
1591 }
1592
1593 /* If the destination is a path, (try to) create it. */
1594 const char *pszDest = Utf8Dest.c_str();
1595 AssertPtr(pszDest);
1596 size_t lenDest = strlen(pszDest);
1597 if ( lenDest
1598 ||pszDest[lenDest - 1] == '/'
1599 || pszDest[lenDest - 1] == '\\')
1600 {
1601 vrc = ctrlCopyDirCreate(pContext, pszDest);
1602 }
1603
1604 if (RT_SUCCESS(vrc))
1605 {
1606 /*
1607 * Here starts the actual fun!
1608 * Handle all given sources one by one.
1609 */
1610 for (unsigned long s = 0; s < vecSources.size(); s++)
1611 {
1612 const char *pszSource = vecSources[s].mSource.c_str();
1613 const char *pszFilter = vecSources[s].mFilter.c_str();
1614 if (!strlen(pszFilter))
1615 pszFilter = NULL; /* If empty filter then there's no filter :-) */
1616
1617 char *pszSourceRoot;
1618 vrc = ctrlCopyCreateSourceRoot(pszSource, &pszSourceRoot);
1619 if (RT_FAILURE(vrc))
1620 {
1621 RTMsgError("Unable to create source root, rc=%Rrc\n", vrc);
1622 break;
1623 }
1624
1625 if (fVerbose)
1626 RTPrintf("Source: %s\n", pszSource);
1627
1628 /** @todo Files with filter?? */
1629 bool fIsFile = false;
1630 bool fExists;
1631 Utf8Str Utf8CurSource(pszSource);
1632 if ( Utf8CurSource.endsWith("/")
1633 || Utf8CurSource.endsWith("\\"))
1634 {
1635#ifndef DEBUG_andy
1636 if (pContext->fHostToGuest)
1637 {
1638#endif
1639 if (pszFilter) /* Directory with filter. */
1640 vrc = ctrlCopyDirExistsOnSource(pContext, pszSourceRoot, &fExists);
1641 else /* Regular directory without filter. */
1642 vrc = ctrlCopyDirExistsOnSource(pContext, pszSource, &fExists);
1643#ifndef DEBUG_andy
1644 }
1645 else
1646 {
1647 RTMsgError("Copying of guest directories to the host is not supported yet!\n");
1648 vrc = VERR_NOT_IMPLEMENTED;
1649 }
1650#endif
1651 }
1652 else
1653 {
1654 vrc = ctrlCopyFileExistsOnSource(pContext, pszSource, &fExists);
1655 if ( RT_SUCCESS(vrc)
1656 && fExists)
1657 fIsFile = true;
1658 }
1659
1660 if (RT_SUCCESS(vrc))
1661 {
1662 if (fIsFile)
1663 {
1664 /* Single file. */
1665 char *pszDestFile;
1666 vrc = ctrlCopyTranslatePath(pszSourceRoot, pszSource,
1667 Utf8Dest.c_str(), &pszDestFile);
1668 if (RT_SUCCESS(vrc))
1669 {
1670 vrc = ctrlCopyFileToTarget(pContext, pszSource,
1671 pszDestFile, fFlags);
1672 RTStrFree(pszDestFile);
1673 }
1674 else
1675 {
1676 RTMsgError("Unable to translate path for \"%s\", rc=%Rrc\n",
1677 pszSource, vrc);
1678 }
1679 }
1680 else
1681 {
1682 /* Directory (with filter?). */
1683 vrc = ctrlCopyDirToTarget(pContext, pszSource, pszFilter,
1684 Utf8Dest.c_str(), fFlags, NULL /* Subdir */);
1685 }
1686 }
1687
1688 ctrlCopyFreeSourceRoot(pszSourceRoot);
1689
1690 if ( RT_SUCCESS(vrc)
1691 && !fExists)
1692 {
1693 RTMsgError("Warning: Source \"%s\" does not exist, skipping!\n",
1694 pszSource);
1695 continue;
1696 }
1697
1698 if (RT_FAILURE(vrc))
1699 {
1700 RTMsgError("Error processing \"%s\", rc=%Rrc\n",
1701 pszSource, vrc);
1702 break;
1703 }
1704 }
1705 }
1706
1707 ctrlCopyContextFree(pContext);
1708
1709 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1710}
1711
1712static int handleCtrlCreateDirectory(ComPtr<IGuest> guest, HandlerArg *pArg)
1713{
1714 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1715
1716 /*
1717 * Parse arguments.
1718 *
1719 * Note! No direct returns here, everyone must go thru the cleanup at the
1720 * end of this function.
1721 */
1722 static const RTGETOPTDEF s_aOptions[] =
1723 {
1724 { "--mode", 'm', RTGETOPT_REQ_UINT32 },
1725 { "--parents", 'P', RTGETOPT_REQ_NOTHING },
1726 { "--password", GETOPTDEF_MKDIR_PASSWORD, RTGETOPT_REQ_STRING },
1727 { "--username", GETOPTDEF_MKDIR_USERNAME, RTGETOPT_REQ_STRING },
1728 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1729 };
1730
1731 int ch;
1732 RTGETOPTUNION ValueUnion;
1733 RTGETOPTSTATE GetState;
1734 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1735 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1736
1737 Utf8Str Utf8UserName;
1738 Utf8Str Utf8Password;
1739 uint32_t fFlags = DirectoryCreateFlag_None;
1740 uint32_t fDirMode = 0; /* Default mode. */
1741 bool fVerbose = false;
1742
1743 DESTDIRMAP mapDirs;
1744
1745 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1746 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1747 && rcExit == RTEXITCODE_SUCCESS)
1748 {
1749 /* For options that require an argument, ValueUnion has received the value. */
1750 switch (ch)
1751 {
1752 case 'm': /* Mode */
1753 fDirMode = ValueUnion.u32;
1754 break;
1755
1756 case 'P': /* Create parents */
1757 fFlags |= DirectoryCreateFlag_Parents;
1758 break;
1759
1760 case GETOPTDEF_MKDIR_PASSWORD: /* Password */
1761 Utf8Password = ValueUnion.psz;
1762 break;
1763
1764 case GETOPTDEF_MKDIR_USERNAME: /* User name */
1765 Utf8UserName = ValueUnion.psz;
1766 break;
1767
1768 case 'v': /* Verbose */
1769 fVerbose = true;
1770 break;
1771
1772 case VINF_GETOPT_NOT_OPTION:
1773 {
1774 mapDirs[ValueUnion.psz]; /* Add destination directory to map. */
1775 break;
1776 }
1777
1778 default:
1779 rcExit = RTGetOptPrintError(ch, &ValueUnion);
1780 break;
1781 }
1782 }
1783
1784 uint32_t cDirs = mapDirs.size();
1785 if (rcExit == RTEXITCODE_SUCCESS && !cDirs)
1786 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No directory to create specified!");
1787
1788 if (rcExit == RTEXITCODE_SUCCESS && Utf8UserName.isEmpty())
1789 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
1790
1791 if (rcExit == RTEXITCODE_SUCCESS)
1792 {
1793 /*
1794 * Create the directories.
1795 */
1796 HRESULT hrc = S_OK;
1797 if (fVerbose && cDirs)
1798 RTPrintf("Creating %u directories ...\n", cDirs);
1799
1800 DESTDIRMAPITER it = mapDirs.begin();
1801 while (it != mapDirs.end())
1802 {
1803 if (fVerbose)
1804 RTPrintf("Creating directory \"%s\" ...\n", it->first.c_str());
1805
1806 hrc = guest->DirectoryCreate(Bstr(it->first).raw(),
1807 Bstr(Utf8UserName).raw(), Bstr(Utf8Password).raw(),
1808 fDirMode, fFlags);
1809 if (FAILED(hrc))
1810 {
1811 ctrlPrintError(guest, COM_IIDOF(IGuest)); /* Return code ignored, save original rc. */
1812 break;
1813 }
1814
1815 it++;
1816 }
1817
1818 if (FAILED(hrc))
1819 rcExit = RTEXITCODE_FAILURE;
1820 }
1821
1822 return rcExit;
1823}
1824
1825static int handleCtrlStat(ComPtr<IGuest> guest, HandlerArg *pArg)
1826{
1827 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1828
1829 static const RTGETOPTDEF s_aOptions[] =
1830 {
1831 { "--dereference", 'L', RTGETOPT_REQ_NOTHING },
1832 { "--file-system", 'f', RTGETOPT_REQ_NOTHING },
1833 { "--format", 'c', RTGETOPT_REQ_STRING },
1834 { "--password", GETOPTDEF_STAT_PASSWORD, RTGETOPT_REQ_STRING },
1835 { "--terse", 't', RTGETOPT_REQ_NOTHING },
1836 { "--username", GETOPTDEF_STAT_USERNAME, RTGETOPT_REQ_STRING },
1837 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1838 };
1839
1840 int ch;
1841 RTGETOPTUNION ValueUnion;
1842 RTGETOPTSTATE GetState;
1843 RTGetOptInit(&GetState, pArg->argc, pArg->argv,
1844 s_aOptions, RT_ELEMENTS(s_aOptions), 0, RTGETOPTINIT_FLAGS_OPTS_FIRST);
1845
1846 Utf8Str Utf8UserName;
1847 Utf8Str Utf8Password;
1848
1849 bool fVerbose = false;
1850 DESTDIRMAP mapObjs;
1851
1852 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
1853 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1854 && rcExit == RTEXITCODE_SUCCESS)
1855 {
1856 /* For options that require an argument, ValueUnion has received the value. */
1857 switch (ch)
1858 {
1859 case GETOPTDEF_STAT_PASSWORD: /* Password */
1860 Utf8Password = ValueUnion.psz;
1861 break;
1862
1863 case GETOPTDEF_STAT_USERNAME: /* User name */
1864 Utf8UserName = ValueUnion.psz;
1865 break;
1866
1867 case 'L': /* Dereference */
1868 case 'f': /* File-system */
1869 case 'c': /* Format */
1870 case 't': /* Terse */
1871 return errorSyntax(USAGE_GUESTCONTROL, "Command \"%s\" not implemented yet!",
1872 ValueUnion.psz);
1873 break; /* Never reached. */
1874
1875 case 'v': /* Verbose */
1876 fVerbose = true;
1877 break;
1878
1879 case VINF_GETOPT_NOT_OPTION:
1880 {
1881 mapObjs[ValueUnion.psz]; /* Add element to check to map. */
1882 break;
1883 }
1884
1885 default:
1886 return RTGetOptPrintError(ch, &ValueUnion);
1887 break; /* Never reached. */
1888 }
1889 }
1890
1891 uint32_t cObjs = mapObjs.size();
1892 if (rcExit == RTEXITCODE_SUCCESS && !cObjs)
1893 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No element(s) to check specified!");
1894
1895 if (rcExit == RTEXITCODE_SUCCESS && Utf8UserName.isEmpty())
1896 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No user name specified!");
1897
1898 if (rcExit == RTEXITCODE_SUCCESS)
1899 {
1900 /*
1901 * Create the directories.
1902 */
1903 HRESULT hrc = S_OK;
1904
1905 DESTDIRMAPITER it = mapObjs.begin();
1906 while (it != mapObjs.end())
1907 {
1908 if (fVerbose)
1909 RTPrintf("Checking for element \"%s\" ...\n", it->first.c_str());
1910
1911 BOOL fExists;
1912 hrc = guest->FileExists(Bstr(it->first).raw(),
1913 Bstr(Utf8UserName).raw(), Bstr(Utf8Password).raw(),
1914 &fExists);
1915 if (FAILED(hrc))
1916 {
1917 ctrlPrintError(guest, COM_IIDOF(IGuest)); /* Return code ignored, save original rc. */
1918 break;
1919 }
1920 else
1921 {
1922 /** @todo: Output vbox_stat's stdout output to get more information about
1923 * what happened. */
1924
1925 /* If there's at least one element which does not exist on the guest,
1926 * drop out with exitcode 1. */
1927 if (!fExists)
1928 {
1929 RTPrintf("Cannot stat for element \"%s\": No such file or directory.\n",
1930 it->first.c_str());
1931 rcExit = RTEXITCODE_FAILURE;
1932 }
1933 }
1934
1935 it++;
1936 }
1937
1938 if (FAILED(hrc))
1939 rcExit = RTEXITCODE_FAILURE;
1940 }
1941
1942 return rcExit;
1943}
1944
1945static int handleCtrlUpdateAdditions(ComPtr<IGuest> guest, HandlerArg *pArg)
1946{
1947 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
1948
1949 /*
1950 * Check the syntax. We can deduce the correct syntax from the number of
1951 * arguments.
1952 */
1953 Utf8Str Utf8Source;
1954 bool fVerbose = false;
1955
1956 static const RTGETOPTDEF s_aOptions[] =
1957 {
1958 { "--source", 's', RTGETOPT_REQ_STRING },
1959 { "--verbose", 'v', RTGETOPT_REQ_NOTHING }
1960 };
1961
1962 int ch;
1963 RTGETOPTUNION ValueUnion;
1964 RTGETOPTSTATE GetState;
1965 RTGetOptInit(&GetState, pArg->argc, pArg->argv, s_aOptions, RT_ELEMENTS(s_aOptions), 0, 0);
1966
1967 int vrc = VINF_SUCCESS;
1968 while ( (ch = RTGetOpt(&GetState, &ValueUnion))
1969 && RT_SUCCESS(vrc))
1970 {
1971 switch (ch)
1972 {
1973 case 's':
1974 Utf8Source = ValueUnion.psz;
1975 break;
1976
1977 case 'v':
1978 fVerbose = true;
1979 break;
1980
1981 default:
1982 return RTGetOptPrintError(ch, &ValueUnion);
1983 }
1984 }
1985
1986 if (fVerbose)
1987 RTPrintf("Updating Guest Additions ...\n");
1988
1989#ifdef DEBUG_andy
1990 if (Utf8Source.isEmpty())
1991 Utf8Source = "c:\\Downloads\\VBoxGuestAdditions-r67158.iso";
1992#endif
1993
1994 /* Determine source if not set yet. */
1995 if (Utf8Source.isEmpty())
1996 {
1997 char strTemp[RTPATH_MAX];
1998 vrc = RTPathAppPrivateNoArch(strTemp, sizeof(strTemp));
1999 AssertRC(vrc);
2000 Utf8Str Utf8Src1 = Utf8Str(strTemp).append("/VBoxGuestAdditions.iso");
2001
2002 vrc = RTPathExecDir(strTemp, sizeof(strTemp));
2003 AssertRC(vrc);
2004 Utf8Str Utf8Src2 = Utf8Str(strTemp).append("/additions/VBoxGuestAdditions.iso");
2005
2006 /* Check the standard image locations */
2007 if (RTFileExists(Utf8Src1.c_str()))
2008 Utf8Source = Utf8Src1;
2009 else if (RTFileExists(Utf8Src2.c_str()))
2010 Utf8Source = Utf8Src2;
2011 else
2012 {
2013 RTMsgError("Source could not be determined! Please use --source to specify a valid source.\n");
2014 vrc = VERR_FILE_NOT_FOUND;
2015 }
2016 }
2017 else if (!RTFileExists(Utf8Source.c_str()))
2018 {
2019 RTMsgError("Source \"%s\" does not exist!\n", Utf8Source.c_str());
2020 vrc = VERR_FILE_NOT_FOUND;
2021 }
2022
2023 if (RT_SUCCESS(vrc))
2024 {
2025 if (fVerbose)
2026 RTPrintf("Using source: %s\n", Utf8Source.c_str());
2027
2028 HRESULT rc = S_OK;
2029 ComPtr<IProgress> progress;
2030 CHECK_ERROR(guest, UpdateGuestAdditions(Bstr(Utf8Source).raw(),
2031 /* Wait for whole update process to complete. */
2032 AdditionsUpdateFlag_None,
2033 progress.asOutParam()));
2034 if (FAILED(rc))
2035 vrc = ctrlPrintError(guest, COM_IIDOF(IGuest));
2036 else
2037 {
2038 rc = showProgress(progress);
2039 CHECK_PROGRESS_ERROR(progress, ("Guest additions update failed"));
2040 if ( SUCCEEDED(rc)
2041 && fVerbose)
2042 RTPrintf("Guest Additions update successful.\n");
2043 }
2044 }
2045
2046 return RT_SUCCESS(vrc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
2047}
2048
2049/**
2050 * Access the guest control store.
2051 *
2052 * @returns program exit code.
2053 * @note see the command line API description for parameters
2054 */
2055int handleGuestControl(HandlerArg *pArg)
2056{
2057 AssertPtrReturn(pArg, VERR_INVALID_PARAMETER);
2058
2059 HandlerArg arg = *pArg;
2060 arg.argc = pArg->argc - 2; /* Skip VM name and sub command. */
2061 arg.argv = pArg->argv + 2; /* Same here. */
2062
2063 ComPtr<IGuest> guest;
2064 int vrc = ctrlInitVM(pArg, pArg->argv[0] /* VM Name */, &guest);
2065 if (RT_SUCCESS(vrc))
2066 {
2067 int rcExit;
2068 if ( !strcmp(pArg->argv[1], "exec")
2069 || !strcmp(pArg->argv[1], "execute"))
2070 {
2071 rcExit = handleCtrlExecProgram(guest, &arg);
2072 }
2073 else if (!strcmp(pArg->argv[1], "copyfrom"))
2074 {
2075 rcExit = handleCtrlCopyTo(guest, &arg,
2076 false /* Guest to host */);
2077 }
2078 else if ( !strcmp(pArg->argv[1], "copyto")
2079 || !strcmp(pArg->argv[1], "cp"))
2080 {
2081 rcExit = handleCtrlCopyTo(guest, &arg,
2082 true /* Host to guest */);
2083 }
2084 else if ( !strcmp(pArg->argv[1], "createdirectory")
2085 || !strcmp(pArg->argv[1], "createdir")
2086 || !strcmp(pArg->argv[1], "mkdir")
2087 || !strcmp(pArg->argv[1], "md"))
2088 {
2089 rcExit = handleCtrlCreateDirectory(guest, &arg);
2090 }
2091 else if ( !strcmp(pArg->argv[1], "stat"))
2092 {
2093 rcExit = handleCtrlStat(guest, &arg);
2094 }
2095 else if ( !strcmp(pArg->argv[1], "updateadditions")
2096 || !strcmp(pArg->argv[1], "updateadds"))
2097 {
2098 rcExit = handleCtrlUpdateAdditions(guest, &arg);
2099 }
2100 else
2101 rcExit = errorSyntax(USAGE_GUESTCONTROL, "No sub command specified!");
2102
2103 ctrlUninitVM(pArg);
2104 return rcExit;
2105 }
2106 return RTEXITCODE_FAILURE;
2107}
2108
2109#endif /* !VBOX_ONLY_DOCS */
2110
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