VirtualBox

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

Last change on this file since 103068 was 98103, checked in by vboxsync, 18 months ago

Copyright year updates by scm.

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

© 2023 Oracle
ContactPrivacy policyTerms of Use