VirtualBox

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

Last change on this file since 42176 was 42176, checked in by vboxsync, 13 years ago

Main+Frontends/VBoxManage: implement saving the settings, and add the matching VBoxManage support

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

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette