VirtualBox

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

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

Frontends/VBoxManage: Use the default disk image format if the source medium format can't create images

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 69.1 KB
Line 
1/* $Id: VBoxManageDisk.cpp 66997 2017-05-22 08:38:38Z 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.215389.xyz. 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 MediumState_T state;
688 pMedium->RefreshState(&state);
689 LONG64 logicalSize;
690 pMedium->COMGETTER(LogicalSize)(&logicalSize);
691 if (cbResize > (uint64_t)logicalSize * 1000)
692 {
693 RTMsgError("Error: Attempt to resize the medium from %RU64.%RU64 MB to %RU64.%RU64 MB. Use --resizebyte if this is intended!\n",
694 logicalSize / _1M, (logicalSize % _1M) / (_1M / 10), cbResize / _1M, (cbResize % _1M) / (_1M / 10));
695 return RTEXITCODE_FAILURE;
696 }
697 }
698
699 if (fModifyMediumType)
700 {
701 MediumType_T enmCurrMediumType;
702 CHECK_ERROR(pMedium, COMGETTER(Type)(&enmCurrMediumType));
703
704 if (enmCurrMediumType != enmMediumType)
705 CHECK_ERROR(pMedium, COMSETTER(Type)(enmMediumType));
706 }
707
708 if (fModifyAutoReset)
709 {
710 CHECK_ERROR(pMedium, COMSETTER(AutoReset)(AutoReset));
711 }
712
713 if (fModifyProperties)
714 {
715 CHECK_ERROR(pMedium, SetProperties(ComSafeArrayAsInParam(mediumPropNames), ComSafeArrayAsInParam(mediumPropValues)));
716 }
717
718 if (fModifyCompact)
719 {
720 ComPtr<IProgress> pProgress;
721 CHECK_ERROR(pMedium, Compact(pProgress.asOutParam()));
722 if (SUCCEEDED(rc))
723 rc = showProgress(pProgress);
724 if (FAILED(rc))
725 {
726 if (rc == E_NOTIMPL)
727 RTMsgError("Compact medium operation is not implemented!");
728 else if (rc == VBOX_E_NOT_SUPPORTED)
729 RTMsgError("Compact medium operation for this format is not implemented yet!");
730 else if (!pProgress.isNull())
731 CHECK_PROGRESS_ERROR(pProgress, ("Failed to compact medium"));
732 else
733 RTMsgError("Failed to compact medium!");
734 }
735 }
736
737 if (fModifyResize)
738 {
739 ComPtr<IProgress> pProgress;
740 CHECK_ERROR(pMedium, Resize(cbResize, pProgress.asOutParam()));
741 if (SUCCEEDED(rc))
742 rc = showProgress(pProgress);
743 if (FAILED(rc))
744 {
745 if (rc == E_NOTIMPL)
746 RTMsgError("Resize medium operation is not implemented!");
747 else if (rc == VBOX_E_NOT_SUPPORTED)
748 RTMsgError("Resize medium operation for this format is not implemented yet!");
749 else if (!pProgress.isNull())
750 CHECK_PROGRESS_ERROR(pProgress, ("Failed to resize medium"));
751 else
752 RTMsgError("Failed to resize medium!");
753 }
754 }
755
756 if (fModifyLocation)
757 {
758 do
759 {
760 ComPtr<IProgress> pProgress;
761 Utf8Str strLocation(pszNewLocation);
762 CHECK_ERROR(pMedium, SetLocation(Bstr(pszNewLocation).raw(), pProgress.asOutParam()));
763
764 if (SUCCEEDED(rc) && !pProgress.isNull())
765 {
766 rc = showProgress(pProgress);
767 CHECK_PROGRESS_ERROR(pProgress, ("Failed to move medium"));
768 }
769
770 Bstr uuid;
771 CHECK_ERROR_BREAK(pMedium, COMGETTER(Id)(uuid.asOutParam()));
772
773 RTPrintf("Move medium with UUID %s finished \n", Utf8Str(uuid).c_str());
774 }
775 while (0);
776 }
777
778 if (fModifyDescription)
779 {
780 CHECK_ERROR(pMedium, COMSETTER(Description)(Bstr(pszNewLocation).raw()));
781
782 RTPrintf("Medium description has been changed. \n");
783 }
784
785 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
786}
787
788static const RTGETOPTDEF g_aCloneMediumOptions[] =
789{
790 { "disk", 'd', RTGETOPT_REQ_NOTHING },
791 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
792 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
793 { "--format", 'o', RTGETOPT_REQ_STRING },
794 { "-format", 'o', RTGETOPT_REQ_STRING },
795 { "--static", 'F', RTGETOPT_REQ_NOTHING },
796 { "-static", 'F', RTGETOPT_REQ_NOTHING },
797 { "--existing", 'E', RTGETOPT_REQ_NOTHING },
798 { "--variant", 'm', RTGETOPT_REQ_STRING },
799 { "-variant", 'm', RTGETOPT_REQ_STRING },
800};
801
802RTEXITCODE handleCloneMedium(HandlerArg *a)
803{
804 HRESULT rc;
805 int vrc;
806 enum {
807 CMD_NONE,
808 CMD_DISK,
809 CMD_DVD,
810 CMD_FLOPPY
811 } cmd = CMD_NONE;
812 const char *pszSrc = NULL;
813 const char *pszDst = NULL;
814 Bstr format;
815 MediumVariant_T enmMediumVariant = MediumVariant_Standard;
816 bool fExisting = false;
817
818 int c;
819 RTGETOPTUNION ValueUnion;
820 RTGETOPTSTATE GetState;
821 // start at 0 because main() has hacked both the argc and argv given to us
822 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloneMediumOptions, RT_ELEMENTS(g_aCloneMediumOptions),
823 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
824 while ((c = RTGetOpt(&GetState, &ValueUnion)))
825 {
826 switch (c)
827 {
828 case 'd': // disk
829 if (cmd != CMD_NONE)
830 return errorSyntax(USAGE_CLONEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
831 cmd = CMD_DISK;
832 break;
833
834 case 'D': // DVD
835 if (cmd != CMD_NONE)
836 return errorSyntax(USAGE_CLONEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
837 cmd = CMD_DVD;
838 break;
839
840 case 'f': // floppy
841 if (cmd != CMD_NONE)
842 return errorSyntax(USAGE_CLONEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
843 cmd = CMD_FLOPPY;
844 break;
845
846 case 'o': // --format
847 format = ValueUnion.psz;
848 break;
849
850 case 'F': // --static
851 {
852 unsigned uMediumVariant = (unsigned)enmMediumVariant;
853 uMediumVariant |= MediumVariant_Fixed;
854 enmMediumVariant = (MediumVariant_T)uMediumVariant;
855 break;
856 }
857
858 case 'E': // --existing
859 fExisting = true;
860 break;
861
862 case 'm': // --variant
863 vrc = parseMediumVariant(ValueUnion.psz, &enmMediumVariant);
864 if (RT_FAILURE(vrc))
865 return errorArgument("Invalid medium variant '%s'", ValueUnion.psz);
866 break;
867
868 case VINF_GETOPT_NOT_OPTION:
869 if (!pszSrc)
870 pszSrc = ValueUnion.psz;
871 else if (!pszDst)
872 pszDst = ValueUnion.psz;
873 else
874 return errorSyntax(USAGE_CLONEMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
875 break;
876
877 default:
878 if (c > 0)
879 {
880 if (RT_C_IS_GRAPH(c))
881 return errorSyntax(USAGE_CLONEMEDIUM, "unhandled option: -%c", c);
882 else
883 return errorSyntax(USAGE_CLONEMEDIUM, "unhandled option: %i", c);
884 }
885 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
886 return errorSyntax(USAGE_CLONEMEDIUM, "unknown option: %s", ValueUnion.psz);
887 else if (ValueUnion.pDef)
888 return errorSyntax(USAGE_CLONEMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
889 else
890 return errorSyntax(USAGE_CLONEMEDIUM, "error: %Rrs", c);
891 }
892 }
893
894 if (cmd == CMD_NONE)
895 cmd = CMD_DISK;
896 if (!pszSrc)
897 return errorSyntax(USAGE_CLONEMEDIUM, "Mandatory UUID or input file parameter missing");
898 if (!pszDst)
899 return errorSyntax(USAGE_CLONEMEDIUM, "Mandatory output file parameter missing");
900 if (fExisting && (!format.isEmpty() || enmMediumVariant != MediumType_Normal))
901 return errorSyntax(USAGE_CLONEMEDIUM, "Specified options which cannot be used with --existing");
902
903 ComPtr<IMedium> pSrcMedium;
904 ComPtr<IMedium> pDstMedium;
905
906 if (cmd == CMD_DISK)
907 rc = openMedium(a, pszSrc, DeviceType_HardDisk, AccessMode_ReadOnly, pSrcMedium,
908 false /* fForceNewUuidOnOpen */, false /* fSilent */);
909 else if (cmd == CMD_DVD)
910 rc = openMedium(a, pszSrc, DeviceType_DVD, AccessMode_ReadOnly, pSrcMedium,
911 false /* fForceNewUuidOnOpen */, false /* fSilent */);
912 else if (cmd == CMD_FLOPPY)
913 rc = openMedium(a, pszSrc, DeviceType_Floppy, AccessMode_ReadOnly, pSrcMedium,
914 false /* fForceNewUuidOnOpen */, false /* fSilent */);
915 else
916 rc = E_INVALIDARG; /* cannot happen but make gcc happy */
917 if (FAILED(rc))
918 return RTEXITCODE_FAILURE;
919
920 do
921 {
922 /* open/create destination medium */
923 if (fExisting)
924 {
925 if (cmd == CMD_DISK)
926 rc = openMedium(a, pszDst, DeviceType_HardDisk, AccessMode_ReadWrite, pDstMedium,
927 false /* fForceNewUuidOnOpen */, false /* fSilent */);
928 else if (cmd == CMD_DVD)
929 rc = openMedium(a, pszDst, DeviceType_DVD, AccessMode_ReadOnly, pDstMedium,
930 false /* fForceNewUuidOnOpen */, false /* fSilent */);
931 else if (cmd == CMD_FLOPPY)
932 rc = openMedium(a, pszDst, DeviceType_Floppy, AccessMode_ReadWrite, pDstMedium,
933 false /* fForceNewUuidOnOpen */, false /* fSilent */);
934 if (FAILED(rc))
935 break;
936
937 /* Perform accessibility check now. */
938 MediumState_T state;
939 CHECK_ERROR_BREAK(pDstMedium, RefreshState(&state));
940 CHECK_ERROR_BREAK(pDstMedium, COMGETTER(Format)(format.asOutParam()));
941 }
942 else
943 {
944 /*
945 * In case the format is unspecified check that the source medium supports
946 * image creation and use the same format for the destination image.
947 * Use the default image format if it is not supported.
948 */
949 if (format.isEmpty())
950 {
951 ComPtr<IMediumFormat> pMediumFmt;
952 com::SafeArray<MediumFormatCapabilities_T> l_caps;
953 CHECK_ERROR_BREAK(pSrcMedium, COMGETTER(MediumFormat)(pMediumFmt.asOutParam()));
954 CHECK_ERROR_BREAK(pMediumFmt, COMGETTER(Capabilities)(ComSafeArrayAsOutParam(l_caps)));
955 ULONG caps=0;
956 for (size_t i = 0; i < l_caps.size(); i++)
957 caps |= l_caps[i];
958 if (caps & ( MediumFormatCapabilities_CreateDynamic
959 | MediumFormatCapabilities_CreateFixed))
960 CHECK_ERROR_BREAK(pMediumFmt, COMGETTER(Id)(format.asOutParam()));
961 }
962 Utf8Str strFormat(format);
963 if (cmd == CMD_DISK)
964 rc = createMedium(a, strFormat.c_str(), pszDst, DeviceType_HardDisk,
965 AccessMode_ReadWrite, pDstMedium);
966 else if (cmd == CMD_DVD)
967 rc = createMedium(a, strFormat.c_str(), pszDst, DeviceType_DVD,
968 AccessMode_ReadOnly, pDstMedium);
969 else if (cmd == CMD_FLOPPY)
970 rc = createMedium(a, strFormat.c_str(), pszDst, DeviceType_Floppy,
971 AccessMode_ReadWrite, pDstMedium);
972 if (FAILED(rc))
973 break;
974 }
975
976 ComPtr<IProgress> pProgress;
977 com::SafeArray<MediumVariant_T> l_variants(sizeof(MediumVariant_T)*8);
978
979 for (ULONG i = 0; i < l_variants.size(); ++i)
980 {
981 ULONG temp = enmMediumVariant;
982 temp &= 1<<i;
983 l_variants [i] = (MediumVariant_T)temp;
984 }
985
986 CHECK_ERROR_BREAK(pSrcMedium, CloneTo(pDstMedium, ComSafeArrayAsInParam(l_variants), NULL, pProgress.asOutParam()));
987
988 rc = showProgress(pProgress);
989 CHECK_PROGRESS_ERROR_BREAK(pProgress, ("Failed to clone medium"));
990
991 Bstr uuid;
992 CHECK_ERROR_BREAK(pDstMedium, COMGETTER(Id)(uuid.asOutParam()));
993
994 RTPrintf("Clone medium created in format '%ls'. UUID: %s\n",
995 format.raw(), Utf8Str(uuid).c_str());
996 }
997 while (0);
998
999 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1000}
1001
1002static const RTGETOPTDEF g_aConvertFromRawHardDiskOptions[] =
1003{
1004 { "--format", 'o', RTGETOPT_REQ_STRING },
1005 { "-format", 'o', RTGETOPT_REQ_STRING },
1006 { "--static", 'F', RTGETOPT_REQ_NOTHING },
1007 { "-static", 'F', RTGETOPT_REQ_NOTHING },
1008 { "--variant", 'm', RTGETOPT_REQ_STRING },
1009 { "-variant", 'm', RTGETOPT_REQ_STRING },
1010 { "--uuid", 'u', RTGETOPT_REQ_STRING },
1011};
1012
1013RTEXITCODE handleConvertFromRaw(HandlerArg *a)
1014{
1015 int rc = VINF_SUCCESS;
1016 bool fReadFromStdIn = false;
1017 const char *format = "VDI";
1018 const char *srcfilename = NULL;
1019 const char *dstfilename = NULL;
1020 const char *filesize = NULL;
1021 unsigned uImageFlags = VD_IMAGE_FLAGS_NONE;
1022 void *pvBuf = NULL;
1023 RTUUID uuid;
1024 PCRTUUID pUuid = NULL;
1025
1026 int c;
1027 RTGETOPTUNION ValueUnion;
1028 RTGETOPTSTATE GetState;
1029 // start at 0 because main() has hacked both the argc and argv given to us
1030 RTGetOptInit(&GetState, a->argc, a->argv, g_aConvertFromRawHardDiskOptions, RT_ELEMENTS(g_aConvertFromRawHardDiskOptions),
1031 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1032 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1033 {
1034 switch (c)
1035 {
1036 case 'u': // --uuid
1037 if (RT_FAILURE(RTUuidFromStr(&uuid, ValueUnion.psz)))
1038 return errorSyntax(USAGE_CONVERTFROMRAW, "Invalid UUID '%s'", ValueUnion.psz);
1039 pUuid = &uuid;
1040 break;
1041 case 'o': // --format
1042 format = ValueUnion.psz;
1043 break;
1044
1045 case 'm': // --variant
1046 {
1047 MediumVariant_T enmMediumVariant = MediumVariant_Standard;
1048 rc = parseMediumVariant(ValueUnion.psz, &enmMediumVariant);
1049 if (RT_FAILURE(rc))
1050 return errorArgument("Invalid medium variant '%s'", ValueUnion.psz);
1051 /// @todo cleaner solution than assuming 1:1 mapping?
1052 uImageFlags = (unsigned)enmMediumVariant;
1053 break;
1054 }
1055 case VINF_GETOPT_NOT_OPTION:
1056 if (!srcfilename)
1057 {
1058 srcfilename = ValueUnion.psz;
1059 fReadFromStdIn = !strcmp(srcfilename, "stdin");
1060 }
1061 else if (!dstfilename)
1062 dstfilename = ValueUnion.psz;
1063 else if (fReadFromStdIn && !filesize)
1064 filesize = ValueUnion.psz;
1065 else
1066 return errorSyntax(USAGE_CONVERTFROMRAW, "Invalid parameter '%s'", ValueUnion.psz);
1067 break;
1068
1069 default:
1070 return errorGetOpt(USAGE_CONVERTFROMRAW, c, &ValueUnion);
1071 }
1072 }
1073
1074 if (!srcfilename || !dstfilename || (fReadFromStdIn && !filesize))
1075 return errorSyntax(USAGE_CONVERTFROMRAW, "Incorrect number of parameters");
1076 RTStrmPrintf(g_pStdErr, "Converting from raw image file=\"%s\" to file=\"%s\"...\n",
1077 srcfilename, dstfilename);
1078
1079 PVDISK pDisk = NULL;
1080
1081 PVDINTERFACE pVDIfs = NULL;
1082 VDINTERFACEERROR vdInterfaceError;
1083 vdInterfaceError.pfnError = handleVDError;
1084 vdInterfaceError.pfnMessage = NULL;
1085
1086 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
1087 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
1088 AssertRC(rc);
1089
1090 /* open raw image file. */
1091 RTFILE File;
1092 if (fReadFromStdIn)
1093 rc = RTFileFromNative(&File, RTFILE_NATIVE_STDIN);
1094 else
1095 rc = RTFileOpen(&File, srcfilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
1096 if (RT_FAILURE(rc))
1097 {
1098 RTMsgError("Cannot open file \"%s\": %Rrc", srcfilename, rc);
1099 goto out;
1100 }
1101
1102 uint64_t cbFile;
1103 /* get image size. */
1104 if (fReadFromStdIn)
1105 cbFile = RTStrToUInt64(filesize);
1106 else
1107 rc = RTFileGetSize(File, &cbFile);
1108 if (RT_FAILURE(rc))
1109 {
1110 RTMsgError("Cannot get image size for file \"%s\": %Rrc", srcfilename, rc);
1111 goto out;
1112 }
1113
1114 RTStrmPrintf(g_pStdErr, "Creating %s image with size %RU64 bytes (%RU64MB)...\n",
1115 (uImageFlags & VD_IMAGE_FLAGS_FIXED) ? "fixed" : "dynamic", cbFile, (cbFile + _1M - 1) / _1M);
1116 char pszComment[256];
1117 RTStrPrintf(pszComment, sizeof(pszComment), "Converted image from %s", srcfilename);
1118 rc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
1119 if (RT_FAILURE(rc))
1120 {
1121 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
1122 goto out;
1123 }
1124
1125 Assert(RT_MIN(cbFile / 512 / 16 / 63, 16383) -
1126 (unsigned int)RT_MIN(cbFile / 512 / 16 / 63, 16383) == 0);
1127 VDGEOMETRY PCHS, LCHS;
1128 PCHS.cCylinders = (unsigned int)RT_MIN(cbFile / 512 / 16 / 63, 16383);
1129 PCHS.cHeads = 16;
1130 PCHS.cSectors = 63;
1131 LCHS.cCylinders = 0;
1132 LCHS.cHeads = 0;
1133 LCHS.cSectors = 0;
1134 rc = VDCreateBase(pDisk, format, dstfilename, cbFile,
1135 uImageFlags, pszComment, &PCHS, &LCHS, pUuid,
1136 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
1137 if (RT_FAILURE(rc))
1138 {
1139 RTMsgError("Cannot create the disk image \"%s\": %Rrc", dstfilename, rc);
1140 goto out;
1141 }
1142
1143 size_t cbBuffer;
1144 cbBuffer = _1M;
1145 pvBuf = RTMemAlloc(cbBuffer);
1146 if (!pvBuf)
1147 {
1148 rc = VERR_NO_MEMORY;
1149 RTMsgError("Out of memory allocating buffers for image \"%s\": %Rrc", dstfilename, rc);
1150 goto out;
1151 }
1152
1153 uint64_t offFile;
1154 offFile = 0;
1155 while (offFile < cbFile)
1156 {
1157 size_t cbRead;
1158 size_t cbToRead;
1159 cbRead = 0;
1160 cbToRead = cbFile - offFile >= (uint64_t)cbBuffer ?
1161 cbBuffer : (size_t)(cbFile - offFile);
1162 rc = RTFileRead(File, pvBuf, cbToRead, &cbRead);
1163 if (RT_FAILURE(rc) || !cbRead)
1164 break;
1165 rc = VDWrite(pDisk, offFile, pvBuf, cbRead);
1166 if (RT_FAILURE(rc))
1167 {
1168 RTMsgError("Failed to write to disk image \"%s\": %Rrc", dstfilename, rc);
1169 goto out;
1170 }
1171 offFile += cbRead;
1172 }
1173
1174out:
1175 if (pvBuf)
1176 RTMemFree(pvBuf);
1177 if (pDisk)
1178 VDClose(pDisk, RT_FAILURE(rc));
1179 if (File != NIL_RTFILE)
1180 RTFileClose(File);
1181
1182 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1183}
1184
1185HRESULT showMediumInfo(const ComPtr<IVirtualBox> &pVirtualBox,
1186 const ComPtr<IMedium> &pMedium,
1187 const char *pszParentUUID,
1188 bool fOptLong)
1189{
1190 HRESULT rc = S_OK;
1191 do
1192 {
1193 Bstr uuid;
1194 pMedium->COMGETTER(Id)(uuid.asOutParam());
1195 RTPrintf("UUID: %ls\n", uuid.raw());
1196 if (pszParentUUID)
1197 RTPrintf("Parent UUID: %s\n", pszParentUUID);
1198
1199 /* check for accessibility */
1200 MediumState_T enmState;
1201 CHECK_ERROR_BREAK(pMedium, RefreshState(&enmState));
1202 const char *pszState = "unknown";
1203 switch (enmState)
1204 {
1205 case MediumState_NotCreated:
1206 pszState = "not created";
1207 break;
1208 case MediumState_Created:
1209 pszState = "created";
1210 break;
1211 case MediumState_LockedRead:
1212 pszState = "locked read";
1213 break;
1214 case MediumState_LockedWrite:
1215 pszState = "locked write";
1216 break;
1217 case MediumState_Inaccessible:
1218 pszState = "inaccessible";
1219 break;
1220 case MediumState_Creating:
1221 pszState = "creating";
1222 break;
1223 case MediumState_Deleting:
1224 pszState = "deleting";
1225 break;
1226 }
1227 RTPrintf("State: %s\n", pszState);
1228
1229 if (fOptLong && enmState == MediumState_Inaccessible)
1230 {
1231 Bstr err;
1232 CHECK_ERROR_BREAK(pMedium, COMGETTER(LastAccessError)(err.asOutParam()));
1233 RTPrintf("Access Error: %ls\n", err.raw());
1234 }
1235
1236 if (fOptLong)
1237 {
1238 Bstr description;
1239 pMedium->COMGETTER(Description)(description.asOutParam());
1240 if (!description.isEmpty())
1241 RTPrintf("Description: %ls\n", description.raw());
1242 }
1243
1244 MediumType_T type;
1245 pMedium->COMGETTER(Type)(&type);
1246 const char *typeStr = "unknown";
1247 switch (type)
1248 {
1249 case MediumType_Normal:
1250 if (pszParentUUID && Guid(pszParentUUID).isValid())
1251 typeStr = "normal (differencing)";
1252 else
1253 typeStr = "normal (base)";
1254 break;
1255 case MediumType_Immutable:
1256 typeStr = "immutable";
1257 break;
1258 case MediumType_Writethrough:
1259 typeStr = "writethrough";
1260 break;
1261 case MediumType_Shareable:
1262 typeStr = "shareable";
1263 break;
1264 case MediumType_Readonly:
1265 typeStr = "readonly";
1266 break;
1267 case MediumType_MultiAttach:
1268 typeStr = "multiattach";
1269 break;
1270 }
1271 RTPrintf("Type: %s\n", typeStr);
1272
1273 /* print out information specific for differencing media */
1274 if (fOptLong && pszParentUUID && Guid(pszParentUUID).isValid())
1275 {
1276 BOOL autoReset = FALSE;
1277 pMedium->COMGETTER(AutoReset)(&autoReset);
1278 RTPrintf("Auto-Reset: %s\n", autoReset ? "on" : "off");
1279 }
1280
1281 Bstr loc;
1282 pMedium->COMGETTER(Location)(loc.asOutParam());
1283 RTPrintf("Location: %ls\n", loc.raw());
1284
1285 Bstr format;
1286 pMedium->COMGETTER(Format)(format.asOutParam());
1287 RTPrintf("Storage format: %ls\n", format.raw());
1288
1289 if (fOptLong)
1290 {
1291 com::SafeArray<MediumVariant_T> safeArray_variant;
1292
1293 pMedium->COMGETTER(Variant)(ComSafeArrayAsOutParam(safeArray_variant));
1294 ULONG variant=0;
1295 for (size_t i = 0; i < safeArray_variant.size(); i++)
1296 variant |= safeArray_variant[i];
1297
1298 const char *variantStr = "unknown";
1299 switch (variant & ~(MediumVariant_Fixed | MediumVariant_Diff))
1300 {
1301 case MediumVariant_VmdkSplit2G:
1302 variantStr = "split2G";
1303 break;
1304 case MediumVariant_VmdkStreamOptimized:
1305 variantStr = "streamOptimized";
1306 break;
1307 case MediumVariant_VmdkESX:
1308 variantStr = "ESX";
1309 break;
1310 case MediumVariant_Standard:
1311 variantStr = "default";
1312 break;
1313 }
1314 const char *variantTypeStr = "dynamic";
1315 if (variant & MediumVariant_Fixed)
1316 variantTypeStr = "fixed";
1317 else if (variant & MediumVariant_Diff)
1318 variantTypeStr = "differencing";
1319 RTPrintf("Format variant: %s %s\n", variantTypeStr, variantStr);
1320 }
1321
1322 LONG64 logicalSize;
1323 pMedium->COMGETTER(LogicalSize)(&logicalSize);
1324 RTPrintf("Capacity: %lld MBytes\n", logicalSize >> 20);
1325 if (fOptLong)
1326 {
1327 LONG64 actualSize;
1328 pMedium->COMGETTER(Size)(&actualSize);
1329 RTPrintf("Size on disk: %lld MBytes\n", actualSize >> 20);
1330 }
1331
1332 Bstr strCipher;
1333 Bstr strPasswordId;
1334 HRESULT rc2 = pMedium->GetEncryptionSettings(strCipher.asOutParam(), strPasswordId.asOutParam());
1335 if (SUCCEEDED(rc2))
1336 {
1337 RTPrintf("Encryption: enabled\n");
1338 if (fOptLong)
1339 {
1340 RTPrintf("Cipher: %ls\n", strCipher.raw());
1341 RTPrintf("Password ID: %ls\n", strPasswordId.raw());
1342 }
1343 }
1344 else
1345 RTPrintf("Encryption: disabled\n");
1346
1347 if (fOptLong)
1348 {
1349 com::SafeArray<BSTR> names;
1350 com::SafeArray<BSTR> values;
1351 pMedium->GetProperties(Bstr().raw(), ComSafeArrayAsOutParam(names), ComSafeArrayAsOutParam(values));
1352 size_t cNames = names.size();
1353 size_t cValues = values.size();
1354 bool fFirst = true;
1355 for (size_t i = 0; i < cNames; i++)
1356 {
1357 Bstr value;
1358 if (i < cValues)
1359 value = values[i];
1360 RTPrintf("%s%ls=%ls\n",
1361 fFirst ? "Property: " : " ",
1362 names[i], value.raw());
1363 }
1364 }
1365
1366 if (fOptLong)
1367 {
1368 bool fFirst = true;
1369 com::SafeArray<BSTR> machineIds;
1370 pMedium->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(machineIds));
1371 for (size_t i = 0; i < machineIds.size(); i++)
1372 {
1373 ComPtr<IMachine> pMachine;
1374 CHECK_ERROR(pVirtualBox, FindMachine(machineIds[i], pMachine.asOutParam()));
1375 if (pMachine)
1376 {
1377 Bstr name;
1378 pMachine->COMGETTER(Name)(name.asOutParam());
1379 pMachine->COMGETTER(Id)(uuid.asOutParam());
1380 RTPrintf("%s%ls (UUID: %ls)",
1381 fFirst ? "In use by VMs: " : " ",
1382 name.raw(), machineIds[i]);
1383 fFirst = false;
1384 com::SafeArray<BSTR> snapshotIds;
1385 pMedium->GetSnapshotIds(machineIds[i],
1386 ComSafeArrayAsOutParam(snapshotIds));
1387 for (size_t j = 0; j < snapshotIds.size(); j++)
1388 {
1389 ComPtr<ISnapshot> pSnapshot;
1390 pMachine->FindSnapshot(snapshotIds[j], pSnapshot.asOutParam());
1391 if (pSnapshot)
1392 {
1393 Bstr snapshotName;
1394 pSnapshot->COMGETTER(Name)(snapshotName.asOutParam());
1395 RTPrintf(" [%ls (UUID: %ls)]", snapshotName.raw(), snapshotIds[j]);
1396 }
1397 }
1398 RTPrintf("\n");
1399 }
1400 }
1401 }
1402
1403 if (fOptLong)
1404 {
1405 com::SafeIfaceArray<IMedium> children;
1406 pMedium->COMGETTER(Children)(ComSafeArrayAsOutParam(children));
1407 bool fFirst = true;
1408 for (size_t i = 0; i < children.size(); i++)
1409 {
1410 ComPtr<IMedium> pChild(children[i]);
1411 if (pChild)
1412 {
1413 Bstr childUUID;
1414 pChild->COMGETTER(Id)(childUUID.asOutParam());
1415 RTPrintf("%s%ls\n",
1416 fFirst ? "Child UUIDs: " : " ",
1417 childUUID.raw());
1418 fFirst = false;
1419 }
1420 }
1421 }
1422 }
1423 while (0);
1424
1425 return rc;
1426}
1427
1428static const RTGETOPTDEF g_aShowMediumInfoOptions[] =
1429{
1430 { "disk", 'd', RTGETOPT_REQ_NOTHING },
1431 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
1432 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
1433};
1434
1435RTEXITCODE handleShowMediumInfo(HandlerArg *a)
1436{
1437 enum {
1438 CMD_NONE,
1439 CMD_DISK,
1440 CMD_DVD,
1441 CMD_FLOPPY
1442 } cmd = CMD_NONE;
1443 const char *pszFilenameOrUuid = NULL;
1444
1445 int c;
1446 RTGETOPTUNION ValueUnion;
1447 RTGETOPTSTATE GetState;
1448 // start at 0 because main() has hacked both the argc and argv given to us
1449 RTGetOptInit(&GetState, a->argc, a->argv, g_aShowMediumInfoOptions, RT_ELEMENTS(g_aShowMediumInfoOptions),
1450 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1451 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1452 {
1453 switch (c)
1454 {
1455 case 'd': // disk
1456 if (cmd != CMD_NONE)
1457 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Only one command can be specified: '%s'", ValueUnion.psz);
1458 cmd = CMD_DISK;
1459 break;
1460
1461 case 'D': // DVD
1462 if (cmd != CMD_NONE)
1463 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Only one command can be specified: '%s'", ValueUnion.psz);
1464 cmd = CMD_DVD;
1465 break;
1466
1467 case 'f': // floppy
1468 if (cmd != CMD_NONE)
1469 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Only one command can be specified: '%s'", ValueUnion.psz);
1470 cmd = CMD_FLOPPY;
1471 break;
1472
1473 case VINF_GETOPT_NOT_OPTION:
1474 if (!pszFilenameOrUuid)
1475 pszFilenameOrUuid = ValueUnion.psz;
1476 else
1477 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Invalid parameter '%s'", ValueUnion.psz);
1478 break;
1479
1480 default:
1481 if (c > 0)
1482 {
1483 if (RT_C_IS_PRINT(c))
1484 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Invalid option -%c", c);
1485 else
1486 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Invalid option case %i", c);
1487 }
1488 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1489 return errorSyntax(USAGE_SHOWMEDIUMINFO, "unknown option: %s\n", ValueUnion.psz);
1490 else if (ValueUnion.pDef)
1491 return errorSyntax(USAGE_SHOWMEDIUMINFO, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1492 else
1493 return errorSyntax(USAGE_SHOWMEDIUMINFO, "error: %Rrs", c);
1494 }
1495 }
1496
1497 if (cmd == CMD_NONE)
1498 cmd = CMD_DISK;
1499
1500 /* check for required options */
1501 if (!pszFilenameOrUuid)
1502 return errorSyntax(USAGE_SHOWMEDIUMINFO, "Medium name or UUID required");
1503
1504 HRESULT rc = S_OK; /* Prevents warning. */
1505
1506 ComPtr<IMedium> pMedium;
1507 if (cmd == CMD_DISK)
1508 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1509 AccessMode_ReadOnly, pMedium,
1510 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1511 else if (cmd == CMD_DVD)
1512 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
1513 AccessMode_ReadOnly, pMedium,
1514 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1515 else if (cmd == CMD_FLOPPY)
1516 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
1517 AccessMode_ReadOnly, pMedium,
1518 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1519 if (FAILED(rc))
1520 return RTEXITCODE_FAILURE;
1521
1522 Utf8Str strParentUUID("base");
1523 ComPtr<IMedium> pParent;
1524 pMedium->COMGETTER(Parent)(pParent.asOutParam());
1525 if (!pParent.isNull())
1526 {
1527 Bstr bstrParentUUID;
1528 pParent->COMGETTER(Id)(bstrParentUUID.asOutParam());
1529 strParentUUID = bstrParentUUID;
1530 }
1531
1532 rc = showMediumInfo(a->virtualBox, pMedium, strParentUUID.c_str(), true);
1533
1534 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1535}
1536
1537static const RTGETOPTDEF g_aCloseMediumOptions[] =
1538{
1539 { "disk", 'd', RTGETOPT_REQ_NOTHING },
1540 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
1541 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
1542 { "--delete", 'r', RTGETOPT_REQ_NOTHING },
1543};
1544
1545RTEXITCODE handleCloseMedium(HandlerArg *a)
1546{
1547 HRESULT rc = S_OK;
1548 enum {
1549 CMD_NONE,
1550 CMD_DISK,
1551 CMD_DVD,
1552 CMD_FLOPPY
1553 } cmd = CMD_NONE;
1554 const char *pszFilenameOrUuid = NULL;
1555 bool fDelete = false;
1556
1557 int c;
1558 RTGETOPTUNION ValueUnion;
1559 RTGETOPTSTATE GetState;
1560 // start at 0 because main() has hacked both the argc and argv given to us
1561 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloseMediumOptions, RT_ELEMENTS(g_aCloseMediumOptions),
1562 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1563 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1564 {
1565 switch (c)
1566 {
1567 case 'd': // disk
1568 if (cmd != CMD_NONE)
1569 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1570 cmd = CMD_DISK;
1571 break;
1572
1573 case 'D': // DVD
1574 if (cmd != CMD_NONE)
1575 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1576 cmd = CMD_DVD;
1577 break;
1578
1579 case 'f': // floppy
1580 if (cmd != CMD_NONE)
1581 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1582 cmd = CMD_FLOPPY;
1583 break;
1584
1585 case 'r': // --delete
1586 fDelete = true;
1587 break;
1588
1589 case VINF_GETOPT_NOT_OPTION:
1590 if (!pszFilenameOrUuid)
1591 pszFilenameOrUuid = ValueUnion.psz;
1592 else
1593 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
1594 break;
1595
1596 default:
1597 if (c > 0)
1598 {
1599 if (RT_C_IS_PRINT(c))
1600 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid option -%c", c);
1601 else
1602 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid option case %i", c);
1603 }
1604 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1605 return errorSyntax(USAGE_CLOSEMEDIUM, "unknown option: %s\n", ValueUnion.psz);
1606 else if (ValueUnion.pDef)
1607 return errorSyntax(USAGE_CLOSEMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1608 else
1609 return errorSyntax(USAGE_CLOSEMEDIUM, "error: %Rrs", c);
1610 }
1611 }
1612
1613 /* check for required options */
1614 if (cmd == CMD_NONE)
1615 cmd = CMD_DISK;
1616 if (!pszFilenameOrUuid)
1617 return errorSyntax(USAGE_CLOSEMEDIUM, "Medium name or UUID required");
1618
1619 ComPtr<IMedium> pMedium;
1620 if (cmd == CMD_DISK)
1621 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1622 AccessMode_ReadWrite, pMedium,
1623 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1624 else if (cmd == CMD_DVD)
1625 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
1626 AccessMode_ReadOnly, pMedium,
1627 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1628 else if (cmd == CMD_FLOPPY)
1629 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
1630 AccessMode_ReadWrite, pMedium,
1631 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1632
1633 if (SUCCEEDED(rc) && pMedium)
1634 {
1635 if (fDelete)
1636 {
1637 ComPtr<IProgress> pProgress;
1638 CHECK_ERROR(pMedium, DeleteStorage(pProgress.asOutParam()));
1639 if (SUCCEEDED(rc))
1640 {
1641 rc = showProgress(pProgress);
1642 CHECK_PROGRESS_ERROR(pProgress, ("Failed to delete medium"));
1643 }
1644 else
1645 RTMsgError("Failed to delete medium. Error code %Rrc", rc);
1646 }
1647 CHECK_ERROR(pMedium, Close());
1648 }
1649
1650 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1651}
1652
1653RTEXITCODE handleMediumProperty(HandlerArg *a)
1654{
1655 HRESULT rc = S_OK;
1656 const char *pszCmd = NULL;
1657 enum {
1658 CMD_NONE,
1659 CMD_DISK,
1660 CMD_DVD,
1661 CMD_FLOPPY
1662 } cmd = CMD_NONE;
1663 const char *pszAction = NULL;
1664 const char *pszFilenameOrUuid = NULL;
1665 const char *pszProperty = NULL;
1666 ComPtr<IMedium> pMedium;
1667
1668 pszCmd = (a->argc > 0) ? a->argv[0] : "";
1669 if ( !RTStrICmp(pszCmd, "disk")
1670 || !RTStrICmp(pszCmd, "dvd")
1671 || !RTStrICmp(pszCmd, "floppy"))
1672 {
1673 if (!RTStrICmp(pszCmd, "disk"))
1674 cmd = CMD_DISK;
1675 else if (!RTStrICmp(pszCmd, "dvd"))
1676 cmd = CMD_DVD;
1677 else if (!RTStrICmp(pszCmd, "floppy"))
1678 cmd = CMD_FLOPPY;
1679 else
1680 {
1681 AssertMsgFailed(("unexpected parameter %s\n", pszCmd));
1682 cmd = CMD_DISK;
1683 }
1684 a->argv++;
1685 a->argc--;
1686 }
1687 else
1688 {
1689 pszCmd = NULL;
1690 cmd = CMD_DISK;
1691 }
1692
1693 if (a->argc == 0)
1694 return errorSyntax(USAGE_MEDIUMPROPERTY, "Missing action");
1695
1696 pszAction = a->argv[0];
1697 if ( RTStrICmp(pszAction, "set")
1698 && RTStrICmp(pszAction, "get")
1699 && RTStrICmp(pszAction, "delete"))
1700 return errorSyntax(USAGE_MEDIUMPROPERTY, "Invalid action given: %s", pszAction);
1701
1702 if ( ( !RTStrICmp(pszAction, "set")
1703 && a->argc != 4)
1704 || ( RTStrICmp(pszAction, "set")
1705 && a->argc != 3))
1706 return errorSyntax(USAGE_MEDIUMPROPERTY, "Invalid number of arguments given for action: %s", pszAction);
1707
1708 pszFilenameOrUuid = a->argv[1];
1709 pszProperty = a->argv[2];
1710
1711 if (cmd == CMD_DISK)
1712 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1713 AccessMode_ReadWrite, pMedium,
1714 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1715 else if (cmd == CMD_DVD)
1716 rc = openMedium(a, pszFilenameOrUuid, DeviceType_DVD,
1717 AccessMode_ReadOnly, pMedium,
1718 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1719 else if (cmd == CMD_FLOPPY)
1720 rc = openMedium(a, pszFilenameOrUuid, DeviceType_Floppy,
1721 AccessMode_ReadWrite, pMedium,
1722 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1723 if (SUCCEEDED(rc) && !pMedium.isNull())
1724 {
1725 if (!RTStrICmp(pszAction, "set"))
1726 {
1727 const char *pszValue = a->argv[3];
1728 CHECK_ERROR(pMedium, SetProperty(Bstr(pszProperty).raw(), Bstr(pszValue).raw()));
1729 }
1730 else if (!RTStrICmp(pszAction, "get"))
1731 {
1732 Bstr strVal;
1733 CHECK_ERROR(pMedium, GetProperty(Bstr(pszProperty).raw(), strVal.asOutParam()));
1734 if (SUCCEEDED(rc))
1735 RTPrintf("%s=%ls\n", pszProperty, strVal.raw());
1736 }
1737 else if (!RTStrICmp(pszAction, "delete"))
1738 {
1739 CHECK_ERROR(pMedium, SetProperty(Bstr(pszProperty).raw(), Bstr().raw()));
1740 /** @todo */
1741 }
1742 }
1743
1744 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1745}
1746
1747static const RTGETOPTDEF g_aEncryptMediumOptions[] =
1748{
1749 { "--newpassword", 'n', RTGETOPT_REQ_STRING },
1750 { "--oldpassword", 'o', RTGETOPT_REQ_STRING },
1751 { "--cipher", 'c', RTGETOPT_REQ_STRING },
1752 { "--newpasswordid", 'i', RTGETOPT_REQ_STRING }
1753};
1754
1755RTEXITCODE handleEncryptMedium(HandlerArg *a)
1756{
1757 HRESULT rc;
1758 ComPtr<IMedium> hardDisk;
1759 const char *pszPasswordNew = NULL;
1760 const char *pszPasswordOld = NULL;
1761 const char *pszCipher = NULL;
1762 const char *pszFilenameOrUuid = NULL;
1763 const char *pszNewPasswordId = NULL;
1764 Utf8Str strPasswordNew;
1765 Utf8Str strPasswordOld;
1766
1767 int c;
1768 RTGETOPTUNION ValueUnion;
1769 RTGETOPTSTATE GetState;
1770 // start at 0 because main() has hacked both the argc and argv given to us
1771 RTGetOptInit(&GetState, a->argc, a->argv, g_aEncryptMediumOptions, RT_ELEMENTS(g_aEncryptMediumOptions),
1772 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1773 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1774 {
1775 switch (c)
1776 {
1777 case 'n': // --newpassword
1778 pszPasswordNew = ValueUnion.psz;
1779 break;
1780
1781 case 'o': // --oldpassword
1782 pszPasswordOld = ValueUnion.psz;
1783 break;
1784
1785 case 'c': // --cipher
1786 pszCipher = ValueUnion.psz;
1787 break;
1788
1789 case 'i': // --newpasswordid
1790 pszNewPasswordId = ValueUnion.psz;
1791 break;
1792
1793 case VINF_GETOPT_NOT_OPTION:
1794 if (!pszFilenameOrUuid)
1795 pszFilenameOrUuid = ValueUnion.psz;
1796 else
1797 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
1798 break;
1799
1800 default:
1801 if (c > 0)
1802 {
1803 if (RT_C_IS_PRINT(c))
1804 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Invalid option -%c", c);
1805 else
1806 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Invalid option case %i", c);
1807 }
1808 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1809 return errorSyntax(USAGE_ENCRYPTMEDIUM, "unknown option: %s\n", ValueUnion.psz);
1810 else if (ValueUnion.pDef)
1811 return errorSyntax(USAGE_ENCRYPTMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1812 else
1813 return errorSyntax(USAGE_ENCRYPTMEDIUM, "error: %Rrs", c);
1814 }
1815 }
1816
1817 if (!pszFilenameOrUuid)
1818 return errorSyntax(USAGE_ENCRYPTMEDIUM, "Disk name or UUID required");
1819
1820 if (!pszPasswordNew && !pszPasswordOld)
1821 return errorSyntax(USAGE_ENCRYPTMEDIUM, "No password specified");
1822
1823 if ( (pszPasswordNew && !pszNewPasswordId)
1824 || (!pszPasswordNew && pszNewPasswordId))
1825 return errorSyntax(USAGE_ENCRYPTMEDIUM, "A new password must always have a valid identifier set at the same time");
1826
1827 if (pszPasswordNew)
1828 {
1829 if (!RTStrCmp(pszPasswordNew, "-"))
1830 {
1831 /* Get password from console. */
1832 RTEXITCODE rcExit = readPasswordFromConsole(&strPasswordNew, "Enter new password:");
1833 if (rcExit == RTEXITCODE_FAILURE)
1834 return rcExit;
1835 }
1836 else
1837 {
1838 RTEXITCODE rcExit = readPasswordFile(pszPasswordNew, &strPasswordNew);
1839 if (rcExit == RTEXITCODE_FAILURE)
1840 {
1841 RTMsgError("Failed to read new password from file");
1842 return rcExit;
1843 }
1844 }
1845 }
1846
1847 if (pszPasswordOld)
1848 {
1849 if (!RTStrCmp(pszPasswordOld, "-"))
1850 {
1851 /* Get password from console. */
1852 RTEXITCODE rcExit = readPasswordFromConsole(&strPasswordOld, "Enter old password:");
1853 if (rcExit == RTEXITCODE_FAILURE)
1854 return rcExit;
1855 }
1856 else
1857 {
1858 RTEXITCODE rcExit = readPasswordFile(pszPasswordOld, &strPasswordOld);
1859 if (rcExit == RTEXITCODE_FAILURE)
1860 {
1861 RTMsgError("Failed to read old password from file");
1862 return rcExit;
1863 }
1864 }
1865 }
1866
1867 /* Always open the medium if necessary, there is no other way. */
1868 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1869 AccessMode_ReadWrite, hardDisk,
1870 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1871 if (FAILED(rc))
1872 return RTEXITCODE_FAILURE;
1873 if (hardDisk.isNull())
1874 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Invalid hard disk reference, avoiding crash");
1875
1876 ComPtr<IProgress> progress;
1877 CHECK_ERROR(hardDisk, ChangeEncryption(Bstr(strPasswordOld).raw(), Bstr(pszCipher).raw(),
1878 Bstr(strPasswordNew).raw(), Bstr(pszNewPasswordId).raw(),
1879 progress.asOutParam()));
1880 if (SUCCEEDED(rc))
1881 rc = showProgress(progress);
1882 if (FAILED(rc))
1883 {
1884 if (rc == E_NOTIMPL)
1885 RTMsgError("Encrypt hard disk operation is not implemented!");
1886 else if (rc == VBOX_E_NOT_SUPPORTED)
1887 RTMsgError("Encrypt hard disk operation for this cipher is not implemented yet!");
1888 else if (!progress.isNull())
1889 CHECK_PROGRESS_ERROR(progress, ("Failed to encrypt hard disk"));
1890 else
1891 RTMsgError("Failed to encrypt hard disk!");
1892 }
1893
1894 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1895}
1896
1897RTEXITCODE handleCheckMediumPassword(HandlerArg *a)
1898{
1899 HRESULT rc;
1900 ComPtr<IMedium> hardDisk;
1901 const char *pszFilenameOrUuid = NULL;
1902 Utf8Str strPassword;
1903
1904 if (a->argc != 2)
1905 return errorSyntax(USAGE_MEDIUMENCCHKPWD, "Invalid number of arguments: %d", a->argc);
1906
1907 pszFilenameOrUuid = a->argv[0];
1908
1909 if (!RTStrCmp(a->argv[1], "-"))
1910 {
1911 /* Get password from console. */
1912 RTEXITCODE rcExit = readPasswordFromConsole(&strPassword, "Enter password:");
1913 if (rcExit == RTEXITCODE_FAILURE)
1914 return rcExit;
1915 }
1916 else
1917 {
1918 RTEXITCODE rcExit = readPasswordFile(a->argv[1], &strPassword);
1919 if (rcExit == RTEXITCODE_FAILURE)
1920 {
1921 RTMsgError("Failed to read password from file");
1922 return rcExit;
1923 }
1924 }
1925
1926 /* Always open the medium if necessary, there is no other way. */
1927 rc = openMedium(a, pszFilenameOrUuid, DeviceType_HardDisk,
1928 AccessMode_ReadWrite, hardDisk,
1929 false /* fForceNewUuidOnOpen */, false /* fSilent */);
1930 if (FAILED(rc))
1931 return RTEXITCODE_FAILURE;
1932 if (hardDisk.isNull())
1933 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Invalid hard disk reference, avoiding crash");
1934
1935 CHECK_ERROR(hardDisk, CheckEncryptionPassword(Bstr(strPassword).raw()));
1936 if (SUCCEEDED(rc))
1937 RTPrintf("The given password is correct\n");
1938 return SUCCEEDED(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
1939}
1940
1941#endif /* !VBOX_ONLY_DOCS */
Note: See TracBrowser for help on using the repository browser.

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