VirtualBox

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

Last change on this file since 56349 was 56349, checked in by vboxsync, 10 years ago

VBoxManage: Let main() set the current command and made 'VBoxManage help extpack' work.

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette