VirtualBox

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

Last change on this file since 37950 was 37900, checked in by vboxsync, 14 years ago

Main-CloneVM;FE/CLI;Doc: update differencing disk names with there new uuid; rename all other disks to the new name + disk#; optional allow keeping old disk names

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

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