VirtualBox

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

Last change on this file since 54939 was 54791, checked in by vboxsync, 10 years ago

Main/Machine: fix long-standing bug with setting extradata (it isn't allowed to use an immutable IMachine instance, see corresponding VBoxManage fix), and while at it fix a long-standing bug which allowed changing most settings at runtime (the i_checkStateDependency logic was broken)

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 41.9 KB
Line 
1/* $Id: VBoxManageMisc.cpp 54791 2015-03-16 16:04:03Z vboxsync $ */
2/** @file
3 * VBoxManage - VirtualBox's command-line interface.
4 */
5
6/*
7 * Copyright (C) 2006-2015 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 /* open an existing session for the VM */
807 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
808 /* get the session machine */
809 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
810 /** @todo passing NULL is deprecated */
811 if (a->argc < 3)
812 CHECK_ERROR(machine, SetExtraData(Bstr(a->argv[1]).raw(),
813 NULL));
814 else if (a->argc == 3)
815 CHECK_ERROR(machine, SetExtraData(Bstr(a->argv[1]).raw(),
816 Bstr(a->argv[2]).raw()));
817 else
818 return errorSyntax(USAGE_SETEXTRADATA, "Too many parameters");
819 }
820 }
821 return SUCCEEDED(rc) ? 0 : 1;
822}
823
824int handleSetProperty(HandlerArg *a)
825{
826 HRESULT rc;
827
828 /* there must be two arguments: property name and value */
829 if (a->argc != 2)
830 return errorSyntax(USAGE_SETPROPERTY, "Incorrect number of parameters");
831
832 ComPtr<ISystemProperties> systemProperties;
833 a->virtualBox->COMGETTER(SystemProperties)(systemProperties.asOutParam());
834
835 if (!strcmp(a->argv[0], "machinefolder"))
836 {
837 /* reset to default? */
838 if (!strcmp(a->argv[1], "default"))
839 CHECK_ERROR(systemProperties, COMSETTER(DefaultMachineFolder)(NULL));
840 else
841 CHECK_ERROR(systemProperties, COMSETTER(DefaultMachineFolder)(Bstr(a->argv[1]).raw()));
842 }
843 else if (!strcmp(a->argv[0], "hwvirtexclusive"))
844 {
845 bool fHwVirtExclusive;
846
847 if (!strcmp(a->argv[1], "on"))
848 fHwVirtExclusive = true;
849 else if (!strcmp(a->argv[1], "off"))
850 fHwVirtExclusive = false;
851 else
852 return errorArgument("Invalid hwvirtexclusive argument '%s'", a->argv[1]);
853 CHECK_ERROR(systemProperties, COMSETTER(ExclusiveHwVirt)(fHwVirtExclusive));
854 }
855 else if ( !strcmp(a->argv[0], "vrdeauthlibrary")
856 || !strcmp(a->argv[0], "vrdpauthlibrary"))
857 {
858 if (!strcmp(a->argv[0], "vrdpauthlibrary"))
859 RTStrmPrintf(g_pStdErr, "Warning: 'vrdpauthlibrary' is deprecated. Use 'vrdeauthlibrary'.\n");
860
861 /* reset to default? */
862 if (!strcmp(a->argv[1], "default"))
863 CHECK_ERROR(systemProperties, COMSETTER(VRDEAuthLibrary)(NULL));
864 else
865 CHECK_ERROR(systemProperties, COMSETTER(VRDEAuthLibrary)(Bstr(a->argv[1]).raw()));
866 }
867 else if (!strcmp(a->argv[0], "websrvauthlibrary"))
868 {
869 /* reset to default? */
870 if (!strcmp(a->argv[1], "default"))
871 CHECK_ERROR(systemProperties, COMSETTER(WebServiceAuthLibrary)(NULL));
872 else
873 CHECK_ERROR(systemProperties, COMSETTER(WebServiceAuthLibrary)(Bstr(a->argv[1]).raw()));
874 }
875 else if (!strcmp(a->argv[0], "vrdeextpack"))
876 {
877 /* disable? */
878 if (!strcmp(a->argv[1], "null"))
879 CHECK_ERROR(systemProperties, COMSETTER(DefaultVRDEExtPack)(NULL));
880 else
881 CHECK_ERROR(systemProperties, COMSETTER(DefaultVRDEExtPack)(Bstr(a->argv[1]).raw()));
882 }
883 else if (!strcmp(a->argv[0], "loghistorycount"))
884 {
885 uint32_t uVal;
886 int vrc;
887 vrc = RTStrToUInt32Ex(a->argv[1], NULL, 0, &uVal);
888 if (vrc != VINF_SUCCESS)
889 return errorArgument("Error parsing Log history count '%s'", a->argv[1]);
890 CHECK_ERROR(systemProperties, COMSETTER(LogHistoryCount)(uVal));
891 }
892 else if (!strcmp(a->argv[0], "autostartdbpath"))
893 {
894 /* disable? */
895 if (!strcmp(a->argv[1], "null"))
896 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(NULL));
897 else
898 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(Bstr(a->argv[1]).raw()));
899 }
900 else if (!strcmp(a->argv[0], "defaultfrontend"))
901 {
902 Bstr bstrDefaultFrontend(a->argv[1]);
903 if (!strcmp(a->argv[1], "default"))
904 bstrDefaultFrontend.setNull();
905 CHECK_ERROR(systemProperties, COMSETTER(DefaultFrontend)(bstrDefaultFrontend.raw()));
906 }
907 else
908 return errorSyntax(USAGE_SETPROPERTY, "Invalid parameter '%s'", a->argv[0]);
909
910 return SUCCEEDED(rc) ? 0 : 1;
911}
912
913int handleSharedFolder(HandlerArg *a)
914{
915 HRESULT rc;
916
917 /* we need at least a command and target */
918 if (a->argc < 2)
919 return errorSyntax(USAGE_SHAREDFOLDER, "Not enough parameters");
920
921 ComPtr<IMachine> machine;
922 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[1]).raw(),
923 machine.asOutParam()));
924 if (!machine)
925 return 1;
926
927 if (!strcmp(a->argv[0], "add"))
928 {
929 /* we need at least four more parameters */
930 if (a->argc < 5)
931 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Not enough parameters");
932
933 char *name = NULL;
934 char *hostpath = NULL;
935 bool fTransient = false;
936 bool fWritable = true;
937 bool fAutoMount = false;
938
939 for (int i = 2; i < a->argc; i++)
940 {
941 if ( !strcmp(a->argv[i], "--name")
942 || !strcmp(a->argv[i], "-name"))
943 {
944 if (a->argc <= i + 1 || !*a->argv[i+1])
945 return errorArgument("Missing argument to '%s'", a->argv[i]);
946 i++;
947 name = a->argv[i];
948 }
949 else if ( !strcmp(a->argv[i], "--hostpath")
950 || !strcmp(a->argv[i], "-hostpath"))
951 {
952 if (a->argc <= i + 1 || !*a->argv[i+1])
953 return errorArgument("Missing argument to '%s'", a->argv[i]);
954 i++;
955 hostpath = a->argv[i];
956 }
957 else if ( !strcmp(a->argv[i], "--readonly")
958 || !strcmp(a->argv[i], "-readonly"))
959 {
960 fWritable = false;
961 }
962 else if ( !strcmp(a->argv[i], "--transient")
963 || !strcmp(a->argv[i], "-transient"))
964 {
965 fTransient = true;
966 }
967 else if ( !strcmp(a->argv[i], "--automount")
968 || !strcmp(a->argv[i], "-automount"))
969 {
970 fAutoMount = true;
971 }
972 else
973 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
974 }
975
976 if (NULL != strstr(name, " "))
977 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "No spaces allowed in parameter '-name'!");
978
979 /* required arguments */
980 if (!name || !hostpath)
981 {
982 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Parameters --name and --hostpath are required");
983 }
984
985 if (fTransient)
986 {
987 ComPtr<IConsole> console;
988
989 /* open an existing session for the VM */
990 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
991 /* get the session machine */
992 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
993 /* get the session console */
994 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
995
996 CHECK_ERROR(console, CreateSharedFolder(Bstr(name).raw(),
997 Bstr(hostpath).raw(),
998 fWritable, fAutoMount));
999 if (console)
1000 a->session->UnlockMachine();
1001 }
1002 else
1003 {
1004 /* open a session for the VM */
1005 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1006
1007 /* get the mutable session machine */
1008 a->session->COMGETTER(Machine)(machine.asOutParam());
1009
1010 CHECK_ERROR(machine, CreateSharedFolder(Bstr(name).raw(),
1011 Bstr(hostpath).raw(),
1012 fWritable, fAutoMount));
1013 if (SUCCEEDED(rc))
1014 CHECK_ERROR(machine, SaveSettings());
1015
1016 a->session->UnlockMachine();
1017 }
1018 }
1019 else if (!strcmp(a->argv[0], "remove"))
1020 {
1021 /* we need at least two more parameters */
1022 if (a->argc < 3)
1023 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Not enough parameters");
1024
1025 char *name = NULL;
1026 bool fTransient = false;
1027
1028 for (int i = 2; i < a->argc; i++)
1029 {
1030 if ( !strcmp(a->argv[i], "--name")
1031 || !strcmp(a->argv[i], "-name"))
1032 {
1033 if (a->argc <= i + 1 || !*a->argv[i+1])
1034 return errorArgument("Missing argument to '%s'", a->argv[i]);
1035 i++;
1036 name = a->argv[i];
1037 }
1038 else if ( !strcmp(a->argv[i], "--transient")
1039 || !strcmp(a->argv[i], "-transient"))
1040 {
1041 fTransient = true;
1042 }
1043 else
1044 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
1045 }
1046
1047 /* required arguments */
1048 if (!name)
1049 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Parameter --name is required");
1050
1051 if (fTransient)
1052 {
1053 ComPtr<IConsole> console;
1054
1055 /* open an existing session for the VM */
1056 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
1057 /* get the session machine */
1058 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
1059 /* get the session console */
1060 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
1061
1062 CHECK_ERROR(console, RemoveSharedFolder(Bstr(name).raw()));
1063
1064 if (console)
1065 a->session->UnlockMachine();
1066 }
1067 else
1068 {
1069 /* open a session for the VM */
1070 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1071
1072 /* get the mutable session machine */
1073 a->session->COMGETTER(Machine)(machine.asOutParam());
1074
1075 CHECK_ERROR(machine, RemoveSharedFolder(Bstr(name).raw()));
1076
1077 /* commit and close the session */
1078 CHECK_ERROR(machine, SaveSettings());
1079 a->session->UnlockMachine();
1080 }
1081 }
1082 else
1083 return errorSyntax(USAGE_SHAREDFOLDER, "Invalid parameter '%s'", Utf8Str(a->argv[0]).c_str());
1084
1085 return 0;
1086}
1087
1088int handleExtPack(HandlerArg *a)
1089{
1090 if (a->argc < 1)
1091 return errorSyntax(USAGE_EXTPACK, "Incorrect number of parameters");
1092
1093 ComObjPtr<IExtPackManager> ptrExtPackMgr;
1094 CHECK_ERROR2_RET(a->virtualBox, COMGETTER(ExtensionPackManager)(ptrExtPackMgr.asOutParam()), RTEXITCODE_FAILURE);
1095
1096 RTGETOPTSTATE GetState;
1097 RTGETOPTUNION ValueUnion;
1098 int ch;
1099 HRESULT hrc = S_OK;
1100
1101 if (!strcmp(a->argv[0], "install"))
1102 {
1103 const char *pszName = NULL;
1104 bool fReplace = false;
1105
1106 static const RTGETOPTDEF s_aInstallOptions[] =
1107 {
1108 { "--replace", 'r', RTGETOPT_REQ_NOTHING },
1109 };
1110
1111 RTGetOptInit(&GetState, a->argc, a->argv, s_aInstallOptions, RT_ELEMENTS(s_aInstallOptions), 1, 0 /*fFlags*/);
1112 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1113 {
1114 switch (ch)
1115 {
1116 case 'r':
1117 fReplace = true;
1118 break;
1119
1120 case VINF_GETOPT_NOT_OPTION:
1121 if (pszName)
1122 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1123 pszName = ValueUnion.psz;
1124 break;
1125
1126 default:
1127 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1128 }
1129 }
1130 if (!pszName)
1131 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack install\"");
1132
1133 char szPath[RTPATH_MAX];
1134 int vrc = RTPathAbs(pszName, szPath, sizeof(szPath));
1135 if (RT_FAILURE(vrc))
1136 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTPathAbs(%s,,) failed with rc=%Rrc", pszName, vrc);
1137
1138 Bstr bstrTarball(szPath);
1139 Bstr bstrName;
1140 ComPtr<IExtPackFile> ptrExtPackFile;
1141 CHECK_ERROR2_RET(ptrExtPackMgr, OpenExtPackFile(bstrTarball.raw(), ptrExtPackFile.asOutParam()), RTEXITCODE_FAILURE);
1142 CHECK_ERROR2_RET(ptrExtPackFile, COMGETTER(Name)(bstrName.asOutParam()), RTEXITCODE_FAILURE);
1143 ComPtr<IProgress> ptrProgress;
1144 CHECK_ERROR2_RET(ptrExtPackFile, Install(fReplace, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1145 hrc = showProgress(ptrProgress);
1146 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to install \"%s\"", szPath), RTEXITCODE_FAILURE);
1147
1148 RTPrintf("Successfully installed \"%ls\".\n", bstrName.raw());
1149 }
1150 else if (!strcmp(a->argv[0], "uninstall"))
1151 {
1152 const char *pszName = NULL;
1153 bool fForced = false;
1154
1155 static const RTGETOPTDEF s_aUninstallOptions[] =
1156 {
1157 { "--force", 'f', RTGETOPT_REQ_NOTHING },
1158 };
1159
1160 RTGetOptInit(&GetState, a->argc, a->argv, s_aUninstallOptions, RT_ELEMENTS(s_aUninstallOptions), 1, 0);
1161 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1162 {
1163 switch (ch)
1164 {
1165 case 'f':
1166 fForced = true;
1167 break;
1168
1169 case VINF_GETOPT_NOT_OPTION:
1170 if (pszName)
1171 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1172 pszName = ValueUnion.psz;
1173 break;
1174
1175 default:
1176 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1177 }
1178 }
1179 if (!pszName)
1180 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack uninstall\"");
1181
1182 Bstr bstrName(pszName);
1183 ComPtr<IProgress> ptrProgress;
1184 CHECK_ERROR2_RET(ptrExtPackMgr, Uninstall(bstrName.raw(), fForced, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1185 hrc = showProgress(ptrProgress);
1186 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to uninstall \"%s\"", pszName), RTEXITCODE_FAILURE);
1187
1188 RTPrintf("Successfully uninstalled \"%s\".\n", pszName);
1189 }
1190 else if (!strcmp(a->argv[0], "cleanup"))
1191 {
1192 if (a->argc > 1)
1193 return errorSyntax(USAGE_EXTPACK, "Too many parameters given to \"extpack cleanup\"");
1194
1195 CHECK_ERROR2_RET(ptrExtPackMgr, Cleanup(), RTEXITCODE_FAILURE);
1196 RTPrintf("Successfully performed extension pack cleanup\n");
1197 }
1198 else
1199 return errorSyntax(USAGE_EXTPACK, "Unknown command \"%s\"", a->argv[0]);
1200
1201 return RTEXITCODE_SUCCESS;
1202}
1203
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