VirtualBox

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

Last change on this file since 77910 was 77887, checked in by vboxsync, 5 years ago

manual/VBoxManage: Made the new clonevm build. Again, there must be '=' between an option name and its value. The help-scope in the example section is not needed for commands without sub-commands. Use 'vmname|uuid' rather than just 'vm' as it's easier to grasp when just seeing the command synopsis.

  • 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 77887 2019-03-26 16:41:15Z 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 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_S_ALL, RTMSGREFENTRYSTR_SCOPE_GLOBAL, 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_S_DUMPOPTS, RTMSGREFENTRYSTR_SCOPE_GLOBAL, 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 != USAGE_INVALID)))
623 {
624 if (pCmd->enmCmdHelp == VBMG_CMD_TODO)
625 printUsage(pCmd->enmHelpCat, RTMSGREFENTRYSTR_SCOPE_GLOBAL, 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 != USAGE_S_NEWCMD
640 ? g_aCommands[i].enmHelpCat != g_aCommands[i - 1].enmHelpCat
641 : g_aCommands[i].enmCmdHelp != g_aCommands[i - 1].enmCmdHelp))
642 RTPrintf(" %s\n", g_aCommands[i].pszCommand);
643 return RTEXITCODE_SUCCESS;
644 }
645 return errorSyntax(USAGE_S_ALL, "Invalid command '%s'", argv[iCmd]);
646 }
647
648 RTEXITCODE rcExit;
649 if (!(pCmd->fFlags & VBMG_CMD_F_NO_COM))
650 {
651 /*
652 * Initialize COM.
653 */
654 using namespace com;
655 HRESULT hrc = com::Initialize();
656 if (FAILED(hrc))
657 {
658# ifdef VBOX_WITH_XPCOM
659 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
660 {
661 char szHome[RTPATH_MAX] = "";
662 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
663 return RTMsgErrorExit(RTEXITCODE_FAILURE,
664 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
665 }
666# endif
667 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM! (hrc=%Rhrc)", hrc);
668 }
669
670
671 /*
672 * Get the remote VirtualBox object and create a local session object.
673 */
674 rcExit = RTEXITCODE_FAILURE;
675 ComPtr<IVirtualBoxClient> virtualBoxClient;
676 ComPtr<IVirtualBox> virtualBox;
677 hrc = virtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
678 if (SUCCEEDED(hrc))
679 hrc = virtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
680 if (SUCCEEDED(hrc))
681 {
682 ComPtr<ISession> session;
683 hrc = session.createInprocObject(CLSID_Session);
684 if (SUCCEEDED(hrc))
685 {
686 /* Session secret. */
687 if (pszSettingsPw)
688 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(Bstr(pszSettingsPw).raw()), rcExit = RTEXITCODE_FAILURE);
689 else if (pszSettingsPwFile)
690 rcExit = settingsPasswordFile(virtualBox, pszSettingsPwFile);
691 else
692 rcExit = RTEXITCODE_SUCCESS;
693 if (rcExit == RTEXITCODE_SUCCESS)
694 {
695 /*
696 * Call the handler.
697 */
698 HandlerArg handlerArg = { argc - iCmdArg, &argv[iCmdArg], virtualBox, session };
699 rcExit = pCmd->pfnHandler(&handlerArg);
700
701 /* Although all handlers should always close the session if they open it,
702 * we do it here just in case if some of the handlers contains a bug --
703 * leaving the direct session not closed will turn the machine state to
704 * Aborted which may have unwanted side effects like killing the saved
705 * state file (if the machine was in the Saved state before). */
706 session->UnlockMachine();
707 }
708
709 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
710 }
711 else
712 {
713 com::ErrorInfo info;
714 RTMsgError("Failed to create a session object!");
715 if (!info.isFullAvailable() && !info.isBasicAvailable())
716 com::GluePrintRCMessage(hrc);
717 else
718 com::GluePrintErrorInfo(info);
719 }
720 }
721 else
722 {
723 com::ErrorInfo info;
724 RTMsgError("Failed to create the VirtualBox object!");
725 if (!info.isFullAvailable() && !info.isBasicAvailable())
726 {
727 com::GluePrintRCMessage(hrc);
728 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
729 }
730 else
731 com::GluePrintErrorInfo(info);
732 }
733
734 /*
735 * Terminate COM, make sure the virtualBox object has been released.
736 */
737 virtualBox.setNull();
738 virtualBoxClient.setNull();
739 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
740 com::Shutdown();
741 }
742 else
743 {
744 /*
745 * The command needs no COM.
746 */
747 HandlerArg handlerArg;
748 handlerArg.argc = argc - iCmdArg;
749 handlerArg.argv = &argv[iCmdArg];
750 rcExit = pCmd->pfnHandler(&handlerArg);
751 }
752
753 if (papszResponseFileArgs)
754 {
755 RTGetOptArgvFree(papszResponseFileArgs);
756 RTMemFree(papszNewArgv);
757 }
758
759 return rcExit;
760#else /* VBOX_ONLY_DOCS */
761 return RTEXITCODE_SUCCESS;
762#endif /* VBOX_ONLY_DOCS */
763}
Note: See TracBrowser for help on using the repository browser.

© 2023 Oracle
ContactPrivacy policyTerms of Use