VirtualBox

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

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

%lS -> %ls.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 40.0 KB
Line 
1/* $Id: VBoxManageDisk.cpp 38735 2011-09-13 13:25:16Z vboxsync $ */
2/** @file
3 * VBoxManage - The disk related commands.
4 */
5
6/*
7 * Copyright (C) 2006-2011 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.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* Header Files *
22*******************************************************************************/
23#include <VBox/com/com.h>
24#include <VBox/com/array.h>
25#include <VBox/com/ErrorInfo.h>
26#include <VBox/com/errorprint.h>
27#include <VBox/com/VirtualBox.h>
28
29#include <iprt/asm.h>
30#include <iprt/file.h>
31#include <iprt/path.h>
32#include <iprt/param.h>
33#include <iprt/stream.h>
34#include <iprt/string.h>
35#include <iprt/ctype.h>
36#include <iprt/getopt.h>
37#include <VBox/log.h>
38#include <VBox/vd.h>
39
40#include "VBoxManage.h"
41using namespace com;
42
43
44// funcs
45///////////////////////////////////////////////////////////////////////////////
46
47
48static DECLCALLBACK(void) handleVDError(void *pvUser, int rc, RT_SRC_POS_DECL, const char *pszFormat, va_list va)
49{
50 RTMsgError(pszFormat, va);
51 RTMsgError("Error code %Rrc at %s(%u) in function %s", rc, RT_SRC_POS_ARGS);
52}
53
54
55static int parseDiskVariant(const char *psz, MediumVariant_T *pDiskVariant)
56{
57 int rc = VINF_SUCCESS;
58 unsigned DiskVariant = (unsigned)(*pDiskVariant);
59 while (psz && *psz && RT_SUCCESS(rc))
60 {
61 size_t len;
62 const char *pszComma = strchr(psz, ',');
63 if (pszComma)
64 len = pszComma - psz;
65 else
66 len = strlen(psz);
67 if (len > 0)
68 {
69 // Parsing is intentionally inconsistent: "standard" resets the
70 // variant, whereas the other flags are cumulative.
71 if (!RTStrNICmp(psz, "standard", len))
72 DiskVariant = MediumVariant_Standard;
73 else if ( !RTStrNICmp(psz, "fixed", len)
74 || !RTStrNICmp(psz, "static", len))
75 DiskVariant |= MediumVariant_Fixed;
76 else if (!RTStrNICmp(psz, "Diff", len))
77 DiskVariant |= MediumVariant_Diff;
78 else if (!RTStrNICmp(psz, "split2g", len))
79 DiskVariant |= MediumVariant_VmdkSplit2G;
80 else if ( !RTStrNICmp(psz, "stream", len)
81 || !RTStrNICmp(psz, "streamoptimized", len))
82 DiskVariant |= MediumVariant_VmdkStreamOptimized;
83 else if (!RTStrNICmp(psz, "esx", len))
84 DiskVariant |= MediumVariant_VmdkESX;
85 else
86 rc = VERR_PARSE_ERROR;
87 }
88 if (pszComma)
89 psz += len + 1;
90 else
91 psz += len;
92 }
93
94 if (RT_SUCCESS(rc))
95 *pDiskVariant = (MediumVariant_T)DiskVariant;
96 return rc;
97}
98
99int parseDiskType(const char *psz, MediumType_T *pDiskType)
100{
101 int rc = VINF_SUCCESS;
102 MediumType_T DiskType = MediumType_Normal;
103 if (!RTStrICmp(psz, "normal"))
104 DiskType = MediumType_Normal;
105 else if (!RTStrICmp(psz, "immutable"))
106 DiskType = MediumType_Immutable;
107 else if (!RTStrICmp(psz, "writethrough"))
108 DiskType = MediumType_Writethrough;
109 else if (!RTStrICmp(psz, "shareable"))
110 DiskType = MediumType_Shareable;
111 else if (!RTStrICmp(psz, "readonly"))
112 DiskType = MediumType_Readonly;
113 else if (!RTStrICmp(psz, "multiattach"))
114 DiskType = MediumType_MultiAttach;
115 else
116 rc = VERR_PARSE_ERROR;
117
118 if (RT_SUCCESS(rc))
119 *pDiskType = DiskType;
120 return rc;
121}
122
123/** @todo move this into getopt, as getting bool values is generic */
124static int parseBool(const char *psz, bool *pb)
125{
126 int rc = VINF_SUCCESS;
127 if ( !RTStrICmp(psz, "on")
128 || !RTStrICmp(psz, "yes")
129 || !RTStrICmp(psz, "true")
130 || !RTStrICmp(psz, "1")
131 || !RTStrICmp(psz, "enable")
132 || !RTStrICmp(psz, "enabled"))
133 {
134 *pb = true;
135 }
136 else if ( !RTStrICmp(psz, "off")
137 || !RTStrICmp(psz, "no")
138 || !RTStrICmp(psz, "false")
139 || !RTStrICmp(psz, "0")
140 || !RTStrICmp(psz, "disable")
141 || !RTStrICmp(psz, "disabled"))
142 {
143 *pb = false;
144 }
145 else
146 rc = VERR_PARSE_ERROR;
147
148 return rc;
149}
150
151HRESULT findMedium(HandlerArg *a, const char *pszFilenameOrUuid,
152 DeviceType_T enmDevType, bool fSilent,
153 ComPtr<IMedium> &pMedium)
154{
155 HRESULT rc;
156 Guid id(pszFilenameOrUuid);
157 char szFilenameAbs[RTPATH_MAX] = "";
158
159 /* If it is no UUID, convert the filename to an absolute one. */
160 if (id.isEmpty())
161 {
162 int irc = RTPathAbs(pszFilenameOrUuid, szFilenameAbs, sizeof(szFilenameAbs));
163 if (RT_FAILURE(irc))
164 {
165 if (!fSilent)
166 RTMsgError("Cannot convert filename \"%s\" to absolute path", pszFilenameOrUuid);
167 return E_FAIL;
168 }
169 pszFilenameOrUuid = szFilenameAbs;
170 }
171
172 if (!fSilent)
173 CHECK_ERROR(a->virtualBox, FindMedium(Bstr(pszFilenameOrUuid).raw(),
174 enmDevType, pMedium.asOutParam()));
175 else
176 rc = a->virtualBox->FindMedium(Bstr(pszFilenameOrUuid).raw(),
177 enmDevType, pMedium.asOutParam());
178 return rc;
179}
180
181HRESULT findOrOpenMedium(HandlerArg *a, const char *pszFilenameOrUuid,
182 DeviceType_T enmDevType, ComPtr<IMedium> &pMedium,
183 bool fForceNewUuidOnOpen, bool *pfWasUnknown)
184{
185 HRESULT rc;
186 bool fWasUnknown = false;
187 Guid id(pszFilenameOrUuid);
188 char szFilenameAbs[RTPATH_MAX] = "";
189
190 /* If it is no UUID, convert the filename to an absolute one. */
191 if (id.isEmpty())
192 {
193 int irc = RTPathAbs(pszFilenameOrUuid, szFilenameAbs, sizeof(szFilenameAbs));
194 if (RT_FAILURE(irc))
195 {
196 RTMsgError("Cannot convert filename \"%s\" to absolute path", pszFilenameOrUuid);
197 return E_FAIL;
198 }
199 pszFilenameOrUuid = szFilenameAbs;
200 }
201
202 rc = a->virtualBox->FindMedium(Bstr(pszFilenameOrUuid).raw(), enmDevType,
203 pMedium.asOutParam());
204 /* If the medium is unknown try to open it. */
205 if (!pMedium)
206 {
207 CHECK_ERROR(a->virtualBox, OpenMedium(Bstr(pszFilenameOrUuid).raw(),
208 enmDevType, AccessMode_ReadWrite,
209 fForceNewUuidOnOpen,
210 pMedium.asOutParam()));
211 if (SUCCEEDED(rc))
212 fWasUnknown = true;
213 }
214 if (RT_VALID_PTR(pfWasUnknown))
215 *pfWasUnknown = fWasUnknown;
216 return rc;
217}
218
219static HRESULT createHardDisk(HandlerArg *a, const char *pszFormat,
220 const char *pszFilename, ComPtr<IMedium> &pMedium)
221{
222 HRESULT rc;
223 char szFilenameAbs[RTPATH_MAX] = "";
224
225 /** @todo laziness shortcut. should really check the MediumFormatCapabilities */
226 if (RTStrICmp(pszFormat, "iSCSI"))
227 {
228 int irc = RTPathAbs(pszFilename, szFilenameAbs, sizeof(szFilenameAbs));
229 if (RT_FAILURE(irc))
230 {
231 RTMsgError("Cannot convert filename \"%s\" to absolute path", pszFilename);
232 return E_FAIL;
233 }
234 pszFilename = szFilenameAbs;
235 }
236
237 CHECK_ERROR(a->virtualBox, CreateHardDisk(Bstr(pszFormat).raw(),
238 Bstr(pszFilename).raw(),
239 pMedium.asOutParam()));
240 return rc;
241}
242
243static const RTGETOPTDEF g_aCreateHardDiskOptions[] =
244{
245 { "--filename", 'f', RTGETOPT_REQ_STRING },
246 { "-filename", 'f', RTGETOPT_REQ_STRING }, // deprecated
247 { "--size", 's', RTGETOPT_REQ_UINT64 },
248 { "-size", 's', RTGETOPT_REQ_UINT64 }, // deprecated
249 { "--sizebyte", 'S', RTGETOPT_REQ_UINT64 },
250 { "--format", 'o', RTGETOPT_REQ_STRING },
251 { "-format", 'o', RTGETOPT_REQ_STRING }, // deprecated
252 { "--static", 'F', RTGETOPT_REQ_NOTHING },
253 { "-static", 'F', RTGETOPT_REQ_NOTHING }, // deprecated
254 { "--variant", 'm', RTGETOPT_REQ_STRING },
255 { "-variant", 'm', RTGETOPT_REQ_STRING }, // deprecated
256};
257
258int handleCreateHardDisk(HandlerArg *a)
259{
260 HRESULT rc;
261 int vrc;
262 const char *filename = NULL;
263 uint64_t size = 0;
264 const char *format = "VDI";
265 MediumVariant_T DiskVariant = MediumVariant_Standard;
266
267 int c;
268 RTGETOPTUNION ValueUnion;
269 RTGETOPTSTATE GetState;
270 // start at 0 because main() has hacked both the argc and argv given to us
271 RTGetOptInit(&GetState, a->argc, a->argv, g_aCreateHardDiskOptions, RT_ELEMENTS(g_aCreateHardDiskOptions),
272 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
273 while ((c = RTGetOpt(&GetState, &ValueUnion)))
274 {
275 switch (c)
276 {
277 case 'f': // --filename
278 filename = ValueUnion.psz;
279 break;
280
281 case 's': // --size
282 size = ValueUnion.u64 * _1M;
283 break;
284
285 case 'S': // --sizebyte
286 size = ValueUnion.u64;
287 break;
288
289 case 'o': // --format
290 format = ValueUnion.psz;
291 break;
292
293 case 'F': // --static ("fixed"/"flat")
294 {
295 unsigned uDiskVariant = (unsigned)DiskVariant;
296 uDiskVariant |= MediumVariant_Fixed;
297 DiskVariant = (MediumVariant_T)uDiskVariant;
298 break;
299 }
300
301 case 'm': // --variant
302 vrc = parseDiskVariant(ValueUnion.psz, &DiskVariant);
303 if (RT_FAILURE(vrc))
304 return errorArgument("Invalid hard disk variant '%s'", ValueUnion.psz);
305 break;
306
307 case VINF_GETOPT_NOT_OPTION:
308 return errorSyntax(USAGE_CREATEHD, "Invalid parameter '%s'", ValueUnion.psz);
309
310 default:
311 if (c > 0)
312 {
313 if (RT_C_IS_PRINT(c))
314 return errorSyntax(USAGE_CREATEHD, "Invalid option -%c", c);
315 else
316 return errorSyntax(USAGE_CREATEHD, "Invalid option case %i", c);
317 }
318 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
319 return errorSyntax(USAGE_CREATEHD, "unknown option: %s\n", ValueUnion.psz);
320 else if (ValueUnion.pDef)
321 return errorSyntax(USAGE_CREATEHD, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
322 else
323 return errorSyntax(USAGE_CREATEHD, "error: %Rrs", c);
324 }
325 }
326
327 /* check the outcome */
328 if ( !filename
329 || !*filename
330 || size == 0)
331 return errorSyntax(USAGE_CREATEHD, "Parameters --filename and --size are required");
332
333 /* check for filename extension */
334 /** @todo use IMediumFormat to cover all extensions generically */
335 Utf8Str strName(filename);
336 if (!RTPathHaveExt(strName.c_str()))
337 {
338 Utf8Str strFormat(format);
339 if (strFormat.compare("vmdk", RTCString::CaseInsensitive) == 0)
340 strName.append(".vmdk");
341 else if (strFormat.compare("vhd", RTCString::CaseInsensitive) == 0)
342 strName.append(".vhd");
343 else
344 strName.append(".vdi");
345 filename = strName.c_str();
346 }
347
348 ComPtr<IMedium> hardDisk;
349 rc = createHardDisk(a, format, filename, hardDisk);
350 if (SUCCEEDED(rc) && hardDisk)
351 {
352 ComPtr<IProgress> progress;
353 CHECK_ERROR(hardDisk, CreateBaseStorage(size, DiskVariant, progress.asOutParam()));
354 if (SUCCEEDED(rc) && progress)
355 {
356 rc = showProgress(progress);
357 CHECK_PROGRESS_ERROR(progress, ("Failed to create hard disk"));
358 if (SUCCEEDED(rc))
359 {
360 Bstr uuid;
361 CHECK_ERROR(hardDisk, COMGETTER(Id)(uuid.asOutParam()));
362 RTPrintf("Disk image created. UUID: %s\n", Utf8Str(uuid).c_str());
363 }
364 }
365 CHECK_ERROR(hardDisk, Close());
366 }
367 return SUCCEEDED(rc) ? 0 : 1;
368}
369
370static const RTGETOPTDEF g_aModifyHardDiskOptions[] =
371{
372 { "--type", 't', RTGETOPT_REQ_STRING },
373 { "-type", 't', RTGETOPT_REQ_STRING }, // deprecated
374 { "settype", 't', RTGETOPT_REQ_STRING }, // deprecated
375 { "--autoreset", 'z', RTGETOPT_REQ_STRING },
376 { "-autoreset", 'z', RTGETOPT_REQ_STRING }, // deprecated
377 { "autoreset", 'z', RTGETOPT_REQ_STRING }, // deprecated
378 { "--compact", 'c', RTGETOPT_REQ_NOTHING },
379 { "-compact", 'c', RTGETOPT_REQ_NOTHING }, // deprecated
380 { "compact", 'c', RTGETOPT_REQ_NOTHING }, // deprecated
381 { "--resize", 'r', RTGETOPT_REQ_UINT64 },
382 { "--resizebyte", 'R', RTGETOPT_REQ_UINT64 }
383};
384
385int handleModifyHardDisk(HandlerArg *a)
386{
387 HRESULT rc;
388 int vrc;
389 ComPtr<IMedium> hardDisk;
390 MediumType_T DiskType;
391 bool AutoReset = false;
392 bool fModifyDiskType = false, fModifyAutoReset = false, fModifyCompact = false;
393 bool fModifyResize = false;
394 uint64_t cbResize = 0;
395 const char *FilenameOrUuid = NULL;
396 bool unknown = false;
397
398 int c;
399 RTGETOPTUNION ValueUnion;
400 RTGETOPTSTATE GetState;
401 // start at 0 because main() has hacked both the argc and argv given to us
402 RTGetOptInit(&GetState, a->argc, a->argv, g_aModifyHardDiskOptions, RT_ELEMENTS(g_aModifyHardDiskOptions),
403 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
404 while ((c = RTGetOpt(&GetState, &ValueUnion)))
405 {
406 switch (c)
407 {
408 case 't': // --type
409 vrc = parseDiskType(ValueUnion.psz, &DiskType);
410 if (RT_FAILURE(vrc))
411 return errorArgument("Invalid hard disk type '%s'", ValueUnion.psz);
412 fModifyDiskType = true;
413 break;
414
415 case 'z': // --autoreset
416 vrc = parseBool(ValueUnion.psz, &AutoReset);
417 if (RT_FAILURE(vrc))
418 return errorArgument("Invalid autoreset parameter '%s'", ValueUnion.psz);
419 fModifyAutoReset = true;
420 break;
421
422 case 'c': // --compact
423 fModifyCompact = true;
424 break;
425
426 case 'r': // --resize
427 cbResize = ValueUnion.u64 * _1M;
428 fModifyResize = true;
429 break;
430
431 case 'R': // --resizebyte
432 cbResize = ValueUnion.u64;
433 fModifyResize = true;
434 break;
435
436 case VINF_GETOPT_NOT_OPTION:
437 if (!FilenameOrUuid)
438 FilenameOrUuid = ValueUnion.psz;
439 else
440 return errorSyntax(USAGE_CREATEHD, "Invalid parameter '%s'", ValueUnion.psz);
441 break;
442
443 default:
444 if (c > 0)
445 {
446 if (RT_C_IS_PRINT(c))
447 return errorSyntax(USAGE_MODIFYHD, "Invalid option -%c", c);
448 else
449 return errorSyntax(USAGE_MODIFYHD, "Invalid option case %i", c);
450 }
451 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
452 return errorSyntax(USAGE_MODIFYHD, "unknown option: %s\n", ValueUnion.psz);
453 else if (ValueUnion.pDef)
454 return errorSyntax(USAGE_MODIFYHD, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
455 else
456 return errorSyntax(USAGE_MODIFYHD, "error: %Rrs", c);
457 }
458 }
459
460 if (!FilenameOrUuid)
461 return errorSyntax(USAGE_MODIFYHD, "Disk name or UUID required");
462
463 if (!fModifyDiskType && !fModifyAutoReset && !fModifyCompact && !fModifyResize)
464 return errorSyntax(USAGE_MODIFYHD, "No operation specified");
465
466 /* Depending on the operation the medium must be in the registry or
467 * may be opened on demand. */
468 if (fModifyDiskType || fModifyAutoReset)
469 rc = findMedium(a, FilenameOrUuid, DeviceType_HardDisk, false /* fSilent */, hardDisk);
470 else
471 rc = findOrOpenMedium(a, FilenameOrUuid, DeviceType_HardDisk,
472 hardDisk, false /* fForceNewUuidOnOpen */, &unknown);
473 if (FAILED(rc))
474 return 1;
475 if (hardDisk.isNull())
476 {
477 RTMsgError("Invalid hard disk reference, avoiding crash");
478 return 1;
479 }
480
481 if (fModifyDiskType)
482 {
483 MediumType_T hddType;
484 CHECK_ERROR(hardDisk, COMGETTER(Type)(&hddType));
485
486 if (hddType != DiskType)
487 CHECK_ERROR(hardDisk, COMSETTER(Type)(DiskType));
488 }
489
490 if (fModifyAutoReset)
491 {
492 CHECK_ERROR(hardDisk, COMSETTER(AutoReset)(AutoReset));
493 }
494
495 if (fModifyCompact)
496 {
497 ComPtr<IProgress> progress;
498 CHECK_ERROR(hardDisk, Compact(progress.asOutParam()));
499 if (SUCCEEDED(rc))
500 rc = showProgress(progress);
501 if (FAILED(rc))
502 {
503 if (rc == E_NOTIMPL)
504 RTMsgError("Compact hard disk operation is not implemented!");
505 else if (rc == VBOX_E_NOT_SUPPORTED)
506 RTMsgError("Compact hard disk operation for this format is not implemented yet!");
507 else
508 CHECK_PROGRESS_ERROR(progress, ("Failed to compact hard disk"));
509 }
510 }
511
512 if (fModifyResize)
513 {
514 ComPtr<IProgress> progress;
515 CHECK_ERROR(hardDisk, Resize(cbResize, progress.asOutParam()));
516 if (SUCCEEDED(rc))
517 rc = showProgress(progress);
518 if (FAILED(rc))
519 {
520 if (rc == E_NOTIMPL)
521 RTMsgError("Resize hard disk operation is not implemented!");
522 else if (rc == VBOX_E_NOT_SUPPORTED)
523 RTMsgError("Resize hard disk operation for this format is not implemented yet!");
524 else
525 CHECK_PROGRESS_ERROR(progress, ("Failed to resize hard disk"));
526 }
527 }
528
529 if (unknown)
530 hardDisk->Close();
531
532 return SUCCEEDED(rc) ? 0 : 1;
533}
534
535static const RTGETOPTDEF g_aCloneHardDiskOptions[] =
536{
537 { "--format", 'o', RTGETOPT_REQ_STRING },
538 { "-format", 'o', RTGETOPT_REQ_STRING },
539 { "--static", 'F', RTGETOPT_REQ_NOTHING },
540 { "-static", 'F', RTGETOPT_REQ_NOTHING },
541 { "--existing", 'E', RTGETOPT_REQ_NOTHING },
542 { "--variant", 'm', RTGETOPT_REQ_STRING },
543 { "-variant", 'm', RTGETOPT_REQ_STRING },
544};
545
546int handleCloneHardDisk(HandlerArg *a)
547{
548 HRESULT rc;
549 int vrc;
550 const char *pszSrc = NULL;
551 const char *pszDst = NULL;
552 Bstr format;
553 MediumVariant_T DiskVariant = MediumVariant_Standard;
554 bool fExisting = false;
555
556 int c;
557 RTGETOPTUNION ValueUnion;
558 RTGETOPTSTATE GetState;
559 // start at 0 because main() has hacked both the argc and argv given to us
560 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloneHardDiskOptions, RT_ELEMENTS(g_aCloneHardDiskOptions),
561 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
562 while ((c = RTGetOpt(&GetState, &ValueUnion)))
563 {
564 switch (c)
565 {
566 case 'o': // --format
567 format = ValueUnion.psz;
568 break;
569
570 case 'F': // --static
571 {
572 unsigned uDiskVariant = (unsigned)DiskVariant;
573 uDiskVariant |= MediumVariant_Fixed;
574 DiskVariant = (MediumVariant_T)uDiskVariant;
575 break;
576 }
577
578 case 'E': // --existing
579 fExisting = true;
580 break;
581
582 case 'm': // --variant
583 vrc = parseDiskVariant(ValueUnion.psz, &DiskVariant);
584 if (RT_FAILURE(vrc))
585 return errorArgument("Invalid hard disk variant '%s'", ValueUnion.psz);
586 break;
587
588 case VINF_GETOPT_NOT_OPTION:
589 if (!pszSrc)
590 pszSrc = ValueUnion.psz;
591 else if (!pszDst)
592 pszDst = ValueUnion.psz;
593 else
594 return errorSyntax(USAGE_CLONEHD, "Invalid parameter '%s'", ValueUnion.psz);
595 break;
596
597 default:
598 if (c > 0)
599 {
600 if (RT_C_IS_GRAPH(c))
601 return errorSyntax(USAGE_CLONEHD, "unhandled option: -%c", c);
602 else
603 return errorSyntax(USAGE_CLONEHD, "unhandled option: %i", c);
604 }
605 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
606 return errorSyntax(USAGE_CLONEHD, "unknown option: %s", ValueUnion.psz);
607 else if (ValueUnion.pDef)
608 return errorSyntax(USAGE_CLONEHD, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
609 else
610 return errorSyntax(USAGE_CLONEHD, "error: %Rrs", c);
611 }
612 }
613
614 if (!pszSrc)
615 return errorSyntax(USAGE_CLONEHD, "Mandatory UUID or input file parameter missing");
616 if (!pszDst)
617 return errorSyntax(USAGE_CLONEHD, "Mandatory output file parameter missing");
618 if (fExisting && (!format.isEmpty() || DiskVariant != MediumType_Normal))
619 return errorSyntax(USAGE_CLONEHD, "Specified options which cannot be used with --existing");
620
621 ComPtr<IMedium> srcDisk;
622 ComPtr<IMedium> dstDisk;
623 bool fSrcUnknown = false;
624 bool fDstUnknown = false;
625
626 rc = findOrOpenMedium(a, pszSrc, DeviceType_HardDisk, srcDisk,
627 false /* fForceNewUuidOnOpen */, &fSrcUnknown);
628 if (FAILED(rc))
629 return 1;
630
631 do
632 {
633 /* open/create destination hard disk */
634 if (fExisting)
635 {
636 rc = findOrOpenMedium(a, pszDst, DeviceType_HardDisk, dstDisk,
637 false /* fForceNewUuidOnOpen */, &fDstUnknown);
638 if (FAILED(rc))
639 break;
640
641 /* Perform accessibility check now. */
642 MediumState_T state;
643 CHECK_ERROR_BREAK(dstDisk, RefreshState(&state));
644 CHECK_ERROR_BREAK(dstDisk, COMGETTER(Format)(format.asOutParam()));
645 }
646 else
647 {
648 /* use the format of the source hard disk if unspecified */
649 if (format.isEmpty())
650 CHECK_ERROR_BREAK(srcDisk, COMGETTER(Format)(format.asOutParam()));
651 rc = createHardDisk(a, Utf8Str(format).c_str(), pszDst, dstDisk);
652 if (FAILED(rc))
653 break;
654 }
655
656 ComPtr<IProgress> progress;
657 CHECK_ERROR_BREAK(srcDisk, CloneTo(dstDisk, DiskVariant, NULL, progress.asOutParam()));
658
659 rc = showProgress(progress);
660 CHECK_PROGRESS_ERROR_BREAK(progress, ("Failed to clone hard disk"));
661
662 Bstr uuid;
663 CHECK_ERROR_BREAK(dstDisk, COMGETTER(Id)(uuid.asOutParam()));
664
665 RTPrintf("Clone hard disk created in format '%ls'. UUID: %s\n",
666 format.raw(), Utf8Str(uuid).c_str());
667 }
668 while (0);
669
670 if (fDstUnknown && !dstDisk.isNull())
671 {
672 /* forget the created clone */
673 dstDisk->Close();
674 }
675 if (fSrcUnknown)
676 {
677 /* close the unknown hard disk to forget it again */
678 srcDisk->Close();
679 }
680
681 return SUCCEEDED(rc) ? 0 : 1;
682}
683
684static const RTGETOPTDEF g_aConvertFromRawHardDiskOptions[] =
685{
686 { "--format", 'o', RTGETOPT_REQ_STRING },
687 { "-format", 'o', RTGETOPT_REQ_STRING },
688 { "--static", 'F', RTGETOPT_REQ_NOTHING },
689 { "-static", 'F', RTGETOPT_REQ_NOTHING },
690 { "--variant", 'm', RTGETOPT_REQ_STRING },
691 { "-variant", 'm', RTGETOPT_REQ_STRING },
692 { "--uuid", 'u', RTGETOPT_REQ_STRING },
693};
694
695RTEXITCODE handleConvertFromRaw(int argc, char *argv[])
696{
697 int rc = VINF_SUCCESS;
698 bool fReadFromStdIn = false;
699 const char *format = "VDI";
700 const char *srcfilename = NULL;
701 const char *dstfilename = NULL;
702 const char *filesize = NULL;
703 unsigned uImageFlags = VD_IMAGE_FLAGS_NONE;
704 void *pvBuf = NULL;
705 RTUUID uuid;
706 PCRTUUID pUuid = NULL;
707
708 int c;
709 RTGETOPTUNION ValueUnion;
710 RTGETOPTSTATE GetState;
711 // start at 0 because main() has hacked both the argc and argv given to us
712 RTGetOptInit(&GetState, argc, argv, g_aConvertFromRawHardDiskOptions, RT_ELEMENTS(g_aConvertFromRawHardDiskOptions),
713 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
714 while ((c = RTGetOpt(&GetState, &ValueUnion)))
715 {
716 switch (c)
717 {
718 case 'u': // --uuid
719 if (RT_FAILURE(RTUuidFromStr(&uuid, ValueUnion.psz)))
720 return errorSyntax(USAGE_CONVERTFROMRAW, "Invalid UUID '%s'", ValueUnion.psz);
721 pUuid = &uuid;
722 break;
723 case 'o': // --format
724 format = ValueUnion.psz;
725 break;
726
727 case 'm': // --variant
728 MediumVariant_T DiskVariant;
729 rc = parseDiskVariant(ValueUnion.psz, &DiskVariant);
730 if (RT_FAILURE(rc))
731 return errorArgument("Invalid hard disk variant '%s'", ValueUnion.psz);
732 /// @todo cleaner solution than assuming 1:1 mapping?
733 uImageFlags = (unsigned)DiskVariant;
734 break;
735
736 case VINF_GETOPT_NOT_OPTION:
737 if (!srcfilename)
738 {
739 srcfilename = ValueUnion.psz;
740// If you change the OS list here don't forget to update VBoxManageHelp.cpp.
741#ifndef RT_OS_WINDOWS
742 fReadFromStdIn = !strcmp(srcfilename, "stdin");
743#endif
744 }
745 else if (!dstfilename)
746 dstfilename = ValueUnion.psz;
747 else if (fReadFromStdIn && !filesize)
748 filesize = ValueUnion.psz;
749 else
750 return errorSyntax(USAGE_CONVERTFROMRAW, "Invalid parameter '%s'", ValueUnion.psz);
751 break;
752
753 default:
754 return errorGetOpt(USAGE_CONVERTFROMRAW, c, &ValueUnion);
755 }
756 }
757
758 if (!srcfilename || !dstfilename || (fReadFromStdIn && !filesize))
759 return errorSyntax(USAGE_CONVERTFROMRAW, "Incorrect number of parameters");
760 RTStrmPrintf(g_pStdErr, "Converting from raw image file=\"%s\" to file=\"%s\"...\n",
761 srcfilename, dstfilename);
762
763 PVBOXHDD pDisk = NULL;
764
765 PVDINTERFACE pVDIfs = NULL;
766 VDINTERFACEERROR vdInterfaceError;
767 vdInterfaceError.pfnError = handleVDError;
768 vdInterfaceError.pfnMessage = NULL;
769
770 rc = VDInterfaceAdd(&vdInterfaceError.Core, "VBoxManage_IError", VDINTERFACETYPE_ERROR,
771 NULL, sizeof(VDINTERFACEERROR), &pVDIfs);
772 AssertRC(rc);
773
774 /* open raw image file. */
775 RTFILE File;
776 if (fReadFromStdIn)
777 File = 0;
778 else
779 rc = RTFileOpen(&File, srcfilename, RTFILE_O_READ | RTFILE_O_OPEN | RTFILE_O_DENY_WRITE);
780 if (RT_FAILURE(rc))
781 {
782 RTMsgError("Cannot open file \"%s\": %Rrc", srcfilename, rc);
783 goto out;
784 }
785
786 uint64_t cbFile;
787 /* get image size. */
788 if (fReadFromStdIn)
789 cbFile = RTStrToUInt64(filesize);
790 else
791 rc = RTFileGetSize(File, &cbFile);
792 if (RT_FAILURE(rc))
793 {
794 RTMsgError("Cannot get image size for file \"%s\": %Rrc", srcfilename, rc);
795 goto out;
796 }
797
798 RTStrmPrintf(g_pStdErr, "Creating %s image with size %RU64 bytes (%RU64MB)...\n",
799 (uImageFlags & VD_IMAGE_FLAGS_FIXED) ? "fixed" : "dynamic", cbFile, (cbFile + _1M - 1) / _1M);
800 char pszComment[256];
801 RTStrPrintf(pszComment, sizeof(pszComment), "Converted image from %s", srcfilename);
802 rc = VDCreate(pVDIfs, VDTYPE_HDD, &pDisk);
803 if (RT_FAILURE(rc))
804 {
805 RTMsgError("Cannot create the virtual disk container: %Rrc", rc);
806 goto out;
807 }
808
809 Assert(RT_MIN(cbFile / 512 / 16 / 63, 16383) -
810 (unsigned int)RT_MIN(cbFile / 512 / 16 / 63, 16383) == 0);
811 VDGEOMETRY PCHS, LCHS;
812 PCHS.cCylinders = (unsigned int)RT_MIN(cbFile / 512 / 16 / 63, 16383);
813 PCHS.cHeads = 16;
814 PCHS.cSectors = 63;
815 LCHS.cCylinders = 0;
816 LCHS.cHeads = 0;
817 LCHS.cSectors = 0;
818 rc = VDCreateBase(pDisk, format, dstfilename, cbFile,
819 uImageFlags, pszComment, &PCHS, &LCHS, pUuid,
820 VD_OPEN_FLAGS_NORMAL, NULL, NULL);
821 if (RT_FAILURE(rc))
822 {
823 RTMsgError("Cannot create the disk image \"%s\": %Rrc", dstfilename, rc);
824 goto out;
825 }
826
827 size_t cbBuffer;
828 cbBuffer = _1M;
829 pvBuf = RTMemAlloc(cbBuffer);
830 if (!pvBuf)
831 {
832 rc = VERR_NO_MEMORY;
833 RTMsgError("Out of memory allocating buffers for image \"%s\": %Rrc", dstfilename, rc);
834 goto out;
835 }
836
837 uint64_t offFile;
838 offFile = 0;
839 while (offFile < cbFile)
840 {
841 size_t cbRead;
842 size_t cbToRead;
843 cbRead = 0;
844 cbToRead = cbFile - offFile >= (uint64_t)cbBuffer ?
845 cbBuffer : (size_t)(cbFile - offFile);
846 rc = RTFileRead(File, pvBuf, cbToRead, &cbRead);
847 if (RT_FAILURE(rc) || !cbRead)
848 break;
849 rc = VDWrite(pDisk, offFile, pvBuf, cbRead);
850 if (RT_FAILURE(rc))
851 {
852 RTMsgError("Failed to write to disk image \"%s\": %Rrc", dstfilename, rc);
853 goto out;
854 }
855 offFile += cbRead;
856 }
857
858out:
859 if (pvBuf)
860 RTMemFree(pvBuf);
861 if (pDisk)
862 VDClose(pDisk, RT_FAILURE(rc));
863 if (File != NIL_RTFILE)
864 RTFileClose(File);
865
866 return RT_SUCCESS(rc) ? RTEXITCODE_SUCCESS : RTEXITCODE_FAILURE;
867}
868
869static const RTGETOPTDEF g_aShowHardDiskInfoOptions[] =
870{
871 { "--dummy", 256, RTGETOPT_REQ_NOTHING }, // placeholder for C++
872};
873
874int handleShowHardDiskInfo(HandlerArg *a)
875{
876 HRESULT rc;
877 const char *FilenameOrUuid = NULL;
878
879 int c;
880 RTGETOPTUNION ValueUnion;
881 RTGETOPTSTATE GetState;
882 // start at 0 because main() has hacked both the argc and argv given to us
883 RTGetOptInit(&GetState, a->argc, a->argv, g_aShowHardDiskInfoOptions, RT_ELEMENTS(g_aShowHardDiskInfoOptions),
884 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
885 while ((c = RTGetOpt(&GetState, &ValueUnion)))
886 {
887 switch (c)
888 {
889 case VINF_GETOPT_NOT_OPTION:
890 if (!FilenameOrUuid)
891 FilenameOrUuid = ValueUnion.psz;
892 else
893 return errorSyntax(USAGE_SHOWHDINFO, "Invalid parameter '%s'", ValueUnion.psz);
894 break;
895
896 default:
897 if (c > 0)
898 {
899 if (RT_C_IS_PRINT(c))
900 return errorSyntax(USAGE_SHOWHDINFO, "Invalid option -%c", c);
901 else
902 return errorSyntax(USAGE_SHOWHDINFO, "Invalid option case %i", c);
903 }
904 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
905 return errorSyntax(USAGE_SHOWHDINFO, "unknown option: %s\n", ValueUnion.psz);
906 else if (ValueUnion.pDef)
907 return errorSyntax(USAGE_SHOWHDINFO, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
908 else
909 return errorSyntax(USAGE_SHOWHDINFO, "error: %Rrs", c);
910 }
911 }
912
913 /* check for required options */
914 if (!FilenameOrUuid)
915 return errorSyntax(USAGE_SHOWHDINFO, "Disk name or UUID required");
916
917 ComPtr<IMedium> hardDisk;
918 bool unknown = false;
919
920 rc = findOrOpenMedium(a, FilenameOrUuid, DeviceType_HardDisk, hardDisk,
921 false /* fForceNewUuidOnOpen */, &unknown);
922 if (FAILED(rc))
923 return 1;
924
925 do
926 {
927 Bstr uuid;
928 hardDisk->COMGETTER(Id)(uuid.asOutParam());
929 RTPrintf("UUID: %s\n", Utf8Str(uuid).c_str());
930
931 /* check for accessibility */
932 /// @todo NEWMEDIA check accessibility of all parents
933 /// @todo NEWMEDIA print the full state value
934 MediumState_T state;
935 CHECK_ERROR_BREAK(hardDisk, RefreshState(&state));
936 RTPrintf("Accessible: %s\n", state != MediumState_Inaccessible ? "yes" : "no");
937
938 if (state == MediumState_Inaccessible)
939 {
940 Bstr err;
941 CHECK_ERROR_BREAK(hardDisk, COMGETTER(LastAccessError)(err.asOutParam()));
942 RTPrintf("Access Error: %ls\n", err.raw());
943 }
944
945 Bstr description;
946 hardDisk->COMGETTER(Description)(description.asOutParam());
947 if (!description.isEmpty())
948 {
949 RTPrintf("Description: %ls\n", description.raw());
950 }
951
952 LONG64 logicalSize;
953 hardDisk->COMGETTER(LogicalSize)(&logicalSize);
954 RTPrintf("Logical size: %lld MBytes\n", logicalSize >> 20);
955 LONG64 actualSize;
956 hardDisk->COMGETTER(Size)(&actualSize);
957 RTPrintf("Current size on disk: %lld MBytes\n", actualSize >> 20);
958
959 ComPtr <IMedium> parent;
960 hardDisk->COMGETTER(Parent)(parent.asOutParam());
961
962 MediumType_T type;
963 hardDisk->COMGETTER(Type)(&type);
964 const char *typeStr = "unknown";
965 switch (type)
966 {
967 case MediumType_Normal:
968 if (!parent.isNull())
969 typeStr = "normal (differencing)";
970 else
971 typeStr = "normal (base)";
972 break;
973 case MediumType_Immutable:
974 typeStr = "immutable";
975 break;
976 case MediumType_Writethrough:
977 typeStr = "writethrough";
978 break;
979 case MediumType_Shareable:
980 typeStr = "shareable";
981 break;
982 case MediumType_Readonly:
983 typeStr = "readonly";
984 break;
985 case MediumType_MultiAttach:
986 typeStr = "multiattach";
987 break;
988 }
989 RTPrintf("Type: %s\n", typeStr);
990
991 Bstr format;
992 hardDisk->COMGETTER(Format)(format.asOutParam());
993 RTPrintf("Storage format: %ls\n", format.raw());
994 ULONG variant;
995 hardDisk->COMGETTER(Variant)(&variant);
996 const char *variantStr = "unknown";
997 switch (variant & ~(MediumVariant_Fixed | MediumVariant_Diff))
998 {
999 case MediumVariant_VmdkSplit2G:
1000 variantStr = "split2G";
1001 break;
1002 case MediumVariant_VmdkStreamOptimized:
1003 variantStr = "streamOptimized";
1004 break;
1005 case MediumVariant_VmdkESX:
1006 variantStr = "ESX";
1007 break;
1008 case MediumVariant_Standard:
1009 variantStr = "default";
1010 break;
1011 }
1012 const char *variantTypeStr = "dynamic";
1013 if (variant & MediumVariant_Fixed)
1014 variantTypeStr = "fixed";
1015 else if (variant & MediumVariant_Diff)
1016 variantTypeStr = "differencing";
1017 RTPrintf("Format variant: %s %s\n", variantTypeStr, variantStr);
1018
1019 /// @todo also dump config parameters (iSCSI)
1020
1021 if (!unknown)
1022 {
1023 com::SafeArray<BSTR> machineIds;
1024 hardDisk->COMGETTER(MachineIds)(ComSafeArrayAsOutParam(machineIds));
1025 for (size_t j = 0; j < machineIds.size(); ++ j)
1026 {
1027 ComPtr<IMachine> machine;
1028 CHECK_ERROR(a->virtualBox, FindMachine(machineIds[j], machine.asOutParam()));
1029 ASSERT(machine);
1030 Bstr name;
1031 machine->COMGETTER(Name)(name.asOutParam());
1032 machine->COMGETTER(Id)(uuid.asOutParam());
1033 RTPrintf("%s%ls (UUID: %ls)\n",
1034 j == 0 ? "In use by VMs: " : " ",
1035 name.raw(), machineIds[j]);
1036 }
1037 /// @todo NEWMEDIA check usage in snapshots too
1038 /// @todo NEWMEDIA also list children
1039 }
1040
1041 Bstr loc;
1042 hardDisk->COMGETTER(Location)(loc.asOutParam());
1043 RTPrintf("Location: %ls\n", loc.raw());
1044
1045 /* print out information specific for differencing hard disks */
1046 if (!parent.isNull())
1047 {
1048 BOOL autoReset = FALSE;
1049 hardDisk->COMGETTER(AutoReset)(&autoReset);
1050 RTPrintf("Auto-Reset: %s\n", autoReset ? "on" : "off");
1051 }
1052 }
1053 while (0);
1054
1055 if (unknown)
1056 {
1057 /* close the unknown hard disk to forget it again */
1058 hardDisk->Close();
1059 }
1060
1061 return SUCCEEDED(rc) ? 0 : 1;
1062}
1063
1064static const RTGETOPTDEF g_aCloseMediumOptions[] =
1065{
1066 { "disk", 'd', RTGETOPT_REQ_NOTHING },
1067 { "dvd", 'D', RTGETOPT_REQ_NOTHING },
1068 { "floppy", 'f', RTGETOPT_REQ_NOTHING },
1069 { "--delete", 'r', RTGETOPT_REQ_NOTHING },
1070};
1071
1072int handleCloseMedium(HandlerArg *a)
1073{
1074 HRESULT rc = S_OK;
1075 enum {
1076 CMD_NONE,
1077 CMD_DISK,
1078 CMD_DVD,
1079 CMD_FLOPPY
1080 } cmd = CMD_NONE;
1081 const char *FilenameOrUuid = NULL;
1082 bool fDelete = false;
1083
1084 int c;
1085 RTGETOPTUNION ValueUnion;
1086 RTGETOPTSTATE GetState;
1087 // start at 0 because main() has hacked both the argc and argv given to us
1088 RTGetOptInit(&GetState, a->argc, a->argv, g_aCloseMediumOptions, RT_ELEMENTS(g_aCloseMediumOptions),
1089 0, RTGETOPTINIT_FLAGS_NO_STD_OPTS);
1090 while ((c = RTGetOpt(&GetState, &ValueUnion)))
1091 {
1092 switch (c)
1093 {
1094 case 'd': // disk
1095 if (cmd != CMD_NONE)
1096 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1097 cmd = CMD_DISK;
1098 break;
1099
1100 case 'D': // DVD
1101 if (cmd != CMD_NONE)
1102 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1103 cmd = CMD_DVD;
1104 break;
1105
1106 case 'f': // floppy
1107 if (cmd != CMD_NONE)
1108 return errorSyntax(USAGE_CLOSEMEDIUM, "Only one command can be specified: '%s'", ValueUnion.psz);
1109 cmd = CMD_FLOPPY;
1110 break;
1111
1112 case 'r': // --delete
1113 fDelete = true;
1114 break;
1115
1116 case VINF_GETOPT_NOT_OPTION:
1117 if (!FilenameOrUuid)
1118 FilenameOrUuid = ValueUnion.psz;
1119 else
1120 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid parameter '%s'", ValueUnion.psz);
1121 break;
1122
1123 default:
1124 if (c > 0)
1125 {
1126 if (RT_C_IS_PRINT(c))
1127 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid option -%c", c);
1128 else
1129 return errorSyntax(USAGE_CLOSEMEDIUM, "Invalid option case %i", c);
1130 }
1131 else if (c == VERR_GETOPT_UNKNOWN_OPTION)
1132 return errorSyntax(USAGE_CLOSEMEDIUM, "unknown option: %s\n", ValueUnion.psz);
1133 else if (ValueUnion.pDef)
1134 return errorSyntax(USAGE_CLOSEMEDIUM, "%s: %Rrs", ValueUnion.pDef->pszLong, c);
1135 else
1136 return errorSyntax(USAGE_CLOSEMEDIUM, "error: %Rrs", c);
1137 }
1138 }
1139
1140 /* check for required options */
1141 if (cmd == CMD_NONE)
1142 return errorSyntax(USAGE_CLOSEMEDIUM, "Command variant disk/dvd/floppy required");
1143 if (!FilenameOrUuid)
1144 return errorSyntax(USAGE_CLOSEMEDIUM, "Disk name or UUID required");
1145
1146 ComPtr<IMedium> medium;
1147
1148 if (cmd == CMD_DISK)
1149 rc = findMedium(a, FilenameOrUuid, DeviceType_HardDisk, false /* fSilent */, medium);
1150 else if (cmd == CMD_DVD)
1151 rc = findMedium(a, FilenameOrUuid, DeviceType_DVD, false /* fSilent */, medium);
1152 else if (cmd == CMD_FLOPPY)
1153 rc = findMedium(a, FilenameOrUuid, DeviceType_Floppy, false /* fSilent */, medium);
1154
1155 if (SUCCEEDED(rc) && medium)
1156 {
1157 if (fDelete)
1158 {
1159 ComPtr<IProgress> progress;
1160 CHECK_ERROR(medium, DeleteStorage(progress.asOutParam()));
1161 if (SUCCEEDED(rc))
1162 {
1163 rc = showProgress(progress);
1164 CHECK_PROGRESS_ERROR(progress, ("Failed to delete medium"));
1165 }
1166 else
1167 RTMsgError("Failed to delete medium. Error code %Rrc", rc);
1168 }
1169 CHECK_ERROR(medium, Close());
1170 }
1171
1172 return SUCCEEDED(rc) ? 0 : 1;
1173}
1174#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