VirtualBox

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

Last change on this file since 75251 was 72949, checked in by vboxsync, 6 years ago

VBoxManage,manual: Added a new command called 'mediumio' to VBoxManage for making use of the IMediumIO interface.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 28.9 KB
Line 
1/* $Id: VBoxManage.cpp 72949 2018-07-07 16:22:45Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2017 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#ifndef VBOX_ONLY_DOCS
23# include <VBox/com/com.h>
24# include <VBox/com/string.h>
25# include <VBox/com/Guid.h>
26# include <VBox/com/array.h>
27# include <VBox/com/ErrorInfo.h>
28# include <VBox/com/errorprint.h>
29# include <VBox/com/NativeEventQueue.h>
30
31# include <VBox/com/VirtualBox.h>
32#endif /* !VBOX_ONLY_DOCS */
33
34#include <VBox/err.h>
35#include <VBox/version.h>
36
37#include <iprt/asm.h>
38#include <iprt/buildconfig.h>
39#include <iprt/ctype.h>
40#include <iprt/file.h>
41#include <iprt/getopt.h>
42#include <iprt/initterm.h>
43#include <iprt/path.h>
44#include <iprt/stream.h>
45#include <iprt/string.h>
46
47#include <signal.h>
48
49#include "VBoxManage.h"
50
51
52/*********************************************************************************************************************************
53* Defined Constants And Macros *
54*********************************************************************************************************************************/
55/** The command doesn't need the COM stuff. */
56#define VBMG_CMD_F_NO_COM RT_BIT_32(0)
57
58#define VBMG_CMD_TODO HELP_CMD_VBOXMANAGE_INVALID
59
60
61/*********************************************************************************************************************************
62* Structures and Typedefs *
63*********************************************************************************************************************************/
64#ifndef VBOX_ONLY_DOCS
65/**
66 * VBoxManage command descriptor.
67 */
68typedef struct VBMGCMD
69{
70 /** The command. */
71 const char *pszCommand;
72 /** The help category. */
73 USAGECATEGORY enmHelpCat;
74 /** The new help command. */
75 enum HELP_CMD_VBOXMANAGE enmCmdHelp;
76 /** The handler. */
77 RTEXITCODE (*pfnHandler)(HandlerArg *pArg);
78 /** VBMG_CMD_F_XXX, */
79 uint32_t fFlags;
80} VBMGCMD;
81/** Pointer to a const VBoxManage command descriptor. */
82typedef VBMGCMD const *PCVBMGCMD;
83#endif
84
85
86/*********************************************************************************************************************************
87* Global Variables *
88*********************************************************************************************************************************/
89/*extern*/ bool g_fDetailedProgress = false;
90
91#ifndef VBOX_ONLY_DOCS
92/** Set by the signal handler. */
93static volatile bool g_fCanceled = false;
94
95
96/**
97 * All registered command handlers
98 */
99static const VBMGCMD g_aCommands[] =
100{
101 { "internalcommands", 0, VBMG_CMD_TODO, handleInternalCommands, 0 },
102 { "list", USAGE_LIST, VBMG_CMD_TODO, handleList, 0 },
103 { "showvminfo", USAGE_SHOWVMINFO, VBMG_CMD_TODO, handleShowVMInfo, 0 },
104 { "registervm", USAGE_REGISTERVM, VBMG_CMD_TODO, handleRegisterVM, 0 },
105 { "unregistervm", USAGE_UNREGISTERVM, VBMG_CMD_TODO, handleUnregisterVM, 0 },
106 { "clonevm", USAGE_CLONEVM, VBMG_CMD_TODO, handleCloneVM, 0 },
107 { "movevm", USAGE_MOVEVM, VBMG_CMD_TODO, handleMoveVM, 0 },
108 { "mediumproperty", USAGE_MEDIUMPROPERTY, VBMG_CMD_TODO, handleMediumProperty, 0 },
109 { "hdproperty", USAGE_MEDIUMPROPERTY, VBMG_CMD_TODO, handleMediumProperty, 0 }, /* backward compatibility */
110 { "createmedium", USAGE_CREATEMEDIUM, VBMG_CMD_TODO, handleCreateMedium, 0 },
111 { "createhd", USAGE_CREATEMEDIUM, VBMG_CMD_TODO, handleCreateMedium, 0 }, /* backward compatibility */
112 { "createvdi", USAGE_CREATEMEDIUM, VBMG_CMD_TODO, handleCreateMedium, 0 }, /* backward compatibility */
113 { "modifymedium", USAGE_MODIFYMEDIUM, VBMG_CMD_TODO, handleModifyMedium, 0 },
114 { "modifyhd", USAGE_MODIFYMEDIUM, VBMG_CMD_TODO, handleModifyMedium, 0 }, /* backward compatibility */
115 { "modifyvdi", USAGE_MODIFYMEDIUM, VBMG_CMD_TODO, handleModifyMedium, 0 }, /* backward compatibility */
116 { "clonemedium", USAGE_CLONEMEDIUM, VBMG_CMD_TODO, handleCloneMedium, 0 },
117 { "clonehd", USAGE_CLONEMEDIUM, VBMG_CMD_TODO, handleCloneMedium, 0 }, /* backward compatibility */
118 { "clonevdi", USAGE_CLONEMEDIUM, VBMG_CMD_TODO, handleCloneMedium, 0 }, /* backward compatibility */
119 { "encryptmedium", USAGE_ENCRYPTMEDIUM, VBMG_CMD_TODO, handleEncryptMedium, 0 },
120 { "checkmediumpwd", USAGE_MEDIUMENCCHKPWD, VBMG_CMD_TODO, handleCheckMediumPassword, 0 },
121 { "createvm", USAGE_CREATEVM, VBMG_CMD_TODO, handleCreateVM, 0 },
122 { "modifyvm", USAGE_MODIFYVM, VBMG_CMD_TODO, handleModifyVM, 0 },
123 { "startvm", USAGE_STARTVM, VBMG_CMD_TODO, handleStartVM, 0 },
124 { "controlvm", USAGE_CONTROLVM, VBMG_CMD_TODO, handleControlVM, 0 },
125 { "unattended", USAGE_UNATTENDED, HELP_CMD_UNATTENDED, handleUnattended, 0 },
126 { "discardstate", USAGE_DISCARDSTATE, VBMG_CMD_TODO, handleDiscardState, 0 },
127 { "adoptstate", USAGE_ADOPTSTATE, VBMG_CMD_TODO, handleAdoptState, 0 },
128 { "snapshot", USAGE_SNAPSHOT, VBMG_CMD_TODO, handleSnapshot, 0 },
129 { "closemedium", USAGE_CLOSEMEDIUM, VBMG_CMD_TODO, handleCloseMedium, 0 },
130 { "storageattach", USAGE_STORAGEATTACH, VBMG_CMD_TODO, handleStorageAttach, 0 },
131 { "storagectl", USAGE_STORAGECONTROLLER,VBMG_CMD_TODO, handleStorageController, 0 },
132 { "showmediuminfo", USAGE_SHOWMEDIUMINFO, VBMG_CMD_TODO, handleShowMediumInfo, 0 },
133 { "showhdinfo", USAGE_SHOWMEDIUMINFO, VBMG_CMD_TODO, handleShowMediumInfo, 0 }, /* backward compatibility */
134 { "showvdiinfo", USAGE_SHOWMEDIUMINFO, VBMG_CMD_TODO, handleShowMediumInfo, 0 }, /* backward compatibility */
135 { "mediumio", USAGE_MEDIUMIO, HELP_CMD_MEDIUMIO, handleMediumIO, 0 },
136 { "getextradata", USAGE_GETEXTRADATA, VBMG_CMD_TODO, handleGetExtraData, 0 },
137 { "setextradata", USAGE_SETEXTRADATA, VBMG_CMD_TODO, handleSetExtraData, 0 },
138 { "setproperty", USAGE_SETPROPERTY, VBMG_CMD_TODO, handleSetProperty, 0 },
139 { "usbfilter", USAGE_USBFILTER, VBMG_CMD_TODO, handleUSBFilter, 0 },
140 { "sharedfolder", USAGE_SHAREDFOLDER, VBMG_CMD_TODO, handleSharedFolder, 0 },
141#ifdef VBOX_WITH_GUEST_PROPS
142 { "guestproperty", USAGE_GUESTPROPERTY, VBMG_CMD_TODO, handleGuestProperty, 0 },
143#endif
144#ifdef VBOX_WITH_GUEST_CONTROL
145 { "guestcontrol", USAGE_GUESTCONTROL, VBMG_CMD_TODO, handleGuestControl, 0 },
146#endif
147 { "metrics", USAGE_METRICS, VBMG_CMD_TODO, handleMetrics, 0 },
148 { "import", USAGE_IMPORTAPPLIANCE, VBMG_CMD_TODO, handleImportAppliance, 0 },
149 { "export", USAGE_EXPORTAPPLIANCE, VBMG_CMD_TODO, handleExportAppliance, 0 },
150#ifdef VBOX_WITH_NETFLT
151 { "hostonlyif", USAGE_HOSTONLYIFS, VBMG_CMD_TODO, handleHostonlyIf, 0 },
152#endif
153 { "dhcpserver", USAGE_DHCPSERVER, VBMG_CMD_TODO, handleDHCPServer, 0 },
154#ifdef VBOX_WITH_NAT_SERVICE
155 { "natnetwork", USAGE_NATNETWORK, VBMG_CMD_TODO, handleNATNetwork, 0 },
156#endif
157 { "extpack", USAGE_EXTPACK, HELP_CMD_EXTPACK, handleExtPack, 0 },
158 { "bandwidthctl", USAGE_BANDWIDTHCONTROL, VBMG_CMD_TODO, handleBandwidthControl, 0 },
159 { "debugvm", USAGE_DEBUGVM, HELP_CMD_DEBUGVM, handleDebugVM, 0 },
160 { "convertfromraw", USAGE_CONVERTFROMRAW, VBMG_CMD_TODO, handleConvertFromRaw, VBMG_CMD_F_NO_COM },
161 { "convertdd", USAGE_CONVERTFROMRAW, VBMG_CMD_TODO, handleConvertFromRaw, VBMG_CMD_F_NO_COM },
162 { "usbdevsource", USAGE_USBDEVSOURCE, VBMG_CMD_TODO, handleUSBDevSource, 0 }
163};
164
165
166/**
167 * Looks up a command by name.
168 *
169 * @returns Pointer to the command structure.
170 * @param pszCommand Name of the command.
171 */
172static PCVBMGCMD lookupCommand(const char *pszCommand)
173{
174 if (pszCommand)
175 for (uint32_t i = 0; i < RT_ELEMENTS(g_aCommands); i++)
176 if (!strcmp(g_aCommands[i].pszCommand, pszCommand))
177 return &g_aCommands[i];
178 return NULL;
179}
180
181
182/**
183 * Signal handler that sets g_fCanceled.
184 *
185 * This can be executed on any thread in the process, on Windows it may even be
186 * a thread dedicated to delivering this signal. Do not doing anything
187 * unnecessary here.
188 */
189static void showProgressSignalHandler(int iSignal)
190{
191 NOREF(iSignal);
192 ASMAtomicWriteBool(&g_fCanceled, true);
193}
194
195/**
196 * Print out progress on the console.
197 *
198 * This runs the main event queue every now and then to prevent piling up
199 * unhandled things (which doesn't cause real problems, just makes things
200 * react a little slower than in the ideal case).
201 */
202HRESULT showProgress(ComPtr<IProgress> progress)
203{
204 using namespace com;
205
206 BOOL fCompleted = FALSE;
207 ULONG ulCurrentPercent = 0;
208 ULONG ulLastPercent = 0;
209
210 ULONG ulLastOperationPercent = (ULONG)-1;
211
212 ULONG ulLastOperation = (ULONG)-1;
213 Bstr bstrOperationDescription;
214
215 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
216
217 ULONG cOperations = 1;
218 HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
219 if (FAILED(hrc))
220 {
221 RTStrmPrintf(g_pStdErr, "Progress object failure: %Rhrc\n", hrc);
222 RTStrmFlush(g_pStdErr);
223 return hrc;
224 }
225
226 /*
227 * Note: Outputting the progress info to stderr (g_pStdErr) is intentional
228 * to not get intermixed with other (raw) stdout data which might get
229 * written in the meanwhile.
230 */
231
232 if (!g_fDetailedProgress)
233 {
234 RTStrmPrintf(g_pStdErr, "0%%...");
235 RTStrmFlush(g_pStdErr);
236 }
237
238 /* setup signal handling if cancelable */
239 bool fCanceledAlready = false;
240 BOOL fCancelable;
241 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
242 if (FAILED(hrc))
243 fCancelable = FALSE;
244 if (fCancelable)
245 {
246 signal(SIGINT, showProgressSignalHandler);
247 signal(SIGTERM, showProgressSignalHandler);
248#ifdef SIGBREAK
249 signal(SIGBREAK, showProgressSignalHandler);
250#endif
251 }
252
253 hrc = progress->COMGETTER(Completed(&fCompleted));
254 while (SUCCEEDED(hrc))
255 {
256 progress->COMGETTER(Percent(&ulCurrentPercent));
257
258 if (g_fDetailedProgress)
259 {
260 ULONG ulOperation = 1;
261 hrc = progress->COMGETTER(Operation)(&ulOperation);
262 if (FAILED(hrc))
263 break;
264 ULONG ulCurrentOperationPercent = 0;
265 hrc = progress->COMGETTER(OperationPercent(&ulCurrentOperationPercent));
266 if (FAILED(hrc))
267 break;
268
269 if (ulLastOperation != ulOperation)
270 {
271 hrc = progress->COMGETTER(OperationDescription(bstrOperationDescription.asOutParam()));
272 if (FAILED(hrc))
273 break;
274 ulLastPercent = (ULONG)-1; // force print
275 ulLastOperation = ulOperation;
276 }
277
278 if ( ulCurrentPercent != ulLastPercent
279 || ulCurrentOperationPercent != ulLastOperationPercent
280 )
281 {
282 LONG lSecsRem = 0;
283 progress->COMGETTER(TimeRemaining)(&lSecsRem);
284
285 RTStrmPrintf(g_pStdErr, "(%u/%u) %ls %02u%% => %02u%% (%d s remaining)\n", ulOperation + 1, cOperations,
286 bstrOperationDescription.raw(), ulCurrentOperationPercent, ulCurrentPercent, lSecsRem);
287 ulLastPercent = ulCurrentPercent;
288 ulLastOperationPercent = ulCurrentOperationPercent;
289 }
290 }
291 else
292 {
293 /* did we cross a 10% mark? */
294 if (ulCurrentPercent / 10 > ulLastPercent / 10)
295 {
296 /* make sure to also print out missed steps */
297 for (ULONG curVal = (ulLastPercent / 10) * 10 + 10; curVal <= (ulCurrentPercent / 10) * 10; curVal += 10)
298 {
299 if (curVal < 100)
300 {
301 RTStrmPrintf(g_pStdErr, "%u%%...", curVal);
302 RTStrmFlush(g_pStdErr);
303 }
304 }
305 ulLastPercent = (ulCurrentPercent / 10) * 10;
306 }
307 }
308 if (fCompleted)
309 break;
310
311 /* process async cancelation */
312 if (g_fCanceled && !fCanceledAlready)
313 {
314 hrc = progress->Cancel();
315 if (SUCCEEDED(hrc))
316 fCanceledAlready = true;
317 else
318 g_fCanceled = false;
319 }
320
321 /* make sure the loop is not too tight */
322 progress->WaitForCompletion(100);
323
324 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
325 hrc = progress->COMGETTER(Completed(&fCompleted));
326 }
327
328 /* undo signal handling */
329 if (fCancelable)
330 {
331 signal(SIGINT, SIG_DFL);
332 signal(SIGTERM, SIG_DFL);
333# ifdef SIGBREAK
334 signal(SIGBREAK, SIG_DFL);
335# endif
336 }
337
338 /* complete the line. */
339 LONG iRc = E_FAIL;
340 hrc = progress->COMGETTER(ResultCode)(&iRc);
341 if (SUCCEEDED(hrc))
342 {
343 if (SUCCEEDED(iRc))
344 RTStrmPrintf(g_pStdErr, "100%%\n");
345 else if (g_fCanceled)
346 RTStrmPrintf(g_pStdErr, "CANCELED\n");
347 else
348 {
349 if (!g_fDetailedProgress)
350 RTStrmPrintf(g_pStdErr, "\n");
351 RTStrmPrintf(g_pStdErr, "Progress state: %Rhrc\n", iRc);
352 }
353 hrc = iRc;
354 }
355 else
356 {
357 if (!g_fDetailedProgress)
358 RTStrmPrintf(g_pStdErr, "\n");
359 RTStrmPrintf(g_pStdErr, "Progress object failure: %Rhrc\n", hrc);
360 }
361 RTStrmFlush(g_pStdErr);
362 return hrc;
363}
364
365RTEXITCODE readPasswordFile(const char *pszFilename, com::Utf8Str *pPasswd)
366{
367 size_t cbFile;
368 char szPasswd[512];
369 int vrc = VINF_SUCCESS;
370 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
371 bool fStdIn = !strcmp(pszFilename, "stdin");
372 PRTSTREAM pStrm;
373 if (!fStdIn)
374 vrc = RTStrmOpen(pszFilename, "r", &pStrm);
375 else
376 pStrm = g_pStdIn;
377 if (RT_SUCCESS(vrc))
378 {
379 vrc = RTStrmReadEx(pStrm, szPasswd, sizeof(szPasswd)-1, &cbFile);
380 if (RT_SUCCESS(vrc))
381 {
382 if (cbFile >= sizeof(szPasswd)-1)
383 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Provided password in file '%s' is too long", pszFilename);
384 else
385 {
386 unsigned i;
387 for (i = 0; i < cbFile && !RT_C_IS_CNTRL(szPasswd[i]); i++)
388 ;
389 szPasswd[i] = '\0';
390 *pPasswd = szPasswd;
391 }
392 }
393 else
394 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot read password from file '%s': %Rrc", pszFilename, vrc);
395 if (!fStdIn)
396 RTStrmClose(pStrm);
397 }
398 else
399 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot open password file '%s' (%Rrc)", pszFilename, vrc);
400
401 return rcExit;
402}
403
404static RTEXITCODE settingsPasswordFile(ComPtr<IVirtualBox> virtualBox, const char *pszFilename)
405{
406 com::Utf8Str passwd;
407 RTEXITCODE rcExit = readPasswordFile(pszFilename, &passwd);
408 if (rcExit == RTEXITCODE_SUCCESS)
409 {
410 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(com::Bstr(passwd).raw()), rcExit = RTEXITCODE_FAILURE);
411 }
412
413 return rcExit;
414}
415
416RTEXITCODE readPasswordFromConsole(com::Utf8Str *pPassword, const char *pszPrompt, ...)
417{
418 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
419 char aszPwdInput[_1K] = { 0 };
420 va_list vaArgs;
421
422 va_start(vaArgs, pszPrompt);
423 int vrc = RTStrmPrintfV(g_pStdOut, pszPrompt, vaArgs);
424 if (RT_SUCCESS(vrc))
425 {
426 bool fEchoOld = false;
427 vrc = RTStrmInputGetEchoChars(g_pStdIn, &fEchoOld);
428 if (RT_SUCCESS(vrc))
429 {
430 vrc = RTStrmInputSetEchoChars(g_pStdIn, false);
431 if (RT_SUCCESS(vrc))
432 {
433 vrc = RTStrmGetLine(g_pStdIn, &aszPwdInput[0], sizeof(aszPwdInput));
434 if (RT_SUCCESS(vrc))
435 *pPassword = aszPwdInput;
436 else
437 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed read password from command line (%Rrc)", vrc);
438
439 int vrc2 = RTStrmInputSetEchoChars(g_pStdIn, fEchoOld);
440 AssertRC(vrc2);
441 }
442 else
443 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to disable echoing typed characters (%Rrc)", vrc);
444 }
445 else
446 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to retrieve echo setting (%Rrc)", vrc);
447
448 RTStrmPutStr(g_pStdOut, "\n");
449 }
450 else
451 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to print prompt (%Rrc)", vrc);
452 va_end(vaArgs);
453
454 return rcExit;
455}
456
457#endif /* !VBOX_ONLY_DOCS */
458
459
460int main(int argc, char *argv[])
461{
462 /*
463 * Before we do anything, init the runtime without loading
464 * the support driver.
465 */
466 int vrc = RTR3InitExe(argc, &argv, 0);
467 if (RT_FAILURE(vrc))
468 return RTMsgInitFailure(vrc);
469#if defined(RT_OS_WINDOWS) && !defined(VBOX_ONLY_DOCS)
470 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
471#endif
472
473 /*
474 * Parse the global options
475 */
476 bool fShowLogo = false;
477 bool fShowHelp = false;
478 int iCmd = 1;
479 int iCmdArg;
480 const char *pszSettingsPw = NULL;
481 const char *pszSettingsPwFile = NULL;
482#ifndef VBOX_ONLY_DOCS
483 int cResponseFileArgs = 0;
484 char **papszResponseFileArgs = NULL;
485 char **papszNewArgv = NULL;
486#endif
487
488 for (int i = 1; i < argc || argc <= iCmd; i++)
489 {
490 if ( argc <= iCmd
491 || !strcmp(argv[i], "help")
492 || !strcmp(argv[i], "--help")
493 || !strcmp(argv[i], "-?")
494 || !strcmp(argv[i], "-h")
495 || !strcmp(argv[i], "-help"))
496 {
497 if (i >= argc - 1)
498 {
499 showLogo(g_pStdOut);
500 printUsage(USAGE_ALL, ~0U, g_pStdOut);
501 return 0;
502 }
503 fShowLogo = true;
504 fShowHelp = true;
505 iCmd++;
506 continue;
507 }
508
509#ifndef VBOX_ONLY_DOCS
510 if ( !strcmp(argv[i], "-V")
511 || !strcmp(argv[i], "--version")
512 || !strcmp(argv[i], "-v") /* deprecated */
513 || !strcmp(argv[i], "-version") /* deprecated */
514 || !strcmp(argv[i], "-Version") /* deprecated */)
515 {
516 /* Print version number, and do nothing else. */
517 RTPrintf("%sr%u\n", VBOX_VERSION_STRING, RTBldCfgRevision());
518 return 0;
519 }
520#endif
521
522 if ( !strcmp(argv[i], "--dumpopts")
523 || !strcmp(argv[i], "-dumpopts") /* deprecated */)
524 {
525 /* Special option to dump really all commands,
526 * even the ones not understood on this platform. */
527 printUsage(USAGE_DUMPOPTS, ~0U, g_pStdOut);
528 return 0;
529 }
530
531 if ( !strcmp(argv[i], "--nologo")
532 || !strcmp(argv[i], "-q")
533 || !strcmp(argv[i], "-nologo") /* deprecated */)
534 {
535 /* suppress the logo */
536 fShowLogo = false;
537 iCmd++;
538 }
539 else if ( !strcmp(argv[i], "--detailed-progress")
540 || !strcmp(argv[i], "-d"))
541 {
542 /* detailed progress report */
543 g_fDetailedProgress = true;
544 iCmd++;
545 }
546 else if (!strcmp(argv[i], "--settingspw"))
547 {
548 if (i >= argc - 1)
549 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Password expected");
550 /* password for certain settings */
551 pszSettingsPw = argv[i + 1];
552 iCmd += 2;
553 }
554 else if (!strcmp(argv[i], "--settingspwfile"))
555 {
556 if (i >= argc-1)
557 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No password file specified");
558 pszSettingsPwFile = argv[i+1];
559 iCmd += 2;
560 }
561#ifndef VBOX_ONLY_DOCS
562 else if (argv[i][0] == '@')
563 {
564 if (papszResponseFileArgs)
565 return RTMsgErrorExitFailure("Only one response file allowed");
566
567 /* Load response file, making sure it's valid UTF-8. */
568 char *pszResponseFile;
569 size_t cbResponseFile;
570 vrc = RTFileReadAllEx(&argv[i][1], 0, RTFOFF_MAX, RTFILE_RDALL_O_DENY_NONE | RTFILE_RDALL_F_TRAILING_ZERO_BYTE,
571 (void **)&pszResponseFile, &cbResponseFile);
572 if (RT_FAILURE(vrc))
573 return RTMsgErrorExitFailure("Error reading response file '%s': %Rrc", &argv[i][1], vrc);
574 vrc = RTStrValidateEncoding(pszResponseFile);
575 if (RT_FAILURE(vrc))
576 {
577 RTFileReadAllFree(pszResponseFile, cbResponseFile);
578 return RTMsgErrorExitFailure("Invalid response file ('%s') encoding: %Rrc", &argv[i][1], vrc);
579 }
580
581 /* Parse it. */
582 vrc = RTGetOptArgvFromString(&papszResponseFileArgs, &cResponseFileArgs, pszResponseFile,
583 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
584 RTFileReadAllFree(pszResponseFile, cbResponseFile);
585 if (RT_FAILURE(vrc))
586 return RTMsgErrorExitFailure("Failed to parse response file '%s' (bourne shell style): %Rrc", &argv[i][1], vrc);
587
588 /* Construct new argv+argc with the response file arguments inserted. */
589 int cNewArgs = argc + cResponseFileArgs;
590 papszNewArgv = (char **)RTMemAllocZ((cNewArgs + 2) * sizeof(papszNewArgv[0]));
591 if (!papszNewArgv)
592 return RTMsgErrorExitFailure("out of memory");
593 memcpy(&papszNewArgv[0], &argv[0], sizeof(argv[0]) * (i + 1));
594 memcpy(&papszNewArgv[i + 1], papszResponseFileArgs, sizeof(argv[0]) * cResponseFileArgs);
595 memcpy(&papszNewArgv[i + 1 + cResponseFileArgs], &argv[i + 1], sizeof(argv[0]) * (argc - i - 1 + 1));
596 argv = papszNewArgv;
597 argc = argc + cResponseFileArgs;
598
599 iCmd++;
600 }
601#endif
602 else
603 break;
604 }
605
606 iCmdArg = iCmd + 1;
607
608 /*
609 * Show the logo and lookup the command and deal with fShowHelp = true.
610 */
611 if (fShowLogo)
612 showLogo(g_pStdOut);
613
614#ifndef VBOX_ONLY_DOCS
615 PCVBMGCMD pCmd = lookupCommand(argv[iCmd]);
616 if (pCmd && pCmd->enmCmdHelp != VBMG_CMD_TODO)
617 setCurrentCommand(pCmd->enmCmdHelp);
618
619 if ( pCmd
620 && ( fShowHelp
621 || ( argc - iCmdArg == 0
622 && pCmd->enmHelpCat != 0)))
623 {
624 if (pCmd->enmCmdHelp == VBMG_CMD_TODO)
625 printUsage(pCmd->enmHelpCat, ~0U, g_pStdOut);
626 else if (fShowHelp)
627 printHelp(g_pStdOut);
628 else
629 printUsage(g_pStdOut);
630 return RTEXITCODE_FAILURE; /* error */
631 }
632 if (!pCmd)
633 {
634 if (!strcmp(argv[iCmd], "commands"))
635 {
636 RTPrintf("commands:\n");
637 for (unsigned i = 0; i < RT_ELEMENTS(g_aCommands); i++)
638 if ( i == 0 /* skip backwards compatibility entries */
639 || g_aCommands[i].enmHelpCat != g_aCommands[i - 1].enmHelpCat)
640 RTPrintf(" %s\n", g_aCommands[i].pszCommand);
641 return RTEXITCODE_SUCCESS;
642 }
643 return errorSyntax(USAGE_ALL, "Invalid command '%s'", argv[iCmd]);
644 }
645
646 RTEXITCODE rcExit;
647 if (!(pCmd->fFlags & VBMG_CMD_F_NO_COM))
648 {
649 /*
650 * Initialize COM.
651 */
652 using namespace com;
653 HRESULT hrc = com::Initialize();
654 if (FAILED(hrc))
655 {
656# ifdef VBOX_WITH_XPCOM
657 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
658 {
659 char szHome[RTPATH_MAX] = "";
660 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
661 return RTMsgErrorExit(RTEXITCODE_FAILURE,
662 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
663 }
664# endif
665 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM! (hrc=%Rhrc)", hrc);
666 }
667
668
669 /*
670 * Get the remote VirtualBox object and create a local session object.
671 */
672 rcExit = RTEXITCODE_FAILURE;
673 ComPtr<IVirtualBoxClient> virtualBoxClient;
674 ComPtr<IVirtualBox> virtualBox;
675 hrc = virtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
676 if (SUCCEEDED(hrc))
677 hrc = virtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
678 if (SUCCEEDED(hrc))
679 {
680 ComPtr<ISession> session;
681 hrc = session.createInprocObject(CLSID_Session);
682 if (SUCCEEDED(hrc))
683 {
684 /* Session secret. */
685 if (pszSettingsPw)
686 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(Bstr(pszSettingsPw).raw()), rcExit = RTEXITCODE_FAILURE);
687 else if (pszSettingsPwFile)
688 rcExit = settingsPasswordFile(virtualBox, pszSettingsPwFile);
689 else
690 rcExit = RTEXITCODE_SUCCESS;
691 if (rcExit == RTEXITCODE_SUCCESS)
692 {
693 /*
694 * Call the handler.
695 */
696 HandlerArg handlerArg = { argc - iCmdArg, &argv[iCmdArg], virtualBox, session };
697 rcExit = pCmd->pfnHandler(&handlerArg);
698
699 /* Although all handlers should always close the session if they open it,
700 * we do it here just in case if some of the handlers contains a bug --
701 * leaving the direct session not closed will turn the machine state to
702 * Aborted which may have unwanted side effects like killing the saved
703 * state file (if the machine was in the Saved state before). */
704 session->UnlockMachine();
705 }
706
707 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
708 }
709 else
710 {
711 com::ErrorInfo info;
712 RTMsgError("Failed to create a session object!");
713 if (!info.isFullAvailable() && !info.isBasicAvailable())
714 com::GluePrintRCMessage(hrc);
715 else
716 com::GluePrintErrorInfo(info);
717 }
718 }
719 else
720 {
721 com::ErrorInfo info;
722 RTMsgError("Failed to create the VirtualBox object!");
723 if (!info.isFullAvailable() && !info.isBasicAvailable())
724 {
725 com::GluePrintRCMessage(hrc);
726 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
727 }
728 else
729 com::GluePrintErrorInfo(info);
730 }
731
732 /*
733 * Terminate COM, make sure the virtualBox object has been released.
734 */
735 virtualBox.setNull();
736 virtualBoxClient.setNull();
737 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
738 com::Shutdown();
739 }
740 else
741 {
742 /*
743 * The command needs no COM.
744 */
745 HandlerArg handlerArg;
746 handlerArg.argc = argc - iCmdArg;
747 handlerArg.argv = &argv[iCmdArg];
748 rcExit = pCmd->pfnHandler(&handlerArg);
749 }
750
751 if (papszResponseFileArgs)
752 {
753 RTGetOptArgvFree(papszResponseFileArgs);
754 RTMemFree(papszNewArgv);
755 }
756
757 return rcExit;
758#else /* VBOX_ONLY_DOCS */
759 return RTEXITCODE_SUCCESS;
760#endif /* VBOX_ONLY_DOCS */
761}
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