VirtualBox

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

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

VBoxManage: A quick command handler return-code cleanup that turned out to be rather tedious.

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