VirtualBox

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

Last change on this file since 92888 was 92842, checked in by vboxsync, 3 years ago

Main: bugref:1909: Fixed type conversion for atomic variable

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.7 KB
Line 
1/* $Id: VBoxManage.cpp 92842 2021-12-09 09:51:57Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2020 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#ifdef VBOX_WITH_VBOXMANAGE_NLS
35# include <VBox/com/AutoLock.h>
36# include <VBox/com/listeners.h>
37#endif
38
39#include <VBox/version.h>
40
41#include <iprt/asm.h>
42#include <iprt/buildconfig.h>
43#include <iprt/ctype.h>
44#include <iprt/file.h>
45#include <iprt/getopt.h>
46#include <iprt/initterm.h>
47#include <iprt/log.h>
48#include <iprt/path.h>
49#include <iprt/stream.h>
50#include <iprt/string.h>
51
52#include <signal.h>
53
54#include "VBoxManage.h"
55
56
57/*********************************************************************************************************************************
58* Defined Constants And Macros *
59*********************************************************************************************************************************/
60
61/** The command doesn't need the COM stuff. */
62#define VBMG_CMD_F_NO_COM RT_BIT_32(0)
63
64#define VBMG_CMD_TODO HELP_CMD_VBOXMANAGE_INVALID
65
66
67/*********************************************************************************************************************************
68* Structures and Typedefs *
69*********************************************************************************************************************************/
70#ifndef VBOX_ONLY_DOCS
71/**
72 * VBoxManage command descriptor.
73 */
74typedef struct VBMGCMD
75{
76 /** The command. */
77 const char *pszCommand;
78 /** The help category. */
79 USAGECATEGORY enmHelpCat;
80 /** The new help command. */
81 enum HELP_CMD_VBOXMANAGE enmCmdHelp;
82 /** The handler. */
83 RTEXITCODE (*pfnHandler)(HandlerArg *pArg);
84 /** VBMG_CMD_F_XXX, */
85 uint32_t fFlags;
86} VBMGCMD;
87/** Pointer to a const VBoxManage command descriptor. */
88typedef VBMGCMD const *PCVBMGCMD;
89#endif
90
91DECLARE_TRANSLATION_CONTEXT(VBoxManage);
92
93void setBuiltInHelpLanguage(const char *pszLang);
94
95#ifdef VBOX_WITH_VBOXMANAGE_NLS
96/* listener class for language updates */
97class VBoxEventListener
98{
99public:
100 VBoxEventListener()
101 {}
102
103
104 HRESULT init(void *)
105 {
106 return S_OK;
107 }
108
109 HRESULT init()
110 {
111 return S_OK;
112 }
113
114 void uninit()
115 {
116 }
117
118 virtual ~VBoxEventListener()
119 {
120 }
121
122 STDMETHOD(HandleEvent)(VBoxEventType_T aType, IEvent *aEvent)
123 {
124 switch(aType)
125 {
126 case VBoxEventType_OnLanguageChanged:
127 {
128 /*
129 * Proceed with uttmost care as we might be racing com::Shutdown()
130 * and have the ground open up beneath us.
131 */
132 LogFunc(("VBoxEventType_OnLanguageChanged\n"));
133 VirtualBoxTranslator *pTranslator = VirtualBoxTranslator::tryInstance();
134 if (pTranslator)
135 {
136 ComPtr<ILanguageChangedEvent> pEvent = aEvent;
137 Assert(pEvent);
138
139 /* This call may fail if we're racing COM shutdown. */
140 com::Bstr bstrLanguageId;
141 HRESULT hrc = pEvent->COMGETTER(LanguageId)(bstrLanguageId.asOutParam());
142 if (SUCCEEDED(hrc))
143 {
144 try
145 {
146 com::Utf8Str strLanguageId(bstrLanguageId);
147 LogFunc(("New language ID: %s\n", strLanguageId.c_str()));
148 pTranslator->i_loadLanguage(strLanguageId.c_str());
149 setBuiltInHelpLanguage(strLanguageId.c_str());
150 }
151 catch (std::bad_alloc &)
152 {
153 LogFunc(("Caught bad_alloc"));
154 }
155 }
156 else
157 LogFunc(("Failed to get new language ID: %Rhrc\n", hrc));
158
159 pTranslator->release();
160 }
161 break;
162 }
163
164 default:
165 AssertFailed();
166 }
167
168 return S_OK;
169 }
170};
171
172typedef ListenerImpl<VBoxEventListener> VBoxEventListenerImpl;
173
174VBOX_LISTENER_DECLARE(VBoxEventListenerImpl)
175#endif /* !VBOX_WITH_VBOXMANAGE_NLS */
176
177
178/*********************************************************************************************************************************
179* Global Variables *
180*********************************************************************************************************************************/
181/*extern*/ bool g_fDetailedProgress = false;
182
183#ifndef VBOX_ONLY_DOCS
184/** Set by the signal handler. */
185static volatile bool g_fCanceled = false;
186
187
188/**
189 * All registered command handlers
190 */
191static const VBMGCMD g_aCommands[] =
192{
193 { "internalcommands", USAGE_INVALID, VBMG_CMD_TODO, handleInternalCommands, 0 },
194 { "list", USAGE_S_NEWCMD, HELP_CMD_LIST, handleList, 0 },
195 { "showvminfo", USAGE_S_NEWCMD, HELP_CMD_SHOWVMINFO, handleShowVMInfo, 0 },
196 { "registervm", USAGE_S_NEWCMD, HELP_CMD_REGISTERVM, handleRegisterVM, 0 },
197 { "unregistervm", USAGE_S_NEWCMD, HELP_CMD_UNREGISTERVM, handleUnregisterVM, 0 },
198 { "clonevm", USAGE_S_NEWCMD, HELP_CMD_CLONEVM, handleCloneVM, 0 },
199 { "movevm", USAGE_S_NEWCMD, HELP_CMD_MOVEVM, handleMoveVM, 0 },
200 { "mediumproperty", USAGE_MEDIUMPROPERTY, VBMG_CMD_TODO, handleMediumProperty, 0 },
201 { "hdproperty", USAGE_MEDIUMPROPERTY, VBMG_CMD_TODO, handleMediumProperty, 0 }, /* backward compatibility */
202 { "createmedium", USAGE_CREATEMEDIUM, VBMG_CMD_TODO, handleCreateMedium, 0 },
203 { "createhd", USAGE_CREATEMEDIUM, VBMG_CMD_TODO, handleCreateMedium, 0 }, /* backward compatibility */
204 { "createvdi", USAGE_CREATEMEDIUM, VBMG_CMD_TODO, handleCreateMedium, 0 }, /* backward compatibility */
205 { "modifymedium", USAGE_MODIFYMEDIUM, VBMG_CMD_TODO, handleModifyMedium, 0 },
206 { "modifyhd", USAGE_MODIFYMEDIUM, VBMG_CMD_TODO, handleModifyMedium, 0 }, /* backward compatibility */
207 { "modifyvdi", USAGE_MODIFYMEDIUM, VBMG_CMD_TODO, handleModifyMedium, 0 }, /* backward compatibility */
208 { "clonemedium", USAGE_CLONEMEDIUM, VBMG_CMD_TODO, handleCloneMedium, 0 },
209 { "clonehd", USAGE_CLONEMEDIUM, VBMG_CMD_TODO, handleCloneMedium, 0 }, /* backward compatibility */
210 { "clonevdi", USAGE_CLONEMEDIUM, VBMG_CMD_TODO, handleCloneMedium, 0 }, /* backward compatibility */
211 { "encryptmedium", USAGE_ENCRYPTMEDIUM, VBMG_CMD_TODO, handleEncryptMedium, 0 },
212 { "checkmediumpwd", USAGE_MEDIUMENCCHKPWD, VBMG_CMD_TODO, handleCheckMediumPassword, 0 },
213 { "createvm", USAGE_S_NEWCMD, HELP_CMD_CREATEVM, handleCreateVM, 0 },
214 { "modifyvm", USAGE_S_NEWCMD, HELP_CMD_MODIFYVM, handleModifyVM, 0 },
215 { "startvm", USAGE_STARTVM, VBMG_CMD_TODO, handleStartVM, 0 },
216 { "controlvm", USAGE_CONTROLVM, VBMG_CMD_TODO, handleControlVM, 0 },
217 { "unattended", USAGE_S_NEWCMD, HELP_CMD_UNATTENDED, handleUnattended, 0 },
218 { "discardstate", USAGE_DISCARDSTATE, VBMG_CMD_TODO, handleDiscardState, 0 },
219 { "adoptstate", USAGE_ADOPTSTATE, VBMG_CMD_TODO, handleAdoptState, 0 },
220 { "snapshot", USAGE_S_NEWCMD, HELP_CMD_SNAPSHOT, handleSnapshot, 0 },
221 { "closemedium", USAGE_CLOSEMEDIUM, VBMG_CMD_TODO, handleCloseMedium, 0 },
222 { "storageattach", USAGE_STORAGEATTACH, VBMG_CMD_TODO, handleStorageAttach, 0 },
223 { "storagectl", USAGE_STORAGECONTROLLER,VBMG_CMD_TODO, handleStorageController, 0 },
224 { "showmediuminfo", USAGE_SHOWMEDIUMINFO, VBMG_CMD_TODO, handleShowMediumInfo, 0 },
225 { "showhdinfo", USAGE_SHOWMEDIUMINFO, VBMG_CMD_TODO, handleShowMediumInfo, 0 }, /* backward compatibility */
226 { "showvdiinfo", USAGE_SHOWMEDIUMINFO, VBMG_CMD_TODO, handleShowMediumInfo, 0 }, /* backward compatibility */
227 { "mediumio", USAGE_S_NEWCMD, HELP_CMD_MEDIUMIO, handleMediumIO, 0 },
228 { "getextradata", USAGE_GETEXTRADATA, VBMG_CMD_TODO, handleGetExtraData, 0 },
229 { "setextradata", USAGE_SETEXTRADATA, VBMG_CMD_TODO, handleSetExtraData, 0 },
230 { "setproperty", USAGE_SETPROPERTY, VBMG_CMD_TODO, handleSetProperty, 0 },
231 { "usbfilter", USAGE_USBFILTER, VBMG_CMD_TODO, handleUSBFilter, 0 },
232 { "sharedfolder", USAGE_S_NEWCMD, HELP_CMD_SHAREDFOLDER, handleSharedFolder, 0 },
233#ifdef VBOX_WITH_GUEST_PROPS
234 { "guestproperty", USAGE_GUESTPROPERTY, VBMG_CMD_TODO, handleGuestProperty, 0 },
235#endif
236#ifdef VBOX_WITH_GUEST_CONTROL
237 { "guestcontrol", USAGE_GUESTCONTROL, VBMG_CMD_TODO, handleGuestControl, 0 },
238#endif
239 { "metrics", USAGE_METRICS, VBMG_CMD_TODO, handleMetrics, 0 },
240 { "import", USAGE_S_NEWCMD, HELP_CMD_IMPORT, handleImportAppliance, 0 },
241 { "export", USAGE_S_NEWCMD, HELP_CMD_EXPORT, handleExportAppliance, 0 },
242 { "signova", USAGE_S_NEWCMD, HELP_CMD_SIGNOVA, handleSignAppliance, VBMG_CMD_F_NO_COM },
243#ifdef VBOX_WITH_NETFLT
244 { "hostonlyif", USAGE_HOSTONLYIFS, VBMG_CMD_TODO, handleHostonlyIf, 0 },
245#endif
246#ifdef VBOX_WITH_VMNET
247 { "hostonlynet", USAGE_S_NEWCMD, HELP_CMD_HOSTONLYNET, handleHostonlyNet, 0 },
248#endif
249 { "dhcpserver", USAGE_S_NEWCMD, HELP_CMD_DHCPSERVER, handleDHCPServer, 0 },
250#ifdef VBOX_WITH_NAT_SERVICE
251 { "natnetwork", USAGE_NATNETWORK, VBMG_CMD_TODO, handleNATNetwork, 0 },
252#endif
253 { "extpack", USAGE_S_NEWCMD, HELP_CMD_EXTPACK, handleExtPack, 0 },
254 { "bandwidthctl", USAGE_BANDWIDTHCONTROL, VBMG_CMD_TODO, handleBandwidthControl, 0 },
255 { "debugvm", USAGE_S_NEWCMD, HELP_CMD_DEBUGVM, handleDebugVM, 0 },
256 { "convertfromraw", USAGE_CONVERTFROMRAW, VBMG_CMD_TODO, handleConvertFromRaw, VBMG_CMD_F_NO_COM },
257 { "convertdd", USAGE_CONVERTFROMRAW, VBMG_CMD_TODO, handleConvertFromRaw, VBMG_CMD_F_NO_COM },
258 { "usbdevsource", USAGE_USBDEVSOURCE, VBMG_CMD_TODO, handleUSBDevSource, 0 },
259 { "cloudprofile", USAGE_S_NEWCMD, HELP_CMD_CLOUDPROFILE, handleCloudProfile, 0 },
260 { "cloud", USAGE_S_NEWCMD, HELP_CMD_CLOUD, handleCloud, 0 },
261 { "updatecheck", USAGE_S_NEWCMD, HELP_CMD_UPDATECHECK, handleUpdateCheck, 0 },
262 { "modifynvram", USAGE_S_NEWCMD, HELP_CMD_MODIFYNVRAM, handleModifyNvram, 0 },
263};
264
265/**
266 * Looks up a command by name.
267 *
268 * @returns Pointer to the command structure.
269 * @param pszCommand Name of the command.
270 */
271static PCVBMGCMD lookupCommand(const char *pszCommand)
272{
273 if (pszCommand)
274 for (uint32_t i = 0; i < RT_ELEMENTS(g_aCommands); i++)
275 if (!strcmp(g_aCommands[i].pszCommand, pszCommand))
276 return &g_aCommands[i];
277 return NULL;
278}
279
280
281/**
282 * Signal handler that sets g_fCanceled.
283 *
284 * This can be executed on any thread in the process, on Windows it may even be
285 * a thread dedicated to delivering this signal. Do not doing anything
286 * unnecessary here.
287 */
288static void showProgressSignalHandler(int iSignal) RT_NOTHROW_DEF
289{
290 NOREF(iSignal);
291 ASMAtomicWriteBool(&g_fCanceled, true);
292}
293
294/**
295 * Print out progress on the console.
296 *
297 * This runs the main event queue every now and then to prevent piling up
298 * unhandled things (which doesn't cause real problems, just makes things
299 * react a little slower than in the ideal case).
300 */
301HRESULT showProgress(ComPtr<IProgress> progress, uint32_t fFlags)
302{
303 using namespace com;
304 HRESULT hrc;
305
306 AssertReturn(progress.isNotNull(), E_FAIL);
307
308 /* grandfather the old callers */
309 if (g_fDetailedProgress)
310 fFlags = SHOW_PROGRESS_DETAILS;
311
312 const bool fDetailed = RT_BOOL(fFlags & SHOW_PROGRESS_DETAILS);
313 const bool fQuiet = !RT_BOOL(fFlags & (SHOW_PROGRESS | SHOW_PROGRESS_DETAILS));
314
315
316 BOOL fCompleted = FALSE;
317 ULONG ulCurrentPercent = 0;
318 ULONG ulLastPercent = 0;
319
320 ULONG ulLastOperationPercent = (ULONG)-1;
321
322 ULONG ulLastOperation = (ULONG)-1;
323 Bstr bstrOperationDescription;
324
325 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
326
327 ULONG cOperations = 1;
328 hrc = progress->COMGETTER(OperationCount)(&cOperations);
329 if (FAILED(hrc))
330 {
331 RTStrmPrintf(g_pStdErr, VBoxManage::tr("Progress object failure: %Rhrc\n"), hrc);
332 RTStrmFlush(g_pStdErr);
333 return hrc;
334 }
335
336 /*
337 * Note: Outputting the progress info to stderr (g_pStdErr) is intentional
338 * to not get intermixed with other (raw) stdout data which might get
339 * written in the meanwhile.
340 */
341
342 if (fFlags & SHOW_PROGRESS_DESC)
343 {
344 com::Bstr bstrDescription;
345 hrc = progress->COMGETTER(Description(bstrDescription.asOutParam()));
346 if (FAILED(hrc))
347 {
348 RTStrmPrintf(g_pStdErr, VBoxManage::tr("Failed to get progress description: %Rhrc\n"), hrc);
349 return hrc;
350 }
351
352 const char *pcszDescSep;
353 if (fDetailed) /* multiline output */
354 pcszDescSep = "\n";
355 else /* continues on the same line */
356 pcszDescSep = ": ";
357
358 RTStrmPrintf(g_pStdErr, "%ls%s", bstrDescription.raw(), pcszDescSep);
359 RTStrmFlush(g_pStdErr);
360 }
361
362 if (!fQuiet && !fDetailed)
363 {
364 RTStrmPrintf(g_pStdErr, "0%%...");
365 RTStrmFlush(g_pStdErr);
366 }
367
368 /* setup signal handling if cancelable */
369 bool fCanceledAlready = false;
370 BOOL fCancelable;
371 hrc = progress->COMGETTER(Cancelable)(&fCancelable);
372 if (FAILED(hrc))
373 fCancelable = FALSE;
374 if (fCancelable)
375 {
376 signal(SIGINT, showProgressSignalHandler);
377 signal(SIGTERM, showProgressSignalHandler);
378#ifdef SIGBREAK
379 signal(SIGBREAK, showProgressSignalHandler);
380#endif
381 }
382
383 hrc = progress->COMGETTER(Completed(&fCompleted));
384 while (SUCCEEDED(hrc))
385 {
386 progress->COMGETTER(Percent(&ulCurrentPercent));
387
388 if (fDetailed)
389 {
390 ULONG ulOperation = 1;
391 hrc = progress->COMGETTER(Operation)(&ulOperation);
392 if (FAILED(hrc))
393 break;
394 ULONG ulCurrentOperationPercent = 0;
395 hrc = progress->COMGETTER(OperationPercent(&ulCurrentOperationPercent));
396 if (FAILED(hrc))
397 break;
398
399 if (ulLastOperation != ulOperation)
400 {
401 hrc = progress->COMGETTER(OperationDescription(bstrOperationDescription.asOutParam()));
402 if (FAILED(hrc))
403 break;
404 ulLastPercent = (ULONG)-1; // force print
405 ulLastOperation = ulOperation;
406 }
407
408 if ( ulCurrentPercent != ulLastPercent
409 || ulCurrentOperationPercent != ulLastOperationPercent
410 )
411 {
412 LONG lSecsRem = 0;
413 progress->COMGETTER(TimeRemaining)(&lSecsRem);
414
415 RTStrmPrintf(g_pStdErr, VBoxManage::tr("(%u/%u) %ls %02u%% => %02u%% (%d s remaining)\n"), ulOperation + 1, cOperations,
416 bstrOperationDescription.raw(), ulCurrentOperationPercent, ulCurrentPercent, lSecsRem);
417 ulLastPercent = ulCurrentPercent;
418 ulLastOperationPercent = ulCurrentOperationPercent;
419 }
420 }
421 else if (!fQuiet)
422 {
423 /* did we cross a 10% mark? */
424 if (ulCurrentPercent / 10 > ulLastPercent / 10)
425 {
426 /* make sure to also print out missed steps */
427 for (ULONG curVal = (ulLastPercent / 10) * 10 + 10; curVal <= (ulCurrentPercent / 10) * 10; curVal += 10)
428 {
429 if (curVal < 100)
430 {
431 RTStrmPrintf(g_pStdErr, "%u%%...", curVal);
432 RTStrmFlush(g_pStdErr);
433 }
434 }
435 ulLastPercent = (ulCurrentPercent / 10) * 10;
436 }
437 }
438 if (fCompleted)
439 break;
440
441 /* process async cancelation */
442 if (g_fCanceled && !fCanceledAlready)
443 {
444 hrc = progress->Cancel();
445 if (SUCCEEDED(hrc))
446 fCanceledAlready = true;
447 else
448 g_fCanceled = false;
449 }
450
451 /* make sure the loop is not too tight */
452 progress->WaitForCompletion(100);
453
454 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
455 hrc = progress->COMGETTER(Completed(&fCompleted));
456 }
457
458 /* undo signal handling */
459 if (fCancelable)
460 {
461 signal(SIGINT, SIG_DFL);
462 signal(SIGTERM, SIG_DFL);
463# ifdef SIGBREAK
464 signal(SIGBREAK, SIG_DFL);
465# endif
466 }
467
468 /* complete the line. */
469 LONG iRc = E_FAIL;
470 hrc = progress->COMGETTER(ResultCode)(&iRc);
471 if (SUCCEEDED(hrc))
472 {
473 /* async operation completed successfully */
474 if (SUCCEEDED(iRc))
475 {
476 if (!fDetailed)
477 {
478 if (fFlags == SHOW_PROGRESS_DESC)
479 RTStrmPrintf(g_pStdErr, "ok\n");
480 else if (!fQuiet)
481 RTStrmPrintf(g_pStdErr, "100%%\n");
482 }
483 }
484 else if (g_fCanceled)
485 RTStrmPrintf(g_pStdErr, VBoxManage::tr("CANCELED\n"));
486 else
487 {
488 if (fDetailed)
489 RTStrmPrintf(g_pStdErr, VBoxManage::tr("Progress state: %Rhrc\n"), iRc);
490 else if (fFlags != SHOW_PROGRESS_NONE)
491 RTStrmPrintf(g_pStdErr, "%Rhrc\n", iRc);
492 }
493 hrc = iRc;
494 }
495 else
496 {
497 if (!fDetailed)
498 RTStrmPrintf(g_pStdErr, "\n");
499 RTStrmPrintf(g_pStdErr, VBoxManage::tr("Progress object failure: %Rhrc\n"), hrc);
500 }
501 RTStrmFlush(g_pStdErr);
502 return hrc;
503}
504
505#endif /* !VBOX_ONLY_DOCS */
506
507
508void setBuiltInHelpLanguage(const char *pszLang)
509{
510#ifdef VBOX_WITH_VBOXMANAGE_NLS
511 if (pszLang == NULL || pszLang[0] == 0 || (pszLang[0] == 'C' && pszLang[1] == 0))
512 pszLang = "en_US";
513 PHELP_LANG_ENTRY pHelpLangEntry = NULL;
514 /* find language entry matching exactly pszLang */
515 for (uint32_t i = 0; i < g_cHelpLangEntries; i++)
516 {
517 if (strcmp(g_apHelpLangEntries[i].pszLang, pszLang) == 0)
518 {
519 pHelpLangEntry = &g_apHelpLangEntries[i];
520 break;
521 }
522 }
523 /* find first entry containing language specified if pszLang contains only language */
524 if (pHelpLangEntry == NULL)
525 {
526 size_t cbLang = strlen(pszLang);
527 for (uint32_t i = 0; i < g_cHelpLangEntries; i++)
528 {
529 if ( cbLang < g_apHelpLangEntries[i].cbLang
530 && memcmp(g_apHelpLangEntries[i].pszLang, pszLang, cbLang) == 0)
531 {
532 pHelpLangEntry = &g_apHelpLangEntries[i];
533 break;
534 }
535 }
536 }
537 /* set to en_US (i.e. untranslated) if not found */
538 if (pHelpLangEntry == NULL)
539 pHelpLangEntry = &g_apHelpLangEntries[0];
540
541 ASMAtomicWritePtr(&g_pHelpLangEntry, pHelpLangEntry);
542#else
543 NOREF(pszLang);
544#endif
545}
546
547
548int main(int argc, char *argv[])
549{
550 /*
551 * Before we do anything, init the runtime without loading
552 * the support driver.
553 */
554 int vrc = RTR3InitExe(argc, &argv, 0);
555 if (RT_FAILURE(vrc))
556 return RTMsgInitFailure(vrc);
557#if defined(RT_OS_WINDOWS) && !defined(VBOX_ONLY_DOCS)
558 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
559#endif
560
561 /*
562 * Parse the global options
563 */
564 bool fShowLogo = false;
565 bool fShowHelp = false;
566 int iCmd = 1;
567 int iCmdArg;
568 const char *pszSettingsPw = NULL;
569 const char *pszSettingsPwFile = NULL;
570#ifndef VBOX_ONLY_DOCS
571 int cResponseFileArgs = 0;
572 char **papszResponseFileArgs = NULL;
573 char **papszNewArgv = NULL;
574#endif
575
576#ifdef VBOX_WITH_VBOXMANAGE_NLS
577 ComPtr<IEventListener> pEventListener;
578 PTRCOMPONENT pTrComponent = NULL;
579 util::InitAutoLockSystem();
580 VirtualBoxTranslator *pTranslator = VirtualBoxTranslator::instance();
581 if (pTranslator != NULL)
582 {
583 char szNlsPath[RTPATH_MAX];
584 vrc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
585 if (RT_SUCCESS(vrc))
586 vrc = RTPathAppend(szNlsPath, sizeof(szNlsPath), "nls" RTPATH_SLASH_STR "VBoxManageNls");
587
588 if (RT_SUCCESS(vrc))
589 {
590 vrc = pTranslator->registerTranslation(szNlsPath, true, &pTrComponent);
591 if (RT_SUCCESS(vrc))
592 {
593 vrc = pTranslator->i_loadLanguage(NULL);
594 if (RT_SUCCESS(vrc))
595 {
596 com::Utf8Str strLang = pTranslator->language();
597 setBuiltInHelpLanguage(strLang.c_str());
598 }
599 else
600 LogRelFunc(("Load language failed: %Rrc\n", vrc));
601 }
602 else
603 LogRelFunc(("Register translation failed: %Rrc\n", vrc));
604 }
605 else
606 LogRelFunc(("Path constructing failed: %Rrc\n", vrc));
607
608 }
609#endif
610
611 for (int i = 1; i < argc || argc <= iCmd; i++)
612 {
613 if ( argc <= iCmd
614 || !strcmp(argv[i], "help")
615 || !strcmp(argv[i], "--help")
616 || !strcmp(argv[i], "-?")
617 || !strcmp(argv[i], "-h")
618 || !strcmp(argv[i], "-help"))
619 {
620 if (i >= argc - 1)
621 {
622 showLogo(g_pStdOut);
623 printUsage(USAGE_S_ALL, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
624 return 0;
625 }
626 fShowLogo = true;
627 fShowHelp = true;
628 iCmd++;
629 continue;
630 }
631
632#ifndef VBOX_ONLY_DOCS
633 if ( !strcmp(argv[i], "-V")
634 || !strcmp(argv[i], "--version")
635 || !strcmp(argv[i], "-v") /* deprecated */
636 || !strcmp(argv[i], "-version") /* deprecated */
637 || !strcmp(argv[i], "-Version") /* deprecated */)
638 {
639 /* Print version number, and do nothing else. */
640 RTPrintf("%sr%u\n", VBOX_VERSION_STRING, RTBldCfgRevision());
641 return 0;
642 }
643 if (!strcmp(argv[i], "--dump-build-type"))
644 {
645 /* Print the build type, and do nothing else. (Used by ValKit to detect build type.) */
646 RTPrintf("%s\n", RTBldCfgType());
647 return 0;
648 }
649#endif
650
651 if ( !strcmp(argv[i], "--dumpopts")
652 || !strcmp(argv[i], "-dumpopts") /* deprecated */)
653 {
654 /* Special option to dump really all commands,
655 * even the ones not understood on this platform. */
656 printUsage(USAGE_S_DUMPOPTS, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
657 return 0;
658 }
659
660 if ( !strcmp(argv[i], "--nologo")
661 || !strcmp(argv[i], "-q")
662 || !strcmp(argv[i], "-nologo") /* deprecated */)
663 {
664 /* suppress the logo */
665 fShowLogo = false;
666 iCmd++;
667 }
668 else if ( !strcmp(argv[i], "--detailed-progress")
669 || !strcmp(argv[i], "-d"))
670 {
671 /* detailed progress report */
672 g_fDetailedProgress = true;
673 iCmd++;
674 }
675 else if (!strcmp(argv[i], "--settingspw"))
676 {
677 if (i >= argc - 1)
678 return RTMsgErrorExit(RTEXITCODE_FAILURE, VBoxManage::tr("Password expected"));
679 /* password for certain settings */
680 pszSettingsPw = argv[i + 1];
681 iCmd += 2;
682 }
683 else if (!strcmp(argv[i], "--settingspwfile"))
684 {
685 if (i >= argc-1)
686 return RTMsgErrorExit(RTEXITCODE_FAILURE, VBoxManage::tr("No password file specified"));
687 pszSettingsPwFile = argv[i+1];
688 iCmd += 2;
689 }
690#ifndef VBOX_ONLY_DOCS
691 else if (argv[i][0] == '@')
692 {
693 if (papszResponseFileArgs)
694 return RTMsgErrorExitFailure(VBoxManage::tr("Only one response file allowed"));
695
696 /* Load response file, making sure it's valid UTF-8. */
697 char *pszResponseFile;
698 size_t cbResponseFile;
699 vrc = RTFileReadAllEx(&argv[i][1], 0, RTFOFF_MAX, RTFILE_RDALL_O_DENY_NONE | RTFILE_RDALL_F_TRAILING_ZERO_BYTE,
700 (void **)&pszResponseFile, &cbResponseFile);
701 if (RT_FAILURE(vrc))
702 return RTMsgErrorExitFailure(VBoxManage::tr("Error reading response file '%s': %Rrc"), &argv[i][1], vrc);
703 vrc = RTStrValidateEncoding(pszResponseFile);
704 if (RT_FAILURE(vrc))
705 {
706 RTFileReadAllFree(pszResponseFile, cbResponseFile);
707 return RTMsgErrorExitFailure(VBoxManage::tr("Invalid response file ('%s') encoding: %Rrc"), &argv[i][1], vrc);
708 }
709
710 /* Parse it. */
711 vrc = RTGetOptArgvFromString(&papszResponseFileArgs, &cResponseFileArgs, pszResponseFile,
712 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
713 RTFileReadAllFree(pszResponseFile, cbResponseFile);
714 if (RT_FAILURE(vrc))
715 return RTMsgErrorExitFailure(VBoxManage::tr("Failed to parse response file '%s' (bourne shell style): %Rrc"), &argv[i][1], vrc);
716
717 /* Construct new argv+argc with the response file arguments inserted. */
718 int cNewArgs = argc + cResponseFileArgs;
719 papszNewArgv = (char **)RTMemAllocZ((cNewArgs + 2) * sizeof(papszNewArgv[0]));
720 if (!papszNewArgv)
721 return RTMsgErrorExitFailure(VBoxManage::tr("out of memory"));
722 memcpy(&papszNewArgv[0], &argv[0], sizeof(argv[0]) * (i + 1));
723 memcpy(&papszNewArgv[i + 1], papszResponseFileArgs, sizeof(argv[0]) * cResponseFileArgs);
724 memcpy(&papszNewArgv[i + 1 + cResponseFileArgs], &argv[i + 1], sizeof(argv[0]) * (argc - i - 1 + 1));
725 argv = papszNewArgv;
726 argc = argc + cResponseFileArgs;
727
728 iCmd++;
729 }
730#endif
731 else
732 break;
733 }
734
735 iCmdArg = iCmd + 1;
736
737 /*
738 * Show the logo and lookup the command and deal with fShowHelp = true.
739 */
740 if (fShowLogo)
741 showLogo(g_pStdOut);
742
743#ifndef VBOX_ONLY_DOCS
744 PCVBMGCMD pCmd = lookupCommand(argv[iCmd]);
745 if (pCmd && pCmd->enmCmdHelp != VBMG_CMD_TODO)
746 setCurrentCommand(pCmd->enmCmdHelp);
747
748 if ( pCmd
749 && ( fShowHelp
750 || ( argc - iCmdArg == 0
751 && pCmd->enmHelpCat != USAGE_INVALID)))
752 {
753 if (pCmd->enmCmdHelp == VBMG_CMD_TODO)
754 printUsage(pCmd->enmHelpCat, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
755 else if (fShowHelp)
756 printHelp(g_pStdOut);
757 else
758 printUsage(g_pStdOut);
759 return RTEXITCODE_FAILURE; /* error */
760 }
761 if (!pCmd)
762 {
763 if (!strcmp(argv[iCmd], "commands"))
764 {
765 RTPrintf(VBoxManage::tr("commands:\n"));
766 for (unsigned i = 0; i < RT_ELEMENTS(g_aCommands); i++)
767 if ( i == 0 /* skip backwards compatibility entries */
768 || (g_aCommands[i].enmHelpCat != USAGE_S_NEWCMD
769 ? g_aCommands[i].enmHelpCat != g_aCommands[i - 1].enmHelpCat
770 : g_aCommands[i].enmCmdHelp != g_aCommands[i - 1].enmCmdHelp))
771 RTPrintf(" %s\n", g_aCommands[i].pszCommand);
772 return RTEXITCODE_SUCCESS;
773 }
774 return errorSyntax(USAGE_S_ALL, VBoxManage::tr("Invalid command '%s'"), argv[iCmd]);
775 }
776
777 RTEXITCODE rcExit;
778 if (!(pCmd->fFlags & VBMG_CMD_F_NO_COM))
779 {
780 /*
781 * Initialize COM.
782 */
783 using namespace com;
784 HRESULT hrc = com::Initialize();
785 if (FAILED(hrc))
786 {
787# ifdef VBOX_WITH_XPCOM
788 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
789 {
790 char szHome[RTPATH_MAX] = "";
791 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
792 return RTMsgErrorExit(RTEXITCODE_FAILURE,
793 VBoxManage::tr("Failed to initialize COM because the global settings directory '%s' is not accessible!"), szHome);
794 }
795# endif
796 return RTMsgErrorExit(RTEXITCODE_FAILURE, VBoxManage::tr("Failed to initialize COM! (hrc=%Rhrc)"), hrc);
797 }
798
799
800 /*
801 * Get the remote VirtualBox object and create a local session object.
802 */
803 rcExit = RTEXITCODE_FAILURE;
804 ComPtr<IVirtualBoxClient> virtualBoxClient;
805 ComPtr<IVirtualBox> virtualBox;
806 hrc = virtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
807 if (SUCCEEDED(hrc))
808 hrc = virtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
809 if (SUCCEEDED(hrc))
810 {
811#ifdef VBOX_WITH_VBOXMANAGE_NLS
812 if (pTranslator != NULL)
813 {
814 HRESULT hrc1 = pTranslator->loadLanguage(virtualBox);
815 if (SUCCEEDED(hrc1))
816 {
817 com::Utf8Str strLang = pTranslator->language();
818 setBuiltInHelpLanguage(strLang.c_str());
819 }
820 else
821 {
822 /* Just log and ignore the language error */
823 LogRel(("Failed to load API language, %Rhrc", hrc1));
824 }
825 /* VirtualBox language events registration. */
826 ComPtr<IEventSource> pES;
827 hrc1 = virtualBox->COMGETTER(EventSource)(pES.asOutParam());
828 if (SUCCEEDED(hrc1))
829 {
830 ComObjPtr<VBoxEventListenerImpl> listener;
831 listener.createObject();
832 listener->init(new VBoxEventListener());
833 pEventListener = listener;
834 com::SafeArray<VBoxEventType_T> eventTypes;
835 eventTypes.push_back(VBoxEventType_OnLanguageChanged);
836 hrc1 = pES->RegisterListener(pEventListener, ComSafeArrayAsInParam(eventTypes), true);
837 if (FAILED(hrc1))
838 {
839 pEventListener.setNull();
840 LogRel(("Failed to register event listener, %Rhrc", hrc1));
841 }
842 }
843 }
844#endif
845
846 ComPtr<ISession> session;
847 hrc = session.createInprocObject(CLSID_Session);
848 if (SUCCEEDED(hrc))
849 {
850 /* Session secret. */
851 if (pszSettingsPw)
852 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(Bstr(pszSettingsPw).raw()), rcExit = RTEXITCODE_FAILURE);
853 else if (pszSettingsPwFile)
854 rcExit = settingsPasswordFile(virtualBox, pszSettingsPwFile);
855 else
856 rcExit = RTEXITCODE_SUCCESS;
857 if (rcExit == RTEXITCODE_SUCCESS)
858 {
859 /*
860 * Call the handler.
861 */
862 HandlerArg handlerArg = { argc - iCmdArg, &argv[iCmdArg], virtualBox, session };
863 rcExit = pCmd->pfnHandler(&handlerArg);
864
865 /* Although all handlers should always close the session if they open it,
866 * we do it here just in case if some of the handlers contains a bug --
867 * leaving the direct session not closed will turn the machine state to
868 * Aborted which may have unwanted side effects like killing the saved
869 * state file (if the machine was in the Saved state before). */
870 session->UnlockMachine();
871 }
872
873 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
874 }
875 else
876 {
877 com::ErrorInfo info;
878 RTMsgError(VBoxManage::tr("Failed to create a session object!"));
879 if (!info.isFullAvailable() && !info.isBasicAvailable())
880 com::GluePrintRCMessage(hrc);
881 else
882 com::GluePrintErrorInfo(info);
883 }
884 }
885 else
886 {
887 com::ErrorInfo info;
888 RTMsgError(VBoxManage::tr("Failed to create the VirtualBox object!"));
889 if (!info.isFullAvailable() && !info.isBasicAvailable())
890 {
891 com::GluePrintRCMessage(hrc);
892 RTMsgError(VBoxManage::tr("Most likely, the VirtualBox COM server is not running or failed to start."));
893 }
894 else
895 com::GluePrintErrorInfo(info);
896 }
897
898#ifdef VBOX_WITH_VBOXMANAGE_NLS
899 /* VirtualBox event callback unregistration. */
900 if (pEventListener.isNotNull())
901 {
902 ComPtr<IEventSource> pES;
903 HRESULT hrc1 = virtualBox->COMGETTER(EventSource)(pES.asOutParam());
904 if (pES.isNotNull())
905 {
906 hrc1 = pES->UnregisterListener(pEventListener);
907 if (FAILED(hrc1))
908 LogRel(("Failed to unregister listener, %Rhrc", hrc1));
909 }
910 pEventListener.setNull();
911 }
912#endif
913 /*
914 * Terminate COM, make sure the virtualBox object has been released.
915 */
916 virtualBox.setNull();
917 virtualBoxClient.setNull();
918 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
919 com::Shutdown();
920 }
921 else
922 {
923 /*
924 * The command needs no COM.
925 */
926 HandlerArg handlerArg;
927 handlerArg.argc = argc - iCmdArg;
928 handlerArg.argv = &argv[iCmdArg];
929 rcExit = pCmd->pfnHandler(&handlerArg);
930 }
931
932#ifdef VBOX_WITH_VBOXMANAGE_NLS
933 if (pTranslator != NULL)
934 {
935 pTranslator->release();
936 pTranslator = NULL;
937 pTrComponent = NULL;
938 }
939#endif
940
941 if (papszResponseFileArgs)
942 {
943 RTGetOptArgvFree(papszResponseFileArgs);
944 RTMemFree(papszNewArgv);
945 }
946
947 return rcExit;
948#else /* VBOX_ONLY_DOCS */
949 return RTEXITCODE_SUCCESS;
950#endif /* VBOX_ONLY_DOCS */
951}
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