VirtualBox

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

Last change on this file was 107506, checked in by vboxsync, 7 weeks ago

ImageMounter/vboximg-mount: Some parfait warning fixes, bugref:3409

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