VirtualBox

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

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

Autostart: Make the path to the autostart database configurable

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 40.3 KB
Line 
1/* $Id: VBoxManageMisc.cpp 42178 2012-07-17 12:35:07Z 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 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 if (!strcmp(a->argv[0], "autostartdbpath"))
860 {
861 /* disable? */
862 if (!strcmp(a->argv[1], "null"))
863 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(NULL));
864 else
865 CHECK_ERROR(systemProperties, COMSETTER(AutostartDatabasePath)(Bstr(a->argv[1]).raw()));
866 }
867 else
868 return errorSyntax(USAGE_SETPROPERTY, "Invalid parameter '%s'", a->argv[0]);
869
870 return SUCCEEDED(rc) ? 0 : 1;
871}
872
873int handleSharedFolder(HandlerArg *a)
874{
875 HRESULT rc;
876
877 /* we need at least a command and target */
878 if (a->argc < 2)
879 return errorSyntax(USAGE_SHAREDFOLDER, "Not enough parameters");
880
881 ComPtr<IMachine> machine;
882 CHECK_ERROR(a->virtualBox, FindMachine(Bstr(a->argv[1]).raw(),
883 machine.asOutParam()));
884 if (!machine)
885 return 1;
886
887 if (!strcmp(a->argv[0], "add"))
888 {
889 /* we need at least four more parameters */
890 if (a->argc < 5)
891 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Not enough parameters");
892
893 char *name = NULL;
894 char *hostpath = NULL;
895 bool fTransient = false;
896 bool fWritable = true;
897 bool fAutoMount = false;
898
899 for (int i = 2; i < a->argc; i++)
900 {
901 if ( !strcmp(a->argv[i], "--name")
902 || !strcmp(a->argv[i], "-name"))
903 {
904 if (a->argc <= i + 1 || !*a->argv[i+1])
905 return errorArgument("Missing argument to '%s'", a->argv[i]);
906 i++;
907 name = a->argv[i];
908 }
909 else if ( !strcmp(a->argv[i], "--hostpath")
910 || !strcmp(a->argv[i], "-hostpath"))
911 {
912 if (a->argc <= i + 1 || !*a->argv[i+1])
913 return errorArgument("Missing argument to '%s'", a->argv[i]);
914 i++;
915 hostpath = a->argv[i];
916 }
917 else if ( !strcmp(a->argv[i], "--readonly")
918 || !strcmp(a->argv[i], "-readonly"))
919 {
920 fWritable = false;
921 }
922 else if ( !strcmp(a->argv[i], "--transient")
923 || !strcmp(a->argv[i], "-transient"))
924 {
925 fTransient = true;
926 }
927 else if ( !strcmp(a->argv[i], "--automount")
928 || !strcmp(a->argv[i], "-automount"))
929 {
930 fAutoMount = true;
931 }
932 else
933 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
934 }
935
936 if (NULL != strstr(name, " "))
937 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "No spaces allowed in parameter '-name'!");
938
939 /* required arguments */
940 if (!name || !hostpath)
941 {
942 return errorSyntax(USAGE_SHAREDFOLDER_ADD, "Parameters --name and --hostpath are required");
943 }
944
945 if (fTransient)
946 {
947 ComPtr <IConsole> console;
948
949 /* open an existing session for the VM */
950 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
951 /* get the session machine */
952 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
953 /* get the session console */
954 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
955
956 CHECK_ERROR(console, CreateSharedFolder(Bstr(name).raw(),
957 Bstr(hostpath).raw(),
958 fWritable, fAutoMount));
959 if (console)
960 a->session->UnlockMachine();
961 }
962 else
963 {
964 /* open a session for the VM */
965 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
966
967 /* get the mutable session machine */
968 a->session->COMGETTER(Machine)(machine.asOutParam());
969
970 CHECK_ERROR(machine, CreateSharedFolder(Bstr(name).raw(),
971 Bstr(hostpath).raw(),
972 fWritable, fAutoMount));
973 if (SUCCEEDED(rc))
974 CHECK_ERROR(machine, SaveSettings());
975
976 a->session->UnlockMachine();
977 }
978 }
979 else if (!strcmp(a->argv[0], "remove"))
980 {
981 /* we need at least two more parameters */
982 if (a->argc < 3)
983 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Not enough parameters");
984
985 char *name = NULL;
986 bool fTransient = false;
987
988 for (int i = 2; i < a->argc; i++)
989 {
990 if ( !strcmp(a->argv[i], "--name")
991 || !strcmp(a->argv[i], "-name"))
992 {
993 if (a->argc <= i + 1 || !*a->argv[i+1])
994 return errorArgument("Missing argument to '%s'", a->argv[i]);
995 i++;
996 name = a->argv[i];
997 }
998 else if ( !strcmp(a->argv[i], "--transient")
999 || !strcmp(a->argv[i], "-transient"))
1000 {
1001 fTransient = true;
1002 }
1003 else
1004 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Invalid parameter '%s'", Utf8Str(a->argv[i]).c_str());
1005 }
1006
1007 /* required arguments */
1008 if (!name)
1009 return errorSyntax(USAGE_SHAREDFOLDER_REMOVE, "Parameter --name is required");
1010
1011 if (fTransient)
1012 {
1013 ComPtr <IConsole> console;
1014
1015 /* open an existing session for the VM */
1016 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Shared), 1);
1017 /* get the session machine */
1018 CHECK_ERROR_RET(a->session, COMGETTER(Machine)(machine.asOutParam()), 1);
1019 /* get the session console */
1020 CHECK_ERROR_RET(a->session, COMGETTER(Console)(console.asOutParam()), 1);
1021
1022 CHECK_ERROR(console, RemoveSharedFolder(Bstr(name).raw()));
1023
1024 if (console)
1025 a->session->UnlockMachine();
1026 }
1027 else
1028 {
1029 /* open a session for the VM */
1030 CHECK_ERROR_RET(machine, LockMachine(a->session, LockType_Write), 1);
1031
1032 /* get the mutable session machine */
1033 a->session->COMGETTER(Machine)(machine.asOutParam());
1034
1035 CHECK_ERROR(machine, RemoveSharedFolder(Bstr(name).raw()));
1036
1037 /* commit and close the session */
1038 CHECK_ERROR(machine, SaveSettings());
1039 a->session->UnlockMachine();
1040 }
1041 }
1042 else
1043 return errorSyntax(USAGE_SHAREDFOLDER, "Invalid parameter '%s'", Utf8Str(a->argv[0]).c_str());
1044
1045 return 0;
1046}
1047
1048int handleExtPack(HandlerArg *a)
1049{
1050 if (a->argc < 1)
1051 return errorSyntax(USAGE_EXTPACK, "Incorrect number of parameters");
1052
1053 ComObjPtr<IExtPackManager> ptrExtPackMgr;
1054 CHECK_ERROR2_RET(a->virtualBox, COMGETTER(ExtensionPackManager)(ptrExtPackMgr.asOutParam()), RTEXITCODE_FAILURE);
1055
1056 RTGETOPTSTATE GetState;
1057 RTGETOPTUNION ValueUnion;
1058 int ch;
1059 HRESULT hrc = S_OK;
1060
1061 if (!strcmp(a->argv[0], "install"))
1062 {
1063 const char *pszName = NULL;
1064 bool fReplace = false;
1065
1066 static const RTGETOPTDEF s_aInstallOptions[] =
1067 {
1068 { "--replace", 'r', RTGETOPT_REQ_NOTHING },
1069 };
1070
1071 RTGetOptInit(&GetState, a->argc, a->argv, s_aInstallOptions, RT_ELEMENTS(s_aInstallOptions), 1, 0 /*fFlags*/);
1072 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1073 {
1074 switch (ch)
1075 {
1076 case 'r':
1077 fReplace = true;
1078 break;
1079
1080 case VINF_GETOPT_NOT_OPTION:
1081 if (pszName)
1082 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1083 pszName = ValueUnion.psz;
1084 break;
1085
1086 default:
1087 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1088 }
1089 }
1090 if (!pszName)
1091 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack install\"");
1092
1093 char szPath[RTPATH_MAX];
1094 int vrc = RTPathAbs(pszName, szPath, sizeof(szPath));
1095 if (RT_FAILURE(vrc))
1096 return RTMsgErrorExit(RTEXITCODE_FAILURE, "RTPathAbs(%s,,) failed with rc=%Rrc", pszName, vrc);
1097
1098 Bstr bstrTarball(szPath);
1099 Bstr bstrName;
1100 ComPtr<IExtPackFile> ptrExtPackFile;
1101 CHECK_ERROR2_RET(ptrExtPackMgr, OpenExtPackFile(bstrTarball.raw(), ptrExtPackFile.asOutParam()), RTEXITCODE_FAILURE);
1102 CHECK_ERROR2_RET(ptrExtPackFile, COMGETTER(Name)(bstrName.asOutParam()), RTEXITCODE_FAILURE);
1103 ComPtr<IProgress> ptrProgress;
1104 CHECK_ERROR2_RET(ptrExtPackFile, Install(fReplace, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1105 hrc = showProgress(ptrProgress);
1106 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to install \"%s\"", szPath), RTEXITCODE_FAILURE);
1107
1108 RTPrintf("Successfully installed \"%ls\".\n", bstrName.raw());
1109 }
1110 else if (!strcmp(a->argv[0], "uninstall"))
1111 {
1112 const char *pszName = NULL;
1113 bool fForced = false;
1114
1115 static const RTGETOPTDEF s_aUninstallOptions[] =
1116 {
1117 { "--force", 'f', RTGETOPT_REQ_NOTHING },
1118 };
1119
1120 RTGetOptInit(&GetState, a->argc, a->argv, s_aUninstallOptions, RT_ELEMENTS(s_aUninstallOptions), 1, 0);
1121 while ((ch = RTGetOpt(&GetState, &ValueUnion)))
1122 {
1123 switch (ch)
1124 {
1125 case 'f':
1126 fForced = true;
1127 break;
1128
1129 case VINF_GETOPT_NOT_OPTION:
1130 if (pszName)
1131 return errorSyntax(USAGE_EXTPACK, "Too many extension pack names given to \"extpack uninstall\"");
1132 pszName = ValueUnion.psz;
1133 break;
1134
1135 default:
1136 return errorGetOpt(USAGE_EXTPACK, ch, &ValueUnion);
1137 }
1138 }
1139 if (!pszName)
1140 return errorSyntax(USAGE_EXTPACK, "No extension pack name was given to \"extpack uninstall\"");
1141
1142 Bstr bstrName(pszName);
1143 ComPtr<IProgress> ptrProgress;
1144 CHECK_ERROR2_RET(ptrExtPackMgr, Uninstall(bstrName.raw(), fForced, NULL, ptrProgress.asOutParam()), RTEXITCODE_FAILURE);
1145 hrc = showProgress(ptrProgress);
1146 CHECK_PROGRESS_ERROR_RET(ptrProgress, ("Failed to uninstall \"%s\"", pszName), RTEXITCODE_FAILURE);
1147
1148 RTPrintf("Successfully uninstalled \"%s\".\n", pszName);
1149 }
1150 else if (!strcmp(a->argv[0], "cleanup"))
1151 {
1152 if (a->argc > 1)
1153 return errorSyntax(USAGE_EXTPACK, "Too many parameters given to \"extpack cleanup\"");
1154
1155 CHECK_ERROR2_RET(ptrExtPackMgr, Cleanup(), RTEXITCODE_FAILURE);
1156 RTPrintf("Successfully performed extension pack cleanup\n");
1157 }
1158 else
1159 return errorSyntax(USAGE_EXTPACK, "Unknown command \"%s\"", a->argv[0]);
1160
1161 return RTEXITCODE_SUCCESS;
1162}
1163
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