VirtualBox

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

Last change on this file since 81644 was 80569, checked in by vboxsync, 5 years ago

Main: bugref:9341: Added VM autostart during boot support for windows host

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 26.4 KB
Line 
1/* $Id: VBoxManage.cpp 80569 2019-09-03 14:34:21Z 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_S_NEWCMD, HELP_CMD_DHCPSERVER, 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
367#endif /* !VBOX_ONLY_DOCS */
368
369
370int main(int argc, char *argv[])
371{
372 /*
373 * Before we do anything, init the runtime without loading
374 * the support driver.
375 */
376 int vrc = RTR3InitExe(argc, &argv, 0);
377 if (RT_FAILURE(vrc))
378 return RTMsgInitFailure(vrc);
379#if defined(RT_OS_WINDOWS) && !defined(VBOX_ONLY_DOCS)
380 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
381#endif
382
383 /*
384 * Parse the global options
385 */
386 bool fShowLogo = false;
387 bool fShowHelp = false;
388 int iCmd = 1;
389 int iCmdArg;
390 const char *pszSettingsPw = NULL;
391 const char *pszSettingsPwFile = NULL;
392#ifndef VBOX_ONLY_DOCS
393 int cResponseFileArgs = 0;
394 char **papszResponseFileArgs = NULL;
395 char **papszNewArgv = NULL;
396#endif
397
398 for (int i = 1; i < argc || argc <= iCmd; i++)
399 {
400 if ( argc <= iCmd
401 || !strcmp(argv[i], "help")
402 || !strcmp(argv[i], "--help")
403 || !strcmp(argv[i], "-?")
404 || !strcmp(argv[i], "-h")
405 || !strcmp(argv[i], "-help"))
406 {
407 if (i >= argc - 1)
408 {
409 showLogo(g_pStdOut);
410 printUsage(USAGE_S_ALL, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
411 return 0;
412 }
413 fShowLogo = true;
414 fShowHelp = true;
415 iCmd++;
416 continue;
417 }
418
419#ifndef VBOX_ONLY_DOCS
420 if ( !strcmp(argv[i], "-V")
421 || !strcmp(argv[i], "--version")
422 || !strcmp(argv[i], "-v") /* deprecated */
423 || !strcmp(argv[i], "-version") /* deprecated */
424 || !strcmp(argv[i], "-Version") /* deprecated */)
425 {
426 /* Print version number, and do nothing else. */
427 RTPrintf("%sr%u\n", VBOX_VERSION_STRING, RTBldCfgRevision());
428 return 0;
429 }
430#endif
431
432 if ( !strcmp(argv[i], "--dumpopts")
433 || !strcmp(argv[i], "-dumpopts") /* deprecated */)
434 {
435 /* Special option to dump really all commands,
436 * even the ones not understood on this platform. */
437 printUsage(USAGE_S_DUMPOPTS, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
438 return 0;
439 }
440
441 if ( !strcmp(argv[i], "--nologo")
442 || !strcmp(argv[i], "-q")
443 || !strcmp(argv[i], "-nologo") /* deprecated */)
444 {
445 /* suppress the logo */
446 fShowLogo = false;
447 iCmd++;
448 }
449 else if ( !strcmp(argv[i], "--detailed-progress")
450 || !strcmp(argv[i], "-d"))
451 {
452 /* detailed progress report */
453 g_fDetailedProgress = true;
454 iCmd++;
455 }
456 else if (!strcmp(argv[i], "--settingspw"))
457 {
458 if (i >= argc - 1)
459 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Password expected");
460 /* password for certain settings */
461 pszSettingsPw = argv[i + 1];
462 iCmd += 2;
463 }
464 else if (!strcmp(argv[i], "--settingspwfile"))
465 {
466 if (i >= argc-1)
467 return RTMsgErrorExit(RTEXITCODE_FAILURE, "No password file specified");
468 pszSettingsPwFile = argv[i+1];
469 iCmd += 2;
470 }
471#ifndef VBOX_ONLY_DOCS
472 else if (argv[i][0] == '@')
473 {
474 if (papszResponseFileArgs)
475 return RTMsgErrorExitFailure("Only one response file allowed");
476
477 /* Load response file, making sure it's valid UTF-8. */
478 char *pszResponseFile;
479 size_t cbResponseFile;
480 vrc = RTFileReadAllEx(&argv[i][1], 0, RTFOFF_MAX, RTFILE_RDALL_O_DENY_NONE | RTFILE_RDALL_F_TRAILING_ZERO_BYTE,
481 (void **)&pszResponseFile, &cbResponseFile);
482 if (RT_FAILURE(vrc))
483 return RTMsgErrorExitFailure("Error reading response file '%s': %Rrc", &argv[i][1], vrc);
484 vrc = RTStrValidateEncoding(pszResponseFile);
485 if (RT_FAILURE(vrc))
486 {
487 RTFileReadAllFree(pszResponseFile, cbResponseFile);
488 return RTMsgErrorExitFailure("Invalid response file ('%s') encoding: %Rrc", &argv[i][1], vrc);
489 }
490
491 /* Parse it. */
492 vrc = RTGetOptArgvFromString(&papszResponseFileArgs, &cResponseFileArgs, pszResponseFile,
493 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
494 RTFileReadAllFree(pszResponseFile, cbResponseFile);
495 if (RT_FAILURE(vrc))
496 return RTMsgErrorExitFailure("Failed to parse response file '%s' (bourne shell style): %Rrc", &argv[i][1], vrc);
497
498 /* Construct new argv+argc with the response file arguments inserted. */
499 int cNewArgs = argc + cResponseFileArgs;
500 papszNewArgv = (char **)RTMemAllocZ((cNewArgs + 2) * sizeof(papszNewArgv[0]));
501 if (!papszNewArgv)
502 return RTMsgErrorExitFailure("out of memory");
503 memcpy(&papszNewArgv[0], &argv[0], sizeof(argv[0]) * (i + 1));
504 memcpy(&papszNewArgv[i + 1], papszResponseFileArgs, sizeof(argv[0]) * cResponseFileArgs);
505 memcpy(&papszNewArgv[i + 1 + cResponseFileArgs], &argv[i + 1], sizeof(argv[0]) * (argc - i - 1 + 1));
506 argv = papszNewArgv;
507 argc = argc + cResponseFileArgs;
508
509 iCmd++;
510 }
511#endif
512 else
513 break;
514 }
515
516 iCmdArg = iCmd + 1;
517
518 /*
519 * Show the logo and lookup the command and deal with fShowHelp = true.
520 */
521 if (fShowLogo)
522 showLogo(g_pStdOut);
523
524#ifndef VBOX_ONLY_DOCS
525 PCVBMGCMD pCmd = lookupCommand(argv[iCmd]);
526 if (pCmd && pCmd->enmCmdHelp != VBMG_CMD_TODO)
527 setCurrentCommand(pCmd->enmCmdHelp);
528
529 if ( pCmd
530 && ( fShowHelp
531 || ( argc - iCmdArg == 0
532 && pCmd->enmHelpCat != USAGE_INVALID)))
533 {
534 if (pCmd->enmCmdHelp == VBMG_CMD_TODO)
535 printUsage(pCmd->enmHelpCat, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
536 else if (fShowHelp)
537 printHelp(g_pStdOut);
538 else
539 printUsage(g_pStdOut);
540 return RTEXITCODE_FAILURE; /* error */
541 }
542 if (!pCmd)
543 {
544 if (!strcmp(argv[iCmd], "commands"))
545 {
546 RTPrintf("commands:\n");
547 for (unsigned i = 0; i < RT_ELEMENTS(g_aCommands); i++)
548 if ( i == 0 /* skip backwards compatibility entries */
549 || (g_aCommands[i].enmHelpCat != USAGE_S_NEWCMD
550 ? g_aCommands[i].enmHelpCat != g_aCommands[i - 1].enmHelpCat
551 : g_aCommands[i].enmCmdHelp != g_aCommands[i - 1].enmCmdHelp))
552 RTPrintf(" %s\n", g_aCommands[i].pszCommand);
553 return RTEXITCODE_SUCCESS;
554 }
555 return errorSyntax(USAGE_S_ALL, "Invalid command '%s'", argv[iCmd]);
556 }
557
558 RTEXITCODE rcExit;
559 if (!(pCmd->fFlags & VBMG_CMD_F_NO_COM))
560 {
561 /*
562 * Initialize COM.
563 */
564 using namespace com;
565 HRESULT hrc = com::Initialize();
566 if (FAILED(hrc))
567 {
568# ifdef VBOX_WITH_XPCOM
569 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
570 {
571 char szHome[RTPATH_MAX] = "";
572 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
573 return RTMsgErrorExit(RTEXITCODE_FAILURE,
574 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
575 }
576# endif
577 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM! (hrc=%Rhrc)", hrc);
578 }
579
580
581 /*
582 * Get the remote VirtualBox object and create a local session object.
583 */
584 rcExit = RTEXITCODE_FAILURE;
585 ComPtr<IVirtualBoxClient> virtualBoxClient;
586 ComPtr<IVirtualBox> virtualBox;
587 hrc = virtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
588 if (SUCCEEDED(hrc))
589 hrc = virtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
590 if (SUCCEEDED(hrc))
591 {
592 ComPtr<ISession> session;
593 hrc = session.createInprocObject(CLSID_Session);
594 if (SUCCEEDED(hrc))
595 {
596 /* Session secret. */
597 if (pszSettingsPw)
598 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(Bstr(pszSettingsPw).raw()), rcExit = RTEXITCODE_FAILURE);
599 else if (pszSettingsPwFile)
600 rcExit = settingsPasswordFile(virtualBox, pszSettingsPwFile);
601 else
602 rcExit = RTEXITCODE_SUCCESS;
603 if (rcExit == RTEXITCODE_SUCCESS)
604 {
605 /*
606 * Call the handler.
607 */
608 HandlerArg handlerArg = { argc - iCmdArg, &argv[iCmdArg], virtualBox, session };
609 rcExit = pCmd->pfnHandler(&handlerArg);
610
611 /* Although all handlers should always close the session if they open it,
612 * we do it here just in case if some of the handlers contains a bug --
613 * leaving the direct session not closed will turn the machine state to
614 * Aborted which may have unwanted side effects like killing the saved
615 * state file (if the machine was in the Saved state before). */
616 session->UnlockMachine();
617 }
618
619 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
620 }
621 else
622 {
623 com::ErrorInfo info;
624 RTMsgError("Failed to create a session object!");
625 if (!info.isFullAvailable() && !info.isBasicAvailable())
626 com::GluePrintRCMessage(hrc);
627 else
628 com::GluePrintErrorInfo(info);
629 }
630 }
631 else
632 {
633 com::ErrorInfo info;
634 RTMsgError("Failed to create the VirtualBox object!");
635 if (!info.isFullAvailable() && !info.isBasicAvailable())
636 {
637 com::GluePrintRCMessage(hrc);
638 RTMsgError("Most likely, the VirtualBox COM server is not running or failed to start.");
639 }
640 else
641 com::GluePrintErrorInfo(info);
642 }
643
644 /*
645 * Terminate COM, make sure the virtualBox object has been released.
646 */
647 virtualBox.setNull();
648 virtualBoxClient.setNull();
649 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
650 com::Shutdown();
651 }
652 else
653 {
654 /*
655 * The command needs no COM.
656 */
657 HandlerArg handlerArg;
658 handlerArg.argc = argc - iCmdArg;
659 handlerArg.argv = &argv[iCmdArg];
660 rcExit = pCmd->pfnHandler(&handlerArg);
661 }
662
663 if (papszResponseFileArgs)
664 {
665 RTGetOptArgvFree(papszResponseFileArgs);
666 RTMemFree(papszNewArgv);
667 }
668
669 return rcExit;
670#else /* VBOX_ONLY_DOCS */
671 return RTEXITCODE_SUCCESS;
672#endif /* VBOX_ONLY_DOCS */
673}
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