VirtualBox

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

Last change on this file since 78294 was 78126, checked in by vboxsync, 6 years ago

VBoxManage: showProgress - assert that progress is not null.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 29.4 KB
Line 
1/* $Id: VBoxManage.cpp 78126 2019-04-15 16:46:46Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2019 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_LIST, VBMG_CMD_TODO, handleList, 0 },
102 { "showvminfo", USAGE_SHOWVMINFO, VBMG_CMD_TODO, handleShowVMInfo, 0 },
103 { "registervm", USAGE_REGISTERVM, VBMG_CMD_TODO, handleRegisterVM, 0 },
104 { "unregistervm", USAGE_UNREGISTERVM, VBMG_CMD_TODO, handleUnregisterVM, 0 },
105 { "clonevm", USAGE_S_NEWCMD, HELP_CMD_CLONEVM, handleCloneVM, 0 },
106 { "movevm", USAGE_MOVEVM, VBMG_CMD_TODO, 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_CREATEVM, VBMG_CMD_TODO, handleCreateVM, 0 },
121 { "modifyvm", USAGE_MODIFYVM, VBMG_CMD_TODO, 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_SHAREDFOLDER, VBMG_CMD_TODO, 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_IMPORTAPPLIANCE, VBMG_CMD_TODO, handleImportAppliance, 0 },
148 { "export", USAGE_EXPORTAPPLIANCE, VBMG_CMD_TODO, handleExportAppliance, 0 },
149#ifdef VBOX_WITH_NETFLT
150 { "hostonlyif", USAGE_HOSTONLYIFS, VBMG_CMD_TODO, handleHostonlyIf, 0 },
151#endif
152 { "dhcpserver", USAGE_DHCPSERVER, VBMG_CMD_TODO, handleDHCPServer, 0 },
153#ifdef VBOX_WITH_NAT_SERVICE
154 { "natnetwork", USAGE_NATNETWORK, VBMG_CMD_TODO, handleNATNetwork, 0 },
155#endif
156 { "extpack", USAGE_S_NEWCMD, HELP_CMD_EXTPACK, handleExtPack, 0 },
157 { "bandwidthctl", USAGE_BANDWIDTHCONTROL, VBMG_CMD_TODO, handleBandwidthControl, 0 },
158 { "debugvm", USAGE_S_NEWCMD, HELP_CMD_DEBUGVM, handleDebugVM, 0 },
159 { "convertfromraw", USAGE_CONVERTFROMRAW, VBMG_CMD_TODO, handleConvertFromRaw, VBMG_CMD_F_NO_COM },
160 { "convertdd", USAGE_CONVERTFROMRAW, VBMG_CMD_TODO, handleConvertFromRaw, VBMG_CMD_F_NO_COM },
161 { "usbdevsource", USAGE_USBDEVSOURCE, VBMG_CMD_TODO, handleUSBDevSource, 0 },
162 { "cloudprofile", USAGE_S_NEWCMD, HELP_CMD_CLOUDPROFILE, handleCloudProfile, 0 },
163 { "cloud", USAGE_S_NEWCMD, VBMG_CMD_TODO, handleCloud, 0 }
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 AssertReturn(progress.isNotNull(), E_FAIL);
207
208 BOOL fCompleted = FALSE;
209 ULONG ulCurrentPercent = 0;
210 ULONG ulLastPercent = 0;
211
212 ULONG ulLastOperationPercent = (ULONG)-1;
213
214 ULONG ulLastOperation = (ULONG)-1;
215 Bstr bstrOperationDescription;
216
217 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
218
219 ULONG cOperations = 1;
220 HRESULT hrc = progress->COMGETTER(OperationCount)(&cOperations);
221 if (FAILED(hrc))
222 {
223 RTStrmPrintf(g_pStdErr, "Progress object failure: %Rhrc\n", hrc);
224 RTStrmFlush(g_pStdErr);
225 return hrc;
226 }
227
228 /*
229 * Note: Outputting the progress info to stderr (g_pStdErr) is intentional
230 * to not get intermixed with other (raw) stdout data which might get
231 * written in the meanwhile.
232 */
233
234 if (!g_fDetailedProgress)
235 {
236 RTStrmPrintf(g_pStdErr, "0%%...");
237 RTStrmFlush(g_pStdErr);
238 }
239
240 /* setup signal handling if cancelable */
241 bool fCanceledAlready = false;
242 BOOL fCancelable;
243 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
244 if (FAILED(hrc))
245 fCancelable = FALSE;
246 if (fCancelable)
247 {
248 signal(SIGINT, showProgressSignalHandler);
249 signal(SIGTERM, showProgressSignalHandler);
250#ifdef SIGBREAK
251 signal(SIGBREAK, showProgressSignalHandler);
252#endif
253 }
254
255 hrc = progress->COMGETTER(Completed(&fCompleted));
256 while (SUCCEEDED(hrc))
257 {
258 progress->COMGETTER(Percent(&ulCurrentPercent));
259
260 if (g_fDetailedProgress)
261 {
262 ULONG ulOperation = 1;
263 hrc = progress->COMGETTER(Operation)(&ulOperation);
264 if (FAILED(hrc))
265 break;
266 ULONG ulCurrentOperationPercent = 0;
267 hrc = progress->COMGETTER(OperationPercent(&ulCurrentOperationPercent));
268 if (FAILED(hrc))
269 break;
270
271 if (ulLastOperation != ulOperation)
272 {
273 hrc = progress->COMGETTER(OperationDescription(bstrOperationDescription.asOutParam()));
274 if (FAILED(hrc))
275 break;
276 ulLastPercent = (ULONG)-1; // force print
277 ulLastOperation = ulOperation;
278 }
279
280 if ( ulCurrentPercent != ulLastPercent
281 || ulCurrentOperationPercent != ulLastOperationPercent
282 )
283 {
284 LONG lSecsRem = 0;
285 progress->COMGETTER(TimeRemaining)(&lSecsRem);
286
287 RTStrmPrintf(g_pStdErr, "(%u/%u) %ls %02u%% => %02u%% (%d s remaining)\n", ulOperation + 1, cOperations,
288 bstrOperationDescription.raw(), ulCurrentOperationPercent, ulCurrentPercent, lSecsRem);
289 ulLastPercent = ulCurrentPercent;
290 ulLastOperationPercent = ulCurrentOperationPercent;
291 }
292 }
293 else
294 {
295 /* did we cross a 10% mark? */
296 if (ulCurrentPercent / 10 > ulLastPercent / 10)
297 {
298 /* make sure to also print out missed steps */
299 for (ULONG curVal = (ulLastPercent / 10) * 10 + 10; curVal <= (ulCurrentPercent / 10) * 10; curVal += 10)
300 {
301 if (curVal < 100)
302 {
303 RTStrmPrintf(g_pStdErr, "%u%%...", curVal);
304 RTStrmFlush(g_pStdErr);
305 }
306 }
307 ulLastPercent = (ulCurrentPercent / 10) * 10;
308 }
309 }
310 if (fCompleted)
311 break;
312
313 /* process async cancelation */
314 if (g_fCanceled && !fCanceledAlready)
315 {
316 hrc = progress->Cancel();
317 if (SUCCEEDED(hrc))
318 fCanceledAlready = true;
319 else
320 g_fCanceled = false;
321 }
322
323 /* make sure the loop is not too tight */
324 progress->WaitForCompletion(100);
325
326 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
327 hrc = progress->COMGETTER(Completed(&fCompleted));
328 }
329
330 /* undo signal handling */
331 if (fCancelable)
332 {
333 signal(SIGINT, SIG_DFL);
334 signal(SIGTERM, SIG_DFL);
335# ifdef SIGBREAK
336 signal(SIGBREAK, SIG_DFL);
337# endif
338 }
339
340 /* complete the line. */
341 LONG iRc = E_FAIL;
342 hrc = progress->COMGETTER(ResultCode)(&iRc);
343 if (SUCCEEDED(hrc))
344 {
345 if (SUCCEEDED(iRc))
346 RTStrmPrintf(g_pStdErr, "100%%\n");
347 else if (g_fCanceled)
348 RTStrmPrintf(g_pStdErr, "CANCELED\n");
349 else
350 {
351 if (!g_fDetailedProgress)
352 RTStrmPrintf(g_pStdErr, "\n");
353 RTStrmPrintf(g_pStdErr, "Progress state: %Rhrc\n", iRc);
354 }
355 hrc = iRc;
356 }
357 else
358 {
359 if (!g_fDetailedProgress)
360 RTStrmPrintf(g_pStdErr, "\n");
361 RTStrmPrintf(g_pStdErr, "Progress object failure: %Rhrc\n", hrc);
362 }
363 RTStrmFlush(g_pStdErr);
364 return hrc;
365}
366
367RTEXITCODE readPasswordFile(const char *pszFilename, com::Utf8Str *pPasswd)
368{
369 size_t cbFile;
370 char szPasswd[512];
371 int vrc = VINF_SUCCESS;
372 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
373 bool fStdIn = !strcmp(pszFilename, "stdin");
374 PRTSTREAM pStrm;
375 if (!fStdIn)
376 vrc = RTStrmOpen(pszFilename, "r", &pStrm);
377 else
378 pStrm = g_pStdIn;
379 if (RT_SUCCESS(vrc))
380 {
381 vrc = RTStrmReadEx(pStrm, szPasswd, sizeof(szPasswd)-1, &cbFile);
382 if (RT_SUCCESS(vrc))
383 {
384 if (cbFile >= sizeof(szPasswd)-1)
385 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Provided password in file '%s' is too long", pszFilename);
386 else
387 {
388 unsigned i;
389 for (i = 0; i < cbFile && !RT_C_IS_CNTRL(szPasswd[i]); i++)
390 ;
391 szPasswd[i] = '\0';
392 *pPasswd = szPasswd;
393 }
394 }
395 else
396 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot read password from file '%s': %Rrc", pszFilename, vrc);
397 if (!fStdIn)
398 RTStrmClose(pStrm);
399 }
400 else
401 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Cannot open password file '%s' (%Rrc)", pszFilename, vrc);
402
403 return rcExit;
404}
405
406static RTEXITCODE settingsPasswordFile(ComPtr<IVirtualBox> virtualBox, const char *pszFilename)
407{
408 com::Utf8Str passwd;
409 RTEXITCODE rcExit = readPasswordFile(pszFilename, &passwd);
410 if (rcExit == RTEXITCODE_SUCCESS)
411 {
412 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(com::Bstr(passwd).raw()), rcExit = RTEXITCODE_FAILURE);
413 }
414
415 return rcExit;
416}
417
418RTEXITCODE readPasswordFromConsole(com::Utf8Str *pPassword, const char *pszPrompt, ...)
419{
420 RTEXITCODE rcExit = RTEXITCODE_SUCCESS;
421 char aszPwdInput[_1K] = { 0 };
422 va_list vaArgs;
423
424 va_start(vaArgs, pszPrompt);
425 int vrc = RTStrmPrintfV(g_pStdOut, pszPrompt, vaArgs);
426 if (RT_SUCCESS(vrc))
427 {
428 bool fEchoOld = false;
429 vrc = RTStrmInputGetEchoChars(g_pStdIn, &fEchoOld);
430 if (RT_SUCCESS(vrc))
431 {
432 vrc = RTStrmInputSetEchoChars(g_pStdIn, false);
433 if (RT_SUCCESS(vrc))
434 {
435 vrc = RTStrmGetLine(g_pStdIn, &aszPwdInput[0], sizeof(aszPwdInput));
436 if (RT_SUCCESS(vrc))
437 *pPassword = aszPwdInput;
438 else
439 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed read password from command line (%Rrc)", vrc);
440
441 int vrc2 = RTStrmInputSetEchoChars(g_pStdIn, fEchoOld);
442 AssertRC(vrc2);
443 }
444 else
445 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to disable echoing typed characters (%Rrc)", vrc);
446 }
447 else
448 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to retrieve echo setting (%Rrc)", vrc);
449
450 RTStrmPutStr(g_pStdOut, "\n");
451 }
452 else
453 rcExit = RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to print prompt (%Rrc)", vrc);
454 va_end(vaArgs);
455
456 return rcExit;
457}
458
459#endif /* !VBOX_ONLY_DOCS */
460
461
462int main(int argc, char *argv[])
463{
464 /*
465 * Before we do anything, init the runtime without loading
466 * the support driver.
467 */
468 int vrc = RTR3InitExe(argc, &argv, 0);
469 if (RT_FAILURE(vrc))
470 return RTMsgInitFailure(vrc);
471#if defined(RT_OS_WINDOWS) && !defined(VBOX_ONLY_DOCS)
472 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
473#endif
474
475 /*
476 * Parse the global options
477 */
478 bool fShowLogo = false;
479 bool fShowHelp = false;
480 int iCmd = 1;
481 int iCmdArg;
482 const char *pszSettingsPw = NULL;
483 const char *pszSettingsPwFile = NULL;
484#ifndef VBOX_ONLY_DOCS
485 int cResponseFileArgs = 0;
486 char **papszResponseFileArgs = NULL;
487 char **papszNewArgv = NULL;
488#endif
489
490 for (int i = 1; i < argc || argc <= iCmd; i++)
491 {
492 if ( argc <= iCmd
493 || !strcmp(argv[i], "help")
494 || !strcmp(argv[i], "--help")
495 || !strcmp(argv[i], "-?")
496 || !strcmp(argv[i], "-h")
497 || !strcmp(argv[i], "-help"))
498 {
499 if (i >= argc - 1)
500 {
501 showLogo(g_pStdOut);
502 printUsage(USAGE_S_ALL, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
503 return 0;
504 }
505 fShowLogo = true;
506 fShowHelp = true;
507 iCmd++;
508 continue;
509 }
510
511#ifndef VBOX_ONLY_DOCS
512 if ( !strcmp(argv[i], "-V")
513 || !strcmp(argv[i], "--version")
514 || !strcmp(argv[i], "-v") /* deprecated */
515 || !strcmp(argv[i], "-version") /* deprecated */
516 || !strcmp(argv[i], "-Version") /* deprecated */)
517 {
518 /* Print version number, and do nothing else. */
519 RTPrintf("%sr%u\n", VBOX_VERSION_STRING, RTBldCfgRevision());
520 return 0;
521 }
522#endif
523
524 if ( !strcmp(argv[i], "--dumpopts")
525 || !strcmp(argv[i], "-dumpopts") /* deprecated */)
526 {
527 /* Special option to dump really all commands,
528 * even the ones not understood on this platform. */
529 printUsage(USAGE_S_DUMPOPTS, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
530 return 0;
531 }
532
533 if ( !strcmp(argv[i], "--nologo")
534 || !strcmp(argv[i], "-q")
535 || !strcmp(argv[i], "-nologo") /* deprecated */)
536 {
537 /* suppress the logo */
538 fShowLogo = false;
539 iCmd++;
540 }
541 else if ( !strcmp(argv[i], "--detailed-progress")
542 || !strcmp(argv[i], "-d"))
543 {
544 /* detailed progress report */
545 g_fDetailedProgress = true;
546 iCmd++;
547 }
548 else if (!strcmp(argv[i], "--settingspw"))
549 {
550 if (i >= argc - 1)
551 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Password expected");
552 /* password for certain settings */
553 pszSettingsPw = argv[i + 1];
554 iCmd += 2;
555 }
556 else if (!strcmp(argv[i], "--settingspwfile"))
557 {
558 if (i >= argc-1)
559 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No password file specified");
560 pszSettingsPwFile = argv[i+1];
561 iCmd += 2;
562 }
563#ifndef VBOX_ONLY_DOCS
564 else if (argv[i][0] == '@')
565 {
566 if (papszResponseFileArgs)
567 return RTMsgErrorExitFailure("Only one response file allowed");
568
569 /* Load response file, making sure it's valid UTF-8. */
570 char *pszResponseFile;
571 size_t cbResponseFile;
572 vrc = RTFileReadAllEx(&argv[i][1], 0, RTFOFF_MAX, RTFILE_RDALL_O_DENY_NONE | RTFILE_RDALL_F_TRAILING_ZERO_BYTE,
573 (void **)&pszResponseFile, &cbResponseFile);
574 if (RT_FAILURE(vrc))
575 return RTMsgErrorExitFailure("Error reading response file '%s': %Rrc", &argv[i][1], vrc);
576 vrc = RTStrValidateEncoding(pszResponseFile);
577 if (RT_FAILURE(vrc))
578 {
579 RTFileReadAllFree(pszResponseFile, cbResponseFile);
580 return RTMsgErrorExitFailure("Invalid response file ('%s') encoding: %Rrc", &argv[i][1], vrc);
581 }
582
583 /* Parse it. */
584 vrc = RTGetOptArgvFromString(&papszResponseFileArgs, &cResponseFileArgs, pszResponseFile,
585 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
586 RTFileReadAllFree(pszResponseFile, cbResponseFile);
587 if (RT_FAILURE(vrc))
588 return RTMsgErrorExitFailure("Failed to parse response file '%s' (bourne shell style): %Rrc", &argv[i][1], vrc);
589
590 /* Construct new argv+argc with the response file arguments inserted. */
591 int cNewArgs = argc + cResponseFileArgs;
592 papszNewArgv = (char **)RTMemAllocZ((cNewArgs + 2) * sizeof(papszNewArgv[0]));
593 if (!papszNewArgv)
594 return RTMsgErrorExitFailure("out of memory");
595 memcpy(&papszNewArgv[0], &argv[0], sizeof(argv[0]) * (i + 1));
596 memcpy(&papszNewArgv[i + 1], papszResponseFileArgs, sizeof(argv[0]) * cResponseFileArgs);
597 memcpy(&papszNewArgv[i + 1 + cResponseFileArgs], &argv[i + 1], sizeof(argv[0]) * (argc - i - 1 + 1));
598 argv = papszNewArgv;
599 argc = argc + cResponseFileArgs;
600
601 iCmd++;
602 }
603#endif
604 else
605 break;
606 }
607
608 iCmdArg = iCmd + 1;
609
610 /*
611 * Show the logo and lookup the command and deal with fShowHelp = true.
612 */
613 if (fShowLogo)
614 showLogo(g_pStdOut);
615
616#ifndef VBOX_ONLY_DOCS
617 PCVBMGCMD pCmd = lookupCommand(argv[iCmd]);
618 if (pCmd && pCmd->enmCmdHelp != VBMG_CMD_TODO)
619 setCurrentCommand(pCmd->enmCmdHelp);
620
621 if ( pCmd
622 && ( fShowHelp
623 || ( argc - iCmdArg == 0
624 && pCmd->enmHelpCat != USAGE_INVALID)))
625 {
626 if (pCmd->enmCmdHelp == VBMG_CMD_TODO)
627 printUsage(pCmd->enmHelpCat, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
628 else if (fShowHelp)
629 printHelp(g_pStdOut);
630 else
631 printUsage(g_pStdOut);
632 return RTEXITCODE_FAILURE; /* error */
633 }
634 if (!pCmd)
635 {
636 if (!strcmp(argv[iCmd], "commands"))
637 {
638 RTPrintf("commands:\n");
639 for (unsigned i = 0; i < RT_ELEMENTS(g_aCommands); i++)
640 if ( i == 0 /* skip backwards compatibility entries */
641 || (g_aCommands[i].enmHelpCat != USAGE_S_NEWCMD
642 ? g_aCommands[i].enmHelpCat != g_aCommands[i - 1].enmHelpCat
643 : g_aCommands[i].enmCmdHelp != g_aCommands[i - 1].enmCmdHelp))
644 RTPrintf(" %s\n", g_aCommands[i].pszCommand);
645 return RTEXITCODE_SUCCESS;
646 }
647 return errorSyntax(USAGE_S_ALL, "Invalid command '%s'", argv[iCmd]);
648 }
649
650 RTEXITCODE rcExit;
651 if (!(pCmd->fFlags & VBMG_CMD_F_NO_COM))
652 {
653 /*
654 * Initialize COM.
655 */
656 using namespace com;
657 HRESULT hrc = com::Initialize();
658 if (FAILED(hrc))
659 {
660# ifdef VBOX_WITH_XPCOM
661 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
662 {
663 char szHome[RTPATH_MAX] = "";
664 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
665 return RTMsgErrorExit(RTEXITCODE_FAILURE,
666 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
667 }
668# endif
669 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM! (hrc=%Rhrc)", hrc);
670 }
671
672
673 /*
674 * Get the remote VirtualBox object and create a local session object.
675 */
676 rcExit = RTEXITCODE_FAILURE;
677 ComPtr<IVirtualBoxClient> virtualBoxClient;
678 ComPtr<IVirtualBox> virtualBox;
679 hrc = virtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
680 if (SUCCEEDED(hrc))
681 hrc = virtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
682 if (SUCCEEDED(hrc))
683 {
684 ComPtr<ISession> session;
685 hrc = session.createInprocObject(CLSID_Session);
686 if (SUCCEEDED(hrc))
687 {
688 /* Session secret. */
689 if (pszSettingsPw)
690 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(Bstr(pszSettingsPw).raw()), rcExit = RTEXITCODE_FAILURE);
691 else if (pszSettingsPwFile)
692 rcExit = settingsPasswordFile(virtualBox, pszSettingsPwFile);
693 else
694 rcExit = RTEXITCODE_SUCCESS;
695 if (rcExit == RTEXITCODE_SUCCESS)
696 {
697 /*
698 * Call the handler.
699 */
700 HandlerArg handlerArg = { argc - iCmdArg, &argv[iCmdArg], virtualBox, session };
701 rcExit = pCmd->pfnHandler(&handlerArg);
702
703 /* Although all handlers should always close the session if they open it,
704 * we do it here just in case if some of the handlers contains a bug --
705 * leaving the direct session not closed will turn the machine state to
706 * Aborted which may have unwanted side effects like killing the saved
707 * state file (if the machine was in the Saved state before). */
708 session->UnlockMachine();
709 }
710
711 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
712 }
713 else
714 {
715 com::ErrorInfo info;
716 RTMsgError("Failed to create a session object!");
717 if (!info.isFullAvailable() && !info.isBasicAvailable())
718 com::GluePrintRCMessage(hrc);
719 else
720 com::GluePrintErrorInfo(info);
721 }
722 }
723 else
724 {
725 com::ErrorInfo info;
726 RTMsgError("Failed to create the VirtualBox object!");
727 if (!info.isFullAvailable() && !info.isBasicAvailable())
728 {
729 com::GluePrintRCMessage(hrc);
730 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
731 }
732 else
733 com::GluePrintErrorInfo(info);
734 }
735
736 /*
737 * Terminate COM, make sure the virtualBox object has been released.
738 */
739 virtualBox.setNull();
740 virtualBoxClient.setNull();
741 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
742 com::Shutdown();
743 }
744 else
745 {
746 /*
747 * The command needs no COM.
748 */
749 HandlerArg handlerArg;
750 handlerArg.argc = argc - iCmdArg;
751 handlerArg.argv = &argv[iCmdArg];
752 rcExit = pCmd->pfnHandler(&handlerArg);
753 }
754
755 if (papszResponseFileArgs)
756 {
757 RTGetOptArgvFree(papszResponseFileArgs);
758 RTMemFree(papszNewArgv);
759 }
760
761 return rcExit;
762#else /* VBOX_ONLY_DOCS */
763 return RTEXITCODE_SUCCESS;
764#endif /* VBOX_ONLY_DOCS */
765}
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