VirtualBox

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

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

typo.

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