VirtualBox

source: vbox/trunk/src/VBox/Frontends/VBoxManage/VBoxManageDisk.cpp@ 64988

Last change on this file since 64988 was 64988, checked in by vboxsync, 8 years ago

typo

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 68.3 KB
Line 
1/* $Id: VBoxManageDisk.cpp 64988 2016-12-21 15:12:49Z vboxsync $ */
2/** @file
3 * VBoxManage - The disk/medium related commands.
4 */
5
6/*
7 * Copyright (C) 2006-2016 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#ifndef VBOX_ONLY_DOCS
19
20
21/*********************************************************************************************************************************
22* Header Files *
23*********************************************************************************************************************************/
24#include <VBox/com/com.h>
25#include <VBox/com/array.h>
26#include <VBox/com/ErrorInfo.h>
27#include <VBox/com/errorprint.h>
28#include <VBox/com/VirtualBox.h>
29
30#include <iprt/asm.h>
31#include <iprt/file.h>
32#include <iprt/path.h>
33#include <iprt/param.h>
34#include <iprt/stream.h>
35#include <iprt/string.h>
36#include <iprt/ctype.h>
37#include <iprt/getopt.h>
38#include <VBox/log.h>
39#include <VBox/vd.h>
40
41#include "VBoxManage.h"
42using namespace com;
43
44
45// funcs
46///////////////////////////////////////////////////////////////////////////////
47
48
49static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
50{
51 RT_NOREF(pvUser);
52 RTMsgErrorV(pszFormat, va);
53 RTMsgError("Error code %Rrc at %s(%u) in function %s", rc, RT_SRC_POS_ARGS);
54}
55
56static int parseMediumVariant(const char *psz, MediumVariant_T *pMediumVariant)
57{
58 int rc = VINF_SUCCESS;
59 unsigned uMediumVariant = (unsigned)(*pMediumVariant);
60 while (psz && *psz && RT_SUCCESS(rc))
61 {
62 size_t len;
63 const char *pszComma = strchr(psz, ',');
64 if (pszComma)
65 len = pszComma - psz;
66 else
67 len = strlen(psz);
68 if (len > 0)
69 {
70 // Parsing is intentionally inconsistent: "standard" resets the
71 // variant, whereas the other flags are cumulative.
72 if (!RTStrNICmp(psz, "standard", len))
73 uMediumVariant = MediumVariant_Standard;
74 else if ( !RTStrNICmp(psz, "fixed", len)
75 || !RTStrNICmp(psz, "static", len))
76 uMediumVariant |= MediumVariant_Fixed;
77 else if (!RTStrNICmp(psz, "Diff", len))
78 uMediumVariant |= MediumVariant_Diff;
79 else if (!RTStrNICmp(psz, "split2g", len))
80 uMediumVariant |= MediumVariant_VmdkSplit2G;
81 else if ( !RTStrNICmp(psz, "stream", len)
82 || !RTStrNICmp(psz, "streamoptimized", len))
83 uMediumVariant |= MediumVariant_VmdkStreamOptimized;
84 else if (!RTStrNICmp(psz, "esx", len))
85 uMediumVariant |= MediumVariant_VmdkESX;
86 else
87 rc = VERR_PARSE_ERROR;
88 }
89 if (pszComma)
90 psz += len + 1;
91 else
92 psz += len;
93 }
94
95 if (RT_SUCCESS(rc))
96 *pMediumVariant = (MediumVariant_T)uMediumVariant;
97 return rc;
98}
99
100int parseMediumType(const char *psz, MediumType_T *penmMediumType)
101{
102 int rc = VINF_SUCCESS;
103 MediumType_T enmMediumType = MediumType_Normal;
104 if (!RTStrICmp(psz, "normal"))
105 enmMediumType = MediumType_Normal;
106 else if (!RTStrICmp(psz, "immutable"))
107 enmMediumType = MediumType_Immutable;
108 else if (!RTStrICmp(psz, "writethrough"))
109 enmMediumType = MediumType_Writethrough;
110 else if (!RTStrICmp(psz, "shareable"))
111 enmMediumType = MediumType_Shareable;
112 else if (!RTStrICmp(psz, "readonly"))
113 enmMediumType = MediumType_Readonly;
114 else if (!RTStrICmp(psz, "multiattach"))
115 enmMediumType = MediumType_MultiAttach;
116 else
117 rc = VERR_PARSE_ERROR;
118
119 if (RT_SUCCESS(rc))
120 *penmMediumType = enmMediumType;
121 return rc;
122}
123
124/** @todo move this into getopt, as getting bool values is generic */
125int parseBool(const char *psz, bool *pb)
126{
127 int rc = VINF_SUCCESS;
128 if ( !RTStrICmp(psz, "on")
129 || !RTStrICmp(psz, "yes")
130 || !RTStrICmp(psz, "true")
131 || !RTStrICmp(psz, "1")
132 || !RTStrICmp(psz, "enable")
133 || !RTStrICmp(psz, "enabled"))
134 {
135 *pb = true;
136 }
137 else if ( !RTStrICmp(psz, "off")
138 || !RTStrICmp(psz, "no")
139 || !RTStrICmp(psz, "false")
140 || !RTStrICmp(psz, "0")
141 || !RTStrICmp(psz, "disable")
142 || !RTStrICmp(psz, "disabled"))
143 {
144 *pb = false;
145 }
146 else
147 rc = VERR_PARSE_ERROR;
148
149 return rc;
150}
151
152HRESULT openMedium(HandlerArg *a, const char *pszFilenameOrUuid,
153 DeviceType_T enmDevType, AccessMode_T enmAccessMode,
154 ComPtr<IMedium> &pMedium, bool fForceNewUuidOnOpen,
155 bool fSilent)
156{
157 HRESULT rc;
158 Guid id(pszFilenameOrUuid);
159 char szFilenameAbs[RTPATH_MAX] = "";
160
161 /* If it is no UUID, convert the filename to an absolute one. */
162 if (!id.isValid())
163 {
164 int irc = RTPathAbs(pszFilenameOrUuid, szFilenameAbs, sizeof(szFilenameAbs));
165 if (RT_FAILURE(irc))
166 {
167 if (!fSilent)
168 RTMsgError("Cannot convert filename \"%s\" to absolute path", pszFilenameOrUuid);
169 return E_FAIL;
170 }
171 pszFilenameOrUuid = szFilenameAbs;
172 }
173
174 if (!fSilent)
175 CHECK_ERROR(a->virtualBox, OpenMedium(Bstr(pszFilenameOrUuid).raw(),
176 enmDevType,
177 enmAccessMode,
178 fForceNewUuidOnOpen,
179 pMedium.asOutParam()));
180 else
181 rc = a->virtualBox->OpenMedium(Bstr(pszFilenameOrUuid).raw(),
182 enmDevType,
183 enmAccessMode,
184 fForceNewUuidOnOpen,
185 pMedium.asOutParam());
186
187 return rc;
188}
189
190static HRESULT createMedium(HandlerArg *a, const char *pszFormat,
191 const char *pszFilename, DeviceType_T enmDevType,
192 AccessMode_T enmAccessMode, ComPtr<IMedium> &pMedium)
193{
194 HRESULT rc;
195 char szFilenameAbs[RTPATH_MAX] = "";
196
197 /** @todo laziness shortcut. should really check the MediumFormatCapabilities */
198 if (RTStrICmp(pszFormat, "iSCSI"))
199 {
200 int irc = RTPathAbs(pszFilename, szFilenameAbs, sizeof(szFilenameAbs));
201 if (RT_FAILURE(irc))
202 {
203 RTMsgError("Cannot convert filename \"%s\" to absolute path", pszFilename);
204 return E_FAIL;
205 }
206 pszFilename = szFilenameAbs;
207 }
208
209 CHECK_ERROR(a->virtualBox, CreateMedium(Bstr(pszFormat).raw(),
210 Bstr(pszFilename).raw(),
211 enmAccessMode,
212 enmDevType,
213 pMedium.asOutParam()));
214 return rc;
215}
216
217static const RTGETOPTDEF g_aCreateMediumOptions[] =
218{
219 { "disk", 'H', RTGETOPT_REQ_NOTHING },
220 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
221 { "floppy", 'L', RTGETOPT_REQ_NOTHING },
222 { "--filename", 'f', RTGETOPT_REQ_STRING },
223 { "-filename", 'f', RTGETOPT_REQ_STRING }, // deprecated
224 { "--diffparent", 'd', RTGETOPT_REQ_STRING },
225 { "--size", 's', RTGETOPT_REQ_UINT64 },
226 { "-size", 's', RTGETOPT_REQ_UINT64 }, // deprecated
227 { "--sizebyte", 'S', RTGETOPT_REQ_UINT64 },
228 { "--format", 'o', RTGETOPT_REQ_STRING },
229 { "-format", 'o', RTGETOPT_REQ_STRING }, // deprecated
230 { "--static", 'F', RTGETOPT_REQ_NOTHING },
231 { "-static", 'F', RTGETOPT_REQ_NOTHING }, // deprecated
232 { "--variant", 'm', RTGETOPT_REQ_STRING },
233 { "-variant", 'm', RTGETOPT_REQ_STRING }, // deprecated
234};
235
236RTEXITCODE handleCreateMedium(HandlerArg *a)
237{
238 HRESULT rc;
239 int vrc;
240 const char *filename = NULL;
241 const char *diffparent = NULL;
242 uint64_t size = 0;
243 enum {
244 CMD_NONE,
245 CMD_DISK,
246 CMD_DVD,
247 CMD_FLOPPY
248 } cmd = CMD_NONE;
249 const char *format = NULL;
250 bool fBase = true;
251 MediumVariant_T enmMediumVariant = MediumVariant_Standard;
252
253 int c;
254 RTGETOPTUNION ValueUnion;
255 RTGETOPTSTATE GetState;
256 // start at 0 because main() has hacked both the argc and argv given to us
257 RTGetOptInit(&GetState, a->argc, a->argv, g_aCreateMediumOptions, RT_ELEMENTS(g_aCreateMediumOptions),
258 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
259 while ((c = RTGetOpt(&GetState, &ValueUnion)))
260 {
261 switch (c)
262 {
263 case 'H': // disk
264 if (cmd != CMD_NONE)
265 return errorSyntax(USAGE_CREATEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
266 cmd = CMD_DISK;
267 break;
268
269 case 'D': // DVD
270 if (cmd != CMD_NONE)
271 return errorSyntax(USAGE_CREATEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
272 cmd = CMD_DVD;
273 break;
274
275 case 'L': // floppy
276 if (cmd != CMD_NONE)
277 return errorSyntax(USAGE_CREATEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
278 cmd = CMD_FLOPPY;
279 break;
280
281 case 'f': // --filename
282 filename = ValueUnion.psz;
283 break;
284
285 case 'd': // --diffparent
286 diffparent = ValueUnion.psz;
287 fBase = false;
288 break;
289
290 case 's': // --size
291 size = ValueUnion.u64 * _1M;
292 break;
293
294 case 'S': // --sizebyte
295 size = ValueUnion.u64;
296 break;
297
298 case 'o': // --format
299 format = ValueUnion.psz;
300 break;
301
302 case 'F': // --static ("fixed"/"flat")
303 {
304 unsigned uMediumVariant = (unsigned)enmMediumVariant;
305 uMediumVariant |= MediumVariant_Fixed;
306 enmMediumVariant = (MediumVariant_T)uMediumVariant;
307 break;
308 }
309
310 case 'm': // --variant
311 vrc = parseMediumVariant(ValueUnion.psz, &enmMediumVariant);
312 if (RT_FAILURE(vrc))
313 return errorArgument("Invalid medium variant '%s'", ValueUnion.psz);
314 break;
315
316 case VINF_GETOPT_NOT_OPTION:
317 return errorSyntax(USAGE_CREATEMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
318
319 default:
320 if (c > 0)
321 {
322 if (RT_C_IS_PRINT(c))
323 return errorSyntax(USAGE_CREATEMEDIUM, "Invalid option -%c", c);
324 else
325 return errorSyntax(USAGE_CREATEMEDIUM, "Invalid option case %i", c);
326 }
327 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
328 return errorSyntax(USAGE_CREATEMEDIUM, "unknown option: %s\n", ValueUnion.psz);
329 else if (ValueUnion.pDef)
330 return errorSyntax(USAGE_CREATEMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
331 else
332 return errorSyntax(USAGE_CREATEMEDIUM, "error: %Rrs", c);
333 }
334 }
335
336 /* check the outcome */
337 if (cmd == CMD_NONE)
338 cmd = CMD_DISK;
339 ComPtr<IMedium> pParentMedium;
340 if (fBase)
341 {
342 if ( !filename
343 || !*filename
344 || size == 0)
345 return errorSyntax(USAGE_CREATEMEDIUM, "Parameters --filename and --size are required");
346 if (!format || !*format)
347 {
348 if (cmd == CMD_DISK)
349 format = "VDI";
350 else if (cmd == CMD_DVD || cmd == CMD_FLOPPY)
351 {
352 format = "RAW";
353 unsigned uMediumVariant = (unsigned)enmMediumVariant;
354 uMediumVariant |= MediumVariant_Fixed;
355 enmMediumVariant = (MediumVariant_T)uMediumVariant;
356 }
357 }
358 }
359 else
360 {
361 if ( !filename
362 || !*filename)
363 return errorSyntax(USAGE_CREATEMEDIUM, "Parameters --filename is required");
364 size = 0;
365 if (cmd != CMD_DISK)
366 return errorSyntax(USAGE_CREATEMEDIUM, "Creating a differencing medium is only supported for hard disks");
367 enmMediumVariant = MediumVariant_Diff;
368 if (!format || !*format)
369 {
370 const char *pszExt = RTPathSuffix(filename);
371 /* Skip over . if there is an extension. */
372 if (pszExt)
373 pszExt++;
374 if (!pszExt || !*pszExt)
375 format = "VDI";
376 else
377 format = pszExt;
378 }
379 rc = openMedium(a, diffparent, DeviceType_HardDisk,
380 AccessMode_ReadWrite, pParentMedium,
381 false /* fForceNewUuidOnOpen */, false /* fSilent */);
382 if (FAILED(rc))
383 return RTEXITCODE_FAILURE;
384 if (pParentMedium.isNull())
385 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Invalid parent hard disk reference, avoiding crash");
386 MediumState_T state;
387 CHECK_ERROR(pParentMedium, COMGETTER(State)(&state));
388 if (FAILED(rc))
389 return RTEXITCODE_FAILURE;
390 if (state == MediumState_Inaccessible)
391 {
392 CHECK_ERROR(pParentMedium, RefreshState(&state));
393 if (FAILED(rc))
394 return RTEXITCODE_FAILURE;
395 }
396 }
397 /* check for filename extension */
398 /** @todo use IMediumFormat to cover all extensions generically */
399 Utf8Str strName(filename);
400 if (!RTPathHasSuffix(strName.c_str()))
401 {
402 Utf8Str strFormat(format);
403 if (cmd == CMD_DISK)
404 {
405 if (strFormat.compare("vmdk", RTCString::CaseInsensitive) == 0)
406 strName.append(".vmdk");
407 else if (strFormat.compare("vhd", RTCString::CaseInsensitive) == 0)
408 strName.append(".vhd");
409 else
410 strName.append(".vdi");
411 } else if (cmd == CMD_DVD)
412 strName.append(".iso");
413 else if (cmd == CMD_FLOPPY)
414 strName.append(".img");
415 filename = strName.c_str();
416 }
417
418 ComPtr<IMedium> pMedium;
419 if (cmd == CMD_DISK)
420 rc = createMedium(a, format, filename, DeviceType_HardDisk,
421 AccessMode_ReadWrite, pMedium);
422 else if (cmd == CMD_DVD)
423 rc = createMedium(a, format, filename, DeviceType_DVD,
424 AccessMode_ReadOnly, pMedium);
425 else if (cmd == CMD_FLOPPY)
426 rc = createMedium(a, format, filename, DeviceType_Floppy,
427 AccessMode_ReadWrite, pMedium);
428 else
429 rc = E_INVALIDARG; /* cannot happen but make gcc happy */
430
431 if (SUCCEEDED(rc) && pMedium)
432 {
433 ComPtr<IProgress> pProgress;
434 com::SafeArray<MediumVariant_T> l_variants(sizeof(MediumVariant_T)*8);
435
436 for (ULONG i = 0; i < l_variants.size(); ++i)
437 {
438 ULONG temp = enmMediumVariant;
439 temp &= 1<<i;
440 l_variants [i] = (MediumVariant_T)temp;
441 }
442
443 if (fBase)
444 CHECK_ERROR(pMedium, CreateBaseStorage(size, ComSafeArrayAsInParam(l_variants), pProgress.asOutParam()));
445 else
446 CHECK_ERROR(pParentMedium, CreateDiffStorage(pMedium, ComSafeArrayAsInParam(l_variants), pProgress.asOutParam()));
447 if (SUCCEEDED(rc) && pProgress)
448 {
449 rc = showProgress(pProgress);
450 CHECK_PROGRESS_ERROR(pProgress, ("Failed to create medium"));
451 }
452 }
453
454 if (SUCCEEDED(rc) && pMedium)
455 {
456 Bstr uuid;
457 CHECK_ERROR(pMedium, COMGETTER(Id)(uuid.asOutParam()));
458 RTPrintf("Medium created. UUID: %s\n", Utf8Str(uuid).c_str());
459
460 //CHECK_ERROR(pMedium, Close());
461 }
462 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
463}
464
465static const RTGETOPTDEF g_aModifyMediumOptions[] =
466{
467 { "disk", 'H', RTGETOPT_REQ_NOTHING },
468 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
469 { "floppy", 'L', RTGETOPT_REQ_NOTHING },
470 { "--type", 't', RTGETOPT_REQ_STRING },
471 { "-type", 't', RTGETOPT_REQ_STRING }, // deprecated
472 { "settype", 't', RTGETOPT_REQ_STRING }, // deprecated
473 { "--autoreset", 'z', RTGETOPT_REQ_STRING },
474 { "-autoreset", 'z', RTGETOPT_REQ_STRING }, // deprecated
475 { "autoreset", 'z', RTGETOPT_REQ_STRING }, // deprecated
476 { "--property", 'p', RTGETOPT_REQ_STRING },
477 { "--compact", 'c', RTGETOPT_REQ_NOTHING },
478 { "-compact", 'c', RTGETOPT_REQ_NOTHING }, // deprecated
479 { "compact", 'c', RTGETOPT_REQ_NOTHING }, // deprecated
480 { "--resize", 'r', RTGETOPT_REQ_UINT64 },
481 { "--resizebyte", 'R', RTGETOPT_REQ_UINT64 },
482 { "--move", 'm', RTGETOPT_REQ_STRING },
483 { "--description", 'd', RTGETOPT_REQ_STRING }
484};
485
486RTEXITCODE handleModifyMedium(HandlerArg *a)
487{
488 HRESULT rc;
489 int vrc;
490 enum {
491 CMD_NONE,
492 CMD_DISK,
493 CMD_DVD,
494 CMD_FLOPPY
495 } cmd = CMD_NONE;
496 ComPtr<IMedium> pMedium;
497 MediumType_T enmMediumType = MediumType_Normal; /* Shut up MSC */
498 bool AutoReset = false;
499 SafeArray<BSTR> mediumPropNames;
500 SafeArray<BSTR> mediumPropValues;
501 bool fModifyMediumType = false;
502 bool fModifyAutoReset = false;
503 bool fModifyProperties = false;
504 bool fModifyCompact = false;
505 bool fModifyResize = false;
506 bool fModifyResizeMB = false;
507 bool fModifyLocation = false;
508 bool fModifyDescription = false;
509 uint64_t cbResize = 0;
510 const char *pszFilenameOrUuid = NULL;
511 const char *pszNewLocation = NULL;
512
513 int c;
514 RTGETOPTUNION ValueUnion;
515 RTGETOPTSTATE GetState;
516 // start at 0 because main() has hacked both the argc and argv given to us
517 RTGetOptInit(&GetState, a->argc, a->argv, g_aModifyMediumOptions, RT_ELEMENTS(g_aModifyMediumOptions),
518 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
519 while ((c = RTGetOpt(&GetState, &ValueUnion)))
520 {
521 switch (c)
522 {
523 case 'H': // disk
524 if (cmd != CMD_NONE)
525 return errorSyntax(USAGE_MODIFYMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
526 cmd = CMD_DISK;
527 break;
528
529 case 'D': // DVD
530 if (cmd != CMD_NONE)
531 return errorSyntax(USAGE_MODIFYMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
532 cmd = CMD_DVD;
533 break;
534
535 case 'L': // floppy
536 if (cmd != CMD_NONE)
537 return errorSyntax(USAGE_MODIFYMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
538 cmd = CMD_FLOPPY;
539 break;
540
541 case 't': // --type
542 vrc = parseMediumType(ValueUnion.psz, &enmMediumType);
543 if (RT_FAILURE(vrc))
544 return errorArgument("Invalid medium type '%s'", ValueUnion.psz);
545 fModifyMediumType = true;
546 break;
547
548 case 'z': // --autoreset
549 vrc = parseBool(ValueUnion.psz, &AutoReset);
550 if (RT_FAILURE(vrc))
551 return errorArgument("Invalid autoreset parameter '%s'", ValueUnion.psz);
552 fModifyAutoReset = true;
553 break;
554
555 case 'p': // --property
556 {
557 /* Parse 'name=value' */
558 char *pszProperty = RTStrDup(ValueUnion.psz);
559 if (pszProperty)
560 {
561 char *pDelimiter = strchr(pszProperty, '=');
562 if (pDelimiter)
563 {
564 *pDelimiter = '\0';
565
566 Bstr bstrName(pszProperty);
567 Bstr bstrValue(&pDelimiter[1]);
568 bstrName.detachTo(mediumPropNames.appendedRaw());
569 bstrValue.detachTo(mediumPropValues.appendedRaw());
570 fModifyProperties = true;
571 }
572 else
573 {
574 errorArgument("Invalid --property argument '%s'", ValueUnion.psz);
575 rc = E_FAIL;
576 }
577 RTStrFree(pszProperty);
578 }
579 else
580 {
581 RTStrmPrintf(g_pStdErr, "Error: Failed to allocate memory for medium property '%s'\n", ValueUnion.psz);
582 rc = E_FAIL;
583 }
584 break;
585 }
586
587 case 'c': // --compact
588 fModifyCompact = true;
589 break;
590
591 case 'r': // --resize
592 cbResize = ValueUnion.u64 * _1M;
593 fModifyResize = true;
594 fModifyResizeMB = true; // do sanity check!
595 break;
596
597 case 'R': // --resizebyte
598 cbResize = ValueUnion.u64;
599 fModifyResize = true;
600 break;
601
602 case 'm': // --move
603 /* Get a new location */
604 pszNewLocation = RTStrDup(ValueUnion.psz);
605 fModifyLocation = true;
606 break;
607
608 case 'd': // --description
609 /* Get a new description */
610 pszNewLocation = RTStrDup(ValueUnion.psz);
611 fModifyDescription = true;
612 break;
613
614 case VINF_GETOPT_NOT_OPTION:
615 if (!pszFilenameOrUuid)
616 pszFilenameOrUuid = ValueUnion.psz;
617 else
618 return errorSyntax(USAGE_MODIFYMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
619 break;
620
621 default:
622 if (c > 0)
623 {
624 if (RT_C_IS_PRINT(c))
625 return errorSyntax(USAGE_MODIFYMEDIUM, "Invalid option -%c", c);
626 else
627 return errorSyntax(USAGE_MODIFYMEDIUM, "Invalid option case %i", c);
628 }
629 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
630 return errorSyntax(USAGE_MODIFYMEDIUM, "unknown option: %s\n", ValueUnion.psz);
631 else if (ValueUnion.pDef)
632 return errorSyntax(USAGE_MODIFYMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
633 else
634 return errorSyntax(USAGE_MODIFYMEDIUM, "error: %Rrs", c);
635 }
636 }
637
638 if (cmd == CMD_NONE)
639 cmd = CMD_DISK;
640
641 if (!pszFilenameOrUuid)
642 return errorSyntax(USAGE_MODIFYMEDIUM, "Medium name or UUID required");
643
644 if (!fModifyMediumType
645 && !fModifyAutoReset
646 && !fModifyProperties
647 && !fModifyCompact
648 && !fModifyResize
649 && !fModifyLocation
650 && !fModifyDescription)
651 return errorSyntax(USAGE_MODIFYMEDIUM, "No operation specified");
652
653 /* Always open the medium if necessary, there is no other way. */
654 if (cmd == CMD_DISK)
655 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
656 AccessMode_ReadWrite, pMedium,
657 false /* fForceNewUuidOnOpen */, false /* fSilent */);
658 else if (cmd == CMD_DVD)
659 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
660 AccessMode_ReadOnly, pMedium,
661 false /* fForceNewUuidOnOpen */, false /* fSilent */);
662 else if (cmd == CMD_FLOPPY)
663 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
664 AccessMode_ReadWrite, pMedium,
665 false /* fForceNewUuidOnOpen */, false /* fSilent */);
666 else
667 rc = E_INVALIDARG; /* cannot happen but make gcc happy */
668 if (FAILED(rc))
669 return RTEXITCODE_FAILURE;
670 if (pMedium.isNull())
671 {
672 RTMsgError("Invalid medium reference, avoiding crash");
673 return RTEXITCODE_FAILURE;
674 }
675
676 if ( fModifyResize
677 && fModifyResizeMB)
678 {
679 // Sanity check
680 //
681 // In general users should know what they do but in this case users have no
682 // alternative to VBoxManage. If happens that one wants to resize the disk
683 // and uses --resize and does not consider that this parameter expects the
684 // new medium size in MB not Byte. If the operation is started and then
685 // aborted by the user, the result is most likely a medium which doesn't
686 // work anymore.
687 LONG64 logicalSize;
688 pMedium->COMGETTER(LogicalSize)(&logicalSize);
689 if (cbResize > (uint64_t)logicalSize * _1M)
690 {
691 RTMsgError("Error: Attempt to resize the medium from %RU64.%RU64 MB to %RU64.%RU64 MB. Use --resizebyte if this is intended!\n",
692 logicalSize / _1M, (logicalSize % _1M) / (_1M / 10), cbResize / _1M, (cbResize % _1M) / (_1M / 10));
693 return RTEXITCODE_FAILURE;
694 }
695 }
696
697 if (fModifyMediumType)
698 {
699 MediumType_T enmCurrMediumType;
700 CHECK_ERROR(pMedium, COMGETTER(Type)(&enmCurrMediumType));
701
702 if (enmCurrMediumType != enmMediumType)
703 CHECK_ERROR(pMedium, COMSETTER(Type)(enmMediumType));
704 }
705
706 if (fModifyAutoReset)
707 {
708 CHECK_ERROR(pMedium, COMSETTER(AutoReset)(AutoReset));
709 }
710
711 if (fModifyProperties)
712 {
713 CHECK_ERROR(pMedium, SetProperties(ComSafeArrayAsInParam(mediumPropNames), ComSafeArrayAsInParam(mediumPropValues)));
714 }
715
716 if (fModifyCompact)
717 {
718 ComPtr<IProgress> pProgress;
719 CHECK_ERROR(pMedium, Compact(pProgress.asOutParam()));
720 if (SUCCEEDED(rc))
721 rc = showProgress(pProgress);
722 if (FAILED(rc))
723 {
724 if (rc == E_NOTIMPL)
725 RTMsgError("Compact medium operation is not implemented!");
726 else if (rc == VBOX_E_NOT_SUPPORTED)
727 RTMsgError("Compact medium operation for this format is not implemented yet!");
728 else if (!pProgress.isNull())
729 CHECK_PROGRESS_ERROR(pProgress, ("Failed to compact medium"));
730 else
731 RTMsgError("Failed to compact medium!");
732 }
733 }
734
735 if (fModifyResize)
736 {
737 ComPtr<IProgress> pProgress;
738 CHECK_ERROR(pMedium, Resize(cbResize, pProgress.asOutParam()));
739 if (SUCCEEDED(rc))
740 rc = showProgress(pProgress);
741 if (FAILED(rc))
742 {
743 if (rc == E_NOTIMPL)
744 RTMsgError("Resize medium operation is not implemented!");
745 else if (rc == VBOX_E_NOT_SUPPORTED)
746 RTMsgError("Resize medium operation for this format is not implemented yet!");
747 else if (!pProgress.isNull())
748 CHECK_PROGRESS_ERROR(pProgress, ("Failed to resize medium"));
749 else
750 RTMsgError("Failed to resize medium!");
751 }
752 }
753
754 if (fModifyLocation)
755 {
756 do
757 {
758 ComPtr<IProgress> pProgress;
759 Utf8Str strLocation(pszNewLocation);
760 CHECK_ERROR(pMedium, SetLocation(Bstr(pszNewLocation).raw(), pProgress.asOutParam()));
761
762 if (SUCCEEDED(rc) && !pProgress.isNull())
763 {
764 rc = showProgress(pProgress);
765 CHECK_PROGRESS_ERROR(pProgress, ("Failed to move medium"));
766 }
767
768 Bstr uuid;
769 CHECK_ERROR_BREAK(pMedium, COMGETTER(Id)(uuid.asOutParam()));
770
771 RTPrintf("Move medium with UUID %s finished \n", Utf8Str(uuid).c_str());
772 }
773 while (0);
774 }
775
776 if (fModifyDescription)
777 {
778 CHECK_ERROR(pMedium, COMSETTER(Description)(Bstr(pszNewLocation).raw()));
779
780 RTPrintf("Medium description has been changed. \n");
781 }
782
783 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
784}
785
786static const RTGETOPTDEF g_aCloneMediumOptions[] =
787{
788 { "disk", 'd', RTGETOPT_REQ_NOTHING },
789 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
790 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
791 { "--format", 'o', RTGETOPT_REQ_STRING },
792 { "-format", 'o', RTGETOPT_REQ_STRING },
793 { "--static", 'F', RTGETOPT_REQ_NOTHING },
794 { "-static", 'F', RTGETOPT_REQ_NOTHING },
795 { "--existing", 'E', RTGETOPT_REQ_NOTHING },
796 { "--variant", 'm', RTGETOPT_REQ_STRING },
797 { "-variant", 'm', RTGETOPT_REQ_STRING },
798};
799
800RTEXITCODE handleCloneMedium(HandlerArg *a)
801{
802 HRESULT rc;
803 int vrc;
804 enum {
805 CMD_NONE,
806 CMD_DISK,
807 CMD_DVD,
808 CMD_FLOPPY
809 } cmd = CMD_NONE;
810 const char *pszSrc = NULL;
811 const char *pszDst = NULL;
812 Bstr format;
813 MediumVariant_T enmMediumVariant = MediumVariant_Standard;
814 bool fExisting = false;
815
816 int c;
817 RTGETOPTUNION ValueUnion;
818 RTGETOPTSTATE GetState;
819 // start at 0 because main() has hacked both the argc and argv given to us
820 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloneMediumOptions, RT_ELEMENTS(g_aCloneMediumOptions),
821 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
822 while ((c = RTGetOpt(&GetState, &ValueUnion)))
823 {
824 switch (c)
825 {
826 case 'd': // disk
827 if (cmd != CMD_NONE)
828 return errorSyntax(USAGE_CLONEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
829 cmd = CMD_DISK;
830 break;
831
832 case 'D': // DVD
833 if (cmd != CMD_NONE)
834 return errorSyntax(USAGE_CLONEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
835 cmd = CMD_DVD;
836 break;
837
838 case 'f': // floppy
839 if (cmd != CMD_NONE)
840 return errorSyntax(USAGE_CLONEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
841 cmd = CMD_FLOPPY;
842 break;
843
844 case 'o': // --format
845 format = ValueUnion.psz;
846 break;
847
848 case 'F': // --static
849 {
850 unsigned uMediumVariant = (unsigned)enmMediumVariant;
851 uMediumVariant |= MediumVariant_Fixed;
852 enmMediumVariant = (MediumVariant_T)uMediumVariant;
853 break;
854 }
855
856 case 'E': // --existing
857 fExisting = true;
858 break;
859
860 case 'm': // --variant
861 vrc = parseMediumVariant(ValueUnion.psz, &enmMediumVariant);
862 if (RT_FAILURE(vrc))
863 return errorArgument("Invalid medium variant '%s'", ValueUnion.psz);
864 break;
865
866 case VINF_GETOPT_NOT_OPTION:
867 if (!pszSrc)
868 pszSrc = ValueUnion.psz;
869 else if (!pszDst)
870 pszDst = ValueUnion.psz;
871 else
872 return errorSyntax(USAGE_CLONEMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
873 break;
874
875 default:
876 if (c > 0)
877 {
878 if (RT_C_IS_GRAPH(c))
879 return errorSyntax(USAGE_CLONEMEDIUM, "unhandled option: -%c", c);
880 else
881 return errorSyntax(USAGE_CLONEMEDIUM, "unhandled option: %i", c);
882 }
883 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
884 return errorSyntax(USAGE_CLONEMEDIUM, "unknown option: %s", ValueUnion.psz);
885 else if (ValueUnion.pDef)
886 return errorSyntax(USAGE_CLONEMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
887 else
888 return errorSyntax(USAGE_CLONEMEDIUM, "error: %Rrs", c);
889 }
890 }
891
892 if (cmd == CMD_NONE)
893 cmd = CMD_DISK;
894 if (!pszSrc)
895 return errorSyntax(USAGE_CLONEMEDIUM, "Mandatory UUID or input file parameter missing");
896 if (!pszDst)
897 return errorSyntax(USAGE_CLONEMEDIUM, "Mandatory output file parameter missing");
898 if (fExisting && (!format.isEmpty() || enmMediumVariant != MediumType_Normal))
899 return errorSyntax(USAGE_CLONEMEDIUM, "Specified options which cannot be used with --existing");
900
901 ComPtr<IMedium> pSrcMedium;
902 ComPtr<IMedium> pDstMedium;
903
904 if (cmd == CMD_DISK)
905 rc = openMedium(a, pszSrc, DeviceType_HardDisk, AccessMode_ReadOnly, pSrcMedium,
906 false /* fForceNewUuidOnOpen */, false /* fSilent */);
907 else if (cmd == CMD_DVD)
908 rc = openMedium(a, pszSrc, DeviceType_DVD, AccessMode_ReadOnly, pSrcMedium,
909 false /* fForceNewUuidOnOpen */, false /* fSilent */);
910 else if (cmd == CMD_FLOPPY)
911 rc = openMedium(a, pszSrc, DeviceType_Floppy, AccessMode_ReadOnly, pSrcMedium,
912 false /* fForceNewUuidOnOpen */, false /* fSilent */);
913 else
914 rc = E_INVALIDARG; /* cannot happen but make gcc happy */
915 if (FAILED(rc))
916 return RTEXITCODE_FAILURE;
917
918 do
919 {
920 /* open/create destination medium */
921 if (fExisting)
922 {
923 if (cmd == CMD_DISK)
924 rc = openMedium(a, pszDst, DeviceType_HardDisk, AccessMode_ReadWrite, pDstMedium,
925 false /* fForceNewUuidOnOpen */, false /* fSilent */);
926 else if (cmd == CMD_DVD)
927 rc = openMedium(a, pszDst, DeviceType_DVD, AccessMode_ReadOnly, pDstMedium,
928 false /* fForceNewUuidOnOpen */, false /* fSilent */);
929 else if (cmd == CMD_FLOPPY)
930 rc = openMedium(a, pszDst, DeviceType_Floppy, AccessMode_ReadWrite, pDstMedium,
931 false /* fForceNewUuidOnOpen */, false /* fSilent */);
932 if (FAILED(rc))
933 break;
934
935 /* Perform accessibility check now. */
936 MediumState_T state;
937 CHECK_ERROR_BREAK(pDstMedium, RefreshState(&state));
938 CHECK_ERROR_BREAK(pDstMedium, COMGETTER(Format)(format.asOutParam()));
939 }
940 else
941 {
942 /* use the format of the source medium if unspecified */
943 if (format.isEmpty())
944 CHECK_ERROR_BREAK(pSrcMedium, COMGETTER(Format)(format.asOutParam()));
945 Utf8Str strFormat(format);
946 if (cmd == CMD_DISK)
947 rc = createMedium(a, strFormat.c_str(), pszDst, DeviceType_HardDisk,
948 AccessMode_ReadWrite, pDstMedium);
949 else if (cmd == CMD_DVD)
950 rc = createMedium(a, strFormat.c_str(), pszDst, DeviceType_DVD,
951 AccessMode_ReadOnly, pDstMedium);
952 else if (cmd == CMD_FLOPPY)
953 rc = createMedium(a, strFormat.c_str(), pszDst, DeviceType_Floppy,
954 AccessMode_ReadWrite, pDstMedium);
955 if (FAILED(rc))
956 break;
957 }
958
959 ComPtr<IProgress> pProgress;
960 com::SafeArray<MediumVariant_T> l_variants(sizeof(MediumVariant_T)*8);
961
962 for (ULONG i = 0; i < l_variants.size(); ++i)
963 {
964 ULONG temp = enmMediumVariant;
965 temp &= 1<<i;
966 l_variants [i] = (MediumVariant_T)temp;
967 }
968
969 CHECK_ERROR_BREAK(pSrcMedium, CloneTo(pDstMedium, ComSafeArrayAsInParam(l_variants), NULL, pProgress.asOutParam()));
970
971 rc = showProgress(pProgress);
972 CHECK_PROGRESS_ERROR_BREAK(pProgress, ("Failed to clone medium"));
973
974 Bstr uuid;
975 CHECK_ERROR_BREAK(pDstMedium, COMGETTER(Id)(uuid.asOutParam()));
976
977 RTPrintf("Clone medium created in format '%ls'. UUID: %s\n",
978 format.raw(), Utf8Str(uuid).c_str());
979 }
980 while (0);
981
982 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
983}
984
985static const RTGETOPTDEF g_aConvertFromRawHardDiskOptions[] =
986{
987 { "--format", 'o', RTGETOPT_REQ_STRING },
988 { "-format", 'o', RTGETOPT_REQ_STRING },
989 { "--static", 'F', RTGETOPT_REQ_NOTHING },
990 { "-static", 'F', RTGETOPT_REQ_NOTHING },
991 { "--variant", 'm', RTGETOPT_REQ_STRING },
992 { "-variant", 'm', RTGETOPT_REQ_STRING },
993 { "--uuid", 'u', RTGETOPT_REQ_STRING },
994};
995
996RTEXITCODE handleConvertFromRaw(HandlerArg *a)
997{
998 int rc = VINF_SUCCESS;
999 bool fReadFromStdIn = false;
1000 const char *format = "VDI";
1001 const char *srcfilename = NULL;
1002 const char *dstfilename = NULL;
1003 const char *filesize = NULL;
1004 unsigned uImageFlags = VD_IMAGE_FLAGS_NONE;
1005 void *pvBuf = NULL;
1006 RTUUID uuid;
1007 PCRTUUID pUuid = NULL;
1008
1009 int c;
1010 RTGETOPTUNION ValueUnion;
1011 RTGETOPTSTATE GetState;
1012 // start at 0 because main() has hacked both the argc and argv given to us
1013 RTGetOptInit(&GetState, a->argc, a->argv, g_aConvertFromRawHardDiskOptions, RT_ELEMENTS(g_aConvertFromRawHardDiskOptions),
1014 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1015 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1016 {
1017 switch (c)
1018 {
1019 case 'u': // --uuid
1020 if (RT_FAILURE(RTUuidFromStr(&uuid, ValueUnion.psz)))
1021 return errorSyntax(USAGE_CONVERTFROMRAW, "Invalid UUID '%s'", ValueUnion.psz);
1022 pUuid = &uuid;
1023 break;
1024 case 'o': // --format
1025 format = ValueUnion.psz;
1026 break;
1027
1028 case 'm': // --variant
1029 {
1030 MediumVariant_T enmMediumVariant = MediumVariant_Standard;
1031 rc = parseMediumVariant(ValueUnion.psz, &enmMediumVariant);
1032 if (RT_FAILURE(rc))
1033 return errorArgument("Invalid medium variant '%s'", ValueUnion.psz);
1034 /// @todo cleaner solution than assuming 1:1 mapping?
1035 uImageFlags = (unsigned)enmMediumVariant;
1036 break;
1037 }
1038 case VINF_GETOPT_NOT_OPTION:
1039 if (!srcfilename)
1040 {
1041 srcfilename = ValueUnion.psz;
1042 fReadFromStdIn = !strcmp(srcfilename, "stdin");
1043 }
1044 else if (!dstfilename)
1045 dstfilename = ValueUnion.psz;
1046 else if (fReadFromStdIn && !filesize)
1047 filesize = ValueUnion.psz;
1048 else
1049 return errorSyntax(USAGE_CONVERTFROMRAW, "Invalid parameter '%s'", ValueUnion.psz);
1050 break;
1051
1052 default:
1053 return errorGetOpt(USAGE_CONVERTFROMRAW, c, &ValueUnion);
1054 }
1055 }
1056
1057 if (!srcfilename || !dstfilename || (fReadFromStdIn && !filesize))
1058 return errorSyntax(USAGE_CONVERTFROMRAW, "Incorrect number of parameters");
1059 RTStrmPrintf(g_pStdErr, "Converting from raw image file=\"%s\" to file=\"%s\"...\n",
1060 srcfilename, dstfilename);
1061
1062 PVBOXHDD pDisk = NULL;
1063
1064 PVDINTERFACE pVDIfs = NULL;
1065 VDINTERFACEERROR vdInterfaceError;
1066 vdInterfaceError.pfnError = handleVDError;
1067 vdInterfaceError.pfnMessage = NULL;
1068
1069 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1070 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1071 AssertRC(rc);
1072
1073 /* open raw image file. */
1074 RTFILE File;
1075 if (fReadFromStdIn)
1076 rc = RTFileFromNative(&File, RTFILE_NATIVE_STDIN);
1077 else
1078 rc = RTFileOpen(&File, srcfilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1079 if (RT_FAILURE(rc))
1080 {
1081 RTMsgError("Cannot open file \"%s\": %Rrc", srcfilename, rc);
1082 goto out;
1083 }
1084
1085 uint64_t cbFile;
1086 /* get image size. */
1087 if (fReadFromStdIn)
1088 cbFile = RTStrToUInt64(filesize);
1089 else
1090 rc = RTFileGetSize(File, &cbFile);
1091 if (RT_FAILURE(rc))
1092 {
1093 RTMsgError("Cannot get image size for file \"%s\": %Rrc", srcfilename, rc);
1094 goto out;
1095 }
1096
1097 RTStrmPrintf(g_pStdErr, "Creating %s image with size %RU64 bytes (%RU64MB)...\n",
1098 (uImageFlags & VD_IMAGE_FLAGS_FIXED) ? "fixed" : "dynamic", cbFile, (cbFile + _1M - 1) / _1M);
1099 char pszComment[256];
1100 RTStrPrintf(pszComment, sizeof(pszComment), "Converted image from %s", srcfilename);
1101 rc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1102 if (RT_FAILURE(rc))
1103 {
1104 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
1105 goto out;
1106 }
1107
1108 Assert(RT_MIN(cbFile / 512 / 16 / 63, 16383) -
1109 (unsigned int)RT_MIN(cbFile / 512 / 16 / 63, 16383) == 0);
1110 VDGEOMETRY PCHS, LCHS;
1111 PCHS.cCylinders = (unsigned int)RT_MIN(cbFile / 512 / 16 / 63, 16383);
1112 PCHS.cHeads = 16;
1113 PCHS.cSectors = 63;
1114 LCHS.cCylinders = 0;
1115 LCHS.cHeads = 0;
1116 LCHS.cSectors = 0;
1117 rc = VDCreateBase(pDisk, format, dstfilename, cbFile,
1118 uImageFlags, pszComment, &PCHS, &LCHS, pUuid,
1119 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1120 if (RT_FAILURE(rc))
1121 {
1122 RTMsgError("Cannot create the disk image \"%s\": %Rrc", dstfilename, rc);
1123 goto out;
1124 }
1125
1126 size_t cbBuffer;
1127 cbBuffer = _1M;
1128 pvBuf = RTMemAlloc(cbBuffer);
1129 if (!pvBuf)
1130 {
1131 rc = VERR_NO_MEMORY;
1132 RTMsgError("Out of memory allocating buffers for image \"%s\": %Rrc", dstfilename, rc);
1133 goto out;
1134 }
1135
1136 uint64_t offFile;
1137 offFile = 0;
1138 while (offFile < cbFile)
1139 {
1140 size_t cbRead;
1141 size_t cbToRead;
1142 cbRead = 0;
1143 cbToRead = cbFile - offFile >= (uint64_t)cbBuffer ?
1144 cbBuffer : (size_t)(cbFile - offFile);
1145 rc = RTFileRead(File, pvBuf, cbToRead, &cbRead);
1146 if (RT_FAILURE(rc) || !cbRead)
1147 break;
1148 rc = VDWrite(pDisk, offFile, pvBuf, cbRead);
1149 if (RT_FAILURE(rc))
1150 {
1151 RTMsgError("Failed to write to disk image \"%s\": %Rrc", dstfilename, rc);
1152 goto out;
1153 }
1154 offFile += cbRead;
1155 }
1156
1157out:
1158 if (pvBuf)
1159 RTMemFree(pvBuf);
1160 if (pDisk)
1161 VDClose(pDisk, RT_FAILURE(rc));
1162 if (File != NIL_RTFILE)
1163 RTFileClose(File);
1164
1165 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1166}
1167
1168HRESULT showMediumInfo(const ComPtr<IVirtualBox> &pVirtualBox,
1169 const ComPtr<IMedium> &pMedium,
1170 const char *pszParentUUID,
1171 bool fOptLong)
1172{
1173 HRESULT rc = S_OK;
1174 do
1175 {
1176 Bstr uuid;
1177 pMedium->COMGETTER(Id)(uuid.asOutParam());
1178 RTPrintf("UUID: %ls\n", uuid.raw());
1179 if (pszParentUUID)
1180 RTPrintf("Parent UUID: %s\n", pszParentUUID);
1181
1182 /* check for accessibility */
1183 MediumState_T enmState;
1184 CHECK_ERROR_BREAK(pMedium, RefreshState(&enmState));
1185 pMedium->RefreshState(&enmState);
1186 const char *pszState = "unknown";
1187 switch (enmState)
1188 {
1189 case MediumState_NotCreated:
1190 pszState = "not created";
1191 break;
1192 case MediumState_Created:
1193 pszState = "created";
1194 break;
1195 case MediumState_LockedRead:
1196 pszState = "locked read";
1197 break;
1198 case MediumState_LockedWrite:
1199 pszState = "locked write";
1200 break;
1201 case MediumState_Inaccessible:
1202 pszState = "inaccessible";
1203 break;
1204 case MediumState_Creating:
1205 pszState = "creating";
1206 break;
1207 case MediumState_Deleting:
1208 pszState = "deleting";
1209 break;
1210 }
1211 RTPrintf("State: %s\n", pszState);
1212
1213 if (fOptLong && enmState == MediumState_Inaccessible)
1214 {
1215 Bstr err;
1216 CHECK_ERROR_BREAK(pMedium, COMGETTER(LastAccessError)(err.asOutParam()));
1217 RTPrintf("Access Error: %ls\n", err.raw());
1218 }
1219
1220 if (fOptLong)
1221 {
1222 Bstr description;
1223 pMedium->COMGETTER(Description)(description.asOutParam());
1224 if (!description.isEmpty())
1225 RTPrintf("Description: %ls\n", description.raw());
1226 }
1227
1228 MediumType_T type;
1229 pMedium->COMGETTER(Type)(&type);
1230 const char *typeStr = "unknown";
1231 switch (type)
1232 {
1233 case MediumType_Normal:
1234 if (pszParentUUID && Guid(pszParentUUID).isValid())
1235 typeStr = "normal (differencing)";
1236 else
1237 typeStr = "normal (base)";
1238 break;
1239 case MediumType_Immutable:
1240 typeStr = "immutable";
1241 break;
1242 case MediumType_Writethrough:
1243 typeStr = "writethrough";
1244 break;
1245 case MediumType_Shareable:
1246 typeStr = "shareable";
1247 break;
1248 case MediumType_Readonly:
1249 typeStr = "readonly";
1250 break;
1251 case MediumType_MultiAttach:
1252 typeStr = "multiattach";
1253 break;
1254 }
1255 RTPrintf("Type: %s\n", typeStr);
1256
1257 /* print out information specific for differencing media */
1258 if (fOptLong && pszParentUUID && Guid(pszParentUUID).isValid())
1259 {
1260 BOOL autoReset = FALSE;
1261 pMedium->COMGETTER(AutoReset)(&autoReset);
1262 RTPrintf("Auto-Reset: %s\n", autoReset ? "on" : "off");
1263 }
1264
1265 Bstr loc;
1266 pMedium->COMGETTER(Location)(loc.asOutParam());
1267 RTPrintf("Location: %ls\n", loc.raw());
1268
1269 Bstr format;
1270 pMedium->COMGETTER(Format)(format.asOutParam());
1271 RTPrintf("Storage format: %ls\n", format.raw());
1272
1273 if (fOptLong)
1274 {
1275 com::SafeArray<MediumVariant_T> safeArray_variant;
1276
1277 pMedium->COMGETTER(Variant)(ComSafeArrayAsOutParam(safeArray_variant));
1278 ULONG variant=0;
1279 for (size_t i = 0; i < safeArray_variant.size(); i++)
1280 variant |= safeArray_variant[i];
1281
1282 const char *variantStr = "unknown";
1283 switch (variant & ~(MediumVariant_Fixed | MediumVariant_Diff))
1284 {
1285 case MediumVariant_VmdkSplit2G:
1286 variantStr = "split2G";
1287 break;
1288 case MediumVariant_VmdkStreamOptimized:
1289 variantStr = "streamOptimized";
1290 break;
1291 case MediumVariant_VmdkESX:
1292 variantStr = "ESX";
1293 break;
1294 case MediumVariant_Standard:
1295 variantStr = "default";
1296 break;
1297 }
1298 const char *variantTypeStr = "dynamic";
1299 if (variant & MediumVariant_Fixed)
1300 variantTypeStr = "fixed";
1301 else if (variant & MediumVariant_Diff)
1302 variantTypeStr = "differencing";
1303 RTPrintf("Format variant: %s %s\n", variantTypeStr, variantStr);
1304 }
1305
1306 LONG64 logicalSize;
1307 pMedium->COMGETTER(LogicalSize)(&logicalSize);
1308 RTPrintf("Capacity: %lld MBytes\n", logicalSize >> 20);
1309 if (fOptLong)
1310 {
1311 LONG64 actualSize;
1312 pMedium->COMGETTER(Size)(&actualSize);
1313 RTPrintf("Size on disk: %lld MBytes\n", actualSize >> 20);
1314 }
1315
1316 Bstr strCipher;
1317 Bstr strPasswordId;
1318 HRESULT rc2 = pMedium->GetEncryptionSettings(strCipher.asOutParam(), strPasswordId.asOutParam());
1319 if (SUCCEEDED(rc2))
1320 {
1321 RTPrintf("Encryption: enabled\n");
1322 if (fOptLong)
1323 {
1324 RTPrintf("Cipher: %ls\n", strCipher.raw());
1325 RTPrintf("Password ID: %ls\n", strPasswordId.raw());
1326 }
1327 }
1328 else
1329 RTPrintf("Encryption: disabled\n");
1330
1331 if (fOptLong)
1332 {
1333 com::SafeArray<BSTR> names;
1334 com::SafeArray<BSTR> values;
1335 pMedium->GetProperties(Bstr().raw(), ComSafeArrayAsOutParam(names), ComSafeArrayAsOutParam(values));
1336 size_t cNames = names.size();
1337 size_t cValues = values.size();
1338 bool fFirst = true;
1339 for (size_t i = 0; i < cNames; i++)
1340 {
1341 Bstr value;
1342 if (i < cValues)
1343 value = values[i];
1344 RTPrintf("%s%ls=%ls\n",
1345 fFirst ? "Property: " : " ",
1346 names[i], value.raw());
1347 }
1348 }
1349
1350 if (fOptLong)
1351 {
1352 bool fFirst = true;
1353 com::SafeArray<BSTR> machineIds;
1354 pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(machineIds));
1355 for (size_t i = 0; i < machineIds.size(); i++)
1356 {
1357 ComPtr<IMachine> pMachine;
1358 CHECK_ERROR(pVirtualBox, FindMachine(machineIds[i], pMachine.asOutParam()));
1359 if (pMachine)
1360 {
1361 Bstr name;
1362 pMachine->COMGETTER(Name)(name.asOutParam());
1363 pMachine->COMGETTER(Id)(uuid.asOutParam());
1364 RTPrintf("%s%ls (UUID: %ls)",
1365 fFirst ? "In use by VMs: " : " ",
1366 name.raw(), machineIds[i]);
1367 fFirst = false;
1368 com::SafeArray<BSTR> snapshotIds;
1369 pMedium->GetSnapshotIds(machineIds[i],
1370 ComSafeArrayAsOutParam(snapshotIds));
1371 for (size_t j = 0; j < snapshotIds.size(); j++)
1372 {
1373 ComPtr<ISnapshot> pSnapshot;
1374 pMachine->FindSnapshot(snapshotIds[j], pSnapshot.asOutParam());
1375 if (pSnapshot)
1376 {
1377 Bstr snapshotName;
1378 pSnapshot->COMGETTER(Name)(snapshotName.asOutParam());
1379 RTPrintf(" [%ls (UUID: %ls)]", snapshotName.raw(), snapshotIds[j]);
1380 }
1381 }
1382 RTPrintf("\n");
1383 }
1384 }
1385 }
1386
1387 if (fOptLong)
1388 {
1389 com::SafeIfaceArray<IMedium> children;
1390 pMedium->COMGETTER(Children)(ComSafeArrayAsOutParam(children));
1391 bool fFirst = true;
1392 for (size_t i = 0; i < children.size(); i++)
1393 {
1394 ComPtr<IMedium> pChild(children[i]);
1395 if (pChild)
1396 {
1397 Bstr childUUID;
1398 pChild->COMGETTER(Id)(childUUID.asOutParam());
1399 RTPrintf("%s%ls\n",
1400 fFirst ? "Child UUIDs: " : " ",
1401 childUUID.raw());
1402 fFirst = false;
1403 }
1404 }
1405 }
1406 }
1407 while (0);
1408
1409 return rc;
1410}
1411
1412static const RTGETOPTDEF g_aShowMediumInfoOptions[] =
1413{
1414 { "disk", 'd', RTGETOPT_REQ_NOTHING },
1415 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
1416 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
1417};
1418
1419RTEXITCODE handleShowMediumInfo(HandlerArg *a)
1420{
1421 enum {
1422 CMD_NONE,
1423 CMD_DISK,
1424 CMD_DVD,
1425 CMD_FLOPPY
1426 } cmd = CMD_NONE;
1427 const char *pszFilenameOrUuid = NULL;
1428
1429 int c;
1430 RTGETOPTUNION ValueUnion;
1431 RTGETOPTSTATE GetState;
1432 // start at 0 because main() has hacked both the argc and argv given to us
1433 RTGetOptInit(&GetState, a->argc, a->argv, g_aShowMediumInfoOptions, RT_ELEMENTS(g_aShowMediumInfoOptions),
1434 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1435 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1436 {
1437 switch (c)
1438 {
1439 case 'd': // disk
1440 if (cmd != CMD_NONE)
1441 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Only one command can be specified: '%s'", ValueUnion.psz);
1442 cmd = CMD_DISK;
1443 break;
1444
1445 case 'D': // DVD
1446 if (cmd != CMD_NONE)
1447 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Only one command can be specified: '%s'", ValueUnion.psz);
1448 cmd = CMD_DVD;
1449 break;
1450
1451 case 'f': // floppy
1452 if (cmd != CMD_NONE)
1453 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Only one command can be specified: '%s'", ValueUnion.psz);
1454 cmd = CMD_FLOPPY;
1455 break;
1456
1457 case VINF_GETOPT_NOT_OPTION:
1458 if (!pszFilenameOrUuid)
1459 pszFilenameOrUuid = ValueUnion.psz;
1460 else
1461 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Invalid parameter '%s'", ValueUnion.psz);
1462 break;
1463
1464 default:
1465 if (c > 0)
1466 {
1467 if (RT_C_IS_PRINT(c))
1468 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Invalid option -%c", c);
1469 else
1470 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Invalid option case %i", c);
1471 }
1472 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1473 return errorSyntax(USAGE_SHOWMEDIUMINFO, "unknown option: %s\n", ValueUnion.psz);
1474 else if (ValueUnion.pDef)
1475 return errorSyntax(USAGE_SHOWMEDIUMINFO, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1476 else
1477 return errorSyntax(USAGE_SHOWMEDIUMINFO, "error: %Rrs", c);
1478 }
1479 }
1480
1481 if (cmd == CMD_NONE)
1482 cmd = CMD_DISK;
1483
1484 /* check for required options */
1485 if (!pszFilenameOrUuid)
1486 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Medium name or UUID required");
1487
1488 HRESULT rc = S_OK; /* Prevents warning. */
1489
1490 ComPtr<IMedium> pMedium;
1491 if (cmd == CMD_DISK)
1492 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1493 AccessMode_ReadOnly, pMedium,
1494 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1495 else if (cmd == CMD_DVD)
1496 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
1497 AccessMode_ReadOnly, pMedium,
1498 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1499 else if (cmd == CMD_FLOPPY)
1500 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
1501 AccessMode_ReadOnly, pMedium,
1502 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1503 if (FAILED(rc))
1504 return RTEXITCODE_FAILURE;
1505
1506 Utf8Str strParentUUID("base");
1507 ComPtr<IMedium> pParent;
1508 pMedium->COMGETTER(Parent)(pParent.asOutParam());
1509 if (!pParent.isNull())
1510 {
1511 Bstr bstrParentUUID;
1512 pParent->COMGETTER(Id)(bstrParentUUID.asOutParam());
1513 strParentUUID = bstrParentUUID;
1514 }
1515
1516 rc = showMediumInfo(a->virtualBox, pMedium, strParentUUID.c_str(), true);
1517
1518 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1519}
1520
1521static const RTGETOPTDEF g_aCloseMediumOptions[] =
1522{
1523 { "disk", 'd', RTGETOPT_REQ_NOTHING },
1524 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
1525 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
1526 { "--delete", 'r', RTGETOPT_REQ_NOTHING },
1527};
1528
1529RTEXITCODE handleCloseMedium(HandlerArg *a)
1530{
1531 HRESULT rc = S_OK;
1532 enum {
1533 CMD_NONE,
1534 CMD_DISK,
1535 CMD_DVD,
1536 CMD_FLOPPY
1537 } cmd = CMD_NONE;
1538 const char *pszFilenameOrUuid = NULL;
1539 bool fDelete = false;
1540
1541 int c;
1542 RTGETOPTUNION ValueUnion;
1543 RTGETOPTSTATE GetState;
1544 // start at 0 because main() has hacked both the argc and argv given to us
1545 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloseMediumOptions, RT_ELEMENTS(g_aCloseMediumOptions),
1546 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1547 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1548 {
1549 switch (c)
1550 {
1551 case 'd': // disk
1552 if (cmd != CMD_NONE)
1553 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1554 cmd = CMD_DISK;
1555 break;
1556
1557 case 'D': // DVD
1558 if (cmd != CMD_NONE)
1559 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1560 cmd = CMD_DVD;
1561 break;
1562
1563 case 'f': // floppy
1564 if (cmd != CMD_NONE)
1565 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1566 cmd = CMD_FLOPPY;
1567 break;
1568
1569 case 'r': // --delete
1570 fDelete = true;
1571 break;
1572
1573 case VINF_GETOPT_NOT_OPTION:
1574 if (!pszFilenameOrUuid)
1575 pszFilenameOrUuid = ValueUnion.psz;
1576 else
1577 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
1578 break;
1579
1580 default:
1581 if (c > 0)
1582 {
1583 if (RT_C_IS_PRINT(c))
1584 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid option -%c", c);
1585 else
1586 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid option case %i", c);
1587 }
1588 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1589 return errorSyntax(USAGE_CLOSEMEDIUM, "unknown option: %s\n", ValueUnion.psz);
1590 else if (ValueUnion.pDef)
1591 return errorSyntax(USAGE_CLOSEMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1592 else
1593 return errorSyntax(USAGE_CLOSEMEDIUM, "error: %Rrs", c);
1594 }
1595 }
1596
1597 /* check for required options */
1598 if (cmd == CMD_NONE)
1599 cmd = CMD_DISK;
1600 if (!pszFilenameOrUuid)
1601 return errorSyntax(USAGE_CLOSEMEDIUM, "Medium name or UUID required");
1602
1603 ComPtr<IMedium> pMedium;
1604 if (cmd == CMD_DISK)
1605 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1606 AccessMode_ReadWrite, pMedium,
1607 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1608 else if (cmd == CMD_DVD)
1609 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
1610 AccessMode_ReadOnly, pMedium,
1611 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1612 else if (cmd == CMD_FLOPPY)
1613 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
1614 AccessMode_ReadWrite, pMedium,
1615 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1616
1617 if (SUCCEEDED(rc) && pMedium)
1618 {
1619 if (fDelete)
1620 {
1621 ComPtr<IProgress> pProgress;
1622 CHECK_ERROR(pMedium, DeleteStorage(pProgress.asOutParam()));
1623 if (SUCCEEDED(rc))
1624 {
1625 rc = showProgress(pProgress);
1626 CHECK_PROGRESS_ERROR(pProgress, ("Failed to delete medium"));
1627 }
1628 else
1629 RTMsgError("Failed to delete medium. Error code %Rrc", rc);
1630 }
1631 CHECK_ERROR(pMedium, Close());
1632 }
1633
1634 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1635}
1636
1637RTEXITCODE handleMediumProperty(HandlerArg *a)
1638{
1639 HRESULT rc = S_OK;
1640 const char *pszCmd = NULL;
1641 enum {
1642 CMD_NONE,
1643 CMD_DISK,
1644 CMD_DVD,
1645 CMD_FLOPPY
1646 } cmd = CMD_NONE;
1647 const char *pszAction = NULL;
1648 const char *pszFilenameOrUuid = NULL;
1649 const char *pszProperty = NULL;
1650 ComPtr<IMedium> pMedium;
1651
1652 pszCmd = (a->argc > 0) ? a->argv[0] : "";
1653 if ( !RTStrICmp(pszCmd, "disk")
1654 || !RTStrICmp(pszCmd, "dvd")
1655 || !RTStrICmp(pszCmd, "floppy"))
1656 {
1657 if (!RTStrICmp(pszCmd, "disk"))
1658 cmd = CMD_DISK;
1659 else if (!RTStrICmp(pszCmd, "dvd"))
1660 cmd = CMD_DVD;
1661 else if (!RTStrICmp(pszCmd, "floppy"))
1662 cmd = CMD_FLOPPY;
1663 else
1664 {
1665 AssertMsgFailed(("unexpected parameter %s\n", pszCmd));
1666 cmd = CMD_DISK;
1667 }
1668 a->argv++;
1669 a->argc--;
1670 }
1671 else
1672 {
1673 pszCmd = NULL;
1674 cmd = CMD_DISK;
1675 }
1676
1677 if (a->argc == 0)
1678 return errorSyntax(USAGE_MEDIUMPROPERTY, "Missing action");
1679
1680 pszAction = a->argv[0];
1681 if ( RTStrICmp(pszAction, "set")
1682 && RTStrICmp(pszAction, "get")
1683 && RTStrICmp(pszAction, "delete"))
1684 return errorSyntax(USAGE_MEDIUMPROPERTY, "Invalid action given: %s", pszAction);
1685
1686 if ( ( !RTStrICmp(pszAction, "set")
1687 && a->argc != 4)
1688 || ( RTStrICmp(pszAction, "set")
1689 && a->argc != 3))
1690 return errorSyntax(USAGE_MEDIUMPROPERTY, "Invalid number of arguments given for action: %s", pszAction);
1691
1692 pszFilenameOrUuid = a->argv[1];
1693 pszProperty = a->argv[2];
1694
1695 if (cmd == CMD_DISK)
1696 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1697 AccessMode_ReadWrite, pMedium,
1698 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1699 else if (cmd == CMD_DVD)
1700 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
1701 AccessMode_ReadOnly, pMedium,
1702 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1703 else if (cmd == CMD_FLOPPY)
1704 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
1705 AccessMode_ReadWrite, pMedium,
1706 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1707 if (SUCCEEDED(rc) && !pMedium.isNull())
1708 {
1709 if (!RTStrICmp(pszAction, "set"))
1710 {
1711 const char *pszValue = a->argv[3];
1712 CHECK_ERROR(pMedium, SetProperty(Bstr(pszProperty).raw(), Bstr(pszValue).raw()));
1713 }
1714 else if (!RTStrICmp(pszAction, "get"))
1715 {
1716 Bstr strVal;
1717 CHECK_ERROR(pMedium, GetProperty(Bstr(pszProperty).raw(), strVal.asOutParam()));
1718 if (SUCCEEDED(rc))
1719 RTPrintf("%s=%ls\n", pszProperty, strVal.raw());
1720 }
1721 else if (!RTStrICmp(pszAction, "delete"))
1722 {
1723 CHECK_ERROR(pMedium, SetProperty(Bstr(pszProperty).raw(), Bstr().raw()));
1724 /** @todo */
1725 }
1726 }
1727
1728 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1729}
1730
1731static const RTGETOPTDEF g_aEncryptMediumOptions[] =
1732{
1733 { "--newpassword", 'n', RTGETOPT_REQ_STRING },
1734 { "--oldpassword", 'o', RTGETOPT_REQ_STRING },
1735 { "--cipher", 'c', RTGETOPT_REQ_STRING },
1736 { "--newpasswordid", 'i', RTGETOPT_REQ_STRING }
1737};
1738
1739RTEXITCODE handleEncryptMedium(HandlerArg *a)
1740{
1741 HRESULT rc;
1742 ComPtr<IMedium> hardDisk;
1743 const char *pszPasswordNew = NULL;
1744 const char *pszPasswordOld = NULL;
1745 const char *pszCipher = NULL;
1746 const char *pszFilenameOrUuid = NULL;
1747 const char *pszNewPasswordId = NULL;
1748 Utf8Str strPasswordNew;
1749 Utf8Str strPasswordOld;
1750
1751 int c;
1752 RTGETOPTUNION ValueUnion;
1753 RTGETOPTSTATE GetState;
1754 // start at 0 because main() has hacked both the argc and argv given to us
1755 RTGetOptInit(&GetState, a->argc, a->argv, g_aEncryptMediumOptions, RT_ELEMENTS(g_aEncryptMediumOptions),
1756 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1757 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1758 {
1759 switch (c)
1760 {
1761 case 'n': // --newpassword
1762 pszPasswordNew = ValueUnion.psz;
1763 break;
1764
1765 case 'o': // --oldpassword
1766 pszPasswordOld = ValueUnion.psz;
1767 break;
1768
1769 case 'c': // --cipher
1770 pszCipher = ValueUnion.psz;
1771 break;
1772
1773 case 'i': // --newpasswordid
1774 pszNewPasswordId = ValueUnion.psz;
1775 break;
1776
1777 case VINF_GETOPT_NOT_OPTION:
1778 if (!pszFilenameOrUuid)
1779 pszFilenameOrUuid = ValueUnion.psz;
1780 else
1781 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
1782 break;
1783
1784 default:
1785 if (c > 0)
1786 {
1787 if (RT_C_IS_PRINT(c))
1788 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Invalid option -%c", c);
1789 else
1790 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Invalid option case %i", c);
1791 }
1792 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1793 return errorSyntax(USAGE_ENCRYPTMEDIUM, "unknown option: %s\n", ValueUnion.psz);
1794 else if (ValueUnion.pDef)
1795 return errorSyntax(USAGE_ENCRYPTMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1796 else
1797 return errorSyntax(USAGE_ENCRYPTMEDIUM, "error: %Rrs", c);
1798 }
1799 }
1800
1801 if (!pszFilenameOrUuid)
1802 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Disk name or UUID required");
1803
1804 if (!pszPasswordNew && !pszPasswordOld)
1805 return errorSyntax(USAGE_ENCRYPTMEDIUM, "No password specified");
1806
1807 if ( (pszPasswordNew && !pszNewPasswordId)
1808 || (!pszPasswordNew && pszNewPasswordId))
1809 return errorSyntax(USAGE_ENCRYPTMEDIUM, "A new password must always have a valid identifier set at the same time");
1810
1811 if (pszPasswordNew)
1812 {
1813 if (!RTStrCmp(pszPasswordNew, "-"))
1814 {
1815 /* Get password from console. */
1816 RTEXITCODE rcExit = readPasswordFromConsole(&strPasswordNew, "Enter new password:");
1817 if (rcExit == RTEXITCODE_FAILURE)
1818 return rcExit;
1819 }
1820 else
1821 {
1822 RTEXITCODE rcExit = readPasswordFile(pszPasswordNew, &strPasswordNew);
1823 if (rcExit == RTEXITCODE_FAILURE)
1824 {
1825 RTMsgError("Failed to read new password from file");
1826 return rcExit;
1827 }
1828 }
1829 }
1830
1831 if (pszPasswordOld)
1832 {
1833 if (!RTStrCmp(pszPasswordOld, "-"))
1834 {
1835 /* Get password from console. */
1836 RTEXITCODE rcExit = readPasswordFromConsole(&strPasswordOld, "Enter old password:");
1837 if (rcExit == RTEXITCODE_FAILURE)
1838 return rcExit;
1839 }
1840 else
1841 {
1842 RTEXITCODE rcExit = readPasswordFile(pszPasswordOld, &strPasswordOld);
1843 if (rcExit == RTEXITCODE_FAILURE)
1844 {
1845 RTMsgError("Failed to read old password from file");
1846 return rcExit;
1847 }
1848 }
1849 }
1850
1851 /* Always open the medium if necessary, there is no other way. */
1852 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1853 AccessMode_ReadWrite, hardDisk,
1854 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1855 if (FAILED(rc))
1856 return RTEXITCODE_FAILURE;
1857 if (hardDisk.isNull())
1858 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Invalid hard disk reference, avoiding crash");
1859
1860 ComPtr<IProgress> progress;
1861 CHECK_ERROR(hardDisk, ChangeEncryption(Bstr(strPasswordOld).raw(), Bstr(pszCipher).raw(),
1862 Bstr(strPasswordNew).raw(), Bstr(pszNewPasswordId).raw(),
1863 progress.asOutParam()));
1864 if (SUCCEEDED(rc))
1865 rc = showProgress(progress);
1866 if (FAILED(rc))
1867 {
1868 if (rc == E_NOTIMPL)
1869 RTMsgError("Encrypt hard disk operation is not implemented!");
1870 else if (rc == VBOX_E_NOT_SUPPORTED)
1871 RTMsgError("Encrypt hard disk operation for this cipher is not implemented yet!");
1872 else if (!progress.isNull())
1873 CHECK_PROGRESS_ERROR(progress, ("Failed to encrypt hard disk"));
1874 else
1875 RTMsgError("Failed to encrypt hard disk!");
1876 }
1877
1878 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1879}
1880
1881RTEXITCODE handleCheckMediumPassword(HandlerArg *a)
1882{
1883 HRESULT rc;
1884 ComPtr<IMedium> hardDisk;
1885 const char *pszFilenameOrUuid = NULL;
1886 Utf8Str strPassword;
1887
1888 if (a->argc != 2)
1889 return errorSyntax(USAGE_MEDIUMENCCHKPWD, "Invalid number of arguments: %d", a->argc);
1890
1891 pszFilenameOrUuid = a->argv[0];
1892
1893 if (!RTStrCmp(a->argv[1], "-"))
1894 {
1895 /* Get password from console. */
1896 RTEXITCODE rcExit = readPasswordFromConsole(&strPassword, "Enter password:");
1897 if (rcExit == RTEXITCODE_FAILURE)
1898 return rcExit;
1899 }
1900 else
1901 {
1902 RTEXITCODE rcExit = readPasswordFile(a->argv[1], &strPassword);
1903 if (rcExit == RTEXITCODE_FAILURE)
1904 {
1905 RTMsgError("Failed to read password from file");
1906 return rcExit;
1907 }
1908 }
1909
1910 /* Always open the medium if necessary, there is no other way. */
1911 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1912 AccessMode_ReadWrite, hardDisk,
1913 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1914 if (FAILED(rc))
1915 return RTEXITCODE_FAILURE;
1916 if (hardDisk.isNull())
1917 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Invalid hard disk reference, avoiding crash");
1918
1919 CHECK_ERROR(hardDisk, CheckEncryptionPassword(Bstr(strPassword).raw()));
1920 if (SUCCEEDED(rc))
1921 RTPrintf("The given password is correct\n");
1922 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1923}
1924
1925#endif /* !VBOX_ONLY_DOCS */
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