VirtualBox

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

Last change on this file since 94701 was 94554, checked in by vboxsync, 3 years ago

ImageMounter/vboximg-mount: Fix broken write support (flags mixup), bugref:3641

  • Property svn:eol-style set to native
  • Property svn:keywords set to Author Date Id Revision
File size: 51.4 KB
Line 
1/* $Id: vboximg-mount.cpp 94554 2022-04-11 10:39:02Z vboxsync $ */
2/** @file
3 * vboximg-mount - Disk Image Flattening FUSE Program.
4 */
5
6/*
7 * Copyright (C) 2009-2022 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#ifdef UNIX_DERIVATIVE
32#include <errno.h>
33#include <fcntl.h>
34#include <stdlib.h>
35#include <libgen.h>
36#include <unistd.h>
37#include <math.h>
38#include <cstdarg>
39#include <sys/stat.h>
40#include <sys/time.h>
41#endif
42#if defined(RT_OS_DARWIN) || defined(RT_OS_FREEBSD) || defined(RT_OS_LINUX)
43# include <sys/param.h>
44# undef PVM /* Blasted old BSD mess still hanging around darwin. */
45#endif
46#ifdef RT_OS_LINUX
47# include <linux/fs.h>
48# include <linux/hdreg.h>
49#endif
50#include <VirtualBox_XPCOM.h>
51#include <VBox/com/VirtualBox.h>
52#include <VBox/vd.h>
53#include <VBox/vd-ifs.h>
54#include <VBox/log.h>
55#include <VBox/err.h>
56#include <VBox/com/ErrorInfo.h>
57#include <VBox/com/NativeEventQueue.h>
58#include <VBox/com/com.h>
59#include <VBox/com/string.h>
60#include <VBox/com/Guid.h>
61#include <VBox/com/array.h>
62#include <VBox/com/errorprint.h>
63#include <VBox/vd-plugin.h>
64#include <iprt/initterm.h>
65#include <iprt/assert.h>
66#include <iprt/message.h>
67#include <iprt/critsect.h>
68#include <iprt/asm.h>
69#include <iprt/mem.h>
70#include <iprt/string.h>
71#include <iprt/initterm.h>
72#include <iprt/stream.h>
73#include <iprt/types.h>
74#include <iprt/path.h>
75#include <iprt/utf16.h>
76#include <iprt/base64.h>
77#include <iprt/vfs.h>
78#include <iprt/dvm.h>
79#include <iprt/time.h>
80
81#include "fuse.h"
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 = NIL_RTVFSFILE; /** 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 = NULL; /** 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, 1),
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 && g_hVfsFileDisk != NIL_RTVFSFILE)
310 *phVfsObj = RTVfsObjFromFile(g_hVfsFileDisk);
311 else if (!RTStrNCmp(pPathSplit->apszComps[1], "vol", sizeof("vol") - 1))
312 {
313 /* Retrieve the accessed volume and return the stat data. */
314 uint32_t idxVol;
315 int rcIprt = RTStrToUInt32Full(&pPathSplit->apszComps[1][3], 10, &idxVol);
316 if ( rcIprt == VINF_SUCCESS
317 && idxVol < g_cVolumes
318 && g_paVolumes[idxVol].hVfsFileVol != NIL_RTVFSFILE)
319 *phVfsObj = RTVfsObjFromFile(g_paVolumes[idxVol].hVfsFileVol);
320 else
321 rc = VERR_NOT_FOUND;
322 }
323 else if (!RTStrNCmp(pPathSplit->apszComps[1], "fs", sizeof("fs") - 1))
324 {
325 /* Retrieve the accessed volume and return the stat data. */
326 uint32_t idxVol;
327 int rcIprt = RTStrToUInt32Full(&pPathSplit->apszComps[1][2], 10, &idxVol);
328 if ( rcIprt == VINF_SUCCESS
329 && idxVol < g_cVolumes
330 && g_paVolumes[idxVol].hVfsDirRoot != NIL_RTVFSDIR)
331 *phVfsObj = RTVfsObjFromDir(g_paVolumes[idxVol].hVfsDirRoot);
332 else
333 rc = VERR_NOT_FOUND;
334
335 /* Is an object inside the guest filesystem requested? */
336 if (pPathSplit->cComps > 2)
337 {
338 PRTPATHSPLIT pPathSplitVfs = (PRTPATHSPLIT)RTMemTmpAllocZ(RT_UOFFSETOF_DYN(RTPATHSPLIT, apszComps[pPathSplit->cComps - 1]));
339 if (RT_LIKELY(pPathSplitVfs))
340 {
341 pPathSplitVfs->cComps = pPathSplit->cComps - 1;
342 pPathSplitVfs->fProps = pPathSplit->fProps;
343 pPathSplitVfs->cchPath = pPathSplit->cchPath - strlen(pPathSplit->apszComps[1]) - 1;
344 pPathSplitVfs->cbNeeded = pPathSplit->cbNeeded;
345 pPathSplitVfs->pszSuffix = pPathSplit->pszSuffix;
346 pPathSplitVfs->apszComps[0] = pPathSplit->apszComps[0];
347 for (uint32_t i = 1; i < pPathSplitVfs->cComps; i++)
348 pPathSplitVfs->apszComps[i] = pPathSplit->apszComps[i + 1];
349
350 /* Reassemble the path. */
351 char *pszPathVfs = (char *)RTMemTmpAllocZ(pPathSplitVfs->cbNeeded);
352 if (RT_LIKELY(pszPathVfs))
353 {
354 rc = RTPathSplitReassemble(pPathSplitVfs, RTPATH_STR_F_STYLE_HOST, pszPathVfs, pPathSplitVfs->cbNeeded);
355 if (RT_SUCCESS(rc))
356 {
357 rc = RTVfsObjOpen(g_paVolumes[idxVol].hVfsRoot, pszPathVfs,
358 RTFILE_O_READWRITE | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
359 RTVFSOBJ_F_OPEN_ANY | RTVFSOBJ_F_CREATE_NOTHING | RTPATH_F_ON_LINK,
360 phVfsObj);
361 }
362 RTMemTmpFree(pszPathVfs);
363 }
364
365 RTMemTmpFree(pPathSplitVfs);
366 }
367 else
368 rc = VERR_NO_MEMORY;
369 }
370 }
371 else
372 rc = VERR_NOT_FOUND;
373
374 rc = VINF_SUCCESS;
375 }
376 else
377 rc = VERR_NOT_FOUND;
378 RTPathSplitFree(pPathSplit);
379 }
380
381 return rc;
382}
383
384
385/** @copydoc fuse_operations::open */
386static int vboximgOp_open(const char *pszPath, struct fuse_file_info *pInfo)
387{
388 LogFlowFunc(("pszPath=%s\n", pszPath));
389 int rc = 0;
390
391 RTVFSOBJ hVfsObj;
392 int rcIprt = vboxImgMntVfsObjQueryFromPath(pszPath, &hVfsObj);
393 if (RT_SUCCESS(rc))
394 {
395 uint32_t fNotSup = 0;
396
397#ifdef UNIX_DERIVATIVE
398# ifdef RT_OS_DARWIN
399 fNotSup = O_APPEND | O_NONBLOCK | O_SYMLINK | O_NOCTTY | O_SHLOCK | O_EXLOCK |
400 O_ASYNC | O_CREAT | O_TRUNC | O_EXCL | O_EVTONLY;
401# elif defined(RT_OS_LINUX)
402 fNotSup = O_APPEND | O_ASYNC | O_DIRECT | O_NOATIME | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
403 /* | O_LARGEFILE | O_SYNC | ? */
404# elif defined(RT_OS_FREEBSD)
405 fNotSup = O_APPEND | O_ASYNC | O_DIRECT | O_NOCTTY | O_NOFOLLOW | O_NONBLOCK;
406 /* | O_LARGEFILE | O_SYNC | ? */
407# endif
408#else
409# error "Port me"
410#endif
411
412 if (!(pInfo->flags & fNotSup))
413 {
414#ifdef UNIX_DERIVATIVE
415 if ((pInfo->flags & O_ACCMODE) == O_ACCMODE)
416 rc = -EINVAL;
417# ifdef O_DIRECTORY
418 if (pInfo->flags & O_DIRECTORY)
419 rc = -ENOTDIR;
420# endif
421#endif
422
423 if (!rc)
424 {
425 pInfo->fh = (uintptr_t)hVfsObj;
426 return 0;
427 }
428 }
429 else
430 rc = -EINVAL;
431
432 RTVfsObjRelease(hVfsObj);
433 }
434 else
435 rc = -RTErrConvertToErrno(rcIprt);
436
437 LogFlowFunc(("rc=%d \"%s\"\n", rc, pszPath));
438 return rc;
439
440}
441
442/** @copydoc fuse_operations::release */
443static int vboximgOp_release(const char *pszPath, struct fuse_file_info *pInfo)
444{
445 NOREF(pszPath);
446
447 LogFlowFunc(("pszPath=%s\n", pszPath));
448
449 RTVFSOBJ hVfsObj = (RTVFSOBJ)(uintptr_t)pInfo->fh;
450 RTVfsObjRelease(hVfsObj);
451
452 LogFlowFunc(("\"%s\"\n", pszPath));
453 return 0;
454}
455
456
457/** @copydoc fuse_operations::read */
458static int vboximgOp_read(const char *pszPath, char *pbBuf, size_t cbBuf,
459 off_t offset, struct fuse_file_info *pInfo)
460{
461 NOREF(pszPath);
462
463 LogFlowFunc(("offset=%#llx size=%#zx path=\"%s\"\n", (uint64_t)offset, cbBuf, pszPath));
464
465 AssertReturn(offset >= 0, -EINVAL);
466 AssertReturn((int)cbBuf >= 0, -EINVAL);
467 AssertReturn((unsigned)cbBuf == cbBuf, -EINVAL);
468
469 int rc = 0;
470 RTVFSOBJ hVfsObj = (RTVFSOBJ)(uintptr_t)pInfo->fh;
471 switch (RTVfsObjGetType(hVfsObj))
472 {
473 case RTVFSOBJTYPE_FILE:
474 {
475 size_t cbRead = 0;
476 RTVFSFILE hVfsFile = RTVfsObjToFile(hVfsObj);
477 int rcIprt = RTVfsFileReadAt(hVfsFile, offset, pbBuf, cbBuf, &cbRead);
478 if (cbRead)
479 rc = cbRead;
480 else if (rcIprt == VINF_EOF)
481 rc = -RTErrConvertToErrno(VERR_EOF);
482 RTVfsFileRelease(hVfsFile);
483 break;
484 }
485 default:
486 rc = -EINVAL;
487 }
488
489 if (rc < 0)
490 LogFlowFunc(("%s\n", strerror(rc)));
491 return rc;
492}
493
494/** @copydoc fuse_operations::write */
495static int vboximgOp_write(const char *pszPath, const char *pbBuf, size_t cbBuf,
496 off_t offset, struct fuse_file_info *pInfo)
497{
498 NOREF(pszPath);
499 NOREF(pInfo);
500
501 LogFlowFunc(("offset=%#llx size=%#zx path=\"%s\"\n", (uint64_t)offset, cbBuf, pszPath));
502
503 AssertReturn(offset >= 0, -EINVAL);
504 AssertReturn((int)cbBuf >= 0, -EINVAL);
505 AssertReturn((unsigned)cbBuf == cbBuf, -EINVAL);
506
507 if (!g_vboximgOpts.fRW)
508 {
509 LogFlowFunc(("WARNING: vboximg-mount (FUSE FS) --rw option not specified\n"
510 " (write operation ignored w/o error!)\n"));
511 return cbBuf;
512 }
513
514 int rc = 0;
515 RTVFSOBJ hVfsObj = (RTVFSOBJ)(uintptr_t)pInfo->fh;
516 switch (RTVfsObjGetType(hVfsObj))
517 {
518 case RTVFSOBJTYPE_FILE:
519 {
520 size_t cbWritten = 0;
521 RTVFSFILE hVfsFile = RTVfsObjToFile(hVfsObj);
522 int rcIprt = RTVfsFileWriteAt(hVfsFile, offset, pbBuf, cbBuf, &cbWritten);
523 if (cbWritten)
524 rc = cbWritten;
525 else if (rcIprt == VINF_EOF)
526 rc = -RTErrConvertToErrno(VERR_EOF);
527 RTVfsFileRelease(hVfsFile);
528 break;
529 }
530 default:
531 rc = -EINVAL;
532 }
533
534 if (rc < 0)
535 LogFlowFunc(("%s\n", strerror(rc)));
536
537 return rc;
538}
539
540/** @copydoc fuse_operations::getattr */
541static int
542vboximgOp_getattr(const char *pszPath, struct stat *stbuf)
543{
544 int rc = 0;
545
546 LogFlowFunc(("pszPath=%s, stat(\"%s\")\n", pszPath, g_pszImagePath));
547
548 memset(stbuf, 0, sizeof(struct stat));
549
550 if (RTStrCmp(pszPath, "/") == 0)
551 {
552 stbuf->st_mode = S_IFDIR | 0755;
553 stbuf->st_nlink = 2;
554 }
555 else if ( g_pszImageName
556 && RTStrNCmp(pszPath + 1, g_pszImageName, strlen(g_pszImageName)) == 0)
557 {
558 /* When the disk is partitioned, the symbolic link named from `basename` of
559 * resolved path to VBox disk image, has appended to it formatted text
560 * representing the offset range of the partition.
561 *
562 * $ vboximg-mount -i /stroll/along/the/path/simple_fixed_disk.vdi -p 1 /mnt/tmpdir
563 * $ ls /mnt/tmpdir
564 * simple_fixed_disk.vdi[20480:2013244928] vhdd
565 */
566 rc = stat(g_pszImagePath, stbuf);
567 if (rc < 0)
568 return rc;
569 stbuf->st_size = 0;
570 stbuf->st_mode = S_IFLNK | 0444;
571 stbuf->st_nlink = 1;
572 stbuf->st_uid = 0;
573 stbuf->st_gid = 0;
574 }
575 else
576 {
577 /* Query the VFS object and fill in the data. */
578 RTVFSOBJ hVfsObj = NIL_RTVFSOBJ;
579 int rcIprt = vboxImgMntVfsObjQueryFromPath(pszPath, &hVfsObj);
580 if (RT_SUCCESS(rcIprt))
581 {
582 RTFSOBJINFO ObjInfo;
583
584 rcIprt = RTVfsObjQueryInfo(hVfsObj, &ObjInfo, RTFSOBJATTRADD_UNIX);
585 if (RT_SUCCESS(rcIprt))
586 {
587 stbuf->st_size = ObjInfo.cbObject;
588 stbuf->st_nlink = 1;
589 stbuf->st_uid = 0;
590 stbuf->st_gid = 0;
591
592#ifdef RT_OS_DARWIN
593 RTTimeSpecGetTimespec(&ObjInfo.AccessTime, &stbuf->st_atimespec);
594 RTTimeSpecGetTimespec(&ObjInfo.ModificationTime, &stbuf->st_mtimespec);
595 RTTimeSpecGetTimespec(&ObjInfo.ChangeTime, &stbuf->st_ctimespec);
596 RTTimeSpecGetTimespec(&ObjInfo.BirthTime, &stbuf->st_birthtimespec);
597#else
598 RTTimeSpecGetTimespec(&ObjInfo.AccessTime, &stbuf->st_atim);
599 RTTimeSpecGetTimespec(&ObjInfo.ModificationTime, &stbuf->st_mtim);
600 RTTimeSpecGetTimespec(&ObjInfo.ChangeTime, &stbuf->st_ctim);
601#endif
602
603 switch (ObjInfo.Attr.fMode & RTFS_TYPE_MASK)
604 {
605 case RTFS_TYPE_FIFO:
606 {
607 stbuf->st_mode = S_IFIFO;
608 break;
609 }
610 case RTFS_TYPE_DEV_CHAR:
611 {
612 stbuf->st_mode = S_IFCHR;
613 break;
614 }
615 case RTFS_TYPE_DIRECTORY:
616 {
617 stbuf->st_mode = S_IFDIR;
618 stbuf->st_nlink = 2;
619 break;
620 }
621 case RTFS_TYPE_DEV_BLOCK:
622 {
623 stbuf->st_mode = S_IFBLK;
624 break;
625 }
626 case RTFS_TYPE_FILE:
627 {
628 stbuf->st_mode = S_IFREG;
629 break;
630 }
631 case RTFS_TYPE_SYMLINK:
632 {
633 stbuf->st_mode = S_IFLNK;
634 break;
635 }
636 case RTFS_TYPE_SOCKET:
637 {
638 stbuf->st_mode = S_IFSOCK;
639 break;
640 }
641#if 0 /* Not existing on Linux. */
642 case RTFS_TYPE_WHITEOUT:
643 {
644 stbuf->st_mode = S_IFWHT;
645 break;
646 }
647#endif
648 default:
649 stbuf->st_mode = 0;
650 }
651
652 if (ObjInfo.Attr.fMode & RTFS_UNIX_ISUID)
653 stbuf->st_mode |= S_ISUID;
654 if (ObjInfo.Attr.fMode & RTFS_UNIX_ISGID)
655 stbuf->st_mode |= S_ISGID;
656 if (ObjInfo.Attr.fMode & RTFS_UNIX_ISTXT)
657 stbuf->st_mode |= S_ISTXT;
658
659 /* Owner permissions. */
660 if (ObjInfo.Attr.fMode & RTFS_UNIX_IRUSR)
661 stbuf->st_mode |= S_IRUSR;
662 if (ObjInfo.Attr.fMode & RTFS_UNIX_IWUSR)
663 stbuf->st_mode |= S_IWUSR;
664 if (ObjInfo.Attr.fMode & RTFS_UNIX_IXUSR)
665 stbuf->st_mode |= S_IXUSR;
666
667 /* Group permissions. */
668 if (ObjInfo.Attr.fMode & RTFS_UNIX_IRGRP)
669 stbuf->st_mode |= S_IRGRP;
670 if (ObjInfo.Attr.fMode & RTFS_UNIX_IWGRP)
671 stbuf->st_mode |= S_IWGRP;
672 if (ObjInfo.Attr.fMode & RTFS_UNIX_IXGRP)
673 stbuf->st_mode |= S_IXGRP;
674
675 /* Other permissions. */
676 if (ObjInfo.Attr.fMode & RTFS_UNIX_IROTH)
677 stbuf->st_mode |= S_IROTH;
678 if (ObjInfo.Attr.fMode & RTFS_UNIX_IWOTH)
679 stbuf->st_mode |= S_IWOTH;
680 if (ObjInfo.Attr.fMode & RTFS_UNIX_IXOTH)
681 stbuf->st_mode |= S_IXOTH;
682
683 if (ObjInfo.Attr.enmAdditional == RTFSOBJATTRADD_UNIX)
684 {
685 stbuf->st_uid = ObjInfo.Attr.u.Unix.uid;
686 stbuf->st_gid = ObjInfo.Attr.u.Unix.gid;
687 stbuf->st_nlink = ObjInfo.Attr.u.Unix.cHardlinks;
688 stbuf->st_ino = ObjInfo.Attr.u.Unix.INodeId;
689 stbuf->st_dev = ObjInfo.Attr.u.Unix.INodeIdDevice;
690 /*stbuf->st_flags = ObjInfo.Attr.u.Unix.fFlags;*/ /* Not existing on Linux. */
691 /*stbuf->st_gen = ObjInfo.Attr.u.Unix.GenerationId;*/ /* Not existing on Linux. */
692 stbuf->st_rdev = ObjInfo.Attr.u.Unix.Device;
693 }
694 }
695
696 RTVfsObjRelease(hVfsObj);
697 }
698 else if (rcIprt == VERR_NOT_FOUND)
699 rc = -ENOENT;
700 else
701 rc = -RTErrConvertToErrno(rcIprt);
702 }
703
704 return rc;
705}
706
707/** @copydoc fuse_operations::readdir */
708static int
709vboximgOp_readdir(const char *pszPath, void *pvBuf, fuse_fill_dir_t pfnFiller,
710 off_t offset, struct fuse_file_info *pInfo)
711
712{
713 RT_NOREF(offset);
714 RT_NOREF(pInfo);
715
716 int rc = 0;
717
718 /* Special root directory handling?. */
719 if (!RTStrCmp(pszPath, "/"))
720 {
721 /*
722 * mandatory '.', '..', ...
723 */
724 pfnFiller(pvBuf, ".", NULL, 0);
725 pfnFiller(pvBuf, "..", NULL, 0);
726
727 if (g_pszImageName)
728 {
729 /*
730 * Create FUSE FS dir entry that is depicted here (and exposed via stat()) as
731 * a symbolic link back to the resolved path to the VBox virtual disk image,
732 * whose symlink name is basename that path. This is a convenience so anyone
733 * listing the dir can figure out easily what the vhdd FUSE node entry
734 * represents.
735 */
736 pfnFiller(pvBuf, g_pszImageName, NULL, 0);
737 }
738
739 if (g_hVfsFileDisk != NIL_RTVFSFILE)
740 {
741 /*
742 * Create entry named "vhdd" denoting the whole disk, which getattr() will describe as a
743 * regular file, and thus will go through the open/release/read/write vectors
744 * to access the VirtualBox image as processed by the IRPT VD API.
745 */
746 pfnFiller(pvBuf, "vhdd", NULL, 0);
747 }
748
749 /* Create entries for the individual volumes. */
750 for (uint32_t i = 0; i < g_cVolumes; i++)
751 {
752 char tmp[64];
753 if (g_paVolumes[i].hVfsFileVol != NIL_RTVFSFILE)
754 {
755 RTStrPrintf(tmp, sizeof (tmp), "vol%u", i);
756 pfnFiller(pvBuf, tmp, NULL, 0);
757 }
758
759 if (g_paVolumes[i].hVfsRoot != NIL_RTVFS)
760 {
761 RTStrPrintf(tmp, sizeof (tmp), "fs%u", i);
762 pfnFiller(pvBuf, tmp, NULL, 0);
763 }
764 }
765 }
766 else
767 {
768 /* Query the VFS object and fill in the data. */
769 RTVFSOBJ hVfsObj = NIL_RTVFSOBJ;
770 int rcIprt = vboxImgMntVfsObjQueryFromPath(pszPath, &hVfsObj);
771 if (RT_SUCCESS(rcIprt))
772 {
773 switch (RTVfsObjGetType(hVfsObj))
774 {
775 case RTVFSOBJTYPE_DIR:
776 {
777 RTVFSDIR hVfsDir = RTVfsObjToDir(hVfsObj);
778 RTDIRENTRYEX DirEntry;
779
780 rcIprt = RTVfsDirRewind(hVfsDir); AssertRC(rcIprt);
781 rcIprt = RTVfsDirReadEx(hVfsDir, &DirEntry, NULL, RTFSOBJATTRADD_NOTHING);
782 while (RT_SUCCESS(rcIprt))
783 {
784 pfnFiller(pvBuf, DirEntry.szName, NULL, 0);
785 rcIprt = RTVfsDirReadEx(hVfsDir, &DirEntry, NULL, RTFSOBJATTRADD_NOTHING);
786 }
787
788 RTVfsDirRelease(hVfsDir);
789 break;
790 }
791 default:
792 rc = -EINVAL;
793 }
794
795 RTVfsObjRelease(hVfsObj);
796 }
797 else
798 rc = -RTErrConvertToErrno(rcIprt);
799 }
800
801 return rc;
802}
803
804/** @copydoc fuse_operations::readlink */
805static int
806vboximgOp_readlink(const char *pszPath, char *buf, size_t size)
807{
808 NOREF(pszPath);
809 RTStrCopy(buf, size, g_pszImagePath);
810 return 0;
811}
812
813
814/**
815 * Displays the list of volumes on the opened image.
816 *
817 * @returns nothing.
818 */
819static void vboxImgMntVolumesDisplay(void)
820{
821 /*
822 * Partition table is most readable and concise when headers and columns
823 * are adapted to the actual data, to avoid insufficient or excessive whitespace.
824 */
825
826 RTPrintf( "Virtual disk image:\n\n");
827 RTPrintf(" Base: %s\n", g_pszBaseImagePath);
828 if (g_cImages > 1)
829 RTPrintf(" Diff: %s\n", g_pszImagePath);
830 if (g_pszDiskUuid)
831 RTPrintf(" UUID: %s\n\n", g_pszDiskUuid);
832
833 SELFSIZINGTABLE tbl(2);
834
835 void *colPartition = tbl.addCol("Partition", "%s(%d)", -1);
836 void *colBoot = tbl.addCol("Boot", "%c ", 1);
837 void *colStart = tbl.addCol("Start", "%lld", 1);
838 void *colSectors = tbl.addCol("Sectors", "%lld", -1, 2);
839 void *colSize = tbl.addCol("Size", "%s", 1);
840 void *colOffset = tbl.addCol("Offset", "%lld", 1);
841 void *colType = tbl.addCol("Type", "%s", -1, 2);
842
843 for (uint32_t i = 0; i < g_cVolumes; i++)
844 {
845 PVBOXIMGMOUNTVOL pVol = &g_paVolumes[i];
846 uint64_t fVolFlags = RTDvmVolumeGetFlags(pVol->hVol);
847 uint64_t cbVol = RTDvmVolumeGetSize(pVol->hVol);
848 RTDVMVOLTYPE enmType = RTDvmVolumeGetType(pVol->hVol);
849 uint64_t offStart = 0;
850 uint64_t offEnd = 0;
851
852 if (fVolFlags & DVMVOLUME_F_CONTIGUOUS)
853 {
854 int rc = RTDvmVolumeQueryRange(pVol->hVol, &offStart, &offEnd);
855 AssertRC(rc);
856 }
857
858 void *row = tbl.addRow();
859 tbl.setCell(row, colPartition, g_pszBaseImageName, i);
860 tbl.setCell(row, colBoot, (fVolFlags & DVMVOLUME_FLAGS_BOOTABLE) ? '*' : ' ');
861 tbl.setCell(row, colStart, offStart / g_cbSector);
862 tbl.setCell(row, colSectors, cbVol / g_cbSector);
863 tbl.setCell(row, colSize, vboximgScaledSize(cbVol));
864 tbl.setCell(row, colOffset, offStart);
865 tbl.setCell(row, colType, RTDvmVolumeTypeGetDescr(enmType));
866 }
867 tbl.displayTable();
868 RTPrintf ("\n");
869}
870
871
872/**
873 * Sets up the volumes for the disk.
874 *
875 * @returns IPRT status code.
876 */
877static int vboxImgMntVolumesSetup(void)
878{
879 g_cVolumes = 0;
880 g_paVolumes = NULL;
881
882 int rc = RTDvmCreate(&g_hDvmMgr, g_hVfsFileDisk, g_cbSector, 0 /*fFlags*/);
883 if (RT_SUCCESS(rc))
884 {
885 rc = RTDvmMapOpen(g_hDvmMgr);
886 if (RT_SUCCESS(rc))
887 {
888 g_cVolumes = RTDvmMapGetValidVolumes(g_hDvmMgr);
889 if ( g_cVolumes != UINT32_MAX
890 && g_cVolumes > 0)
891 {
892 g_paVolumes = (PVBOXIMGMOUNTVOL)RTMemAllocZ(g_cVolumes * sizeof(VBOXIMGMOUNTVOL));
893 if (RT_LIKELY(g_paVolumes))
894 {
895 g_paVolumes[0].hVfsRoot = NIL_RTVFS;
896
897 rc = RTDvmMapQueryFirstVolume(g_hDvmMgr, &g_paVolumes[0].hVol);
898 if (RT_SUCCESS(rc))
899 rc = RTDvmVolumeCreateVfsFile(g_paVolumes[0].hVol,
900 RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_READWRITE,
901 &g_paVolumes[0].hVfsFileVol);
902
903 for (uint32_t i = 1; i < g_cVolumes && RT_SUCCESS(rc); i++)
904 {
905 g_paVolumes[i].hVfsRoot = NIL_RTVFS;
906 rc = RTDvmMapQueryNextVolume(g_hDvmMgr, g_paVolumes[i-1].hVol, &g_paVolumes[i].hVol);
907 if (RT_SUCCESS(rc))
908 rc = RTDvmVolumeCreateVfsFile(g_paVolumes[i].hVol,
909 RTFILE_O_OPEN | RTFILE_O_DENY_NONE | RTFILE_O_READWRITE,
910 &g_paVolumes[i].hVfsFileVol);
911 }
912
913 if (RT_SUCCESS(rc))
914 return VINF_SUCCESS;
915
916 RTMemFree(g_paVolumes);
917 g_paVolumes = NULL;
918 g_cVolumes = 0;
919 }
920 else
921 rc = VERR_NO_MEMORY;
922 }
923 else if (g_cVolumes == UINT32_MAX)
924 {
925 g_cVolumes = 0;
926 rc = VERR_INTERNAL_ERROR;
927 }
928
929 RTDvmRelease(g_hDvmMgr);
930 }
931 else if (rc == VERR_NOT_FOUND)
932 rc = VINF_SUCCESS;
933 }
934
935 return rc;
936}
937
938
939static int vboxImgMntImageSetup(struct fuse_args *args)
940{
941 /*
942 * Initialize COM.
943 */
944 using namespace com;
945 HRESULT hrc = com::Initialize();
946 if (FAILED(hrc))
947 {
948# ifdef VBOX_WITH_XPCOM
949 if (hrc == NS_ERROR_FILE_ACCESS_DENIED)
950 {
951 char szHome[RTPATH_MAX] = "";
952 com::GetVBoxUserHomeDirectory(szHome, sizeof(szHome));
953 return RTMsgErrorExit(RTEXITCODE_FAILURE,
954 "Failed to initialize COM because the global settings directory '%s' is not accessible!", szHome);
955 }
956# endif
957 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to initialize COM! (hrc=%Rhrc)", hrc);
958 }
959
960 /*
961 * Get the remote VirtualBox object and create a local session object.
962 */
963 ComPtr<IVirtualBoxClient> pVirtualBoxClient;
964 ComPtr<IVirtualBox> pVirtualBox;
965
966 hrc = pVirtualBoxClient.createInprocObject(CLSID_VirtualBoxClient);
967 if (SUCCEEDED(hrc))
968 hrc = pVirtualBoxClient->COMGETTER(VirtualBox)(pVirtualBox.asOutParam());
969
970 if (FAILED(hrc))
971 return RTMsgErrorExit(RTEXITCODE_FAILURE, "Failed to get IVirtualBox object! (hrc=%Rhrc)", hrc);
972
973 if (g_vboximgOpts.fList && g_vboximgOpts.pszImageUuidOrPath == NULL)
974 {
975 vboximgListVMs(pVirtualBox);
976 return VINF_SUCCESS;
977 }
978
979 if (!g_vboximgOpts.pszImageUuidOrPath)
980 return RTMsgErrorExitFailure("A image UUID or path needs to be provided using the --image/-i option\n");
981
982 Bstr pMediumUuid;
983 ComPtr<IMedium> pVDiskMedium = NULL;
984 char *pszFormat;
985 VDTYPE enmType;
986
987 /*
988 * Open chain of images from what is provided on command line, to base image
989 */
990 if (g_vboximgOpts.pszImageUuidOrPath)
991 {
992 HRESULT rc;
993
994 /* compiler was too fussy about access mode's data type in conditional expr, so... */
995 if (g_vboximgOpts.fRW)
996 CHECK_ERROR(pVirtualBox, OpenMedium(Bstr(g_vboximgOpts.pszImageUuidOrPath).raw(), DeviceType_HardDisk,
997 AccessMode_ReadWrite, false /* forceNewUuid */, pVDiskMedium.asOutParam()));
998
999 else
1000 CHECK_ERROR(pVirtualBox, OpenMedium(Bstr(g_vboximgOpts.pszImageUuidOrPath).raw(), DeviceType_HardDisk,
1001 AccessMode_ReadOnly, false /* forceNewUuid */, pVDiskMedium.asOutParam()));
1002
1003 if (FAILED(hrc))
1004 return RTMsgErrorExitFailure("\nCould't find specified VirtualBox base or snapshot disk image:\n%s",
1005 g_vboximgOpts.pszImageUuidOrPath);
1006
1007
1008 CHECK_ERROR(pVDiskMedium, COMGETTER(Id)(pMediumUuid.asOutParam()));
1009 g_pszDiskUuid = RTStrDup((char *)CSTR(pMediumUuid));
1010
1011 /*
1012 * Lock & cache the disk image media chain (from leaf to base).
1013 * Only leaf can be rw (and only if media is being mounted in non-default writable (rw) mode)
1014 *
1015 * Note: Failure to acquire lock is intentionally fatal (e.g. program termination)
1016 */
1017
1018 if (VERBOSE)
1019 RTPrintf("\nAttempting to lock medium chain from leaf image to base image\n");
1020
1021 bool fLeaf = true;
1022 g_cImages = 0;
1023
1024 do
1025 {
1026 ++g_cImages;
1027 IMAGELIST *pNewEntry= new IMAGELIST();
1028 pNewEntry->pImage = pVDiskMedium;
1029 CHECK_ERROR(pVDiskMedium, COMGETTER(Name)((pNewEntry->pImageName).asOutParam()));
1030 CHECK_ERROR(pVDiskMedium, COMGETTER(Location)((pNewEntry->pImagePath).asOutParam()));
1031
1032 if (VERBOSE)
1033 RTPrintf(" %s", CSTR(pNewEntry->pImageName));
1034
1035 if (fLeaf && g_vboximgOpts.fRW)
1036 {
1037 if (VERBOSE)
1038 RTPrintf(" ... Locking for write\n");
1039 CHECK_ERROR_RET(pVDiskMedium, LockWrite((pNewEntry->pLockToken).asOutParam()), rc);
1040 pNewEntry->fWriteable = true;
1041 }
1042 else
1043 {
1044 if (VERBOSE)
1045 RTPrintf(" ... Locking for read\n");
1046 CHECK_ERROR_RET(pVDiskMedium, LockRead((pNewEntry->pLockToken).asOutParam()), rc);
1047 }
1048
1049 IMAGELIST *pCurImageEntry = &listHeadLockList;
1050 while (pCurImageEntry->next)
1051 pCurImageEntry = pCurImageEntry->next;
1052 pCurImageEntry->next = pNewEntry;
1053 pNewEntry->prev = pCurImageEntry;
1054 listHeadLockList.prev = pNewEntry;
1055
1056 CHECK_ERROR(pVDiskMedium, COMGETTER(Parent)(pVDiskMedium.asOutParam()));
1057 fLeaf = false;
1058 }
1059 while(pVDiskMedium);
1060 }
1061
1062 ComPtr<IMedium> pVDiskBaseMedium = listHeadLockList.prev->pImage;
1063 Bstr pVDiskBaseImagePath = listHeadLockList.prev->pImagePath;
1064 Bstr pVDiskBaseImageName = listHeadLockList.prev->pImageName;
1065
1066 g_pszBaseImagePath = RTStrDup((char *)CSTR(pVDiskBaseImagePath));
1067 g_pszBaseImageName = RTStrDup((char *)CSTR(pVDiskBaseImageName));
1068
1069 g_pszImagePath = RTStrDup((char *)CSTR(listHeadLockList.next->pImagePath));
1070 g_pszImageName = RTStrDup((char *)CSTR(listHeadLockList.next->pImageName));
1071
1072 /*
1073 * Attempt to VDOpen media (base and any snapshots), handling encryption,
1074 * if that property is set for base media
1075 */
1076 Bstr pBase64EncodedKeyStore;
1077
1078 hrc = pVDiskBaseMedium->GetProperty(Bstr("CRYPT/KeyStore").raw(), pBase64EncodedKeyStore.asOutParam());
1079 if (SUCCEEDED(hrc) && strlen(CSTR(pBase64EncodedKeyStore)) != 0)
1080 {
1081 RTPrintf("\nvboximgMount: Encrypted disks not supported in this version\n\n");
1082 return -1;
1083 }
1084
1085
1086/* ***************** BEGIN IFDEF'D (STUBBED-OUT) CODE ************** */
1087/* vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv */
1088
1089#if 0 /* The following encrypted disk related code is stubbed out until it can be finished.
1090 * What is here is an attempt to port the VBoxSVC specific code in i_openForIO to
1091 * a client's proximity. It is supplemented by code in vboximgCrypto.cpp and
1092 * vboximageCrypt.h that was lifed from SecretKeyStore.cpp along with the setup
1093 * task function.
1094 *
1095 * The ultimate solution may be to use a simpler but less efficient COM interface,
1096 * or to use VD encryption interfaces and key containers entirely. The keystore
1097 * handling/filter approach that is here may be a bumbling hybrid approach
1098 * that is broken (trying to bridge incompatible disk encryption mechanisms) or otherwise
1099 * doesn't make sense. */
1100
1101 Bstr pKeyId;
1102 ComPtr<IExtPackManager> pExtPackManager;
1103 ComPtr<IExtPack> pExtPack;
1104 com::SafeIfaceArray<IExtPackPlugIn> pExtPackPlugIns;
1105
1106 if (SUCCEEDED(rc))
1107 {
1108 RTPrintf("Got GetProperty(\"CRYPT/KeyStore\") = %s\n", CSTR(pBase64EncodedKeyStore));
1109 if (strlen(CSTR(pBase64EncodedKeyStore)) == 0)
1110 return RTMsgErrorExitFailure("Image '%s' is configured for encryption but "
1111 "there is no key store to retrieve the password from", CSTR(pVDiskBaseImageName));
1112
1113 SecretKeyStore keyStore(false);
1114 RTBase64Decode(CSTR(pBase64EncodedKeyStore), &keyStore, sizeof (SecretKeyStore), NULL, NULL);
1115
1116 rc = pVDiskBaseMedium->GetProperty(Bstr("CRYPT/KeyId").raw(), pKeyId.asOutParam());
1117 if (SUCCEEDED(rc) && strlen(CSTR(pKeyId)) == 0)
1118 return RTMsgErrorExitFailure("Image '%s' is configured for encryption but "
1119 "doesn't have a key identifier set", CSTR(pVDiskBaseImageName));
1120
1121 RTPrintf(" key id: %s\n", CSTR(pKeyId));
1122
1123#ifndef VBOX_WITH_EXTPACK
1124 return RTMsgErrorExitFailure(
1125 "Encryption is not supported because extension pack support is not built in");
1126#endif
1127
1128 CHECK_ERROR(pVirtualBox, COMGETTER(ExtensionPackManager)(pExtPackManager.asOutParam()));
1129 BOOL fExtPackUsable;
1130 CHECK_ERROR(pExtPackManager, IsExtPackUsable((PRUnichar *)VBOX_EXTPACK, &fExtPackUsable));
1131 if (fExtPackUsable)
1132 {
1133 /* Load the PlugIn */
1134
1135 CHECK_ERROR(pExtPackManager, Find((PRUnichar *)VBOX_EXTPACK, pExtPack.asOutParam()));
1136 if (RT_FAILURE(rc))
1137 return RTMsgErrorExitFailure(
1138 "Encryption is not supported because the extension pack '%s' is missing",
1139 VBOX_EXTPACK);
1140
1141 CHECK_ERROR(pExtPack, COMGETTER(PlugIns)(ComSafeArrayAsOutParam(pExtPackPlugIns)));
1142
1143 Bstr pPlugInPath;
1144 size_t iPlugIn;
1145 for (iPlugIn = 0; iPlugIn < pExtPackPlugIns.size(); iPlugIn++)
1146 {
1147 Bstr pPlugInName;
1148 CHECK_ERROR(pExtPackPlugIns[iPlugIn], COMGETTER(Name)(pPlugInName.asOutParam()));
1149 if (RTStrCmp(CSTR(pPlugInName), "VDPlugInCrypt") == 0)
1150 {
1151 CHECK_ERROR(pExtPackPlugIns[iPlugIn], COMGETTER(ModulePath)(pPlugInPath.asOutParam()));
1152 break;
1153 }
1154 }
1155 if (iPlugIn == pExtPackPlugIns.size())
1156 return RTMsgErrorExitFailure("Encryption is not supported because the extension pack '%s' "
1157 "is missing the encryption PlugIn (old extension pack installed?)", VBOX_EXTPACK);
1158
1159 rc = VDPluginLoadFromFilename(CSTR(pPlugInPath));
1160 if (RT_FAILURE(rc))
1161 return RTMsgErrorExitFailure("Retrieving encryption settings of the image failed "
1162 "because the encryption PlugIn could not be loaded\n");
1163 }
1164
1165 SecretKey *pKey = NULL;
1166 rc = keyStore.retainSecretKey(Utf8Str(pKeyId), &pKey);
1167 if (RT_FAILURE(rc))
1168 return RTMsgErrorExitFailure(
1169 "Failed to retrieve the secret key with ID \"%s\" from the store (%Rrc)",
1170 CSTR(pKeyId), rc);
1171
1172 VDISKCRYPTOSETTINGS vdiskCryptoSettings, *pVDiskCryptoSettings = &vdiskCryptoSettings;
1173
1174 vboxImageCryptoSetup(pVDiskCryptoSettings, NULL,
1175 (const char *)CSTR(pBase64EncodedKeyStore), (const char *)pKey->getKeyBuffer(), false);
1176
1177 rc = VDFilterAdd(g_pVDisk, "CRYPT", VD_FILTER_FLAGS_DEFAULT, pVDiskCryptoSettings->vdFilterIfaces);
1178 keyStore.releaseSecretKey(Utf8Str(pKeyId));
1179
1180 if (rc == VERR_VD_PASSWORD_INCORRECT)
1181 return RTMsgErrorExitFailure("The password to decrypt the image is incorrect");
1182
1183 if (RT_FAILURE(rc))
1184 return RTMsgErrorExitFailure("Failed to load the decryption filter: %Rrc", rc);
1185 }
1186#endif
1187
1188/* ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ */
1189/* **************** END IFDEF'D (STUBBED-OUT) CODE ***************** */
1190
1191 int rc = RTCritSectInit(&g_vdioLock);
1192 if (RT_SUCCESS(rc))
1193 {
1194 g_VDIfThreadSync.pfnStartRead = vboximgThreadStartRead;
1195 g_VDIfThreadSync.pfnFinishRead = vboximgThreadFinishRead;
1196 g_VDIfThreadSync.pfnStartWrite = vboximgThreadStartWrite;
1197 g_VDIfThreadSync.pfnFinishWrite = vboximgThreadFinishWrite;
1198 rc = VDInterfaceAdd(&g_VDIfThreadSync.Core, "vboximg_ThreadSync", VDINTERFACETYPE_THREADSYNC,
1199 &g_vdioLock, sizeof(VDINTERFACETHREADSYNC), &g_pVdIfs);
1200 }
1201 else
1202 return RTMsgErrorExitFailure("ERROR: Failed to create critsects "
1203 "for virtual disk I/O, rc=%Rrc\n", rc);
1204
1205 /*
1206 * Create HDD container to open base image and differencing images into
1207 */
1208 rc = VDGetFormat(NULL /* pVDIIfsDisk */, NULL /* pVDIIfsImage*/,
1209 CSTR(pVDiskBaseImagePath), VDTYPE_INVALID, &pszFormat, &enmType);
1210
1211 if (RT_FAILURE(rc))
1212 return RTMsgErrorExitFailure("VDGetFormat(,,%s,,) "
1213 "failed (during HDD container creation), rc=%Rrc\n", g_pszImagePath, rc);
1214
1215 if (VERBOSE)
1216 RTPrintf("\nCreating container for base image of format %s\n", pszFormat);
1217
1218 PVDISK pVDisk = NULL;
1219 rc = VDCreate(g_pVdIfs, enmType, &pVDisk);
1220 if ((rc))
1221 return RTMsgErrorExitFailure("ERROR: Couldn't create virtual disk container\n");
1222
1223 /* Open all virtual disk media from leaf snapshot (if any) to base image*/
1224
1225 if (VERBOSE)
1226 RTPrintf("\nOpening medium chain\n");
1227
1228 IMAGELIST *pCurMedium = listHeadLockList.prev; /* point to base image */
1229 while (pCurMedium != &listHeadLockList)
1230 {
1231 if (VERBOSE)
1232 RTPrintf(" Open: %s\n", CSTR(pCurMedium->pImagePath));
1233
1234 rc = VDOpen(pVDisk,
1235 pszFormat,
1236 CSTR(pCurMedium->pImagePath),
1237 pCurMedium->fWriteable ? 0 : VD_OPEN_FLAGS_READONLY,
1238 g_pVdIfs);
1239
1240 if (RT_FAILURE(rc))
1241 return RTMsgErrorExitFailure("Could not open the medium storage unit '%s' %Rrc",
1242 CSTR(pCurMedium->pImagePath), rc);
1243
1244 pCurMedium = pCurMedium->prev;
1245 }
1246
1247 RTStrFree(pszFormat);
1248
1249 /* Create the VFS file to use for the disk image access. */
1250 rc = VDCreateVfsFileFromDisk(pVDisk, VD_VFSFILE_DESTROY_ON_RELEASE, &g_hVfsFileDisk);
1251 if (RT_FAILURE(rc))
1252 return RTMsgErrorExitFailure("Error creating VFS file wrapper for disk image\n");
1253
1254 g_cbSector = VDGetSectorSize(pVDisk, VD_LAST_IMAGE);
1255
1256 rc = vboxImgMntVolumesSetup();
1257 if (RT_FAILURE(rc))
1258 return RTMsgErrorExitFailure("Error parsing volumes on disk\n");
1259
1260 if (g_vboximgOpts.fList)
1261 {
1262 if (g_hVfsFileDisk == NIL_RTVFSFILE)
1263 return RTMsgErrorExitFailure("No valid --image to list partitions from\n");
1264
1265 RTPrintf("\n");
1266 vboxImgMntVolumesDisplay();
1267 return 0;
1268 }
1269
1270 /* Try to "mount" supported filesystems inside the disk image if specified. */
1271 if (g_vboximgOpts.fGstFs)
1272 {
1273 for (uint32_t i = 0; i < g_cVolumes; i++)
1274 {
1275 rc = RTVfsMountVol(g_paVolumes[i].hVfsFileVol,
1276 g_vboximgOpts.fRW ? 0 : RTVFSMNT_F_READ_ONLY,
1277 &g_paVolumes[i].hVfsRoot,
1278 NULL);
1279 if (RT_SUCCESS(rc))
1280 {
1281 rc = RTVfsOpenRoot(g_paVolumes[i].hVfsRoot, &g_paVolumes[i].hVfsDirRoot);
1282 if (RT_FAILURE(rc))
1283 {
1284 RTPrintf("\nvboximg-mount: Failed to access filesystem on volume %u, ignoring\n", i);
1285 RTVfsRelease(g_paVolumes[i].hVfsRoot);
1286 g_paVolumes[i].hVfsRoot = NIL_RTVFS;
1287 }
1288 }
1289 else
1290 RTPrintf("\nvboximg-mount: Failed to access filesystem on volume %u, ignoring\n", i);
1291 }
1292 }
1293
1294 /*
1295 * Hand control over to libfuse.
1296 */
1297 if (VERBOSE)
1298 RTPrintf("\nvboximg-mount: Going into background...\n");
1299
1300 rc = fuse_main_real(args->argc, args->argv, &g_vboximgOps, sizeof(g_vboximgOps), NULL);
1301
1302 int rc2 = RTVfsFileRelease(g_hVfsFileDisk);
1303 AssertRC(rc2);
1304 RTPrintf("vboximg-mount: fuse_main -> %d\n", rc);
1305 return rc;
1306}
1307
1308
1309int main(int argc, char **argv)
1310{
1311
1312 int rc = RTR3InitExe(argc, &argv, 0);
1313 if (RT_FAILURE(rc))
1314 return RTMsgErrorExitFailure("RTR3InitExe failed, rc=%Rrc\n", rc);
1315
1316 rc = VDInit();
1317 if (RT_FAILURE(rc))
1318 return RTMsgErrorExitFailure("VDInit failed, rc=%Rrc\n", rc);
1319
1320 rc = RTFuseLoadLib();
1321 if (RT_FAILURE(rc))
1322 return RTMsgErrorExitFailure("Failed to load the fuse library, rc=%Rrc\n", rc);
1323
1324 memset(&g_vboximgOps, 0, sizeof(g_vboximgOps));
1325 g_vboximgOps.open = vboximgOp_open;
1326 g_vboximgOps.read = vboximgOp_read;
1327 g_vboximgOps.write = vboximgOp_write;
1328 g_vboximgOps.getattr = vboximgOp_getattr;
1329 g_vboximgOps.release = vboximgOp_release;
1330 g_vboximgOps.readdir = vboximgOp_readdir;
1331 g_vboximgOps.readlink = vboximgOp_readlink;
1332
1333 struct fuse_args args = FUSE_ARGS_INIT(argc, argv);
1334 memset(&g_vboximgOpts, 0, sizeof(g_vboximgOpts));
1335
1336 rc = fuse_opt_parse(&args, &g_vboximgOpts, vboximgOptDefs, vboximgOptHandler);
1337 if (rc < 0 || argc < 2 || RTStrCmp(argv[1], "-?" ) == 0 || g_vboximgOpts.fBriefUsage)
1338 {
1339 briefUsage();
1340 return 0;
1341 }
1342
1343 if (g_vboximgOpts.fAllowRoot)
1344 fuse_opt_add_arg(&args, "-oallow_root");
1345
1346 /*
1347 * FUSE doesn't seem to like combining options with one hyphen, as traditional UNIX
1348 * command line utilities allow. The following flags, fWideList and fVerboseList,
1349 * and their respective option definitions give the appearance of combined opts,
1350 * so that -vl, -lv, -wl, -lw options are allowed, since those in particular would
1351 * tend to conveniently facilitate some of the most common use cases.
1352 */
1353 if (g_vboximgOpts.fWideList)
1354 {
1355 g_vboximgOpts.fWide = true;
1356 g_vboximgOpts.fList = true;
1357 }
1358 if (g_vboximgOpts.fVerboseList)
1359 {
1360 g_vboximgOpts.fVerbose = true;
1361 g_vboximgOpts.fList = true;
1362 }
1363 if (g_vboximgOpts.fAllowRoot)
1364 fuse_opt_add_arg(&args, "-oallow_root");
1365
1366 if ( !g_vboximgOpts.pszImageUuidOrPath
1367 || !RTVfsChainIsSpec(g_vboximgOpts.pszImageUuidOrPath))
1368 return vboxImgMntImageSetup(&args);
1369
1370 /* Mount the VFS chain. */
1371 RTVFSOBJ hVfsObj;
1372 rc = RTVfsChainOpenObj(g_vboximgOpts.pszImageUuidOrPath, RTFILE_O_READWRITE | RTFILE_O_DENY_NONE | RTFILE_O_OPEN,
1373 RTVFSOBJ_F_OPEN_ANY | RTVFSOBJ_F_CREATE_NOTHING | RTPATH_F_ON_LINK,
1374 &hVfsObj, NULL, NULL);
1375 if ( RT_SUCCESS(rc)
1376 && RTVfsObjGetType(hVfsObj) == RTVFSOBJTYPE_VFS)
1377 {
1378 g_paVolumes = (PVBOXIMGMOUNTVOL)RTMemAllocZ(sizeof(*g_paVolumes));
1379 if (RT_LIKELY(g_paVolumes))
1380 {
1381 g_cVolumes = 1;
1382 g_paVolumes[0].hVfsRoot = RTVfsObjToVfs(hVfsObj);
1383 g_paVolumes[0].hVfsFileVol = NIL_RTVFSFILE;
1384 RTVfsObjRelease(hVfsObj);
1385
1386 rc = RTVfsOpenRoot(g_paVolumes[0].hVfsRoot, &g_paVolumes[0].hVfsDirRoot);
1387 if (RT_SUCCESS(rc))
1388 {
1389 /*
1390 * Hand control over to libfuse.
1391 */
1392 if (VERBOSE)
1393 RTPrintf("\nvboximg-mount: Going into background...\n");
1394
1395 rc = fuse_main_real(args.argc, args.argv, &g_vboximgOps, sizeof(g_vboximgOps), NULL);
1396 RTVfsDirRelease(g_paVolumes[0].hVfsDirRoot);
1397 RTVfsRelease(g_paVolumes[0].hVfsRoot);
1398 }
1399
1400 RTMemFree(g_paVolumes);
1401 g_paVolumes = NULL;
1402 g_cVolumes = 0;
1403 }
1404 else
1405 rc = VERR_NO_MEMORY;
1406
1407 RTVfsObjRelease(hVfsObj);
1408 }
1409
1410 return rc;
1411}
1412
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