VirtualBox

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

Last change on this file since 54731 was 53927, checked in by vboxsync, 10 years ago

VBoxManage: fix return code if a VM didn't start successfully

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.6 KB
Line 
1/* $Id: VBoxManageMisc.cpp 53927 2015-01-22 16:36:25Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2013 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/VirtualBox.h>
30#endif /* !VBOX_ONLY_DOCS */
31
32#include <iprt/asm.h>
33#include <iprt/buildconfig.h>
34#include <iprt/cidr.h>
35#include <iprt/ctype.h>
36#include <iprt/dir.h>
37#include <iprt/env.h>
38#include <VBox/err.h>
39#include <iprt/file.h>
40#include <iprt/initterm.h>
41#include <iprt/param.h>
42#include <iprt/path.h>
43#include <iprt/stream.h>
44#include <iprt/string.h>
45#include <iprt/stdarg.h>
46#include <iprt/thread.h>
47#include <iprt/uuid.h>
48#include <iprt/getopt.h>
49#include <iprt/ctype.h>
50#include <VBox/version.h>
51#include <VBox/log.h>
52
53#include "VBoxManage.h"
54
55#include <list>
56
57using namespace com;
58
59
60
61int handleRegisterVM(HandlerArg *a)
62{
63 HRESULT rc;
64
65 if (a->argc != 1)
66 return errorSyntax(USAGE_REGISTERVM, "Incorrect number of parameters");
67
68 ComPtr<IMachine> machine;
69 /** @todo Ugly hack to get both the API interpretation of relative paths
70 * and the client's interpretation of relative paths. Remove after the API
71 * has been redesigned. */
72 rc = a->virtualBox->OpenMachine(Bstr(a->argv[0]).raw(),
73 machine.asOutParam());
74 if (rc == VBOX_E_FILE_ERROR)
75 {
76 char szVMFileAbs[RTPATH_MAX] = "";
77 int vrc = RTPathAbs(a->argv[0], szVMFileAbs, sizeof(szVMFileAbs));
78 if (RT_FAILURE(vrc))
79 {
80 RTMsgError("Cannot convert filename \"%s\" to absolute path", a->argv[0]);
81 return 1;
82 }
83 CHECK_ERROR(a->virtualBox, OpenMachine(Bstr(szVMFileAbs).raw(),
84 machine.asOutParam()));
85 }
86 else if (FAILED(rc))
87 CHECK_ERROR(a->virtualBox, OpenMachine(Bstr(a->argv[0]).raw(),
88 machine.asOutParam()));
89 if (SUCCEEDED(rc))
90 {
91 ASSERT(machine);
92 CHECK_ERROR(a->virtualBox, RegisterMachine(machine));
93 }
94 return SUCCEEDED(rc) ? 0 : 1;
95}
96
97static const RTGETOPTDEF g_aUnregisterVMOptions[] =
98{
99 { "--delete", 'd', RTGETOPT_REQ_NOTHING },
100 { "-delete", 'd', RTGETOPT_REQ_NOTHING }, // deprecated
101};
102
103int handleUnregisterVM(HandlerArg *a)
104{
105 HRESULT rc;
106 const char *VMName = NULL;
107 bool fDelete = false;
108
109 int c;
110 RTGETOPTUNION ValueUnion;
111 RTGETOPTSTATE GetState;
112 // start at 0 because main() has hacked both the argc and argv given to us
113 RTGetOptInit(&GetState, a->argc, a->argv, g_aUnregisterVMOptions, RT_ELEMENTS(g_aUnregisterVMOptions),
114 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
115 while ((c = RTGetOpt(&GetState, &ValueUnion)))
116 {
117 switch (c)
118 {
119 case 'd': // --delete
120 fDelete = true;
121 break;
122
123 case VINF_GETOPT_NOT_OPTION:
124 if (!VMName)
125 VMName = ValueUnion.psz;
126 else
127 return errorSyntax(USAGE_UNREGISTERVM, "Invalid parameter '%s'", ValueUnion.psz);
128 break;
129
130 default:
131 if (c > 0)
132 {
133 if (RT_C_IS_PRINT(c))
134 return errorSyntax(USAGE_UNREGISTERVM, "Invalid option -%c", c);
135 else
136 return errorSyntax(USAGE_UNREGISTERVM, "Invalid option case %i", c);
137 }
138 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
139 return errorSyntax(USAGE_UNREGISTERVM, "unknown option: %s\n", ValueUnion.psz);
140 else if (ValueUnion.pDef)
141 return errorSyntax(USAGE_UNREGISTERVM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
142 else
143 return errorSyntax(USAGE_UNREGISTERVM, "error: %Rrs", c);
144 }
145 }
146
147 /* check for required options */
148 if (!VMName)
149 return errorSyntax(USAGE_UNREGISTERVM, "VM name required");
150
151 ComPtr<IMachine> machine;
152 CHECK_ERROR_RET(a->virtualBox, FindMachine(Bstr(VMName).raw(),
153 machine.asOutParam()),
154 RTEXITCODE_FAILURE);
155 SafeIfaceArray<IMedium> aMedia;
156 CHECK_ERROR_RET(machine, Unregister(CleanupMode_DetachAllReturnHardDisksOnly,
157 ComSafeArrayAsOutParam(aMedia)),
158 RTEXITCODE_FAILURE);
159 if (fDelete)
160 {
161 ComPtr<IProgress> pProgress;
162 CHECK_ERROR_RET(machine, DeleteConfig(ComSafeArrayAsInParam(aMedia), pProgress.asOutParam()),
163 RTEXITCODE_FAILURE);
164
165 rc = showProgress(pProgress);
166 CHECK_PROGRESS_ERROR_RET(pProgress, ("Machine delete failed"), RTEXITCODE_FAILURE);
167 }
168 else
169 {
170 /* Note that the IMachine::Unregister method will return the medium
171 * reference in a sane order, which means that closing will normally
172 * succeed, unless there is still another machine which uses the
173 * medium. No harm done if we ignore the error. */
174 for (size_t i = 0; i < aMedia.size(); i++)
175 {
176 IMedium *pMedium = aMedia[i];
177 if (pMedium)
178 rc = pMedium->Close();
179 }
180 rc = S_OK;
181 }
182 return RTEXITCODE_SUCCESS;
183}
184
185static const RTGETOPTDEF g_aCreateVMOptions[] =
186{
187 { "--name", 'n', RTGETOPT_REQ_STRING },
188 { "-name", 'n', RTGETOPT_REQ_STRING },
189 { "--groups", 'g', RTGETOPT_REQ_STRING },
190 { "--basefolder", 'p', RTGETOPT_REQ_STRING },
191 { "-basefolder", 'p', RTGETOPT_REQ_STRING },
192 { "--ostype", 'o', RTGETOPT_REQ_STRING },
193 { "-ostype", 'o', RTGETOPT_REQ_STRING },
194 { "--uuid", 'u', RTGETOPT_REQ_UUID },
195 { "-uuid", 'u', RTGETOPT_REQ_UUID },
196 { "--register", 'r', RTGETOPT_REQ_NOTHING },
197 { "-register", 'r', RTGETOPT_REQ_NOTHING },
198};
199
200int handleCreateVM(HandlerArg *a)
201{
202 HRESULT rc;
203 Bstr bstrBaseFolder;
204 Bstr bstrName;
205 Bstr bstrOsTypeId;
206 Bstr bstrUuid;
207 bool fRegister = false;
208 com::SafeArray<BSTR> groups;
209
210 int c;
211 RTGETOPTUNION ValueUnion;
212 RTGETOPTSTATE GetState;
213 // start at 0 because main() has hacked both the argc and argv given to us
214 RTGetOptInit(&GetState, a->argc, a->argv, g_aCreateVMOptions, RT_ELEMENTS(g_aCreateVMOptions),
215 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
216 while ((c = RTGetOpt(&GetState, &ValueUnion)))
217 {
218 switch (c)
219 {
220 case 'n': // --name
221 bstrName = ValueUnion.psz;
222 break;
223
224 case 'g': // --groups
225 parseGroups(ValueUnion.psz, &groups);
226 break;
227
228 case 'p': // --basefolder
229 bstrBaseFolder = ValueUnion.psz;
230 break;
231
232 case 'o': // --ostype
233 bstrOsTypeId = ValueUnion.psz;
234 break;
235
236 case 'u': // --uuid
237 bstrUuid = Guid(ValueUnion.Uuid).toUtf16().raw();
238 break;
239
240 case 'r': // --register
241 fRegister = true;
242 break;
243
244 default:
245 return errorGetOpt(USAGE_CREATEVM, c, &ValueUnion);
246 }
247 }
248
249 /* check for required options */
250 if (bstrName.isEmpty())
251 return errorSyntax(USAGE_CREATEVM, "Parameter --name is required");
252
253 do
254 {
255 Bstr createFlags;
256 if (!bstrUuid.isEmpty())
257 createFlags = BstrFmt("UUID=%ls", bstrUuid.raw());
258 Bstr bstrPrimaryGroup;
259 if (groups.size())
260 bstrPrimaryGroup = groups[0];
261 Bstr bstrSettingsFile;
262 CHECK_ERROR_BREAK(a->virtualBox,
263 ComposeMachineFilename(bstrName.raw(),
264 bstrPrimaryGroup.raw(),
265 createFlags.raw(),
266 bstrBaseFolder.raw(),
267 bstrSettingsFile.asOutParam()));
268 ComPtr<IMachine> machine;
269 CHECK_ERROR_BREAK(a->virtualBox,
270 CreateMachine(bstrSettingsFile.raw(),
271 bstrName.raw(),
272 ComSafeArrayAsInParam(groups),
273 bstrOsTypeId.raw(),
274 createFlags.raw(),
275 machine.asOutParam()));
276
277 CHECK_ERROR_BREAK(machine, SaveSettings());
278 if (fRegister)
279 {
280 CHECK_ERROR_BREAK(a->virtualBox, RegisterMachine(machine));
281 }
282 Bstr uuid;
283 CHECK_ERROR_BREAK(machine, COMGETTER(Id)(uuid.asOutParam()));
284 Bstr settingsFile;
285 CHECK_ERROR_BREAK(machine, COMGETTER(SettingsFilePath)(settingsFile.asOutParam()));
286 RTPrintf("Virtual machine '%ls' is created%s.\n"
287 "UUID: %s\n"
288 "Settings file: '%ls'\n",
289 bstrName.raw(), fRegister ? " and registered" : "",
290 Utf8Str(uuid).c_str(), settingsFile.raw());
291 }
292 while (0);
293
294 return SUCCEEDED(rc) ? 0 : 1;
295}
296
297static const RTGETOPTDEF g_aCloneVMOptions[] =
298{
299 { "--snapshot", 's', RTGETOPT_REQ_STRING },
300 { "--name", 'n', RTGETOPT_REQ_STRING },
301 { "--groups", 'g', RTGETOPT_REQ_STRING },
302 { "--mode", 'm', RTGETOPT_REQ_STRING },
303 { "--options", 'o', RTGETOPT_REQ_STRING },
304 { "--register", 'r', RTGETOPT_REQ_NOTHING },
305 { "--basefolder", 'p', RTGETOPT_REQ_STRING },
306 { "--uuid", 'u', RTGETOPT_REQ_UUID },
307};
308
309static int parseCloneMode(const char *psz, CloneMode_T *pMode)
310{
311 if (!RTStrICmp(psz, "machine"))
312 *pMode = CloneMode_MachineState;
313 else if (!RTStrICmp(psz, "machineandchildren"))
314 *pMode = CloneMode_MachineAndChildStates;
315 else if (!RTStrICmp(psz, "all"))
316 *pMode = CloneMode_AllStates;
317 else
318 return VERR_PARSE_ERROR;
319
320 return VINF_SUCCESS;
321}
322
323static int parseCloneOptions(const char *psz, com::SafeArray<CloneOptions_T> *options)
324{
325 int rc = VINF_SUCCESS;
326 while (psz && *psz && RT_SUCCESS(rc))
327 {
328 size_t len;
329 const char *pszComma = strchr(psz, ',');
330 if (pszComma)
331 len = pszComma - psz;
332 else
333 len = strlen(psz);
334 if (len > 0)
335 {
336 if (!RTStrNICmp(psz, "KeepAllMACs", len))
337 options->push_back(CloneOptions_KeepAllMACs);
338 else if (!RTStrNICmp(psz, "KeepNATMACs", len))
339 options->push_back(CloneOptions_KeepNATMACs);
340 else if (!RTStrNICmp(psz, "KeepDiskNames", len))
341 options->push_back(CloneOptions_KeepDiskNames);
342 else if ( !RTStrNICmp(psz, "Link", len)
343 || !RTStrNICmp(psz, "Linked", len))
344 options->push_back(CloneOptions_Link);
345 else
346 rc = VERR_PARSE_ERROR;
347 }
348 if (pszComma)
349 psz += len + 1;
350 else
351 psz += len;
352 }
353
354 return rc;
355}
356
357int handleCloneVM(HandlerArg *a)
358{
359 HRESULT rc;
360 const char *pszSrcName = NULL;
361 const char *pszSnapshotName = NULL;
362 CloneMode_T mode = CloneMode_MachineState;
363 com::SafeArray<CloneOptions_T> options;
364 const char *pszTrgName = NULL;
365 const char *pszTrgBaseFolder = NULL;
366 bool fRegister = false;
367 Bstr bstrUuid;
368 com::SafeArray<BSTR> groups;
369
370 int c;
371 RTGETOPTUNION ValueUnion;
372 RTGETOPTSTATE GetState;
373 // start at 0 because main() has hacked both the argc and argv given to us
374 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloneVMOptions, RT_ELEMENTS(g_aCloneVMOptions),
375 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
376 while ((c = RTGetOpt(&GetState, &ValueUnion)))
377 {
378 switch (c)
379 {
380 case 's': // --snapshot
381 pszSnapshotName = ValueUnion.psz;
382 break;
383
384 case 'n': // --name
385 pszTrgName = ValueUnion.psz;
386 break;
387
388 case 'g': // --groups
389 parseGroups(ValueUnion.psz, &groups);
390 break;
391
392 case 'p': // --basefolder
393 pszTrgBaseFolder = ValueUnion.psz;
394 break;
395
396 case 'm': // --mode
397 if (RT_FAILURE(parseCloneMode(ValueUnion.psz, &mode)))
398 return errorArgument("Invalid clone mode '%s'\n", ValueUnion.psz);
399 break;
400
401 case 'o': // --options
402 if (RT_FAILURE(parseCloneOptions(ValueUnion.psz, &options)))
403 return errorArgument("Invalid clone options '%s'\n", ValueUnion.psz);
404 break;
405
406 case 'u': // --uuid
407 bstrUuid = Guid(ValueUnion.Uuid).toUtf16().raw();
408 break;
409
410 case 'r': // --register
411 fRegister = true;
412 break;
413
414 case VINF_GETOPT_NOT_OPTION:
415 if (!pszSrcName)
416 pszSrcName = ValueUnion.psz;
417 else
418 return errorSyntax(USAGE_CLONEVM, "Invalid parameter '%s'", ValueUnion.psz);
419 break;
420
421 default:
422 return errorGetOpt(USAGE_CLONEVM, c, &ValueUnion);
423 }
424 }
425
426 /* Check for required options */
427 if (!pszSrcName)
428 return errorSyntax(USAGE_CLONEVM, "VM name required");
429
430 /* Get the machine object */
431 ComPtr<IMachine> srcMachine;
432 CHECK_ERROR_RET(a->virtualBox, FindMachine(Bstr(pszSrcName).raw(),
433 srcMachine.asOutParam()),
434 RTEXITCODE_FAILURE);
435
436 /* If a snapshot name/uuid was given, get the particular machine of this
437 * snapshot. */
438 if (pszSnapshotName)
439 {
440 ComPtr<ISnapshot> srcSnapshot;
441 CHECK_ERROR_RET(srcMachine, FindSnapshot(Bstr(pszSnapshotName).raw(),
442 srcSnapshot.asOutParam()),
443 RTEXITCODE_FAILURE);
444 CHECK_ERROR_RET(srcSnapshot, COMGETTER(Machine)(srcMachine.asOutParam()),
445 RTEXITCODE_FAILURE);
446 }
447
448 /* Default name necessary? */
449 if (!pszTrgName)
450 pszTrgName = RTStrAPrintf2("%s Clone", pszSrcName);
451
452 Bstr createFlags;
453 if (!bstrUuid.isEmpty())
454 createFlags = BstrFmt("UUID=%ls", bstrUuid.raw());
455 Bstr bstrPrimaryGroup;
456 if (groups.size())
457 bstrPrimaryGroup = groups[0];
458 Bstr bstrSettingsFile;
459 CHECK_ERROR_RET(a->virtualBox,
460 ComposeMachineFilename(Bstr(pszTrgName).raw(),
461 bstrPrimaryGroup.raw(),
462 createFlags.raw(),
463 Bstr(pszTrgBaseFolder).raw(),
464 bstrSettingsFile.asOutParam()),
465 RTEXITCODE_FAILURE);
466
467 ComPtr<IMachine> trgMachine;
468 CHECK_ERROR_RET(a->virtualBox, CreateMachine(bstrSettingsFile.raw(),
469 Bstr(pszTrgName).raw(),
470 ComSafeArrayAsInParam(groups),
471 NULL,
472 createFlags.raw(),
473 trgMachine.asOutParam()),
474 RTEXITCODE_FAILURE);
475
476 /* Start the cloning */
477 ComPtr<IProgress> progress;
478 CHECK_ERROR_RET(srcMachine, CloneTo(trgMachine,
479 mode,
480 ComSafeArrayAsInParam(options),
481 progress.asOutParam()),
482 RTEXITCODE_FAILURE);
483 rc = showProgress(progress);
484 CHECK_PROGRESS_ERROR_RET(progress, ("Clone VM failed"), RTEXITCODE_FAILURE);
485
486 if (fRegister)
487 CHECK_ERROR_RET(a->virtualBox, RegisterMachine(trgMachine), RTEXITCODE_FAILURE);
488
489 Bstr bstrNewName;
490 CHECK_ERROR_RET(trgMachine, COMGETTER(Name)(bstrNewName.asOutParam()), RTEXITCODE_FAILURE);
491 RTPrintf("Machine has been successfully cloned as \"%ls\"\n", bstrNewName.raw());
492
493 return RTEXITCODE_SUCCESS;
494}
495
496int handleStartVM(HandlerArg *a)
497{
498 HRESULT rc = S_OK;
499 std::list<const char *> VMs;
500 Bstr sessionType;
501
502 static const RTGETOPTDEF s_aStartVMOptions[] =
503 {
504 { "--type", 't', RTGETOPT_REQ_STRING },
505 { "-type", 't', RTGETOPT_REQ_STRING }, // deprecated
506 };
507 int c;
508 RTGETOPTUNION ValueUnion;
509 RTGETOPTSTATE GetState;
510 // start at 0 because main() has hacked both the argc and argv given to us
511 RTGetOptInit(&GetState, a->argc, a->argv, s_aStartVMOptions, RT_ELEMENTS(s_aStartVMOptions),
512 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
513 while ((c = RTGetOpt(&GetState, &ValueUnion)))
514 {
515 switch (c)
516 {
517 case 't': // --type
518 if (!RTStrICmp(ValueUnion.psz, "gui"))
519 {
520 sessionType = "gui";
521 }
522#ifdef VBOX_WITH_VBOXSDL
523 else if (!RTStrICmp(ValueUnion.psz, "sdl"))
524 {
525 sessionType = "sdl";
526 }
527#endif
528#ifdef VBOX_WITH_HEADLESS
529 else if (!RTStrICmp(ValueUnion.psz, "capture"))
530 {
531 sessionType = "capture";
532 }
533 else if (!RTStrICmp(ValueUnion.psz, "headless"))
534 {
535 sessionType = "headless";
536 }
537#endif
538 else
539 sessionType = ValueUnion.psz;
540 break;
541
542 case VINF_GETOPT_NOT_OPTION:
543 VMs.push_back(ValueUnion.psz);
544 break;
545
546 default:
547 if (c > 0)
548 {
549 if (RT_C_IS_PRINT(c))
550 return errorSyntax(USAGE_STARTVM, "Invalid option -%c", c);
551 else
552 return errorSyntax(USAGE_STARTVM, "Invalid option case %i", c);
553 }
554 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
555 return errorSyntax(USAGE_STARTVM, "unknown option: %s\n", ValueUnion.psz);
556 else if (ValueUnion.pDef)
557 return errorSyntax(USAGE_STARTVM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
558 else
559 return errorSyntax(USAGE_STARTVM, "error: %Rrs", c);
560 }
561 }
562
563 /* check for required options */
564 if (VMs.empty())
565 return errorSyntax(USAGE_STARTVM, "at least one VM name or uuid required");
566
567 for (std::list<const char *>::const_iterator it = VMs.begin();
568 it != VMs.end();
569 ++it)
570 {
571 HRESULT rc2 = rc;
572 const char *pszVM = *it;
573 ComPtr<IMachine> machine;
574 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(pszVM).raw(),
575 machine.asOutParam()));
576 if (machine)
577 {
578 Bstr env;
579#if defined(RT_OS_LINUX) || defined(RT_OS_SOLARIS)
580 /* make sure the VM process will start on the same display as VBoxManage */
581 Utf8Str str;
582 const char *pszDisplay = RTEnvGet("DISPLAY");
583 if (pszDisplay)
584 str = Utf8StrFmt("DISPLAY=%s\n", pszDisplay);
585 const char *pszXAuth = RTEnvGet("XAUTHORITY");
586 if (pszXAuth)
587 str.append(Utf8StrFmt("XAUTHORITY=%s\n", pszXAuth));
588 env = str;
589#endif
590 ComPtr<IProgress> progress;
591 CHECK_ERROR(machine, LaunchVMProcess(a->session, sessionType.raw(),
592 env.raw(), progress.asOutParam()));
593 if (SUCCEEDED(rc) && !progress.isNull())
594 {
595 RTPrintf("Waiting for VM \"%s\" to power on...\n", pszVM);
596 CHECK_ERROR(progress, WaitForCompletion(-1));
597 if (SUCCEEDED(rc))
598 {
599 BOOL completed = true;
600 CHECK_ERROR(progress, COMGETTER(Completed)(&completed));
601 if (SUCCEEDED(rc))
602 {
603 ASSERT(completed);
604
605 LONG iRc;
606 CHECK_ERROR(progress, COMGETTER(ResultCode)(&iRc));
607 if (SUCCEEDED(rc))
608 {
609 if (SUCCEEDED(rc))
610 RTPrintf("VM \"%s\" has been successfully started.\n", pszVM);
611 else
612 {
613 ProgressErrorInfo info(progress);
614 com::GluePrintErrorInfo(info);
615 }
616 rc = iRc;
617 }
618 }
619 }
620 }
621 }
622
623 /* it's important to always close sessions */
624 a->session->UnlockMachine();
625
626 /* make sure that we remember the failed state */
627 if (FAILED(rc2))
628 rc = rc2;
629 }
630
631 return SUCCEEDED(rc) ? 0 : 1;
632}
633
634int handleDiscardState(HandlerArg *a)
635{
636 HRESULT rc;
637
638 if (a->argc != 1)
639 return errorSyntax(USAGE_DISCARDSTATE, "Incorrect number of parameters");
640
641 ComPtr<IMachine> machine;
642 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
643 machine.asOutParam()));
644 if (machine)
645 {
646 do
647 {
648 /* we have to open a session for this task */
649 CHECK_ERROR_BREAK(machine, LockMachine(a->session, LockType_Write));
650 do
651 {
652 ComPtr<IConsole> console;
653 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
654 CHECK_ERROR_BREAK(console, DiscardSavedState(true /* fDeleteFile */));
655 } while (0);
656 CHECK_ERROR_BREAK(a->session, UnlockMachine());
657 } while (0);
658 }
659
660 return SUCCEEDED(rc) ? 0 : 1;
661}
662
663int handleAdoptState(HandlerArg *a)
664{
665 HRESULT rc;
666
667 if (a->argc != 2)
668 return errorSyntax(USAGE_ADOPTSTATE, "Incorrect number of parameters");
669
670 ComPtr<IMachine> machine;
671 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
672 machine.asOutParam()));
673 if (machine)
674 {
675 char szStateFileAbs[RTPATH_MAX] = "";
676 int vrc = RTPathAbs(a->argv[1], szStateFileAbs, sizeof(szStateFileAbs));
677 if (RT_FAILURE(vrc))
678 {
679 RTMsgError("Cannot convert filename \"%s\" to absolute path", a->argv[0]);
680 return 1;
681 }
682
683 do
684 {
685 /* we have to open a session for this task */
686 CHECK_ERROR_BREAK(machine, LockMachine(a->session, LockType_Write));
687 do
688 {
689 ComPtr<IConsole> console;
690 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
691 CHECK_ERROR_BREAK(console, AdoptSavedState(Bstr(szStateFileAbs).raw()));
692 } while (0);
693 CHECK_ERROR_BREAK(a->session, UnlockMachine());
694 } while (0);
695 }
696
697 return SUCCEEDED(rc) ? 0 : 1;
698}
699
700int handleGetExtraData(HandlerArg *a)
701{
702 HRESULT rc = S_OK;
703
704 if (a->argc != 2)
705 return errorSyntax(USAGE_GETEXTRADATA, "Incorrect number of parameters");
706
707 /* global data? */
708 if (!strcmp(a->argv[0], "global"))
709 {
710 /* enumeration? */
711 if (!strcmp(a->argv[1], "enumerate"))
712 {
713 SafeArray<BSTR> aKeys;
714 CHECK_ERROR(a->virtualBox, GetExtraDataKeys(ComSafeArrayAsOutParam(aKeys)));
715
716 for (size_t i = 0;
717 i < aKeys.size();
718 ++i)
719 {
720 Bstr bstrKey(aKeys[i]);
721 Bstr bstrValue;
722 CHECK_ERROR(a->virtualBox, GetExtraData(bstrKey.raw(),
723 bstrValue.asOutParam()));
724
725 RTPrintf("Key: %ls, Value: %ls\n", bstrKey.raw(), bstrValue.raw());
726 }
727 }
728 else
729 {
730 Bstr value;
731 CHECK_ERROR(a->virtualBox, GetExtraData(Bstr(a->argv[1]).raw(),
732 value.asOutParam()));
733 if (!value.isEmpty())
734 RTPrintf("Value: %ls\n", value.raw());
735 else
736 RTPrintf("No value set!\n");
737 }
738 }
739 else
740 {
741 ComPtr<IMachine> machine;
742 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
743 machine.asOutParam()));
744 if (machine)
745 {
746 /* enumeration? */
747 if (!strcmp(a->argv[1], "enumerate"))
748 {
749 SafeArray<BSTR> aKeys;
750 CHECK_ERROR(machine, GetExtraDataKeys(ComSafeArrayAsOutParam(aKeys)));
751
752 for (size_t i = 0;
753 i < aKeys.size();
754 ++i)
755 {
756 Bstr bstrKey(aKeys[i]);
757 Bstr bstrValue;
758 CHECK_ERROR(machine, GetExtraData(bstrKey.raw(),
759 bstrValue.asOutParam()));
760
761 RTPrintf("Key: %ls, Value: %ls\n", bstrKey.raw(), bstrValue.raw());
762 }
763 }
764 else
765 {
766 Bstr value;
767 CHECK_ERROR(machine, GetExtraData(Bstr(a->argv[1]).raw(),
768 value.asOutParam()));
769 if (!value.isEmpty())
770 RTPrintf("Value: %ls\n", value.raw());
771 else
772 RTPrintf("No value set!\n");
773 }
774 }
775 }
776 return SUCCEEDED(rc) ? 0 : 1;
777}
778
779int handleSetExtraData(HandlerArg *a)
780{
781 HRESULT rc = S_OK;
782
783 if (a->argc < 2)
784 return errorSyntax(USAGE_SETEXTRADATA, "Not enough parameters");
785
786 /* global data? */
787 if (!strcmp(a->argv[0], "global"))
788 {
789 /** @todo passing NULL is deprecated */
790 if (a->argc < 3)
791 CHECK_ERROR(a->virtualBox, SetExtraData(Bstr(a->argv[1]).raw(),
792 NULL));
793 else if (a->argc == 3)
794 CHECK_ERROR(a->virtualBox, SetExtraData(Bstr(a->argv[1]).raw(),
795 Bstr(a->argv[2]).raw()));
796 else
797 return errorSyntax(USAGE_SETEXTRADATA, "Too many parameters");
798 }
799 else
800 {
801 ComPtr<IMachine> machine;
802 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
803 machine.asOutParam()));
804 if (machine)
805 {
806 /** @todo passing NULL is deprecated */
807 if (a->argc < 3)
808 CHECK_ERROR(machine, SetExtraData(Bstr(a->argv[1]).raw(),
809 NULL));
810 else if (a->argc == 3)
811 CHECK_ERROR(machine, SetExtraData(Bstr(a->argv[1]).raw(),
812 Bstr(a->argv[2]).raw()));
813 else
814 return errorSyntax(USAGE_SETEXTRADATA, "Too many parameters");
815 }
816 }
817 return SUCCEEDED(rc) ? 0 : 1;
818}
819
820int handleSetProperty(HandlerArg *a)
821{
822 HRESULT rc;
823
824 /* there must be two arguments: property name and value */
825 if (a->argc != 2)
826 return errorSyntax(USAGE_SETPROPERTY, "Incorrect number of parameters");
827
828 ComPtr<ISystemProperties> systemProperties;
829 a->virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
830
831 if (!strcmp(a->argv[0], "machinefolder"))
832 {
833 /* reset to default? */
834 if (!strcmp(a->argv[1], "default"))
835 CHECK_ERROR(systemProperties, COMSETTER(DefaultMachineFolder)(NULL));
836 else
837 CHECK_ERROR(systemProperties, COMSETTER(DefaultMachineFolder)(Bstr(a->argv[1]).raw()));
838 }
839 else if (!strcmp(a->argv[0], "hwvirtexclusive"))
840 {
841 bool fHwVirtExclusive;
842
843 if (!strcmp(a->argv[1], "on"))
844 fHwVirtExclusive = true;
845 else if (!strcmp(a->argv[1], "off"))
846 fHwVirtExclusive = false;
847 else
848 return errorArgument("Invalid hwvirtexclusive argument '%s'", a->argv[1]);
849 CHECK_ERROR(systemProperties, COMSETTER(ExclusiveHwVirt)(fHwVirtExclusive));
850 }
851 else if ( !strcmp(a->argv[0], "vrdeauthlibrary")
852 || !strcmp(a->argv[0], "vrdpauthlibrary"))
853 {
854 if (!strcmp(a->argv[0], "vrdpauthlibrary"))
855 RTStrmPrintf(g_pStdErr, "Warning: 'vrdpauthlibrary' is deprecated. Use 'vrdeauthlibrary'.\n");
856
857 /* reset to default? */
858 if (!strcmp(a->argv[1], "default"))
859 CHECK_ERROR(systemProperties, COMSETTER(VRDEAuthLibrary)(NULL));
860 else
861 CHECK_ERROR(systemProperties, COMSETTER(VRDEAuthLibrary)(Bstr(a->argv[1]).raw()));
862 }
863 else if (!strcmp(a->argv[0], "websrvauthlibrary"))
864 {
865 /* reset to default? */
866 if (!strcmp(a->argv[1], "default"))
867 CHECK_ERROR(systemProperties, COMSETTER(WebServiceAuthLibrary)(NULL));
868 else
869 CHECK_ERROR(systemProperties, COMSETTER(WebServiceAuthLibrary)(Bstr(a->argv[1]).raw()));
870 }
871 else if (!strcmp(a->argv[0], "vrdeextpack"))
872 {
873 /* disable? */
874 if (!strcmp(a->argv[1], "null"))
875 CHECK_ERROR(systemProperties, COMSETTER(DefaultVRDEExtPack)(NULL));
876 else
877 CHECK_ERROR(systemProperties, COMSETTER(DefaultVRDEExtPack)(Bstr(a->argv[1]).raw()));
878 }
879 else if (!strcmp(a->argv[0], "loghistorycount"))
880 {
881 uint32_t uVal;
882 int vrc;
883 vrc = RTStrToUInt32Ex(a->argv[1], NULL, 0, &uVal);
884 if (vrc != VINF_SUCCESS)
885 return errorArgument("Error parsing Log history count '%s'", a->argv[1]);
886 CHECK_ERROR(systemProperties, COMSETTER(LogHistoryCount)(uVal));
887 }
888 else if (!strcmp(a->argv[0], "autostartdbpath"))
889 {
890 /* disable? */
891 if (!strcmp(a->argv[1], "null"))
892 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(NULL));
893 else
894 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(Bstr(a->argv[1]).raw()));
895 }
896 else if (!strcmp(a->argv[0], "defaultfrontend"))
897 {
898 Bstr bstrDefaultFrontend(a->argv[1]);
899 if (!strcmp(a->argv[1], "default"))
900 bstrDefaultFrontend.setNull();
901 CHECK_ERROR(systemProperties, COMSETTER(DefaultFrontend)(bstrDefaultFrontend.raw()));
902 }
903 else
904 return errorSyntax(USAGE_SETPROPERTY, "Invalid parameter '%s'", a->argv[0]);
905
906 return SUCCEEDED(rc) ? 0 : 1;
907}
908
909int handleSharedFolder(HandlerArg *a)
910{
911 HRESULT rc;
912
913 /* we need at least a command and target */
914 if (a->argc < 2)
915 return errorSyntax(USAGE_SHAREDFOLDER, "Not enough parameters");
916
917 ComPtr<IMachine> machine;
918 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[1]).raw(),
919 machine.asOutParam()));
920 if (!machine)
921 return 1;
922
923 if (!strcmp(a->argv[0], "add"))
924 {
925 /* we need at least four more parameters */
926 if (a->argc < 5)
927 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Not enough parameters");
928
929 char *name = NULL;
930 char *hostpath = NULL;
931 bool fTransient = false;
932 bool fWritable = true;
933 bool fAutoMount = false;
934
935 for (int i = 2; i < a->argc; i++)
936 {
937 if ( !strcmp(a->argv[i], "--name")
938 || !strcmp(a->argv[i], "-name"))
939 {
940 if (a->argc <= i + 1 || !*a->argv[i+1])
941 return errorArgument("Missing argument to '%s'", a->argv[i]);
942 i++;
943 name = a->argv[i];
944 }
945 else if ( !strcmp(a->argv[i], "--hostpath")
946 || !strcmp(a->argv[i], "-hostpath"))
947 {
948 if (a->argc <= i + 1 || !*a->argv[i+1])
949 return errorArgument("Missing argument to '%s'", a->argv[i]);
950 i++;
951 hostpath = a->argv[i];
952 }
953 else if ( !strcmp(a->argv[i], "--readonly")
954 || !strcmp(a->argv[i], "-readonly"))
955 {
956 fWritable = false;
957 }
958 else if ( !strcmp(a->argv[i], "--transient")
959 || !strcmp(a->argv[i], "-transient"))
960 {
961 fTransient = true;
962 }
963 else if ( !strcmp(a->argv[i], "--automount")
964 || !strcmp(a->argv[i], "-automount"))
965 {
966 fAutoMount = true;
967 }
968 else
969 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
970 }
971
972 if (NULL != strstr(name, " "))
973 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "No spaces allowed in parameter '-name'!");
974
975 /* required arguments */
976 if (!name || !hostpath)
977 {
978 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Parameters --name and --hostpath are required");
979 }
980
981 if (fTransient)
982 {
983 ComPtr<IConsole> console;
984
985 /* open an existing session for the VM */
986 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
987 /* get the session machine */
988 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
989 /* get the session console */
990 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
991
992 CHECK_ERROR(console, CreateSharedFolder(Bstr(name).raw(),
993 Bstr(hostpath).raw(),
994 fWritable, fAutoMount));
995 if (console)
996 a->session->UnlockMachine();
997 }
998 else
999 {
1000 /* open a session for the VM */
1001 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1002
1003 /* get the mutable session machine */
1004 a->session->COMGETTER(Machine)(machine.asOutParam());
1005
1006 CHECK_ERROR(machine, CreateSharedFolder(Bstr(name).raw(),
1007 Bstr(hostpath).raw(),
1008 fWritable, fAutoMount));
1009 if (SUCCEEDED(rc))
1010 CHECK_ERROR(machine, SaveSettings());
1011
1012 a->session->UnlockMachine();
1013 }
1014 }
1015 else if (!strcmp(a->argv[0], "remove"))
1016 {
1017 /* we need at least two more parameters */
1018 if (a->argc < 3)
1019 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Not enough parameters");
1020
1021 char *name = NULL;
1022 bool fTransient = false;
1023
1024 for (int i = 2; i < a->argc; i++)
1025 {
1026 if ( !strcmp(a->argv[i], "--name")
1027 || !strcmp(a->argv[i], "-name"))
1028 {
1029 if (a->argc <= i + 1 || !*a->argv[i+1])
1030 return errorArgument("Missing argument to '%s'", a->argv[i]);
1031 i++;
1032 name = a->argv[i];
1033 }
1034 else if ( !strcmp(a->argv[i], "--transient")
1035 || !strcmp(a->argv[i], "-transient"))
1036 {
1037 fTransient = true;
1038 }
1039 else
1040 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
1041 }
1042
1043 /* required arguments */
1044 if (!name)
1045 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Parameter --name is required");
1046
1047 if (fTransient)
1048 {
1049 ComPtr<IConsole> console;
1050
1051 /* open an existing session for the VM */
1052 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
1053 /* get the session machine */
1054 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
1055 /* get the session console */
1056 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
1057
1058 CHECK_ERROR(console, RemoveSharedFolder(Bstr(name).raw()));
1059
1060 if (console)
1061 a->session->UnlockMachine();
1062 }
1063 else
1064 {
1065 /* open a session for the VM */
1066 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1067
1068 /* get the mutable session machine */
1069 a->session->COMGETTER(Machine)(machine.asOutParam());
1070
1071 CHECK_ERROR(machine, RemoveSharedFolder(Bstr(name).raw()));
1072
1073 /* commit and close the session */
1074 CHECK_ERROR(machine, SaveSettings());
1075 a->session->UnlockMachine();
1076 }
1077 }
1078 else
1079 return errorSyntax(USAGE_SHAREDFOLDER, "Invalid parameter '%s'", Utf8Str(a->argv[0]).c_str());
1080
1081 return 0;
1082}
1083
1084int handleExtPack(HandlerArg *a)
1085{
1086 if (a->argc < 1)
1087 return errorSyntax(USAGE_EXTPACK, "Incorrect number of parameters");
1088
1089 ComObjPtr<IExtPackManager> ptrExtPackMgr;
1090 CHECK_ERROR2_RET(a->virtualBox, COMGETTER(ExtensionPackManager)(ptrExtPackMgr.asOutParam()), RTEXITCODE_FAILURE);
1091
1092 RTGETOPTSTATE GetState;
1093 RTGETOPTUNION ValueUnion;
1094 int ch;
1095 HRESULT hrc = S_OK;
1096
1097 if (!strcmp(a->argv[0], "install"))
1098 {
1099 const char *pszName = NULL;
1100 bool fReplace = false;
1101
1102 static const RTGETOPTDEF s_aInstallOptions[] =
1103 {
1104 { "--replace", 'r', RTGETOPT_REQ_NOTHING },
1105 };
1106
1107 RTGetOptInit(&GetState, a->argc, a->argv, s_aInstallOptions, RT_ELEMENTS(s_aInstallOptions), 1, 0 /*fFlags*/);
1108 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1109 {
1110 switch (ch)
1111 {
1112 case 'r':
1113 fReplace = true;
1114 break;
1115
1116 case VINF_GETOPT_NOT_OPTION:
1117 if (pszName)
1118 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1119 pszName = ValueUnion.psz;
1120 break;
1121
1122 default:
1123 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1124 }
1125 }
1126 if (!pszName)
1127 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack install\"");
1128
1129 char szPath[RTPATH_MAX];
1130 int vrc = RTPathAbs(pszName, szPath, sizeof(szPath));
1131 if (RT_FAILURE(vrc))
1132 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTPathAbs(%s,,) failed with rc=%Rrc", pszName, vrc);
1133
1134 Bstr bstrTarball(szPath);
1135 Bstr bstrName;
1136 ComPtr<IExtPackFile> ptrExtPackFile;
1137 CHECK_ERROR2_RET(ptrExtPackMgr, OpenExtPackFile(bstrTarball.raw(), ptrExtPackFile.asOutParam()), RTEXITCODE_FAILURE);
1138 CHECK_ERROR2_RET(ptrExtPackFile, COMGETTER(Name)(bstrName.asOutParam()), RTEXITCODE_FAILURE);
1139 ComPtr<IProgress> ptrProgress;
1140 CHECK_ERROR2_RET(ptrExtPackFile, Install(fReplace, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1141 hrc = showProgress(ptrProgress);
1142 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to install \"%s\"", szPath), RTEXITCODE_FAILURE);
1143
1144 RTPrintf("Successfully installed \"%ls\".\n", bstrName.raw());
1145 }
1146 else if (!strcmp(a->argv[0], "uninstall"))
1147 {
1148 const char *pszName = NULL;
1149 bool fForced = false;
1150
1151 static const RTGETOPTDEF s_aUninstallOptions[] =
1152 {
1153 { "--force", 'f', RTGETOPT_REQ_NOTHING },
1154 };
1155
1156 RTGetOptInit(&GetState, a->argc, a->argv, s_aUninstallOptions, RT_ELEMENTS(s_aUninstallOptions), 1, 0);
1157 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1158 {
1159 switch (ch)
1160 {
1161 case 'f':
1162 fForced = true;
1163 break;
1164
1165 case VINF_GETOPT_NOT_OPTION:
1166 if (pszName)
1167 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1168 pszName = ValueUnion.psz;
1169 break;
1170
1171 default:
1172 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1173 }
1174 }
1175 if (!pszName)
1176 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack uninstall\"");
1177
1178 Bstr bstrName(pszName);
1179 ComPtr<IProgress> ptrProgress;
1180 CHECK_ERROR2_RET(ptrExtPackMgr, Uninstall(bstrName.raw(), fForced, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1181 hrc = showProgress(ptrProgress);
1182 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to uninstall \"%s\"", pszName), RTEXITCODE_FAILURE);
1183
1184 RTPrintf("Successfully uninstalled \"%s\".\n", pszName);
1185 }
1186 else if (!strcmp(a->argv[0], "cleanup"))
1187 {
1188 if (a->argc > 1)
1189 return errorSyntax(USAGE_EXTPACK, "Too many parameters given to \"extpack cleanup\"");
1190
1191 CHECK_ERROR2_RET(ptrExtPackMgr, Cleanup(), RTEXITCODE_FAILURE);
1192 RTPrintf("Successfully performed extension pack cleanup\n");
1193 }
1194 else
1195 return errorSyntax(USAGE_EXTPACK, "Unknown command \"%s\"", a->argv[0]);
1196
1197 return RTEXITCODE_SUCCESS;
1198}
1199
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