VirtualBox

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

Last change on this file since 42699 was 42444, checked in by vboxsync, 12 years ago

Frontends/VBoxManage: add options to specify passwords through a file

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