VirtualBox

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

Last change on this file since 45559 was 45068, checked in by vboxsync, 12 years ago

Main/Machine: rename two methods for better compatibility with programming languages - delete and export might be keywords.

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