VirtualBox

source: vbox/trunk/src/VBox/ImageMounter/vboximg-mount/vboximg-mount.cpp@ 80524

Last change on this file since 80524 was 80524, checked in by vboxsync, 5 years ago

vboximg-mount: Properly retrieve inode information from a guest filesystem and fill the stat buffer

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 48.4 KB
Line 
1/* $Id: vboximg-mount.cpp 80524 2019-09-01 13:17:00Z vboxsync $ */
2/** @file
3 * vboximg-mount - Disk Image Flattening FUSE Program.
4 */
5
6/*
7 * Copyright (C) 2009-2019 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 */
17
18
19/*********************************************************************************************************************************
20* Header Files *
21*********************************************************************************************************************************/
22
23#define LOG_GROUP LOG_GROUP_DEFAULT /** @todo log group */
24
25#define RTTIME_INCL_TIMESPEC
26#define FUSE_USE_VERSION 27
27#if defined(RT_OS_DARWIN) || defined(RT_OS_LINUX) || defined(RT_OS_FREEBSD)
28# define UNIX_DERIVATIVE
29#endif
30#define MAX_READERS (INT32_MAX / 32)
31#include <fuse.h>
32#ifdef UNIX_DERIVATIVE
33#include <errno.h>
34#include <fcntl.h>
35#include <stdlib.h>
36#include <libgen.h>
37#include <unistd.h>
38#include <math.h>
39#include <cstdarg>
40#include <sys/stat.h>
41#include <sys/time.h>
42#endif
43#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) || defined(RT_OS_LINUX)
44# include <sys/param.h>
45# undef PVM /* Blasted old BSD mess still hanging around darwin. */
46#endif
47#ifdef RT_OS_LINUX
48# include <linux/fs.h>
49# include <linux/hdreg.h>
50#endif
51#include <VirtualBox_XPCOM.h>
52#include <VBox/com/VirtualBox.h>
53#include <VBox/vd.h>
54#include <VBox/vd-ifs.h>
55#include <VBox/log.h>
56#include <VBox/err.h>
57#include <VBox/com/ErrorInfo.h>
58#include <VBox/com/NativeEventQueue.h>
59#include <VBox/com/com.h>
60#include <VBox/com/string.h>
61#include <VBox/com/Guid.h>
62#include <VBox/com/array.h>
63#include <VBox/com/errorprint.h>
64#include <VBox/vd-plugin.h>
65#include <iprt/initterm.h>
66#include <iprt/assert.h>
67#include <iprt/message.h>
68#include <iprt/critsect.h>
69#include <iprt/asm.h>
70#include <iprt/mem.h>
71#include <iprt/string.h>
72#include <iprt/initterm.h>
73#include <iprt/stream.h>
74#include <iprt/types.h>
75#include <iprt/path.h>
76#include <iprt/utf16.h>
77#include <iprt/base64.h>
78#include <iprt/vfs.h>
79#include <iprt/dvm.h>
80#include <iprt/time.h>
81
82#include "vboximgCrypto.h"
83#include "vboximgMedia.h"
84#include "SelfSizingTable.h"
85#include "vboximgOpts.h"
86
87using namespace com;
88
89enum {
90 USAGE_FLAG,
91};
92
93#if !defined(S_ISTXT) && defined(S_ISVTX)
94# define S_ISTXT (S_ISVTX)
95#endif
96
97#define VBOX_EXTPACK "Oracle VM VirtualBox Extension Pack"
98#define VERBOSE g_vboximgOpts.fVerbose
99
100#define SAFENULL(strPtr) (strPtr ? strPtr : "")
101#define CSTR(arg) Utf8Str(arg).c_str() /* Converts XPCOM string type to C string type */
102
103static struct fuse_operations g_vboximgOps; /** FUSE structure that defines allowed ops for this FS */
104
105/**
106 * Volume data.
107 */
108typedef struct VBOXIMGMOUNTVOL
109{
110 /** The volume handle. */
111 RTDVMVOLUME hVol;
112 /** The VFS file associated with the volume. */
113 RTVFSFILE hVfsFileVol;
114 /** Handle to the VFS root if supported and specified. */
115 RTVFS hVfsRoot;
116 /** Handle to the root directory. */
117 RTVFSDIR hVfsDirRoot;
118} VBOXIMGMOUNTVOL;
119/** Pointer to a volume data structure. */
120typedef VBOXIMGMOUNTVOL *PVBOXIMGMOUNTVOL;
121
122/* Global variables */
123static RTVFSFILE g_hVfsFileDisk; /** Disk as VFS file handle. */
124static uint32_t g_cbSector; /** Disk sector size. */
125static RTDVM g_hDvmMgr; /** Handle to the volume manager. */
126static char *g_pszDiskUuid; /** UUID of image (if known, otherwise NULL) */
127static PVDINTERFACE g_pVdIfs; /** @todo Remove when VD I/O becomes threadsafe */
128static VDINTERFACETHREADSYNC g_VDIfThreadSync; /** @todo Remove when VD I/O becomes threadsafe */
129static RTCRITSECT g_vdioLock; /** @todo Remove when VD I/O becomes threadsafe */
130static char *g_pszImageName; /** Base filename for current VD image */
131static char *g_pszImagePath; /** Full path to current VD image */
132static char *g_pszBaseImagePath; /** Base image known after parsing */
133static char *g_pszBaseImageName; /** Base image known after parsing */
134static uint32_t g_cImages; /** Number of images in diff chain */
135
136/** Pointer to the detected volumes. */
137static PVBOXIMGMOUNTVOL g_paVolumes;
138/** Number of detected volumes. */
139static uint32_t g_cVolumes;
140
141VBOXIMGOPTS g_vboximgOpts;
142
143#define OPTION(fmt, pos, val) { fmt, offsetof(struct vboximgOpts, pos), val }
144
145static struct fuse_opt vboximgOptDefs[] = {
146 OPTION("--image %s", pszImageUuidOrPath, 0),
147 OPTION("-i %s", pszImageUuidOrPath, 0),
148 OPTION("--rw", fRW, 1),
149 OPTION("--root", fAllowRoot, 0),
150 OPTION("--vm %s", pszVm, 0),
151 OPTION("-l", fList, 1),
152 OPTION("--list", fList, 1),
153 OPTION("-g", fGstFs, 1),
154 OPTION("--guest-filesystem", fGstFs, 1),
155 OPTION("--verbose", fVerbose, 1),
156 OPTION("-v", fVerbose, 1),
157 OPTION("--wide", fWide, 1),
158 OPTION("-w", fWide, 1),
159 OPTION("-lv", fVerboseList, 1),
160 OPTION("-vl", fVerboseList, 1),
161 OPTION("-lw", fWideList, 1),
162 OPTION("-wl", fWideList, 1),
163 OPTION("-h", fBriefUsage, 1),
164 FUSE_OPT_KEY("--help", USAGE_FLAG),
165 FUSE_OPT_KEY("-vm", FUSE_OPT_KEY_NONOPT),
166 FUSE_OPT_END
167};
168
169typedef struct IMAGELIST
170{
171 struct IMAGELIST *next;
172 struct IMAGELIST *prev;
173 ComPtr<IToken> pLockToken;
174 bool fWriteable;
175 ComPtr<IMedium> pImage;
176 Bstr pImageName;
177 Bstr pImagePath;
178} IMAGELIST;
179
180IMAGELIST listHeadLockList; /* flink & blink intentionally left NULL */
181
182
183
184/** @todo Remove when VD I/O becomes threadsafe */
185static DECLCALLBACK(int) vboximgThreadStartRead(void *pvUser)
186{
187 PRTCRITSECT vdioLock = (PRTCRITSECT)pvUser;
188 return RTCritSectEnter(vdioLock);
189}
190
191static DECLCALLBACK(int) vboximgThreadFinishRead(void *pvUser)
192{
193 PRTCRITSECT vdioLock = (PRTCRITSECT)pvUser;
194 return RTCritSectLeave(vdioLock);
195}
196
197static DECLCALLBACK(int) vboximgThreadStartWrite(void *pvUser)
198{
199 PRTCRITSECT vdioLock = (PRTCRITSECT)pvUser;
200 return RTCritSectEnter(vdioLock);
201}
202
203static DECLCALLBACK(int) vboximgThreadFinishWrite(void *pvUser)
204{
205 PRTCRITSECT vdioLock = (PRTCRITSECT)pvUser;
206 return RTCritSectLeave(vdioLock);
207}
208/** @todo (end of to do section) */
209
210
211static void
212briefUsage()
213{
214 RTPrintf("usage: vboximg-mount [options] <mount point directory path>\n\n"
215 "vboximg-mount options:\n\n"
216 " [ { -i | --image } <specifier> ] VirtualBox disk base image or snapshot,\n"
217 " specified by UUID or path\n"
218 "\n"
219 " [ { -l | --list } ] If --image specified, list its partitions,\n"
220 " otherwise, list registered VMs and their\n"
221 " attached virtual HDD disk media. In verbose\n"
222 " mode, VM/media list will be long format,\n"
223 " i.e. including snapshot images and paths.\n"
224 "\n"
225 " [ { -w | --wide } ] List media in wide / tabular format\n"
226 " (reduces vertical scrolling but requires\n"
227 " wider than standard 80 column window)\n"
228 "\n"
229 " [ { -g | --guest-filesystem } ] Exposes supported guest filesystems directly\n"
230 " in the mounted directory without the need\n"
231 " for a filesystem driver on the host\n"
232 "\n"
233 " [ --vm UUID ] Restrict media list to specified vm.\n"
234 "\n"
235 " [ --rw ] Make image writeable (default = readonly)\n"
236 "\n"
237 " [ --root ] Same as -o allow_root.\n"
238 "\n"
239 " [ { -v | --verbose } ] Log extra information.\n"
240 "\n"
241 " [ -o opt[,opt...]] FUSE mount options.\n"
242 "\n"
243 " [ { --help | -h | -? } ] Display this usage information.\n"
244 );
245 RTPrintf("\n"
246 "vboximg-mount is a utility to make VirtualBox disk images available to the host\n"
247 "operating system for privileged or non-priviliged access. Any version of the\n"
248 "disk can be mounted from its available history of snapshots.\n"
249 "\n"
250 "If the user specifies a base image identifier using the --image option, only\n"
251 "the base image will be mounted, disregarding any snapshots. Alternatively,\n"
252 "if a snapshot is specified, the state of the FUSE-mounted virtual disk\n"
253 "is synthesized from the implied chain of snapshots, including the base image.\n"
254 "\n"
255 "The virtual disk is exposed as a device node within a FUSE-based filesystem\n"
256 "that overlays the user-provided mount point. The FUSE filesystem consists of a\n"
257 "directory containing a number of files and possibly other directories:"
258 " * vhdd: Provides access to the raw disk image data as a flat image\n"
259 " * vol<id>: Provides access to individual volumes on the accessed disk image\n"
260 " * fs<id>: Provides access to a supported filesystem without the need for a"
261 " host filesystem driver\n"
262 "\n"
263 "The directory will also contain a symbolic link which has the same basename(1)\n"
264 "as the virtual disk base image and points to the location of the\n"
265 "virtual disk base image.\n"
266 "\n"
267 );
268}
269
270static int
271vboximgOptHandler(void *data, const char *arg, int optKey, struct fuse_args *outargs)
272{
273 NOREF(data);
274 NOREF(arg);
275 NOREF(optKey);
276 NOREF(outargs);
277
278 /*
279 * Apparently this handler is only called for arguments FUSE can't parse,
280 * and arguments that don't result in variable assignment such as "USAGE"
281 * In this impl. that's always deemed a parsing error.
282 */
283 if (*arg != '-') /* could be user's mount point */
284 return 1;
285
286 return -1;
287}
288
289
290/**
291 * Queries the VFS object handle from the given path.
292 *
293 * @returns IPRT status code.
294 * @retval VERR_NOT_FOUND if the object denoted by the path couldn't be found.
295 * @param pszPath The path.
296 * @param phVfsObj Where to store the handle to the VFS object on success.
297 */
298static int vboxImgMntVfsObjQueryFromPath(const char *pszPath, PRTVFSOBJ phVfsObj)
299{
300 PRTPATHSPLIT pPathSplit = NULL;
301 int rc = RTPathSplitA(pszPath, &pPathSplit, RTPATH_STR_F_STYLE_HOST);
302 if (RT_SUCCESS(rc))
303 {
304 if ( RTPATH_PROP_HAS_ROOT_SPEC(pPathSplit->fProps)
305 && pPathSplit->cComps >= 2)
306 {
307 /* Skip the root specifier and start with the component coming afterwards. */
308 if (!RTStrCmp(pPathSplit->apszComps[1], "vhdd"))
309 *phVfsObj = RTVfsObjFromFile(g_hVfsFileDisk);
310 else if (!RTStrNCmp(pPathSplit->apszComps[1], "vol", sizeof("vol") - 1))
311 {
312 /* Retrieve the accessed volume and return the stat data. */
313 uint32_t idxVol;
314 int rcIprt = RTStrToUInt32Full(&pPathSplit->apszComps[1][3], 10, &idxVol);
315 if ( rcIprt == VINF_SUCCESS
316 && idxVol < g_cVolumes)
317 *phVfsObj = RTVfsObjFromFile(g_paVolumes[idxVol].hVfsFileVol);
318 else
319 rc = VERR_NOT_FOUND;
320 }
321 else if (!RTStrNCmp(pPathSplit->apszComps[1], "fs", sizeof("fs") - 1))
322 {
323 /* Retrieve the accessed volume and return the stat data. */
324 uint32_t idxVol;
325 int rcIprt = RTStrToUInt32Full(&pPathSplit->apszComps[1][2], 10, &idxVol);
326 if ( rcIprt == VINF_SUCCESS
327 && idxVol < g_cVolumes
328 && g_paVolumes[idxVol].hVfsDirRoot != NIL_RTVFSDIR)
329 *phVfsObj = RTVfsObjFromDir(g_paVolumes[idxVol].hVfsDirRoot);
330 else
331 rc = VERR_NOT_FOUND;
332
333 /* Is an object inside the guest filesystem requested? */
334 if (pPathSplit->cComps > 2)
335 {
336 PRTPATHSPLIT pPathSplitVfs = (PRTPATHSPLIT)RTMemTmpAllocZ(RT_UOFFSETOF_DYN(RTPATHSPLIT, apszComps[pPathSplit->cComps - 1]));
337 if (RT_LIKELY(pPathSplitVfs))
338 {
339 pPathSplitVfs->cComps = pPathSplit->cComps - 1;
340 pPathSplitVfs->fProps = pPathSplit->fProps;
341 pPathSplitVfs->cchPath = pPathSplit->cchPath - strlen(pPathSplit->apszComps[1]) - 1;
342 pPathSplitVfs->cbNeeded = pPathSplit->cbNeeded;
343 pPathSplitVfs->pszSuffix = pPathSplit->pszSuffix;
344 pPathSplitVfs->apszComps[0] = pPathSplit->apszComps[0];
345 for (uint32_t i = 1; i < pPathSplitVfs->cComps; i++)
346 pPathSplitVfs->apszComps[i] = pPathSplit->apszComps[i + 1];
347
348 /* Reassemble the path. */
349 char *pszPathVfs = (char *)RTMemTmpAllocZ(pPathSplitVfs->cbNeeded);
350 if (RT_LIKELY(pszPathVfs))
351 {
352 rc = RTPathSplitReassemble(pPathSplitVfs, RTPATH_STR_F_STYLE_HOST, pszPathVfs, pPathSplitVfs->cbNeeded);
353 if (RT_SUCCESS(rc))
354 {
355 rc = RTVfsObjOpen(g_paVolumes[idxVol].hVfsRoot, pszPathVfs,
356 RTFILE_O_READWRITE | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
357 RTVFSOBJ_F_OPEN_ANY | RTVFSOBJ_F_CREATE_NOTHING | RTPATH_F_ON_LINK,
358 phVfsObj);
359 }
360 RTMemTmpFree(pszPathVfs);
361 }
362
363 RTMemTmpFree(pPathSplitVfs);
364 }
365 else
366 rc = VERR_NO_MEMORY;
367 }
368 }
369 else
370 rc = VERR_NOT_FOUND;
371
372 rc = VINF_SUCCESS;
373 }
374 else
375 rc = VERR_NOT_FOUND;
376 RTPathSplitFree(pPathSplit);
377 }
378
379 return rc;
380}
381
382
383/** @copydoc fuse_operations::open */
384static int vboximgOp_open(const char *pszPath, struct fuse_file_info *pInfo)
385{
386 LogFlowFunc(("pszPath=%s\n", pszPath));
387 int rc = 0;
388
389 RTVFSOBJ hVfsObj;
390 int rcIprt = vboxImgMntVfsObjQueryFromPath(pszPath, &hVfsObj);
391 if (RT_SUCCESS(rc))
392 {
393 uint32_t fNotSup = 0;
394
395#ifdef UNIX_DERIVATIVE
396# ifdef RT_OS_DARWIN
397 fNotSup = O_APPEND | O_NONBLOCK | O_SYMLINK | O_NOCTTY | O_SHLOCK | O_EXLOCK |
398 O_ASYNC | O_CREAT | O_TRUNC | O_EXCL | O_EVTONLY;
399# elif defined(RT_OS_LINUX)
400 fNotSup = O_APPEND | O_ASYNC | O_DIRECT | O_NOATIME | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
401 /* | O_LARGEFILE | O_SYNC | ? */
402# elif defined(RT_OS_FREEBSD)
403 fNotSup = O_APPEND | O_ASYNC | O_DIRECT | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
404 /* | O_LARGEFILE | O_SYNC | ? */
405# endif
406#else
407# error "Port me"
408#endif
409
410 if (!(pInfo->flags & fNotSup))
411 {
412#ifdef UNIX_DERIVATIVE
413 if ((pInfo->flags & O_ACCMODE) == O_ACCMODE)
414 rc = -EINVAL;
415# ifdef O_DIRECTORY
416 if (pInfo->flags & O_DIRECTORY)
417 rc = -ENOTDIR;
418# endif
419#endif
420
421 if (!rc)
422 {
423 pInfo->fh = (uintptr_t)hVfsObj;
424 return 0;
425 }
426 }
427 else
428 rc = -EINVAL;
429
430 RTVfsObjRelease(hVfsObj);
431 }
432 else
433 rc = -RTErrConvertToErrno(rcIprt);
434
435 LogFlowFunc(("rc=%d \"%s\"\n", rc, pszPath));
436 return rc;
437
438}
439
440/** @copydoc fuse_operations::release */
441static int vboximgOp_release(const char *pszPath, struct fuse_file_info *pInfo)
442{
443 NOREF(pszPath);
444
445 LogFlowFunc(("pszPath=%s\n", pszPath));
446
447 RTVFSOBJ hVfsObj = (RTVFSOBJ)(uintptr_t)pInfo->fh;
448 RTVfsObjRelease(hVfsObj);
449
450 LogFlowFunc(("\"%s\"\n", pszPath));
451 return 0;
452}
453
454
455/** @copydoc fuse_operations::read */
456static int vboximgOp_read(const char *pszPath, char *pbBuf, size_t cbBuf,
457 off_t offset, struct fuse_file_info *pInfo)
458{
459 NOREF(pszPath);
460
461 LogFlowFunc(("offset=%#llx size=%#zx path=\"%s\"\n", (uint64_t)offset, cbBuf, pszPath));
462
463 AssertReturn(offset >= 0, -EINVAL);
464 AssertReturn((int)cbBuf >= 0, -EINVAL);
465 AssertReturn((unsigned)cbBuf == cbBuf, -EINVAL);
466
467 int rc = 0;
468 RTVFSOBJ hVfsObj = (RTVFSOBJ)(uintptr_t)pInfo->fh;
469 switch (RTVfsObjGetType(hVfsObj))
470 {
471 case RTVFSOBJTYPE_FILE:
472 {
473 RTVFSFILE hVfsFile = RTVfsObjToFile(hVfsObj);
474 int rcIprt = RTVfsFileReadAt(hVfsFile, offset, pbBuf, cbBuf, NULL);
475 if (RT_FAILURE(rc))
476 rc = -RTErrConvertToErrno(rcIprt);
477 else
478 rc = cbBuf;
479 RTVfsFileRelease(hVfsFile);
480 break;
481 }
482 default:
483 rc = -EINVAL;
484 }
485
486 if (rc < 0)
487 LogFlowFunc(("%s\n", strerror(rc)));
488 return rc;
489}
490
491/** @copydoc fuse_operations::write */
492static int vboximgOp_write(const char *pszPath, const char *pbBuf, size_t cbBuf,
493 off_t offset, struct fuse_file_info *pInfo)
494{
495 NOREF(pszPath);
496 NOREF(pInfo);
497
498 LogFlowFunc(("offset=%#llx size=%#zx path=\"%s\"\n", (uint64_t)offset, cbBuf, pszPath));
499
500 AssertReturn(offset >= 0, -EINVAL);
501 AssertReturn((int)cbBuf >= 0, -EINVAL);
502 AssertReturn((unsigned)cbBuf == cbBuf, -EINVAL);
503
504 if (!g_vboximgOpts.fRW)
505 {
506 LogFlowFunc(("WARNING: vboximg-mount (FUSE FS) --rw option not specified\n"
507 " (write operation ignored w/o error!)\n"));
508 return cbBuf;
509 }
510
511 int rc = 0;
512 RTVFSOBJ hVfsObj = (RTVFSOBJ)(uintptr_t)pInfo->fh;
513 switch (RTVfsObjGetType(hVfsObj))
514 {
515 case RTVFSOBJTYPE_FILE:
516 {
517 RTVFSFILE hVfsFile = RTVfsObjToFile(hVfsObj);
518 int rcIprt = RTVfsFileWriteAt(hVfsFile, offset, pbBuf, cbBuf, NULL);
519 if (RT_FAILURE(rc))
520 rc = -RTErrConvertToErrno(rcIprt);
521 else
522 rc = cbBuf;
523 RTVfsFileRelease(hVfsFile);
524 break;
525 }
526 default:
527 rc = -EINVAL;
528 }
529
530 if (rc < 0)
531 LogFlowFunc(("%s\n", strerror(rc)));
532
533 return rc;
534}
535
536/** @copydoc fuse_operations::getattr */
537static int
538vboximgOp_getattr(const char *pszPath, struct stat *stbuf)
539{
540 int rc = 0;
541
542 LogFlowFunc(("pszPath=%s, stat(\"%s\")\n", pszPath, g_pszImagePath));
543
544 memset(stbuf, 0, sizeof(struct stat));
545
546 if (RTStrCmp(pszPath, "/") == 0)
547 {
548 stbuf->st_mode = S_IFDIR | 0755;
549 stbuf->st_nlink = 2;
550 }
551 else if (RTStrNCmp(pszPath + 1, g_pszImageName, strlen(g_pszImageName)) == 0)
552 {
553 /* When the disk is partitioned, the symbolic link named from `basename` of
554 * resolved path to VBox disk image, has appended to it formatted text
555 * representing the offset range of the partition.
556 *
557 * $ vboximg-mount -i /stroll/along/the/path/simple_fixed_disk.vdi -p 1 /mnt/tmpdir
558 * $ ls /mnt/tmpdir
559 * simple_fixed_disk.vdi[20480:2013244928] vhdd
560 */
561 rc = stat(g_pszImagePath, stbuf);
562 if (rc < 0)
563 return rc;
564 stbuf->st_size = 0;
565 stbuf->st_mode = S_IFLNK | 0444;
566 stbuf->st_nlink = 1;
567 stbuf->st_uid = 0;
568 stbuf->st_gid = 0;
569 }
570 else
571 {
572 /* Query the VFS object and fill in the data. */
573 RTVFSOBJ hVfsObj = NIL_RTVFSOBJ;
574 int rcIprt = vboxImgMntVfsObjQueryFromPath(pszPath, &hVfsObj);
575 if (RT_SUCCESS(rcIprt))
576 {
577 RTFSOBJINFO ObjInfo;
578
579 rcIprt = RTVfsObjQueryInfo(hVfsObj, &ObjInfo, RTFSOBJATTRADD_UNIX);
580 if (RT_SUCCESS(rcIprt))
581 {
582 stbuf->st_size = ObjInfo.cbObject;
583 stbuf->st_nlink = 1;
584 stbuf->st_uid = 0;
585 stbuf->st_gid = 0;
586
587 RTTimeSpecGetTimespec(&ObjInfo.AccessTime, &stbuf->st_atim);
588 RTTimeSpecGetTimespec(&ObjInfo.ModificationTime, &stbuf->st_mtim);
589 RTTimeSpecGetTimespec(&ObjInfo.ChangeTime, &stbuf->st_ctim);
590 /*RTTimeSpecGetTimespec(&ObjInfo.BirthTime, &stbuf->st_birthtime);*/ /* Not existing on Linux. */
591
592 switch (ObjInfo.Attr.fMode & RTFS_TYPE_MASK)
593 {
594 case RTFS_TYPE_FIFO:
595 {
596 stbuf->st_mode = S_IFIFO;
597 break;
598 }
599 case RTFS_TYPE_DEV_CHAR:
600 {
601 stbuf->st_mode = S_IFCHR;
602 break;
603 }
604 case RTFS_TYPE_DIRECTORY:
605 {
606 stbuf->st_mode = S_IFDIR;
607 stbuf->st_nlink = 2;
608 break;
609 }
610 case RTFS_TYPE_DEV_BLOCK:
611 {
612 stbuf->st_mode = S_IFBLK;
613 break;
614 }
615 case RTFS_TYPE_FILE:
616 {
617 stbuf->st_mode = S_IFREG;
618 break;
619 }
620 case RTFS_TYPE_SYMLINK:
621 {
622 stbuf->st_mode = S_IFLNK;
623 break;
624 }
625 case RTFS_TYPE_SOCKET:
626 {
627 stbuf->st_mode = S_IFSOCK;
628 break;
629 }
630#if 0 /* Not existing on Linux. */
631 case RTFS_TYPE_WHITEOUT:
632 {
633 stbuf->st_mode = S_IFWHT;
634 break;
635 }
636#endif
637 default:
638 stbuf->st_mode = 0;
639 }
640
641 if (ObjInfo.Attr.fMode & RTFS_UNIX_ISUID)
642 stbuf->st_mode |= S_ISUID;
643 if (ObjInfo.Attr.fMode & RTFS_UNIX_ISGID)
644 stbuf->st_mode |= S_ISGID;
645 if (ObjInfo.Attr.fMode & RTFS_UNIX_ISTXT)
646 stbuf->st_mode |= S_ISTXT;
647
648 /* Owner permissions. */
649 if (ObjInfo.Attr.fMode & RTFS_UNIX_IRUSR)
650 stbuf->st_mode |= S_IRUSR;
651 if (ObjInfo.Attr.fMode & RTFS_UNIX_IWUSR)
652 stbuf->st_mode |= S_IWUSR;
653 if (ObjInfo.Attr.fMode & RTFS_UNIX_IXUSR)
654 stbuf->st_mode |= S_IXUSR;
655
656 /* Group permissions. */
657 if (ObjInfo.Attr.fMode & RTFS_UNIX_IRGRP)
658 stbuf->st_mode |= S_IRGRP;
659 if (ObjInfo.Attr.fMode & RTFS_UNIX_IWGRP)
660 stbuf->st_mode |= S_IWGRP;
661 if (ObjInfo.Attr.fMode & RTFS_UNIX_IXGRP)
662 stbuf->st_mode |= S_IXGRP;
663
664 /* Other permissions. */
665 if (ObjInfo.Attr.fMode & RTFS_UNIX_IROTH)
666 stbuf->st_mode |= S_IROTH;
667 if (ObjInfo.Attr.fMode & RTFS_UNIX_IWOTH)
668 stbuf->st_mode |= S_IWOTH;
669 if (ObjInfo.Attr.fMode & RTFS_UNIX_IXOTH)
670 stbuf->st_mode |= S_IXOTH;
671
672 if (ObjInfo.Attr.enmAdditional == RTFSOBJATTRADD_UNIX)
673 {
674 stbuf->st_uid = ObjInfo.Attr.u.Unix.uid;
675 stbuf->st_gid = ObjInfo.Attr.u.Unix.gid;
676 stbuf->st_nlink = ObjInfo.Attr.u.Unix.cHardlinks;
677 stbuf->st_ino = ObjInfo.Attr.u.Unix.INodeId;
678 stbuf->st_dev = ObjInfo.Attr.u.Unix.INodeIdDevice;
679 /*stbuf->st_flags = ObjInfo.Attr.u.Unix.fFlags;*/ /* Not existing on Linux. */
680 /*stbuf->st_gen = ObjInfo.Attr.u.Unix.GenerationId;*/ /* Not existing on Linux. */
681 stbuf->st_rdev = ObjInfo.Attr.u.Unix.Device;
682 }
683 }
684
685 RTVfsObjRelease(hVfsObj);
686 }
687 else if (rcIprt == VERR_NOT_FOUND)
688 rc = -ENOENT;
689 else
690 rc = -RTErrConvertToErrno(rcIprt);
691 }
692
693 return rc;
694}
695
696/** @copydoc fuse_operations::readdir */
697static int
698vboximgOp_readdir(const char *pszPath, void *pvBuf, fuse_fill_dir_t pfnFiller,
699 off_t offset, struct fuse_file_info *pInfo)
700
701{
702 RT_NOREF(offset);
703 RT_NOREF(pInfo);
704
705 int rc = 0;
706
707 /* Special root directory handling?. */
708 if (!RTStrCmp(pszPath, "/"))
709 {
710 /*
711 * mandatory '.', '..', ...
712 */
713 pfnFiller(pvBuf, ".", NULL, 0);
714 pfnFiller(pvBuf, "..", NULL, 0);
715
716 /*
717 * Create FUSE FS dir entry that is depicted here (and exposed via stat()) as
718 * a symbolic link back to the resolved path to the VBox virtual disk image,
719 * whose symlink name is basename that path. This is a convenience so anyone
720 * listing the dir can figure out easily what the vhdd FUSE node entry
721 * represents.
722 */
723 pfnFiller(pvBuf, g_pszImageName, NULL, 0);
724
725 /*
726 * Create entry named "vhdd" denoting the whole disk, which getattr() will describe as a
727 * regular file, and thus will go through the open/release/read/write vectors
728 * to access the VirtualBox image as processed by the IRPT VD API.
729 */
730 pfnFiller(pvBuf, "vhdd", NULL, 0);
731
732 /* Create entries for the individual volumes. */
733 for (uint32_t i = 0; i < g_cVolumes; i++)
734 {
735 char tmp[64];
736 RTStrPrintf(tmp, sizeof (tmp), "vol%u", i);
737 pfnFiller(pvBuf, tmp, NULL, 0);
738
739 if (g_paVolumes[i].hVfsRoot != NIL_RTVFS)
740 {
741 RTStrPrintf(tmp, sizeof (tmp), "fs%u", i);
742 pfnFiller(pvBuf, tmp, NULL, 0);
743 }
744 }
745 }
746 else
747 {
748 /* Query the VFS object and fill in the data. */
749 RTVFSOBJ hVfsObj = NIL_RTVFSOBJ;
750 int rcIprt = vboxImgMntVfsObjQueryFromPath(pszPath, &hVfsObj);
751 if (RT_SUCCESS(rcIprt))
752 {
753 switch (RTVfsObjGetType(hVfsObj))
754 {
755 case RTVFSOBJTYPE_DIR:
756 {
757 RTVFSDIR hVfsDir = RTVfsObjToDir(hVfsObj);
758 RTDIRENTRYEX DirEntry;
759
760 rcIprt = RTVfsDirRewind(hVfsDir); AssertRC(rcIprt);
761 rcIprt = RTVfsDirReadEx(hVfsDir, &DirEntry, NULL, RTFSOBJATTRADD_NOTHING);
762 while (RT_SUCCESS(rcIprt))
763 {
764 pfnFiller(pvBuf, DirEntry.szName, NULL, 0);
765 rcIprt = RTVfsDirReadEx(hVfsDir, &DirEntry, NULL, RTFSOBJATTRADD_NOTHING);
766 }
767
768 RTVfsDirRelease(hVfsDir);
769 break;
770 }
771 default:
772 rc = -EINVAL;
773 }
774
775 RTVfsObjRelease(hVfsObj);
776 }
777 else
778 rc = -RTErrConvertToErrno(rcIprt);
779 }
780
781 return rc;
782}
783
784/** @copydoc fuse_operations::readlink */
785static int
786vboximgOp_readlink(const char *pszPath, char *buf, size_t size)
787{
788 NOREF(pszPath);
789 RTStrCopy(buf, size, g_pszImagePath);
790 return 0;
791}
792
793
794/**
795 * Displays the list of volumes on the opened image.
796 *
797 * @returns nothing.
798 */
799static void vboxImgMntVolumesDisplay(void)
800{
801 /*
802 * Partition table is most readable and concise when headers and columns
803 * are adapted to the actual data, to avoid insufficient or excessive whitespace.
804 */
805
806 RTPrintf( "Virtual disk image:\n\n");
807 RTPrintf(" Base: %s\n", g_pszBaseImagePath);
808 if (g_cImages > 1)
809 RTPrintf(" Diff: %s\n", g_pszImagePath);
810 if (g_pszDiskUuid)
811 RTPrintf(" UUID: %s\n\n", g_pszDiskUuid);
812
813 SELFSIZINGTABLE tbl(2);
814
815 void *colPartition = tbl.addCol("Partition", "%s(%d)", -1);
816 void *colBoot = tbl.addCol("Boot", "%c ", 1);
817 void *colStart = tbl.addCol("Start", "%lld", 1);
818 void *colSectors = tbl.addCol("Sectors", "%lld", -1, 2);
819 void *colSize = tbl.addCol("Size", "%s", 1);
820 void *colOffset = tbl.addCol("Offset", "%lld", 1);
821 void *colType = tbl.addCol("Type", "%s", -1, 2);
822
823 for (uint32_t i = 0; i < g_cVolumes; i++)
824 {
825 PVBOXIMGMOUNTVOL pVol = &g_paVolumes[i];
826 uint64_t fVolFlags = RTDvmVolumeGetFlags(pVol->hVol);
827 uint64_t cbVol = RTDvmVolumeGetSize(pVol->hVol);
828 RTDVMVOLTYPE enmType = RTDvmVolumeGetType(pVol->hVol);
829 uint64_t offStart = 0;
830 uint64_t offEnd = 0;
831
832 if (fVolFlags & DVMVOLUME_F_CONTIGUOUS)
833 {
834 int rc = RTDvmVolumeQueryRange(pVol->hVol, &offStart, &offEnd);
835 AssertRC(rc);
836 }
837
838 void *row = tbl.addRow();
839 tbl.setCell(row, colPartition, g_pszBaseImageName, i);
840 tbl.setCell(row, colBoot, (fVolFlags & DVMVOLUME_FLAGS_BOOTABLE) ? '*' : ' ');
841 tbl.setCell(row, colStart, offStart / g_cbSector);
842 tbl.setCell(row, colSectors, cbVol / g_cbSector);
843 tbl.setCell(row, colSize, vboximgScaledSize(cbVol));
844 tbl.setCell(row, colOffset, offStart);
845 tbl.setCell(row, colType, RTDvmVolumeTypeGetDescr(enmType));
846 }
847 tbl.displayTable();
848 RTPrintf ("\n");
849}
850
851
852/**
853 * Sets up the volumes for the disk.
854 *
855 * @returns IPRT status code.
856 */
857static int vboxImgMntVolumesSetup(void)
858{
859 g_cVolumes = 0;
860 g_paVolumes = NULL;
861
862 int rc = RTDvmCreate(&g_hDvmMgr, g_hVfsFileDisk, g_cbSector, 0 /*fFlags*/);
863 if (RT_SUCCESS(rc))
864 {
865 rc = RTDvmMapOpen(g_hDvmMgr);
866 if (RT_SUCCESS(rc))
867 {
868 g_cVolumes = RTDvmMapGetValidVolumes(g_hDvmMgr);
869 if ( g_cVolumes != UINT32_MAX
870 && g_cVolumes > 0)
871 {
872 g_paVolumes = (PVBOXIMGMOUNTVOL)RTMemAllocZ(g_cVolumes * sizeof(VBOXIMGMOUNTVOL));
873 if (RT_LIKELY(g_paVolumes))
874 {
875 g_paVolumes[0].hVfsRoot = NIL_RTVFS;
876
877 rc = RTDvmMapQueryFirstVolume(g_hDvmMgr, &g_paVolumes[0].hVol);
878 if (RT_SUCCESS(rc))
879 rc = RTDvmVolumeCreateVfsFile(g_paVolumes[0].hVol,
880 RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_READWRITE,
881 &g_paVolumes[0].hVfsFileVol);
882
883 for (uint32_t i = 1; i < g_cVolumes && RT_SUCCESS(rc); i++)
884 {
885 g_paVolumes[i].hVfsRoot = NIL_RTVFS;
886 rc = RTDvmMapQueryNextVolume(g_hDvmMgr, g_paVolumes[i-1].hVol, &g_paVolumes[i].hVol);
887 if (RT_SUCCESS(rc))
888 rc = RTDvmVolumeCreateVfsFile(g_paVolumes[i].hVol,
889 RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_READWRITE,
890 &g_paVolumes[i].hVfsFileVol);
891 }
892
893 if (RT_SUCCESS(rc))
894 return VINF_SUCCESS;
895
896 RTMemFree(g_paVolumes);
897 g_paVolumes = NULL;
898 g_cVolumes = 0;
899 }
900 else
901 rc = VERR_NO_MEMORY;
902 }
903 else if (g_cVolumes == UINT32_MAX)
904 {
905 g_cVolumes = 0;
906 rc = VERR_INTERNAL_ERROR;
907 }
908
909 RTDvmRelease(g_hDvmMgr);
910 }
911 else if (rc == VERR_NOT_FOUND)
912 rc = VINF_SUCCESS;
913 }
914
915 return rc;
916}
917
918int
919main(int argc, char **argv)
920{
921
922 int rc = RTR3InitExe(argc, &argv, 0);
923 if (RT_FAILURE(rc))
924 return RTMsgErrorExitFailure("RTR3InitExe failed, rc=%Rrc\n", rc);
925
926 rc = VDInit();
927 if (RT_FAILURE(rc))
928 return RTMsgErrorExitFailure("VDInit failed, rc=%Rrc\n", rc);
929
930 memset(&g_vboximgOps, 0, sizeof(g_vboximgOps));
931 g_vboximgOps.open = vboximgOp_open;
932 g_vboximgOps.read = vboximgOp_read;
933 g_vboximgOps.write = vboximgOp_write;
934 g_vboximgOps.getattr = vboximgOp_getattr;
935 g_vboximgOps.release = vboximgOp_release;
936 g_vboximgOps.readdir = vboximgOp_readdir;
937 g_vboximgOps.readlink = vboximgOp_readlink;
938
939 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
940 memset(&g_vboximgOpts, 0, sizeof(g_vboximgOpts));
941
942 rc = fuse_opt_parse(&args, &g_vboximgOpts, vboximgOptDefs, vboximgOptHandler);
943 if (rc < 0 || argc < 2 || RTStrCmp(argv[1], "-?" ) == 0 || g_vboximgOpts.fBriefUsage)
944 {
945 briefUsage();
946 return 0;
947 }
948
949 if (g_vboximgOpts.fAllowRoot)
950 fuse_opt_add_arg(&args, "-oallow_root");
951
952 /*
953 * FUSE doesn't seem to like combining options with one hyphen, as traditional UNIX
954 * command line utilities allow. The following flags, fWideList and fVerboseList,
955 * and their respective option definitions give the appearance of combined opts,
956 * so that -vl, -lv, -wl, -lw options are allowed, since those in particular would
957 * tend to conveniently facilitate some of the most common use cases.
958 */
959 if (g_vboximgOpts.fWideList)
960 {
961 g_vboximgOpts.fWide = true;
962 g_vboximgOpts.fList = true;
963 }
964 if (g_vboximgOpts.fVerboseList)
965 {
966 g_vboximgOpts.fVerbose = true;
967 g_vboximgOpts.fList = true;
968 }
969 if (g_vboximgOpts.fAllowRoot)
970 fuse_opt_add_arg(&args, "-oallow_root");
971
972 /*
973 * Initialize COM.
974 */
975 using namespace com;
976 HRESULT hrc = com::Initialize();
977 if (FAILED(hrc))
978 {
979# ifdef VBOX_WITH_XPCOM
980 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
981 {
982 char szHome[RTPATH_MAX] = "";
983 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
984 return RTMsgErrorExit(RTEXITCODE_FAILURE,
985 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
986 }
987# endif
988 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM! (hrc=%Rhrc)", hrc);
989 }
990
991 /*
992 * Get the remote VirtualBox object and create a local session object.
993 */
994 ComPtr<IVirtualBoxClient> pVirtualBoxClient;
995 ComPtr<IVirtualBox> pVirtualBox;
996
997 hrc = pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
998 if (SUCCEEDED(hrc))
999 hrc = pVirtualBoxClient->COMGETTER(VirtualBox)(pVirtualBox.asOutParam());
1000
1001 if (FAILED(hrc))
1002 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to get IVirtualBox object! (hrc=%Rhrc)", hrc);
1003
1004 if (g_vboximgOpts.fList && g_vboximgOpts.pszImageUuidOrPath == NULL)
1005 {
1006 vboximgListVMs(pVirtualBox);
1007 return VINF_SUCCESS;
1008 }
1009
1010 Bstr pMediumUuid;
1011 ComPtr<IMedium> pVDiskMedium = NULL;
1012 char *pszFormat;
1013 VDTYPE enmType;
1014
1015 /*
1016 * Open chain of images from what is provided on command line, to base image
1017 */
1018 if (g_vboximgOpts.pszImageUuidOrPath)
1019 {
1020 /* compiler was too fussy about access mode's data type in conditional expr, so... */
1021 if (g_vboximgOpts.fRW)
1022 CHECK_ERROR(pVirtualBox, OpenMedium(Bstr(g_vboximgOpts.pszImageUuidOrPath).raw(), DeviceType_HardDisk,
1023 AccessMode_ReadWrite, false /* forceNewUuid */, pVDiskMedium.asOutParam()));
1024
1025 else
1026 CHECK_ERROR(pVirtualBox, OpenMedium(Bstr(g_vboximgOpts.pszImageUuidOrPath).raw(), DeviceType_HardDisk,
1027 AccessMode_ReadOnly, false /* forceNewUuid */, pVDiskMedium.asOutParam()));
1028
1029 if (FAILED(rc))
1030 return RTMsgErrorExitFailure("\nCould't find specified VirtualBox base or snapshot disk image:\n%s",
1031 g_vboximgOpts.pszImageUuidOrPath);
1032
1033
1034 CHECK_ERROR(pVDiskMedium, COMGETTER(Id)(pMediumUuid.asOutParam()));
1035 g_pszDiskUuid = RTStrDup((char *)CSTR(pMediumUuid));
1036
1037 /*
1038 * Lock & cache the disk image media chain (from leaf to base).
1039 * Only leaf can be rw (and only if media is being mounted in non-default writable (rw) mode)
1040 *
1041 * Note: Failure to acquire lock is intentionally fatal (e.g. program termination)
1042 */
1043
1044 if (VERBOSE)
1045 RTPrintf("\nAttempting to lock medium chain from leaf image to base image\n");
1046
1047 bool fLeaf = true;
1048 g_cImages = 0;
1049
1050 do
1051 {
1052 ++g_cImages;
1053 IMAGELIST *pNewEntry= new IMAGELIST();
1054 pNewEntry->pImage = pVDiskMedium;
1055 CHECK_ERROR(pVDiskMedium, COMGETTER(Name)((pNewEntry->pImageName).asOutParam()));
1056 CHECK_ERROR(pVDiskMedium, COMGETTER(Location)((pNewEntry->pImagePath).asOutParam()));
1057
1058 if (VERBOSE)
1059 RTPrintf(" %s", CSTR(pNewEntry->pImageName));
1060
1061 if (fLeaf && g_vboximgOpts.fRW)
1062 {
1063 if (VERBOSE)
1064 RTPrintf(" ... Locking for write\n");
1065 CHECK_ERROR_RET(pVDiskMedium, LockWrite((pNewEntry->pLockToken).asOutParam()), rc);
1066 pNewEntry->fWriteable = true;
1067 }
1068 else
1069 {
1070 if (VERBOSE)
1071 RTPrintf(" ... Locking for read\n");
1072 CHECK_ERROR_RET(pVDiskMedium, LockRead((pNewEntry->pLockToken).asOutParam()), rc);
1073 }
1074
1075 IMAGELIST *pCurImageEntry = &listHeadLockList;
1076 while (pCurImageEntry->next)
1077 pCurImageEntry = pCurImageEntry->next;
1078 pCurImageEntry->next = pNewEntry;
1079 pNewEntry->prev = pCurImageEntry;
1080 listHeadLockList.prev = pNewEntry;
1081
1082 CHECK_ERROR(pVDiskMedium, COMGETTER(Parent)(pVDiskMedium.asOutParam()));
1083 fLeaf = false;
1084 }
1085 while(pVDiskMedium);
1086 }
1087
1088 ComPtr<IMedium> pVDiskBaseMedium = listHeadLockList.prev->pImage;
1089 Bstr pVDiskBaseImagePath = listHeadLockList.prev->pImagePath;
1090 Bstr pVDiskBaseImageName = listHeadLockList.prev->pImageName;
1091
1092 g_pszBaseImagePath = RTStrDup((char *)CSTR(pVDiskBaseImagePath));
1093 g_pszBaseImageName = RTStrDup((char *)CSTR(pVDiskBaseImageName));
1094
1095 g_pszImagePath = RTStrDup((char *)CSTR(listHeadLockList.next->pImagePath));
1096 g_pszImageName = RTStrDup((char *)CSTR(listHeadLockList.next->pImageName));
1097
1098 /*
1099 * Attempt to VDOpen media (base and any snapshots), handling encryption,
1100 * if that property is set for base media
1101 */
1102 Bstr pBase64EncodedKeyStore;
1103
1104 rc = pVDiskBaseMedium->GetProperty(Bstr("CRYPT/KeyStore").raw(), pBase64EncodedKeyStore.asOutParam());
1105 if (SUCCEEDED(rc) && strlen(CSTR(pBase64EncodedKeyStore)) != 0)
1106 {
1107 RTPrintf("\nvboximgMount: Encrypted disks not supported in this version\n\n");
1108 return -1;
1109 }
1110
1111
1112/* ***************** BEGIN IFDEF'D (STUBBED-OUT) CODE ************** */
1113/* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
1114
1115#if 0 /* The following encrypted disk related code is stubbed out until it can be finished.
1116 * What is here is an attempt to port the VBoxSVC specific code in i_openForIO to
1117 * a client's proximity. It is supplemented by code in vboximgCrypto.cpp and
1118 * vboximageCrypt.h that was lifed from SecretKeyStore.cpp along with the setup
1119 * task function.
1120 *
1121 * The ultimate solution may be to use a simpler but less efficient COM interface,
1122 * or to use VD encryption interfaces and key containers entirely. The keystore
1123 * handling/filter approach that is here may be a bumbling hybrid approach
1124 * that is broken (trying to bridge incompatible disk encryption mechanisms) or otherwise
1125 * doesn't make sense. */
1126
1127 Bstr pKeyId;
1128 ComPtr<IExtPackManager> pExtPackManager;
1129 ComPtr<IExtPack> pExtPack;
1130 com::SafeIfaceArray<IExtPackPlugIn> pExtPackPlugIns;
1131
1132 if (SUCCEEDED(rc))
1133 {
1134 RTPrintf("Got GetProperty(\"CRYPT/KeyStore\") = %s\n", CSTR(pBase64EncodedKeyStore));
1135 if (strlen(CSTR(pBase64EncodedKeyStore)) == 0)
1136 return RTMsgErrorExitFailure("Image '%s' is configured for encryption but "
1137 "there is no key store to retrieve the password from", CSTR(pVDiskBaseImageName));
1138
1139 SecretKeyStore keyStore(false);
1140 RTBase64Decode(CSTR(pBase64EncodedKeyStore), &keyStore, sizeof (SecretKeyStore), NULL, NULL);
1141
1142 rc = pVDiskBaseMedium->GetProperty(Bstr("CRYPT/KeyId").raw(), pKeyId.asOutParam());
1143 if (SUCCEEDED(rc) && strlen(CSTR(pKeyId)) == 0)
1144 return RTMsgErrorExitFailure("Image '%s' is configured for encryption but "
1145 "doesn't have a key identifier set", CSTR(pVDiskBaseImageName));
1146
1147 RTPrintf(" key id: %s\n", CSTR(pKeyId));
1148
1149#ifndef VBOX_WITH_EXTPACK
1150 return RTMsgErrorExitFailure(
1151 "Encryption is not supported because extension pack support is not built in");
1152#endif
1153
1154 CHECK_ERROR(pVirtualBox, COMGETTER(ExtensionPackManager)(pExtPackManager.asOutParam()));
1155 BOOL fExtPackUsable;
1156 CHECK_ERROR(pExtPackManager, IsExtPackUsable((PRUnichar *)VBOX_EXTPACK, &fExtPackUsable));
1157 if (fExtPackUsable)
1158 {
1159 /* Load the PlugIn */
1160
1161 CHECK_ERROR(pExtPackManager, Find((PRUnichar *)VBOX_EXTPACK, pExtPack.asOutParam()));
1162 if (RT_FAILURE(rc))
1163 return RTMsgErrorExitFailure(
1164 "Encryption is not supported because the extension pack '%s' is missing",
1165 VBOX_EXTPACK);
1166
1167 CHECK_ERROR(pExtPack, COMGETTER(PlugIns)(ComSafeArrayAsOutParam(pExtPackPlugIns)));
1168
1169 Bstr pPlugInPath;
1170 size_t iPlugIn;
1171 for (iPlugIn = 0; iPlugIn < pExtPackPlugIns.size(); iPlugIn++)
1172 {
1173 Bstr pPlugInName;
1174 CHECK_ERROR(pExtPackPlugIns[iPlugIn], COMGETTER(Name)(pPlugInName.asOutParam()));
1175 if (RTStrCmp(CSTR(pPlugInName), "VDPlugInCrypt") == 0)
1176 {
1177 CHECK_ERROR(pExtPackPlugIns[iPlugIn], COMGETTER(ModulePath)(pPlugInPath.asOutParam()));
1178 break;
1179 }
1180 }
1181 if (iPlugIn == pExtPackPlugIns.size())
1182 return RTMsgErrorExitFailure("Encryption is not supported because the extension pack '%s' "
1183 "is missing the encryption PlugIn (old extension pack installed?)", VBOX_EXTPACK);
1184
1185 rc = VDPluginLoadFromFilename(CSTR(pPlugInPath));
1186 if (RT_FAILURE(rc))
1187 return RTMsgErrorExitFailure("Retrieving encryption settings of the image failed "
1188 "because the encryption PlugIn could not be loaded\n");
1189 }
1190
1191 SecretKey *pKey = NULL;
1192 rc = keyStore.retainSecretKey(Utf8Str(pKeyId), &pKey);
1193 if (RT_FAILURE(rc))
1194 return RTMsgErrorExitFailure(
1195 "Failed to retrieve the secret key with ID \"%s\" from the store (%Rrc)",
1196 CSTR(pKeyId), rc);
1197
1198 VDISKCRYPTOSETTINGS vdiskCryptoSettings, *pVDiskCryptoSettings = &vdiskCryptoSettings;
1199
1200 vboxImageCryptoSetup(pVDiskCryptoSettings, NULL,
1201 (const char *)CSTR(pBase64EncodedKeyStore), (const char *)pKey->getKeyBuffer(), false);
1202
1203 rc = VDFilterAdd(g_pVDisk, "CRYPT", VD_FILTER_FLAGS_DEFAULT, pVDiskCryptoSettings->vdFilterIfaces);
1204 keyStore.releaseSecretKey(Utf8Str(pKeyId));
1205
1206 if (rc == VERR_VD_PASSWORD_INCORRECT)
1207 return RTMsgErrorExitFailure("The password to decrypt the image is incorrect");
1208
1209 if (RT_FAILURE(rc))
1210 return RTMsgErrorExitFailure("Failed to load the decryption filter: %Rrc", rc);
1211 }
1212#endif
1213
1214/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
1215/* **************** END IFDEF'D (STUBBED-OUT) CODE ***************** */
1216
1217 rc = RTCritSectInit(&g_vdioLock);
1218 if (RT_SUCCESS(rc))
1219 {
1220 g_VDIfThreadSync.pfnStartRead = vboximgThreadStartRead;
1221 g_VDIfThreadSync.pfnFinishRead = vboximgThreadFinishRead;
1222 g_VDIfThreadSync.pfnStartWrite = vboximgThreadStartWrite;
1223 g_VDIfThreadSync.pfnFinishWrite = vboximgThreadFinishWrite;
1224 rc = VDInterfaceAdd(&g_VDIfThreadSync.Core, "vboximg_ThreadSync", VDINTERFACETYPE_THREADSYNC,
1225 &g_vdioLock, sizeof(VDINTERFACETHREADSYNC), &g_pVdIfs);
1226 }
1227 else
1228 return RTMsgErrorExitFailure("ERROR: Failed to create critsects "
1229 "for virtual disk I/O, rc=%Rrc\n", rc);
1230
1231 /*
1232 * Create HDD container to open base image and differencing images into
1233 */
1234 rc = VDGetFormat(NULL /* pVDIIfsDisk */, NULL /* pVDIIfsImage*/,
1235 CSTR(pVDiskBaseImagePath), VDTYPE_INVALID, &pszFormat, &enmType);
1236
1237 if (RT_FAILURE(rc))
1238 return RTMsgErrorExitFailure("VDGetFormat(,,%s,,) "
1239 "failed (during HDD container creation), rc=%Rrc\n", g_pszImagePath, rc);
1240
1241 if (VERBOSE)
1242 RTPrintf("\nCreating container for base image of format %s\n", pszFormat);
1243
1244 PVDISK pVDisk = NULL;
1245 rc = VDCreate(g_pVdIfs, enmType, &pVDisk);
1246 if ((rc))
1247 return RTMsgErrorExitFailure("ERROR: Couldn't create virtual disk container\n");
1248
1249 /* Open all virtual disk media from leaf snapshot (if any) to base image*/
1250
1251 if (VERBOSE)
1252 RTPrintf("\nOpening medium chain\n");
1253
1254 IMAGELIST *pCurMedium = listHeadLockList.prev; /* point to base image */
1255 while (pCurMedium != &listHeadLockList)
1256 {
1257 if (VERBOSE)
1258 RTPrintf(" Open: %s\n", CSTR(pCurMedium->pImagePath));
1259
1260 rc = VDOpen(pVDisk,
1261 pszFormat,
1262 CSTR(pCurMedium->pImagePath),
1263 pCurMedium->fWriteable,
1264 g_pVdIfs);
1265
1266 if (RT_FAILURE(rc))
1267 return RTMsgErrorExitFailure("Could not open the medium storage unit '%s' %Rrc",
1268 CSTR(pCurMedium->pImagePath), rc);
1269
1270 pCurMedium = pCurMedium->prev;
1271 }
1272
1273 RTStrFree(pszFormat);
1274
1275 /* Create the VFS file to use for the disk image access. */
1276 rc = VDCreateVfsFileFromDisk(pVDisk, VD_VFSFILE_DESTROY_ON_RELEASE, &g_hVfsFileDisk);
1277 if (RT_FAILURE(rc))
1278 return RTMsgErrorExitFailure("Error creating VFS file wrapper for disk image\n");
1279
1280 g_cbSector = VDGetSectorSize(pVDisk, VD_LAST_IMAGE);
1281
1282 rc = vboxImgMntVolumesSetup();
1283 if (RT_FAILURE(rc))
1284 return RTMsgErrorExitFailure("Error parsing volumes on disk\n");
1285
1286 if (g_vboximgOpts.fList)
1287 {
1288 if (g_hVfsFileDisk == NIL_RTVFSFILE)
1289 return RTMsgErrorExitFailure("No valid --image to list partitions from\n");
1290
1291 RTPrintf("\n");
1292 vboxImgMntVolumesDisplay();
1293 return 0;
1294 }
1295
1296 /* Try to "mount" supported filesystems inside the disk image if specified. */
1297 if (g_vboximgOpts.fGstFs)
1298 {
1299 for (uint32_t i = 0; i < g_cVolumes; i++)
1300 {
1301 rc = RTVfsMountVol(g_paVolumes[i].hVfsFileVol,
1302 g_vboximgOpts.fRW ? 0 : RTVFSMNT_F_READ_ONLY,
1303 &g_paVolumes[i].hVfsRoot,
1304 NULL);
1305 if (RT_SUCCESS(rc))
1306 {
1307 rc = RTVfsOpenRoot(g_paVolumes[i].hVfsRoot, &g_paVolumes[i].hVfsDirRoot);
1308 if (RT_FAILURE(rc))
1309 {
1310 RTPrintf("\nvboximg-mount: Failed to access filesystem on volume %u, ignoring\n", i);
1311 RTVfsRelease(g_paVolumes[i].hVfsRoot);
1312 g_paVolumes[i].hVfsRoot = NIL_RTVFS;
1313 }
1314 }
1315 else
1316 RTPrintf("\nvboximg-mount: Failed to access filesystem on volume %u, ignoring\n", i);
1317 }
1318 }
1319
1320 /*
1321 * Hand control over to libfuse.
1322 */
1323 if (VERBOSE)
1324 RTPrintf("\nvboximg-mount: Going into background...\n");
1325
1326 rc = fuse_main(args.argc, args.argv, &g_vboximgOps, NULL);
1327
1328 int rc2 = RTVfsFileRelease(g_hVfsFileDisk);
1329 AssertRC(rc2);
1330 RTPrintf("vboximg-mount: fuse_main -> %d\n", rc);
1331 return rc;
1332}
1333
Note: See TracBrowser for help on using the repository browser.

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