VirtualBox

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

Last change on this file since 91999 was 91617, checked in by vboxsync, 3 years ago

doc/manual,FE/VBoxManage: Document the modifynvram sub-command of VBoxManage, bugref:9580

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