VirtualBox

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

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

Main: fix COM/XPCOM incompatibility issues and add safearray setter support to the C binding XSLT, too

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