VirtualBox

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

Last change on this file since 93845 was 93708, checked in by vboxsync, 3 years ago

include/iprt/message.h: Max out the available bits for the scope, we need a lot for the VBoxManage controlvm docs.

docs, VBoxManage: Integrate refman (and fix some content) for VBoxManage startvm and VBoxManage controlvm. Needs about 60 scopes (do RT_BIT_64 is a must have), and for protection against exceeding the limit there are now checks (as AssertCompile).

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 35.8 KB
Line 
1/* $Id: VBoxManage.cpp 93708 2022-02-11 20:46:11Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2022 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_S_NEWCMD, HELP_CMD_STARTVM, handleStartVM, 0 },
216 { "controlvm", USAGE_S_NEWCMD, HELP_CMD_CONTROLVM, 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
514 /* find language entry matching exactly pszLang */
515 PCHELP_LANG_ENTRY_T pHelpLangEntry = NULL;
516 for (uint32_t i = 0; i < g_cHelpLangEntries; i++)
517 {
518 if (strcmp(g_aHelpLangEntries[i].pszLang, pszLang) == 0)
519 {
520 pHelpLangEntry = &g_aHelpLangEntries[i];
521 break;
522 }
523 }
524
525 /* find first entry containing language specified if pszLang contains only language */
526 if (pHelpLangEntry == NULL)
527 {
528 size_t const cchLang = strlen(pszLang);
529 for (uint32_t i = 0; i < g_cHelpLangEntries; i++)
530 {
531 if ( cchLang < g_aHelpLangEntries[i].cchLang
532 && memcmp(g_aHelpLangEntries[i].pszLang, pszLang, cchLang) == 0)
533 {
534 pHelpLangEntry = &g_aHelpLangEntries[i];
535 break;
536 }
537 }
538 }
539
540 /* set to en_US (i.e. untranslated) if not found */
541 if (pHelpLangEntry == NULL)
542 pHelpLangEntry = &g_aHelpLangEntries[0];
543
544 ASMAtomicWritePtr(&g_pHelpLangEntry, pHelpLangEntry);
545#else
546 NOREF(pszLang);
547#endif
548}
549
550
551int main(int argc, char *argv[])
552{
553 /*
554 * Before we do anything, init the runtime without loading
555 * the support driver.
556 */
557 int vrc = RTR3InitExe(argc, &argv, 0);
558 if (RT_FAILURE(vrc))
559 return RTMsgInitFailure(vrc);
560#if defined(RT_OS_WINDOWS) && !defined(VBOX_ONLY_DOCS)
561 ATL::CComModule _Module; /* Required internally by ATL (constructor records instance in global variable). */
562#endif
563
564#ifdef VBOX_WITH_VBOXMANAGE_NLS
565 /*
566 * Initialize the translator and associated fun.
567 */
568 util::InitAutoLockSystem();
569 ComObjPtr<VBoxEventListenerImpl> ptrEventListner;
570 PTRCOMPONENT pTrComponent = NULL;
571 VirtualBoxTranslator *pTranslator = VirtualBoxTranslator::instance();
572 if (pTranslator != NULL)
573 {
574 char szNlsPath[RTPATH_MAX];
575 vrc = RTPathAppPrivateNoArch(szNlsPath, sizeof(szNlsPath));
576 if (RT_SUCCESS(vrc))
577 vrc = RTPathAppend(szNlsPath, sizeof(szNlsPath), "nls" RTPATH_SLASH_STR "VBoxManageNls");
578 if (RT_SUCCESS(vrc))
579 {
580 vrc = pTranslator->registerTranslation(szNlsPath, true, &pTrComponent);
581 if (RT_SUCCESS(vrc))
582 {
583 vrc = pTranslator->i_loadLanguage(NULL);
584 if (RT_SUCCESS(vrc))
585 {
586 com::Utf8Str strLang = pTranslator->language();
587 setBuiltInHelpLanguage(strLang.c_str());
588 }
589 else
590 RTMsgWarning("Load language failed: %Rrc\n", vrc);
591 }
592 else
593 RTMsgWarning("Register translation failed: %Rrc\n", vrc);
594 }
595 else
596 RTMsgWarning("Path constructing failed: %Rrc\n", vrc);
597 }
598#endif
599
600 /*
601 * Parse the global options
602 */
603 bool fShowLogo = false;
604 bool fShowHelp = false;
605 int iCmd = 1;
606 int iCmdArg;
607 const char *pszSettingsPw = NULL;
608 const char *pszSettingsPwFile = NULL;
609#ifndef VBOX_ONLY_DOCS
610 int cResponseFileArgs = 0;
611 char **papszResponseFileArgs = NULL;
612 char **papszNewArgv = NULL;
613#endif
614 for (int i = 1; i < argc || argc <= iCmd; i++)
615 {
616 if ( argc <= iCmd
617 || !strcmp(argv[i], "help")
618 || !strcmp(argv[i], "--help")
619 || !strcmp(argv[i], "-?")
620 || !strcmp(argv[i], "-h")
621 || !strcmp(argv[i], "-help"))
622 {
623 if (i >= argc - 1)
624 {
625 showLogo(g_pStdOut);
626 printUsage(USAGE_S_ALL, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
627 return 0;
628 }
629 fShowLogo = true;
630 fShowHelp = true;
631 iCmd++;
632 continue;
633 }
634
635#ifndef VBOX_ONLY_DOCS
636 if ( !strcmp(argv[i], "-V")
637 || !strcmp(argv[i], "--version")
638 || !strcmp(argv[i], "-v") /* deprecated */
639 || !strcmp(argv[i], "-version") /* deprecated */
640 || !strcmp(argv[i], "-Version") /* deprecated */)
641 {
642 /* Print version number, and do nothing else. */
643 RTPrintf("%sr%u\n", VBOX_VERSION_STRING, RTBldCfgRevision());
644 return 0;
645 }
646 if (!strcmp(argv[i], "--dump-build-type"))
647 {
648 /* Print the build type, and do nothing else. (Used by ValKit to detect build type.) */
649 RTPrintf("%s\n", RTBldCfgType());
650 return 0;
651 }
652#endif
653
654 if ( !strcmp(argv[i], "--dumpopts")
655 || !strcmp(argv[i], "-dumpopts") /* deprecated */)
656 {
657 /* Special option to dump really all commands,
658 * even the ones not understood on this platform. */
659 printUsage(USAGE_S_DUMPOPTS, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
660 return 0;
661 }
662
663 if ( !strcmp(argv[i], "--nologo")
664 || !strcmp(argv[i], "-q")
665 || !strcmp(argv[i], "-nologo") /* deprecated */)
666 {
667 /* suppress the logo */
668 fShowLogo = false;
669 iCmd++;
670 }
671 else if ( !strcmp(argv[i], "--detailed-progress")
672 || !strcmp(argv[i], "-d"))
673 {
674 /* detailed progress report */
675 g_fDetailedProgress = true;
676 iCmd++;
677 }
678 else if (!strcmp(argv[i], "--settingspw"))
679 {
680 if (i >= argc - 1)
681 return RTMsgErrorExit(RTEXITCODE_FAILURE, VBoxManage::tr("Password expected"));
682 /* password for certain settings */
683 pszSettingsPw = argv[i + 1];
684 iCmd += 2;
685 }
686 else if (!strcmp(argv[i], "--settingspwfile"))
687 {
688 if (i >= argc-1)
689 return RTMsgErrorExit(RTEXITCODE_FAILURE, VBoxManage::tr("No password file specified"));
690 pszSettingsPwFile = argv[i+1];
691 iCmd += 2;
692 }
693#ifndef VBOX_ONLY_DOCS
694 else if (argv[i][0] == '@')
695 {
696 if (papszResponseFileArgs)
697 return RTMsgErrorExitFailure(VBoxManage::tr("Only one response file allowed"));
698
699 /* Load response file, making sure it's valid UTF-8. */
700 char *pszResponseFile;
701 size_t cbResponseFile;
702 vrc = RTFileReadAllEx(&argv[i][1], 0, RTFOFF_MAX, RTFILE_RDALL_O_DENY_NONE | RTFILE_RDALL_F_TRAILING_ZERO_BYTE,
703 (void **)&pszResponseFile, &cbResponseFile);
704 if (RT_FAILURE(vrc))
705 return RTMsgErrorExitFailure(VBoxManage::tr("Error reading response file '%s': %Rrc"), &argv[i][1], vrc);
706 vrc = RTStrValidateEncoding(pszResponseFile);
707 if (RT_FAILURE(vrc))
708 {
709 RTFileReadAllFree(pszResponseFile, cbResponseFile);
710 return RTMsgErrorExitFailure(VBoxManage::tr("Invalid response file ('%s') encoding: %Rrc"), &argv[i][1], vrc);
711 }
712
713 /* Parse it. */
714 vrc = RTGetOptArgvFromString(&papszResponseFileArgs, &cResponseFileArgs, pszResponseFile,
715 RTGETOPTARGV_CNV_QUOTE_BOURNE_SH, NULL);
716 RTFileReadAllFree(pszResponseFile, cbResponseFile);
717 if (RT_FAILURE(vrc))
718 return RTMsgErrorExitFailure(VBoxManage::tr("Failed to parse response file '%s' (bourne shell style): %Rrc"), &argv[i][1], vrc);
719
720 /* Construct new argv+argc with the response file arguments inserted. */
721 int cNewArgs = argc + cResponseFileArgs;
722 papszNewArgv = (char **)RTMemAllocZ((cNewArgs + 2) * sizeof(papszNewArgv[0]));
723 if (!papszNewArgv)
724 return RTMsgErrorExitFailure(VBoxManage::tr("out of memory"));
725 memcpy(&papszNewArgv[0], &argv[0], sizeof(argv[0]) * (i + 1));
726 memcpy(&papszNewArgv[i + 1], papszResponseFileArgs, sizeof(argv[0]) * cResponseFileArgs);
727 memcpy(&papszNewArgv[i + 1 + cResponseFileArgs], &argv[i + 1], sizeof(argv[0]) * (argc - i - 1 + 1));
728 argv = papszNewArgv;
729 argc = argc + cResponseFileArgs;
730
731 iCmd++;
732 }
733#endif
734 else
735 break;
736 }
737
738 iCmdArg = iCmd + 1;
739
740 /*
741 * Show the logo and lookup the command and deal with fShowHelp = true.
742 */
743 if (fShowLogo)
744 showLogo(g_pStdOut);
745
746#ifndef VBOX_ONLY_DOCS
747 PCVBMGCMD pCmd = lookupCommand(argv[iCmd]);
748 if (pCmd && pCmd->enmCmdHelp != VBMG_CMD_TODO)
749 setCurrentCommand(pCmd->enmCmdHelp);
750
751 if ( pCmd
752 && ( fShowHelp
753 || ( argc - iCmdArg == 0
754 && pCmd->enmHelpCat != USAGE_INVALID)))
755 {
756 if (pCmd->enmCmdHelp == VBMG_CMD_TODO)
757 printUsage(pCmd->enmHelpCat, RTMSGREFENTRYSTR_SCOPE_GLOBAL, g_pStdOut);
758 else if (fShowHelp)
759 printHelp(g_pStdOut);
760 else
761 printUsage(g_pStdOut);
762 return RTEXITCODE_FAILURE; /* error */
763 }
764 if (!pCmd)
765 {
766 if (!strcmp(argv[iCmd], "commands"))
767 {
768 RTPrintf(VBoxManage::tr("commands:\n"));
769 for (unsigned i = 0; i < RT_ELEMENTS(g_aCommands); i++)
770 if ( i == 0 /* skip backwards compatibility entries */
771 || (g_aCommands[i].enmHelpCat != USAGE_S_NEWCMD
772 ? g_aCommands[i].enmHelpCat != g_aCommands[i - 1].enmHelpCat
773 : g_aCommands[i].enmCmdHelp != g_aCommands[i - 1].enmCmdHelp))
774 RTPrintf(" %s\n", g_aCommands[i].pszCommand);
775 return RTEXITCODE_SUCCESS;
776 }
777 return errorSyntax(USAGE_S_ALL, VBoxManage::tr("Invalid command '%s'"), argv[iCmd]);
778 }
779
780 RTEXITCODE rcExit;
781 if (!(pCmd->fFlags & VBMG_CMD_F_NO_COM))
782 {
783 /*
784 * Initialize COM.
785 */
786 using namespace com;
787 HRESULT hrc = com::Initialize();
788 if (FAILED(hrc))
789 {
790# ifdef VBOX_WITH_XPCOM
791 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
792 {
793 char szHome[RTPATH_MAX] = "";
794 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
795 return RTMsgErrorExit(RTEXITCODE_FAILURE,
796 VBoxManage::tr("Failed to initialize COM because the global settings directory '%s' is not accessible!"), szHome);
797 }
798# endif
799 return RTMsgErrorExit(RTEXITCODE_FAILURE, VBoxManage::tr("Failed to initialize COM! (hrc=%Rhrc)"), hrc);
800 }
801
802
803 /*
804 * Get the remote VirtualBox object and create a local session object.
805 */
806 rcExit = RTEXITCODE_FAILURE;
807 ComPtr<IVirtualBoxClient> virtualBoxClient;
808 ComPtr<IVirtualBox> virtualBox;
809 hrc = virtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
810 if (SUCCEEDED(hrc))
811 hrc = virtualBoxClient->COMGETTER(VirtualBox)(virtualBox.asOutParam());
812 if (SUCCEEDED(hrc))
813 {
814#ifdef VBOX_WITH_VBOXMANAGE_NLS
815 /* Load language settings from IVirtualBox. */
816 if (pTranslator != NULL)
817 {
818 HRESULT hrc1 = pTranslator->loadLanguage(virtualBox);
819 if (SUCCEEDED(hrc1))
820 {
821 com::Utf8Str strLang = pTranslator->language();
822 setBuiltInHelpLanguage(strLang.c_str());
823 }
824 else
825 RTMsgWarning("Failed to load API language: %Rhrc", hrc1);
826
827 /* VirtualBox language events registration. */
828 ComPtr<IEventSource> pES;
829 hrc1 = virtualBox->COMGETTER(EventSource)(pES.asOutParam());
830 if (SUCCEEDED(hrc1))
831 {
832 hrc1 = ptrEventListner.createObject();
833 if (SUCCEEDED(hrc1))
834 hrc1 = ptrEventListner->init(new VBoxEventListener());
835 if (SUCCEEDED(hrc1))
836 {
837 com::SafeArray<VBoxEventType_T> eventTypes;
838 eventTypes.push_back(VBoxEventType_OnLanguageChanged);
839 hrc1 = pES->RegisterListener(ptrEventListner, ComSafeArrayAsInParam(eventTypes), true);
840 }
841 if (FAILED(hrc1))
842 {
843 ptrEventListner.setNull();
844 RTMsgWarning("Failed to register event listener: %Rhrc", hrc1);
845 }
846 }
847 }
848#endif
849
850 ComPtr<ISession> session;
851 hrc = session.createInprocObject(CLSID_Session);
852 if (SUCCEEDED(hrc))
853 {
854 /* Session secret. */
855 if (pszSettingsPw)
856 CHECK_ERROR2I_STMT(virtualBox, SetSettingsSecret(Bstr(pszSettingsPw).raw()), rcExit = RTEXITCODE_FAILURE);
857 else if (pszSettingsPwFile)
858 rcExit = settingsPasswordFile(virtualBox, pszSettingsPwFile);
859 else
860 rcExit = RTEXITCODE_SUCCESS;
861 if (rcExit == RTEXITCODE_SUCCESS)
862 {
863 /*
864 * Call the handler.
865 */
866 HandlerArg handlerArg = { argc - iCmdArg, &argv[iCmdArg], virtualBox, session };
867 rcExit = pCmd->pfnHandler(&handlerArg);
868
869 /* Although all handlers should always close the session if they open it,
870 * we do it here just in case if some of the handlers contains a bug --
871 * leaving the direct session not closed will turn the machine state to
872 * Aborted which may have unwanted side effects like killing the saved
873 * state file (if the machine was in the Saved state before). */
874 session->UnlockMachine();
875 }
876
877 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
878 }
879 else
880 {
881 com::ErrorInfo info;
882 RTMsgError(VBoxManage::tr("Failed to create a session object!"));
883 if (!info.isFullAvailable() && !info.isBasicAvailable())
884 com::GluePrintRCMessage(hrc);
885 else
886 com::GluePrintErrorInfo(info);
887 }
888 }
889 else
890 {
891 com::ErrorInfo info;
892 RTMsgError(VBoxManage::tr("Failed to create the VirtualBox object!"));
893 if (!info.isFullAvailable() && !info.isBasicAvailable())
894 {
895 com::GluePrintRCMessage(hrc);
896 RTMsgError(VBoxManage::tr("Most likely, the VirtualBox COM server is not running or failed to start."));
897 }
898 else
899 com::GluePrintErrorInfo(info);
900 }
901
902#ifdef VBOX_WITH_VBOXMANAGE_NLS
903 /* VirtualBox event callback unregistration. */
904 if (ptrEventListner.isNotNull())
905 {
906 ComPtr<IEventSource> pES;
907 HRESULT hrc1 = virtualBox->COMGETTER(EventSource)(pES.asOutParam());
908 if (pES.isNotNull())
909 {
910 hrc1 = pES->UnregisterListener(ptrEventListner);
911 if (FAILED(hrc1))
912 LogRel(("Failed to unregister listener, %Rhrc", hrc1));
913 }
914 ptrEventListner.setNull();
915 }
916#endif
917 /*
918 * Terminate COM, make sure the virtualBox object has been released.
919 */
920 virtualBox.setNull();
921 virtualBoxClient.setNull();
922 NativeEventQueue::getMainEventQueue()->processEventQueue(0);
923 com::Shutdown();
924 }
925 else
926 {
927 /*
928 * The command needs no COM.
929 */
930 HandlerArg handlerArg;
931 handlerArg.argc = argc - iCmdArg;
932 handlerArg.argv = &argv[iCmdArg];
933 rcExit = pCmd->pfnHandler(&handlerArg);
934 }
935
936#ifdef VBOX_WITH_VBOXMANAGE_NLS
937 if (pTranslator != NULL)
938 {
939 pTranslator->release();
940 pTranslator = NULL;
941 pTrComponent = NULL;
942 }
943#endif
944
945 if (papszResponseFileArgs)
946 {
947 RTGetOptArgvFree(papszResponseFileArgs);
948 RTMemFree(papszNewArgv);
949 }
950
951 return rcExit;
952#else /* VBOX_ONLY_DOCS */
953 return RTEXITCODE_SUCCESS;
954#endif /* VBOX_ONLY_DOCS */
955}
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