VirtualBox

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

Last change on this file since 48458 was 48087, checked in by vboxsync, 11 years ago

Frontends/VirtualBox+VBoxManage: when unregistering a VM, also unregister the
hard disk images which are used exclusively (public bug #10311)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.7 KB
Line 
1/* $Id: VBoxManageMisc.cpp 48087 2013-08-27 15:37:30Z 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 (FAILED(iRc))
610 {
611 ProgressErrorInfo info(progress);
612 com::GluePrintErrorInfo(info);
613 }
614 else
615 {
616 RTPrintf("VM \"%s\" has been successfully started.\n", pszVM);
617 }
618 }
619 }
620 }
621 }
622 }
623
624 /* it's important to always close sessions */
625 a->session->UnlockMachine();
626
627 /* make sure that we remember the failed state */
628 if (FAILED(rc2))
629 rc = rc2;
630 }
631
632 return SUCCEEDED(rc) ? 0 : 1;
633}
634
635int handleDiscardState(HandlerArg *a)
636{
637 HRESULT rc;
638
639 if (a->argc != 1)
640 return errorSyntax(USAGE_DISCARDSTATE, "Incorrect number of parameters");
641
642 ComPtr<IMachine> machine;
643 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
644 machine.asOutParam()));
645 if (machine)
646 {
647 do
648 {
649 /* we have to open a session for this task */
650 CHECK_ERROR_BREAK(machine, LockMachine(a->session, LockType_Write));
651 do
652 {
653 ComPtr<IConsole> console;
654 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
655 CHECK_ERROR_BREAK(console, DiscardSavedState(true /* fDeleteFile */));
656 } while (0);
657 CHECK_ERROR_BREAK(a->session, UnlockMachine());
658 } while (0);
659 }
660
661 return SUCCEEDED(rc) ? 0 : 1;
662}
663
664int handleAdoptState(HandlerArg *a)
665{
666 HRESULT rc;
667
668 if (a->argc != 2)
669 return errorSyntax(USAGE_ADOPTSTATE, "Incorrect number of parameters");
670
671 ComPtr<IMachine> machine;
672 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
673 machine.asOutParam()));
674 if (machine)
675 {
676 char szStateFileAbs[RTPATH_MAX] = "";
677 int vrc = RTPathAbs(a->argv[1], szStateFileAbs, sizeof(szStateFileAbs));
678 if (RT_FAILURE(vrc))
679 {
680 RTMsgError("Cannot convert filename \"%s\" to absolute path", a->argv[0]);
681 return 1;
682 }
683
684 do
685 {
686 /* we have to open a session for this task */
687 CHECK_ERROR_BREAK(machine, LockMachine(a->session, LockType_Write));
688 do
689 {
690 ComPtr<IConsole> console;
691 CHECK_ERROR_BREAK(a->session, COMGETTER(Console)(console.asOutParam()));
692 CHECK_ERROR_BREAK(console, AdoptSavedState(Bstr(szStateFileAbs).raw()));
693 } while (0);
694 CHECK_ERROR_BREAK(a->session, UnlockMachine());
695 } while (0);
696 }
697
698 return SUCCEEDED(rc) ? 0 : 1;
699}
700
701int handleGetExtraData(HandlerArg *a)
702{
703 HRESULT rc = S_OK;
704
705 if (a->argc != 2)
706 return errorSyntax(USAGE_GETEXTRADATA, "Incorrect number of parameters");
707
708 /* global data? */
709 if (!strcmp(a->argv[0], "global"))
710 {
711 /* enumeration? */
712 if (!strcmp(a->argv[1], "enumerate"))
713 {
714 SafeArray<BSTR> aKeys;
715 CHECK_ERROR(a->virtualBox, GetExtraDataKeys(ComSafeArrayAsOutParam(aKeys)));
716
717 for (size_t i = 0;
718 i < aKeys.size();
719 ++i)
720 {
721 Bstr bstrKey(aKeys[i]);
722 Bstr bstrValue;
723 CHECK_ERROR(a->virtualBox, GetExtraData(bstrKey.raw(),
724 bstrValue.asOutParam()));
725
726 RTPrintf("Key: %ls, Value: %ls\n", bstrKey.raw(), bstrValue.raw());
727 }
728 }
729 else
730 {
731 Bstr value;
732 CHECK_ERROR(a->virtualBox, GetExtraData(Bstr(a->argv[1]).raw(),
733 value.asOutParam()));
734 if (!value.isEmpty())
735 RTPrintf("Value: %ls\n", value.raw());
736 else
737 RTPrintf("No value set!\n");
738 }
739 }
740 else
741 {
742 ComPtr<IMachine> machine;
743 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
744 machine.asOutParam()));
745 if (machine)
746 {
747 /* enumeration? */
748 if (!strcmp(a->argv[1], "enumerate"))
749 {
750 SafeArray<BSTR> aKeys;
751 CHECK_ERROR(machine, GetExtraDataKeys(ComSafeArrayAsOutParam(aKeys)));
752
753 for (size_t i = 0;
754 i < aKeys.size();
755 ++i)
756 {
757 Bstr bstrKey(aKeys[i]);
758 Bstr bstrValue;
759 CHECK_ERROR(machine, GetExtraData(bstrKey.raw(),
760 bstrValue.asOutParam()));
761
762 RTPrintf("Key: %ls, Value: %ls\n", bstrKey.raw(), bstrValue.raw());
763 }
764 }
765 else
766 {
767 Bstr value;
768 CHECK_ERROR(machine, GetExtraData(Bstr(a->argv[1]).raw(),
769 value.asOutParam()));
770 if (!value.isEmpty())
771 RTPrintf("Value: %ls\n", value.raw());
772 else
773 RTPrintf("No value set!\n");
774 }
775 }
776 }
777 return SUCCEEDED(rc) ? 0 : 1;
778}
779
780int handleSetExtraData(HandlerArg *a)
781{
782 HRESULT rc = S_OK;
783
784 if (a->argc < 2)
785 return errorSyntax(USAGE_SETEXTRADATA, "Not enough parameters");
786
787 /* global data? */
788 if (!strcmp(a->argv[0], "global"))
789 {
790 /** @todo passing NULL is deprecated */
791 if (a->argc < 3)
792 CHECK_ERROR(a->virtualBox, SetExtraData(Bstr(a->argv[1]).raw(),
793 NULL));
794 else if (a->argc == 3)
795 CHECK_ERROR(a->virtualBox, SetExtraData(Bstr(a->argv[1]).raw(),
796 Bstr(a->argv[2]).raw()));
797 else
798 return errorSyntax(USAGE_SETEXTRADATA, "Too many parameters");
799 }
800 else
801 {
802 ComPtr<IMachine> machine;
803 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[0]).raw(),
804 machine.asOutParam()));
805 if (machine)
806 {
807 /** @todo passing NULL is deprecated */
808 if (a->argc < 3)
809 CHECK_ERROR(machine, SetExtraData(Bstr(a->argv[1]).raw(),
810 NULL));
811 else if (a->argc == 3)
812 CHECK_ERROR(machine, SetExtraData(Bstr(a->argv[1]).raw(),
813 Bstr(a->argv[2]).raw()));
814 else
815 return errorSyntax(USAGE_SETEXTRADATA, "Too many parameters");
816 }
817 }
818 return SUCCEEDED(rc) ? 0 : 1;
819}
820
821int handleSetProperty(HandlerArg *a)
822{
823 HRESULT rc;
824
825 /* there must be two arguments: property name and value */
826 if (a->argc != 2)
827 return errorSyntax(USAGE_SETPROPERTY, "Incorrect number of parameters");
828
829 ComPtr<ISystemProperties> systemProperties;
830 a->virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
831
832 if (!strcmp(a->argv[0], "machinefolder"))
833 {
834 /* reset to default? */
835 if (!strcmp(a->argv[1], "default"))
836 CHECK_ERROR(systemProperties, COMSETTER(DefaultMachineFolder)(NULL));
837 else
838 CHECK_ERROR(systemProperties, COMSETTER(DefaultMachineFolder)(Bstr(a->argv[1]).raw()));
839 }
840 else if (!strcmp(a->argv[0], "hwvirtexclusive"))
841 {
842 bool fHwVirtExclusive;
843
844 if (!strcmp(a->argv[1], "on"))
845 fHwVirtExclusive = true;
846 else if (!strcmp(a->argv[1], "off"))
847 fHwVirtExclusive = false;
848 else
849 return errorArgument("Invalid hwvirtexclusive argument '%s'", a->argv[1]);
850 CHECK_ERROR(systemProperties, COMSETTER(ExclusiveHwVirt)(fHwVirtExclusive));
851 }
852 else if ( !strcmp(a->argv[0], "vrdeauthlibrary")
853 || !strcmp(a->argv[0], "vrdpauthlibrary"))
854 {
855 if (!strcmp(a->argv[0], "vrdpauthlibrary"))
856 RTStrmPrintf(g_pStdErr, "Warning: 'vrdpauthlibrary' is deprecated. Use 'vrdeauthlibrary'.\n");
857
858 /* reset to default? */
859 if (!strcmp(a->argv[1], "default"))
860 CHECK_ERROR(systemProperties, COMSETTER(VRDEAuthLibrary)(NULL));
861 else
862 CHECK_ERROR(systemProperties, COMSETTER(VRDEAuthLibrary)(Bstr(a->argv[1]).raw()));
863 }
864 else if (!strcmp(a->argv[0], "websrvauthlibrary"))
865 {
866 /* reset to default? */
867 if (!strcmp(a->argv[1], "default"))
868 CHECK_ERROR(systemProperties, COMSETTER(WebServiceAuthLibrary)(NULL));
869 else
870 CHECK_ERROR(systemProperties, COMSETTER(WebServiceAuthLibrary)(Bstr(a->argv[1]).raw()));
871 }
872 else if (!strcmp(a->argv[0], "vrdeextpack"))
873 {
874 /* disable? */
875 if (!strcmp(a->argv[1], "null"))
876 CHECK_ERROR(systemProperties, COMSETTER(DefaultVRDEExtPack)(NULL));
877 else
878 CHECK_ERROR(systemProperties, COMSETTER(DefaultVRDEExtPack)(Bstr(a->argv[1]).raw()));
879 }
880 else if (!strcmp(a->argv[0], "loghistorycount"))
881 {
882 uint32_t uVal;
883 int vrc;
884 vrc = RTStrToUInt32Ex(a->argv[1], NULL, 0, &uVal);
885 if (vrc != VINF_SUCCESS)
886 return errorArgument("Error parsing Log history count '%s'", a->argv[1]);
887 CHECK_ERROR(systemProperties, COMSETTER(LogHistoryCount)(uVal));
888 }
889 else if (!strcmp(a->argv[0], "autostartdbpath"))
890 {
891 /* disable? */
892 if (!strcmp(a->argv[1], "null"))
893 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(NULL));
894 else
895 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(Bstr(a->argv[1]).raw()));
896 }
897 else if (!strcmp(a->argv[0], "defaultfrontend"))
898 {
899 Bstr bstrDefaultFrontend(a->argv[1]);
900 if (!strcmp(a->argv[1], "default"))
901 bstrDefaultFrontend.setNull();
902 CHECK_ERROR(systemProperties, COMSETTER(DefaultFrontend)(bstrDefaultFrontend.raw()));
903 }
904 else
905 return errorSyntax(USAGE_SETPROPERTY, "Invalid parameter '%s'", a->argv[0]);
906
907 return SUCCEEDED(rc) ? 0 : 1;
908}
909
910int handleSharedFolder(HandlerArg *a)
911{
912 HRESULT rc;
913
914 /* we need at least a command and target */
915 if (a->argc < 2)
916 return errorSyntax(USAGE_SHAREDFOLDER, "Not enough parameters");
917
918 ComPtr<IMachine> machine;
919 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[1]).raw(),
920 machine.asOutParam()));
921 if (!machine)
922 return 1;
923
924 if (!strcmp(a->argv[0], "add"))
925 {
926 /* we need at least four more parameters */
927 if (a->argc < 5)
928 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Not enough parameters");
929
930 char *name = NULL;
931 char *hostpath = NULL;
932 bool fTransient = false;
933 bool fWritable = true;
934 bool fAutoMount = false;
935
936 for (int i = 2; i < a->argc; i++)
937 {
938 if ( !strcmp(a->argv[i], "--name")
939 || !strcmp(a->argv[i], "-name"))
940 {
941 if (a->argc <= i + 1 || !*a->argv[i+1])
942 return errorArgument("Missing argument to '%s'", a->argv[i]);
943 i++;
944 name = a->argv[i];
945 }
946 else if ( !strcmp(a->argv[i], "--hostpath")
947 || !strcmp(a->argv[i], "-hostpath"))
948 {
949 if (a->argc <= i + 1 || !*a->argv[i+1])
950 return errorArgument("Missing argument to '%s'", a->argv[i]);
951 i++;
952 hostpath = a->argv[i];
953 }
954 else if ( !strcmp(a->argv[i], "--readonly")
955 || !strcmp(a->argv[i], "-readonly"))
956 {
957 fWritable = false;
958 }
959 else if ( !strcmp(a->argv[i], "--transient")
960 || !strcmp(a->argv[i], "-transient"))
961 {
962 fTransient = true;
963 }
964 else if ( !strcmp(a->argv[i], "--automount")
965 || !strcmp(a->argv[i], "-automount"))
966 {
967 fAutoMount = true;
968 }
969 else
970 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
971 }
972
973 if (NULL != strstr(name, " "))
974 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "No spaces allowed in parameter '-name'!");
975
976 /* required arguments */
977 if (!name || !hostpath)
978 {
979 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Parameters --name and --hostpath are required");
980 }
981
982 if (fTransient)
983 {
984 ComPtr<IConsole> console;
985
986 /* open an existing session for the VM */
987 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
988 /* get the session machine */
989 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
990 /* get the session console */
991 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
992
993 CHECK_ERROR(console, CreateSharedFolder(Bstr(name).raw(),
994 Bstr(hostpath).raw(),
995 fWritable, fAutoMount));
996 if (console)
997 a->session->UnlockMachine();
998 }
999 else
1000 {
1001 /* open a session for the VM */
1002 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1003
1004 /* get the mutable session machine */
1005 a->session->COMGETTER(Machine)(machine.asOutParam());
1006
1007 CHECK_ERROR(machine, CreateSharedFolder(Bstr(name).raw(),
1008 Bstr(hostpath).raw(),
1009 fWritable, fAutoMount));
1010 if (SUCCEEDED(rc))
1011 CHECK_ERROR(machine, SaveSettings());
1012
1013 a->session->UnlockMachine();
1014 }
1015 }
1016 else if (!strcmp(a->argv[0], "remove"))
1017 {
1018 /* we need at least two more parameters */
1019 if (a->argc < 3)
1020 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Not enough parameters");
1021
1022 char *name = NULL;
1023 bool fTransient = false;
1024
1025 for (int i = 2; i < a->argc; i++)
1026 {
1027 if ( !strcmp(a->argv[i], "--name")
1028 || !strcmp(a->argv[i], "-name"))
1029 {
1030 if (a->argc <= i + 1 || !*a->argv[i+1])
1031 return errorArgument("Missing argument to '%s'", a->argv[i]);
1032 i++;
1033 name = a->argv[i];
1034 }
1035 else if ( !strcmp(a->argv[i], "--transient")
1036 || !strcmp(a->argv[i], "-transient"))
1037 {
1038 fTransient = true;
1039 }
1040 else
1041 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
1042 }
1043
1044 /* required arguments */
1045 if (!name)
1046 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Parameter --name is required");
1047
1048 if (fTransient)
1049 {
1050 ComPtr<IConsole> console;
1051
1052 /* open an existing session for the VM */
1053 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
1054 /* get the session machine */
1055 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
1056 /* get the session console */
1057 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
1058
1059 CHECK_ERROR(console, RemoveSharedFolder(Bstr(name).raw()));
1060
1061 if (console)
1062 a->session->UnlockMachine();
1063 }
1064 else
1065 {
1066 /* open a session for the VM */
1067 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1068
1069 /* get the mutable session machine */
1070 a->session->COMGETTER(Machine)(machine.asOutParam());
1071
1072 CHECK_ERROR(machine, RemoveSharedFolder(Bstr(name).raw()));
1073
1074 /* commit and close the session */
1075 CHECK_ERROR(machine, SaveSettings());
1076 a->session->UnlockMachine();
1077 }
1078 }
1079 else
1080 return errorSyntax(USAGE_SHAREDFOLDER, "Invalid parameter '%s'", Utf8Str(a->argv[0]).c_str());
1081
1082 return 0;
1083}
1084
1085int handleExtPack(HandlerArg *a)
1086{
1087 if (a->argc < 1)
1088 return errorSyntax(USAGE_EXTPACK, "Incorrect number of parameters");
1089
1090 ComObjPtr<IExtPackManager> ptrExtPackMgr;
1091 CHECK_ERROR2_RET(a->virtualBox, COMGETTER(ExtensionPackManager)(ptrExtPackMgr.asOutParam()), RTEXITCODE_FAILURE);
1092
1093 RTGETOPTSTATE GetState;
1094 RTGETOPTUNION ValueUnion;
1095 int ch;
1096 HRESULT hrc = S_OK;
1097
1098 if (!strcmp(a->argv[0], "install"))
1099 {
1100 const char *pszName = NULL;
1101 bool fReplace = false;
1102
1103 static const RTGETOPTDEF s_aInstallOptions[] =
1104 {
1105 { "--replace", 'r', RTGETOPT_REQ_NOTHING },
1106 };
1107
1108 RTGetOptInit(&GetState, a->argc, a->argv, s_aInstallOptions, RT_ELEMENTS(s_aInstallOptions), 1, 0 /*fFlags*/);
1109 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1110 {
1111 switch (ch)
1112 {
1113 case 'r':
1114 fReplace = true;
1115 break;
1116
1117 case VINF_GETOPT_NOT_OPTION:
1118 if (pszName)
1119 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1120 pszName = ValueUnion.psz;
1121 break;
1122
1123 default:
1124 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1125 }
1126 }
1127 if (!pszName)
1128 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack install\"");
1129
1130 char szPath[RTPATH_MAX];
1131 int vrc = RTPathAbs(pszName, szPath, sizeof(szPath));
1132 if (RT_FAILURE(vrc))
1133 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTPathAbs(%s,,) failed with rc=%Rrc", pszName, vrc);
1134
1135 Bstr bstrTarball(szPath);
1136 Bstr bstrName;
1137 ComPtr<IExtPackFile> ptrExtPackFile;
1138 CHECK_ERROR2_RET(ptrExtPackMgr, OpenExtPackFile(bstrTarball.raw(), ptrExtPackFile.asOutParam()), RTEXITCODE_FAILURE);
1139 CHECK_ERROR2_RET(ptrExtPackFile, COMGETTER(Name)(bstrName.asOutParam()), RTEXITCODE_FAILURE);
1140 ComPtr<IProgress> ptrProgress;
1141 CHECK_ERROR2_RET(ptrExtPackFile, Install(fReplace, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1142 hrc = showProgress(ptrProgress);
1143 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to install \"%s\"", szPath), RTEXITCODE_FAILURE);
1144
1145 RTPrintf("Successfully installed \"%ls\".\n", bstrName.raw());
1146 }
1147 else if (!strcmp(a->argv[0], "uninstall"))
1148 {
1149 const char *pszName = NULL;
1150 bool fForced = false;
1151
1152 static const RTGETOPTDEF s_aUninstallOptions[] =
1153 {
1154 { "--force", 'f', RTGETOPT_REQ_NOTHING },
1155 };
1156
1157 RTGetOptInit(&GetState, a->argc, a->argv, s_aUninstallOptions, RT_ELEMENTS(s_aUninstallOptions), 1, 0);
1158 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1159 {
1160 switch (ch)
1161 {
1162 case 'f':
1163 fForced = true;
1164 break;
1165
1166 case VINF_GETOPT_NOT_OPTION:
1167 if (pszName)
1168 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1169 pszName = ValueUnion.psz;
1170 break;
1171
1172 default:
1173 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1174 }
1175 }
1176 if (!pszName)
1177 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack uninstall\"");
1178
1179 Bstr bstrName(pszName);
1180 ComPtr<IProgress> ptrProgress;
1181 CHECK_ERROR2_RET(ptrExtPackMgr, Uninstall(bstrName.raw(), fForced, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1182 hrc = showProgress(ptrProgress);
1183 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to uninstall \"%s\"", pszName), RTEXITCODE_FAILURE);
1184
1185 RTPrintf("Successfully uninstalled \"%s\".\n", pszName);
1186 }
1187 else if (!strcmp(a->argv[0], "cleanup"))
1188 {
1189 if (a->argc > 1)
1190 return errorSyntax(USAGE_EXTPACK, "Too many parameters given to \"extpack cleanup\"");
1191
1192 CHECK_ERROR2_RET(ptrExtPackMgr, Cleanup(), RTEXITCODE_FAILURE);
1193 RTPrintf("Successfully performed extension pack cleanup\n");
1194 }
1195 else
1196 return errorSyntax(USAGE_EXTPACK, "Unknown command \"%s\"", a->argv[0]);
1197
1198 return RTEXITCODE_SUCCESS;
1199}
1200
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