1 /*
2 * storage_source.c: file utility functions for FS storage backend
3 *
4 * Copyright (C) 2007-2017 Red Hat, Inc.
5 * Copyright (C) 2007-2008 Daniel P. Berrange
6 *
7 * This library is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * This library is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this library. If not, see
19 * <http://www.gnu.org/licenses/>.
20 */
21
22 #include <config.h>
23
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include "internal.h"
28 #include "storage_file_backend.h"
29 #include "storage_file_probe.h"
30 #include "storage_source.h"
31 #include "storage_source_backingstore.h"
32 #include "viralloc.h"
33 #include "virerror.h"
34 #include "virfile.h"
35 #include "virhash.h"
36 #include "virlog.h"
37 #include "virobject.h"
38 #include "virstoragefile.h"
39 #include "virstring.h"
40 #include "virutil.h"
41
42 #define VIR_FROM_THIS VIR_FROM_STORAGE
43
44 VIR_LOG_INIT("storage_source");
45
46
47 static bool
virStorageSourceBackinStoreStringIsFile(const char * backing)48 virStorageSourceBackinStoreStringIsFile(const char *backing)
49 {
50 char *colon;
51 char *slash;
52
53 if (!backing)
54 return false;
55
56 colon = strchr(backing, ':');
57 slash = strchr(backing, '/');
58
59 /* Reject anything that looks like a protocol (such as nbd: or
60 * rbd:); if someone really does want a relative file name that
61 * includes ':', they can always prefix './'. */
62 if (colon && (!slash || colon < slash))
63 return false;
64 return true;
65 }
66
67
68 static bool
virStorageSourceBackinStoreStringIsRelative(const char * backing)69 virStorageSourceBackinStoreStringIsRelative(const char *backing)
70 {
71 if (g_path_is_absolute(backing))
72 return false;
73
74 if (!virStorageSourceBackinStoreStringIsFile(backing))
75 return false;
76
77 return true;
78 }
79
80
81 static virStorageSource *
virStorageSourceMetadataNew(const char * path,int format)82 virStorageSourceMetadataNew(const char *path,
83 int format)
84 {
85 g_autoptr(virStorageSource) def = virStorageSourceNew();
86
87 def->format = format;
88 def->type = VIR_STORAGE_TYPE_FILE;
89
90 def->path = g_strdup(path);
91
92 return g_steal_pointer(&def);
93 }
94
95
96 /**
97 * virStorageSourceGetMetadataFromBuf:
98 * @path: name of file, for error messages
99 * @buf: header bytes from @path
100 * @len: length of @buf
101 * @format: format of the storage file
102 *
103 * Extract metadata about the storage volume with the specified image format.
104 * If image format is VIR_STORAGE_FILE_AUTO, it will probe to automatically
105 * identify the format. Does not recurse.
106 *
107 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a format on a file
108 * that might be raw if that file will then be passed to a guest, since a
109 * malicious guest can turn a raw file into any other non-raw format at will.
110 *
111 * If the 'backingStoreRawFormat' field of the returned structure is
112 * VIR_STORAGE_FILE_AUTO it indicates the image didn't specify an explicit
113 * format for its backing store. Callers are advised against probing for the
114 * backing store format in this case.
115 *
116 * Caller MUST free the result after use via virObjectUnref.
117 */
118 virStorageSource *
virStorageSourceGetMetadataFromBuf(const char * path,char * buf,size_t len,int format)119 virStorageSourceGetMetadataFromBuf(const char *path,
120 char *buf,
121 size_t len,
122 int format)
123 {
124 virStorageSource *ret = NULL;
125
126 if (!(ret = virStorageSourceMetadataNew(path, format)))
127 return NULL;
128
129 if (virStorageFileProbeGetMetadata(ret, buf, len) < 0) {
130 virObjectUnref(ret);
131 return NULL;
132 }
133
134 return ret;
135 }
136
137
138 /**
139 * virStorageSourceGetMetadataFromFD:
140 *
141 * Extract metadata about the storage volume with the specified
142 * image format. If image format is VIR_STORAGE_FILE_AUTO, it
143 * will probe to automatically identify the format. Does not recurse.
144 *
145 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a
146 * format, since a malicious guest can turn a raw file into any
147 * other non-raw format at will.
148 *
149 * Caller MUST free the result after use via virObjectUnref.
150 */
151 virStorageSource *
virStorageSourceGetMetadataFromFD(const char * path,int fd,int format)152 virStorageSourceGetMetadataFromFD(const char *path,
153 int fd,
154 int format)
155
156 {
157 ssize_t len = VIR_STORAGE_MAX_HEADER;
158 struct stat sb;
159 g_autofree char *buf = NULL;
160 g_autoptr(virStorageSource) meta = NULL;
161
162 if (fstat(fd, &sb) < 0) {
163 virReportSystemError(errno,
164 _("cannot stat file '%s'"), path);
165 return NULL;
166 }
167
168 if (!(meta = virStorageSourceMetadataNew(path, format)))
169 return NULL;
170
171 if (S_ISDIR(sb.st_mode)) {
172 /* No header to probe for directories, but also no backing file. Just
173 * update the metadata.*/
174 meta->type = VIR_STORAGE_TYPE_DIR;
175 meta->format = VIR_STORAGE_FILE_DIR;
176 return g_steal_pointer(&meta);
177 }
178
179 if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
180 virReportSystemError(errno, _("cannot seek to start of '%s'"), meta->path);
181 return NULL;
182 }
183
184 if ((len = virFileReadHeaderFD(fd, len, &buf)) < 0) {
185 virReportSystemError(errno, _("cannot read header '%s'"), meta->path);
186 return NULL;
187 }
188
189 if (virStorageFileProbeGetMetadata(meta, buf, len) < 0)
190 return NULL;
191
192 if (S_ISREG(sb.st_mode))
193 meta->type = VIR_STORAGE_TYPE_FILE;
194 else if (S_ISBLK(sb.st_mode))
195 meta->type = VIR_STORAGE_TYPE_BLOCK;
196
197 return g_steal_pointer(&meta);
198 }
199
200
201 /**
202 * virStorageSourceChainLookup:
203 * @chain: chain top to look in
204 * @startFrom: move the starting point of @chain if non-NULL
205 * @name: name of the file to look for in @chain
206 * @diskTarget: optional disk target to validate against
207 * @parent: Filled with parent virStorageSource of the returned value if non-NULL.
208 *
209 * Looks up a storage source definition corresponding to @name in @chain and
210 * returns the corresponding virStorageSource. If @startFrom is non-NULL, the
211 * lookup starts from that virStorageSource.
212 *
213 * @name can be:
214 * - NULL: the end of the source chain is returned
215 * - "vda[4]": Storage source with 'id' == 4 is returned. If @diskTarget is
216 * non-NULL it's also validated that the part before the square
217 * bracket matches the requested target
218 * - "/path/to/file": Literal path is matched. Symlink resolution is attempted
219 * if the filename doesn't string-match with the path.
220 */
221 virStorageSource *
virStorageSourceChainLookup(virStorageSource * chain,virStorageSource * startFrom,const char * name,const char * diskTarget,virStorageSource ** parent)222 virStorageSourceChainLookup(virStorageSource *chain,
223 virStorageSource *startFrom,
224 const char *name,
225 const char *diskTarget,
226 virStorageSource **parent)
227 {
228 virStorageSource *prev;
229 const char *start = chain->path;
230 bool nameIsFile = virStorageSourceBackinStoreStringIsFile(name);
231 g_autofree char *target = NULL;
232 unsigned int idx = 0;
233
234 if (diskTarget)
235 start = diskTarget;
236
237 if (!parent)
238 parent = &prev;
239 *parent = NULL;
240
241 /* parse the "vda[4]" type string */
242 if (name &&
243 virStorageFileParseBackingStoreStr(name, &target, &idx) == 0) {
244 if (diskTarget &&
245 idx != 0 &&
246 STRNEQ(diskTarget, target)) {
247 virReportError(VIR_ERR_INVALID_ARG,
248 _("requested target '%s' does not match target '%s'"),
249 target, diskTarget);
250 return NULL;
251 }
252 }
253
254 if (startFrom) {
255 while (virStorageSourceIsBacking(chain) &&
256 chain != startFrom->backingStore)
257 chain = chain->backingStore;
258
259 *parent = startFrom;
260 }
261
262 while (virStorageSourceIsBacking(chain)) {
263 if (!name && !idx) {
264 if (!virStorageSourceHasBacking(chain))
265 break;
266 } else if (idx) {
267 VIR_DEBUG("%u: %s", chain->id, chain->path);
268 if (idx == chain->id)
269 break;
270 } else {
271 if (STREQ_NULLABLE(name, chain->relPath) ||
272 STREQ_NULLABLE(name, chain->path))
273 break;
274
275 if (nameIsFile && virStorageSourceIsLocalStorage(chain)) {
276 g_autofree char *parentDir = NULL;
277 int result;
278
279 if (*parent && virStorageSourceIsLocalStorage(*parent))
280 parentDir = g_path_get_dirname((*parent)->path);
281 else
282 parentDir = g_strdup(".");
283
284 result = virFileRelLinkPointsTo(parentDir, name,
285 chain->path);
286
287 if (result < 0)
288 goto error;
289
290 if (result > 0)
291 break;
292 }
293 }
294 *parent = chain;
295 chain = chain->backingStore;
296 }
297
298 if (!virStorageSourceIsBacking(chain))
299 goto error;
300
301 return chain;
302
303 error:
304 if (idx) {
305 virReportError(VIR_ERR_INVALID_ARG,
306 _("could not find backing store index '%u' in chain for '%s'"),
307 idx, NULLSTR(start));
308 } else if (name) {
309 if (startFrom)
310 virReportError(VIR_ERR_INVALID_ARG,
311 _("could not find image '%s' beneath '%s' in chain for '%s'"),
312 name, NULLSTR(startFrom->path), NULLSTR(start));
313 else
314 virReportError(VIR_ERR_INVALID_ARG,
315 _("could not find image '%s' in chain for '%s'"),
316 name, NULLSTR(start));
317 } else {
318 virReportError(VIR_ERR_INVALID_ARG,
319 _("could not find base image in chain for '%s'"),
320 NULLSTR(start));
321 }
322 *parent = NULL;
323 return NULL;
324 }
325
326
327 static virStorageSource *
virStorageSourceNewFromBackingRelative(virStorageSource * parent,const char * rel)328 virStorageSourceNewFromBackingRelative(virStorageSource *parent,
329 const char *rel)
330 {
331 g_autofree char *dirname = NULL;
332 g_autoptr(virStorageSource) def = virStorageSourceNew();
333
334 /* store relative name */
335 def->relPath = g_strdup(rel);
336
337 dirname = g_path_get_dirname(parent->path);
338
339 if (STRNEQ(dirname, "/")) {
340 def->path = g_strdup_printf("%s/%s", dirname, rel);
341 } else {
342 def->path = g_strdup_printf("/%s", rel);
343 }
344
345 if (virStorageSourceGetActualType(parent) == VIR_STORAGE_TYPE_NETWORK) {
346 def->type = VIR_STORAGE_TYPE_NETWORK;
347
348 /* copy the host network part */
349 def->protocol = parent->protocol;
350 if (parent->nhosts) {
351 if (!(def->hosts = virStorageNetHostDefCopy(parent->nhosts,
352 parent->hosts)))
353 return NULL;
354
355 def->nhosts = parent->nhosts;
356 }
357
358 def->volume = g_strdup(parent->volume);
359 } else {
360 /* set the type to _FILE, the caller shall update it to the actual type */
361 def->type = VIR_STORAGE_TYPE_FILE;
362 }
363
364 return g_steal_pointer(&def);
365 }
366
367
368 /**
369 * virStorageSourceNewFromBackingAbsolute
370 * @path: string representing absolute location of a storage source
371 * @src: filled with virStorageSource object representing @path
372 *
373 * Returns 0 on success, 1 if we could parse all location data but @path
374 * specified other data unrepresentable by libvirt (e.g. inline authentication).
375 * In both cases @src is filled. On error -1 is returned @src is NULL and an
376 * error is reported.
377 */
378 int
virStorageSourceNewFromBackingAbsolute(const char * path,virStorageSource ** src)379 virStorageSourceNewFromBackingAbsolute(const char *path,
380 virStorageSource **src)
381 {
382 const char *json;
383 const char *dirpath;
384 int rc = 0;
385 g_autoptr(virStorageSource) def = virStorageSourceNew();
386
387 *src = NULL;
388
389 if (virStorageSourceBackinStoreStringIsFile(path)) {
390 def->type = VIR_STORAGE_TYPE_FILE;
391
392 def->path = g_strdup(path);
393 } else {
394 if ((dirpath = STRSKIP(path, "fat:"))) {
395 def->type = VIR_STORAGE_TYPE_DIR;
396 def->format = VIR_STORAGE_FILE_FAT;
397 def->path = g_strdup(dirpath);
398 *src = g_steal_pointer(&def);
399 return 0;
400 }
401
402 def->type = VIR_STORAGE_TYPE_NETWORK;
403
404 VIR_DEBUG("parsing backing store string: '%s'", path);
405
406 /* handle URI formatted backing stores */
407 if ((json = STRSKIP(path, "json:")))
408 rc = virStorageSourceParseBackingJSON(def, json);
409 else if (strstr(path, "://"))
410 rc = virStorageSourceParseBackingURI(def, path);
411 else
412 rc = virStorageSourceParseBackingColon(def, path);
413
414 if (rc < 0)
415 return -1;
416
417 virStorageSourceNetworkAssignDefaultPorts(def);
418
419 /* Some of the legacy parsers parse authentication data since they are
420 * also used in other places. For backing store detection the
421 * authentication data would be invalid anyways, so we clear it */
422 if (def->auth) {
423 virStorageAuthDefFree(def->auth);
424 def->auth = NULL;
425 }
426 }
427
428 *src = g_steal_pointer(&def);
429 return rc;
430 }
431
432
433 /**
434 * virStorageSourceNewFromChild:
435 * @parent: storage source parent
436 * @child: returned child/backing store definition
437 * @parentRaw: raw child string (backingStoreRaw)
438 *
439 * Creates a storage source which describes the backing image of @parent and
440 * fills it into @backing depending on the passed parentRaw (backingStoreRaw)
441 * and other data. Note that for local storage this function accesses the file
442 * to update the actual type of the child store.
443 *
444 * Returns 0 on success, 1 if we could parse all location data but the child
445 * store specification contained other data unrepresentable by libvirt (e.g.
446 * inline authentication).
447 * In both cases @src is filled. On error -1 is returned @src is NULL and an
448 * error is reported.
449 */
450 static int
virStorageSourceNewFromChild(virStorageSource * parent,const char * parentRaw,virStorageSource ** child)451 virStorageSourceNewFromChild(virStorageSource *parent,
452 const char *parentRaw,
453 virStorageSource **child)
454 {
455 struct stat st;
456 g_autoptr(virStorageSource) def = NULL;
457 int rc = 0;
458
459 *child = NULL;
460
461 if (virStorageSourceBackinStoreStringIsRelative(parentRaw)) {
462 if (!(def = virStorageSourceNewFromBackingRelative(parent, parentRaw)))
463 return -1;
464 } else {
465 if ((rc = virStorageSourceNewFromBackingAbsolute(parentRaw, &def)) < 0)
466 return -1;
467 }
468
469 /* possibly update local type */
470 if (def->type == VIR_STORAGE_TYPE_FILE) {
471 if (stat(def->path, &st) == 0) {
472 if (S_ISDIR(st.st_mode)) {
473 def->type = VIR_STORAGE_TYPE_DIR;
474 def->format = VIR_STORAGE_FILE_DIR;
475 } else if (S_ISBLK(st.st_mode)) {
476 def->type = VIR_STORAGE_TYPE_BLOCK;
477 }
478 }
479 }
480
481 /* copy parent's labelling and other top level stuff */
482 if (virStorageSourceInitChainElement(def, parent, true) < 0)
483 return -1;
484
485 def->detected = true;
486
487 *child = g_steal_pointer(&def);
488 return rc;
489 }
490
491
492 int
virStorageSourceNewFromBacking(virStorageSource * parent,virStorageSource ** backing)493 virStorageSourceNewFromBacking(virStorageSource *parent,
494 virStorageSource **backing)
495 {
496 int rc;
497
498 if ((rc = virStorageSourceNewFromChild(parent,
499 parent->backingStoreRaw,
500 backing)) < 0)
501 return rc;
502
503 (*backing)->format = parent->backingStoreRawFormat;
504 (*backing)->readonly = true;
505 return rc;
506 }
507
508
509 /**
510 * @src: disk source definition structure
511 * @fd: file descriptor
512 * @sb: stat buffer
513 *
514 * Updates src->physical depending on the actual type of storage being used.
515 * To be called for domain storage source reporting as the volume code does
516 * not set/use the 'type' field for the voldef->source.target
517 *
518 * Returns 0 on success, -1 on error. No libvirt errors are reported.
519 */
520 int
virStorageSourceUpdatePhysicalSize(virStorageSource * src,int fd,struct stat const * sb)521 virStorageSourceUpdatePhysicalSize(virStorageSource *src,
522 int fd,
523 struct stat const *sb)
524 {
525 off_t end;
526 virStorageType actual_type = virStorageSourceGetActualType(src);
527
528 switch (actual_type) {
529 case VIR_STORAGE_TYPE_FILE:
530 case VIR_STORAGE_TYPE_NETWORK:
531 src->physical = sb->st_size;
532 break;
533
534 case VIR_STORAGE_TYPE_BLOCK:
535 if ((end = lseek(fd, 0, SEEK_END)) == (off_t) -1)
536 return -1;
537
538 src->physical = end;
539 break;
540
541 case VIR_STORAGE_TYPE_DIR:
542 src->physical = 0;
543 break;
544
545 /* We shouldn't get VOLUME, but the switch requires all cases */
546 case VIR_STORAGE_TYPE_VOLUME:
547 case VIR_STORAGE_TYPE_NVME:
548 case VIR_STORAGE_TYPE_VHOST_USER:
549 case VIR_STORAGE_TYPE_NONE:
550 case VIR_STORAGE_TYPE_LAST:
551 return -1;
552 }
553
554 return 0;
555 }
556
557
558 /**
559 * @src: disk source definition structure
560 * @fd: file descriptor
561 * @sb: stat buffer
562 *
563 * Update the capacity, allocation, physical values for the storage @src
564 * Shared between the domain storage source for an inactive domain and the
565 * voldef source target as the result is not affected by the 'type' field.
566 *
567 * Returns 0 on success, -1 on error.
568 */
569 int
virStorageSourceUpdateBackingSizes(virStorageSource * src,int fd,struct stat const * sb)570 virStorageSourceUpdateBackingSizes(virStorageSource *src,
571 int fd,
572 struct stat const *sb)
573 {
574 /* Get info for normal formats */
575 if (S_ISREG(sb->st_mode) || fd == -1) {
576 #ifndef WIN32
577 src->allocation = (unsigned long long)sb->st_blocks *
578 (unsigned long long)DEV_BSIZE;
579 #else
580 src->allocation = sb->st_size;
581 #endif
582 /* Regular files may be sparse, so logical size (capacity) is not same
583 * as actual allocation above
584 */
585 src->capacity = sb->st_size;
586
587 /* Allocation tracks when the file is sparse, physical is the
588 * last offset of the file. */
589 src->physical = sb->st_size;
590 } else if (S_ISDIR(sb->st_mode)) {
591 src->allocation = 0;
592 src->capacity = 0;
593 src->physical = 0;
594 } else if (fd >= 0) {
595 off_t end;
596
597 /* XXX this is POSIX compliant, but doesn't work for CHAR files,
598 * only BLOCK. There is a Linux specific ioctl() for getting
599 * size of both CHAR / BLOCK devices we should check for in
600 * configure
601 *
602 * NB. Because we configure with AC_SYS_LARGEFILE, off_t
603 * should be 64 bits on all platforms. For block devices, we
604 * have to seek (safe even if someone else is writing) to
605 * determine physical size, and assume that allocation is the
606 * same as physical (but can refine that assumption later if
607 * qemu is still running).
608 */
609 if ((end = lseek(fd, 0, SEEK_END)) == (off_t)-1) {
610 virReportSystemError(errno,
611 _("failed to seek to end of %s"), src->path);
612 return -1;
613 }
614 src->physical = end;
615 src->allocation = end;
616 src->capacity = end;
617 }
618
619 return 0;
620 }
621
622
623 /**
624 * @src: disk source definition structure
625 * @buf: buffer to the storage file header
626 * @len: length of the storage file header
627 *
628 * Update the storage @src capacity.
629 *
630 * Returns 0 on success, -1 on error.
631 */
632 int
virStorageSourceUpdateCapacity(virStorageSource * src,char * buf,ssize_t len)633 virStorageSourceUpdateCapacity(virStorageSource *src,
634 char *buf,
635 ssize_t len)
636 {
637 int format = src->format;
638 g_autoptr(virStorageSource) meta = NULL;
639
640 /* Raw files: capacity is physical size. For all other files: if
641 * the metadata has a capacity, use that, otherwise fall back to
642 * physical size. */
643 if (format == VIR_STORAGE_FILE_NONE) {
644 virReportError(VIR_ERR_INTERNAL_ERROR,
645 _("no disk format for %s was specified"),
646 src->path);
647 return -1;
648 }
649
650 if (format == VIR_STORAGE_FILE_RAW && !src->encryption) {
651 src->capacity = src->physical;
652 } else if ((meta = virStorageSourceGetMetadataFromBuf(src->path, buf,
653 len, format))) {
654 src->capacity = meta->capacity ? meta->capacity : src->physical;
655 if (src->encryption && meta->encryption)
656 src->encryption->payload_offset = meta->encryption->payload_offset;
657 } else {
658 return -1;
659 }
660
661 if (src->encryption && src->encryption->payload_offset != -1)
662 src->capacity -= src->encryption->payload_offset * 512;
663
664 return 0;
665 }
666
667
668 /**
669 * virStorageSourceRemoveLastPathComponent:
670 *
671 * @path: Path string to remove the last component from
672 *
673 * Removes the last path component of a path. This function is designed to be
674 * called on file paths only (no trailing slashes in @path). Caller is
675 * responsible to free the returned string.
676 */
677 static char *
virStorageSourceRemoveLastPathComponent(const char * path)678 virStorageSourceRemoveLastPathComponent(const char *path)
679 {
680 char *ret;
681
682 ret = g_strdup(NULLSTR_EMPTY(path));
683
684 virFileRemoveLastComponent(ret);
685
686 return ret;
687 }
688
689
690 /*
691 * virStorageSourceGetRelativeBackingPath:
692 *
693 * Resolve relative path to be written to the overlay of @top image when
694 * collapsing the backing chain between @top and @base.
695 *
696 * Returns 0 on success; 1 if backing chain isn't relative and -1 on error.
697 */
698 int
virStorageSourceGetRelativeBackingPath(virStorageSource * top,virStorageSource * base,char ** relpath)699 virStorageSourceGetRelativeBackingPath(virStorageSource *top,
700 virStorageSource *base,
701 char **relpath)
702 {
703 virStorageSource *next;
704 g_autofree char *tmp = NULL;
705 g_autofree char *path = NULL;
706
707 *relpath = NULL;
708
709 for (next = top; virStorageSourceIsBacking(next); next = next->backingStore) {
710 if (!next->relPath)
711 return 1;
712
713 if (!(tmp = virStorageSourceRemoveLastPathComponent(path)))
714 return -1;
715
716 VIR_FREE(path);
717
718 path = g_strdup_printf("%s%s", tmp, next->relPath);
719
720 VIR_FREE(tmp);
721
722 if (next == base)
723 break;
724 }
725
726 if (next != base) {
727 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
728 _("failed to resolve relative backing name: "
729 "base image is not in backing chain"));
730 return -1;
731 }
732
733 *relpath = g_steal_pointer(&path);
734 return 0;
735 }
736
737
738 /**
739 * virStorageSourceFetchRelativeBackingPath:
740 * @src: storage object
741 * @relPath: filled with the relative path to the backing image of @src if
742 * the metadata of @src refer to it as relative.
743 *
744 * Fetches the backing store definition of @src by updating the metadata from
745 * disk and fills 'relPath' if the backing store string is relative. The data
746 * is used by virStorageSourceGetRelativeBackingPath to establish the relative
747 * path between two images.
748 */
749 int
virStorageSourceFetchRelativeBackingPath(virStorageSource * src,char ** relPath)750 virStorageSourceFetchRelativeBackingPath(virStorageSource *src,
751 char **relPath)
752 {
753 ssize_t headerLen;
754 int rv;
755 g_autofree char *buf = NULL;
756 g_autoptr(virStorageSource) tmp = NULL;
757
758 g_clear_pointer(relPath, g_free);
759
760 /* exit if we can't load information about the current image */
761 if (!virStorageSourceSupportsBackingChainTraversal(src))
762 return 0;
763
764 rv = virStorageSourceAccess(src, F_OK);
765 if (rv == -2)
766 return 0;
767 if (rv < 0) {
768 virStorageSourceReportBrokenChain(errno, src, src);
769 return -1;
770 }
771
772 if ((headerLen = virStorageSourceRead(src, 0, VIR_STORAGE_MAX_HEADER,
773 &buf)) < 0) {
774 if (headerLen == -2)
775 return 0;
776 return -1;
777 }
778
779 if (!(tmp = virStorageSourceCopy(src, false)))
780 return -1;
781
782 if (virStorageFileProbeGetMetadata(tmp, buf, headerLen) < 0)
783 return -1;
784
785 if (virStorageSourceBackinStoreStringIsRelative(tmp->backingStoreRaw))
786 *relPath = g_steal_pointer(&tmp->backingStoreRaw);
787
788 return 0;
789 }
790
791
792 static bool
virStorageSourceIsInitialized(const virStorageSource * src)793 virStorageSourceIsInitialized(const virStorageSource *src)
794 {
795 return src && src->drv;
796 }
797
798
799 /**
800 * virStorageSourceGetBackendForSupportCheck:
801 * @src: storage source to check support for
802 * @backend: pointer to the storage backend for @src if it's supported
803 *
804 * Returns 0 if @src is not supported by any storage backend currently linked
805 * 1 if it is supported and -1 on error with an error reported.
806 */
807 static int
virStorageSourceGetBackendForSupportCheck(const virStorageSource * src,virStorageFileBackend ** backend)808 virStorageSourceGetBackendForSupportCheck(const virStorageSource *src,
809 virStorageFileBackend **backend)
810 {
811 int actualType;
812
813
814 if (!src) {
815 *backend = NULL;
816 return 0;
817 }
818
819 if (src->drv) {
820 virStorageDriverData *drv = src->drv;
821 *backend = drv->backend;
822 return 1;
823 }
824
825 actualType = virStorageSourceGetActualType(src);
826
827 if (virStorageFileBackendForType(actualType, src->protocol, false, backend) < 0)
828 return -1;
829
830 if (!*backend)
831 return 0;
832
833 return 1;
834 }
835
836
837 int
virStorageSourceSupportsBackingChainTraversal(const virStorageSource * src)838 virStorageSourceSupportsBackingChainTraversal(const virStorageSource *src)
839 {
840 virStorageFileBackend *backend;
841 int rv;
842
843 if ((rv = virStorageSourceGetBackendForSupportCheck(src, &backend)) < 1)
844 return rv;
845
846 return backend->storageFileRead &&
847 backend->storageFileAccess ? 1 : 0;
848 }
849
850
851 /**
852 * virStorageSourceSupportsSecurityDriver:
853 *
854 * @src: a storage file structure
855 *
856 * Check if a storage file supports operations needed by the security
857 * driver to perform labelling
858 */
859 int
virStorageSourceSupportsSecurityDriver(const virStorageSource * src)860 virStorageSourceSupportsSecurityDriver(const virStorageSource *src)
861 {
862 virStorageFileBackend *backend;
863 int rv;
864
865 if ((rv = virStorageSourceGetBackendForSupportCheck(src, &backend)) < 1)
866 return rv;
867
868 return backend->storageFileChown ? 1 : 0;
869 }
870
871
872 /**
873 * virStorageSourceSupportsAccess:
874 *
875 * @src: a storage file structure
876 *
877 * Check if a storage file supports checking if the storage source is accessible
878 * for the given vm.
879 */
880 int
virStorageSourceSupportsAccess(const virStorageSource * src)881 virStorageSourceSupportsAccess(const virStorageSource *src)
882 {
883 virStorageFileBackend *backend;
884 int rv;
885
886 if ((rv = virStorageSourceGetBackendForSupportCheck(src, &backend)) < 1)
887 return rv;
888
889 return backend->storageFileAccess ? 1 : 0;
890 }
891
892
893 /**
894 * virStorageSourceSupportsCreate:
895 * @src: a storage file structure
896 *
897 * Check if the storage driver supports creating storage described by @src
898 * via virStorageSourceCreate.
899 */
900 int
virStorageSourceSupportsCreate(const virStorageSource * src)901 virStorageSourceSupportsCreate(const virStorageSource *src)
902 {
903 virStorageFileBackend *backend;
904 int rv;
905
906 if ((rv = virStorageSourceGetBackendForSupportCheck(src, &backend)) < 1)
907 return rv;
908
909 return backend->storageFileCreate ? 1 : 0;
910 }
911
912
913 void
virStorageSourceDeinit(virStorageSource * src)914 virStorageSourceDeinit(virStorageSource *src)
915 {
916 virStorageDriverData *drv = NULL;
917
918 if (!virStorageSourceIsInitialized(src))
919 return;
920
921 drv = src->drv;
922
923 if (drv->backend &&
924 drv->backend->backendDeinit)
925 drv->backend->backendDeinit(src);
926
927 VIR_FREE(src->drv);
928 }
929
930
931 /**
932 * virStorageSourceInitAs:
933 *
934 * @src: storage source definition
935 * @uid: uid used to access the file, or -1 for current uid
936 * @gid: gid used to access the file, or -1 for current gid
937 *
938 * Initialize a storage source to be used with storage driver. Use the provided
939 * uid and gid if possible for the operations.
940 *
941 * Returns 0 if the storage file was successfully initialized, -1 if the
942 * initialization failed. Libvirt error is reported.
943 */
944 int
virStorageSourceInitAs(virStorageSource * src,uid_t uid,gid_t gid)945 virStorageSourceInitAs(virStorageSource *src,
946 uid_t uid, gid_t gid)
947 {
948 int actualType = virStorageSourceGetActualType(src);
949 virStorageDriverData *drv = g_new0(virStorageDriverData, 1);
950
951 src->drv = drv;
952
953 if (uid == (uid_t) -1)
954 drv->uid = geteuid();
955 else
956 drv->uid = uid;
957
958 if (gid == (gid_t) -1)
959 drv->gid = getegid();
960 else
961 drv->gid = gid;
962
963 if (virStorageFileBackendForType(actualType,
964 src->protocol,
965 true,
966 &drv->backend) < 0)
967 goto error;
968
969 if (drv->backend->backendInit &&
970 drv->backend->backendInit(src) < 0)
971 goto error;
972
973 return 0;
974
975 error:
976 VIR_FREE(src->drv);
977 return -1;
978 }
979
980
981 /**
982 * virStorageSourceInit:
983 *
984 * See virStorageSourceInitAs. The file is initialized to be accessed by the
985 * current user.
986 */
987 int
virStorageSourceInit(virStorageSource * src)988 virStorageSourceInit(virStorageSource *src)
989 {
990 return virStorageSourceInitAs(src, -1, -1);
991 }
992
993
994 /**
995 * virStorageSourceCreate: Creates an empty storage file via storage driver
996 *
997 * @src: file structure pointing to the file
998 *
999 * Returns 0 on success, -2 if the function isn't supported by the backend,
1000 * -1 on other failure. Errno is set in case of failure.
1001 */
1002 int
virStorageSourceCreate(virStorageSource * src)1003 virStorageSourceCreate(virStorageSource *src)
1004 {
1005 virStorageDriverData *drv = NULL;
1006 int ret;
1007
1008 if (!virStorageSourceIsInitialized(src)) {
1009 errno = ENOSYS;
1010 return -2;
1011 }
1012
1013 drv = src->drv;
1014
1015 if (!drv->backend->storageFileCreate) {
1016 errno = ENOSYS;
1017 return -2;
1018 }
1019
1020 ret = drv->backend->storageFileCreate(src);
1021
1022 VIR_DEBUG("created storage file %p: ret=%d, errno=%d",
1023 src, ret, errno);
1024
1025 return ret;
1026 }
1027
1028
1029 /**
1030 * virStorageSourceUnlink: Unlink storage file via storage driver
1031 *
1032 * @src: file structure pointing to the file
1033 *
1034 * Unlinks the file described by the @file structure.
1035 *
1036 * Returns 0 on success, -2 if the function isn't supported by the backend,
1037 * -1 on other failure. Errno is set in case of failure.
1038 */
1039 int
virStorageSourceUnlink(virStorageSource * src)1040 virStorageSourceUnlink(virStorageSource *src)
1041 {
1042 virStorageDriverData *drv = NULL;
1043 int ret;
1044
1045 if (!virStorageSourceIsInitialized(src)) {
1046 errno = ENOSYS;
1047 return -2;
1048 }
1049
1050 drv = src->drv;
1051
1052 if (!drv->backend->storageFileUnlink) {
1053 errno = ENOSYS;
1054 return -2;
1055 }
1056
1057 ret = drv->backend->storageFileUnlink(src);
1058
1059 VIR_DEBUG("unlinked storage file %p: ret=%d, errno=%d",
1060 src, ret, errno);
1061
1062 return ret;
1063 }
1064
1065
1066 /**
1067 * virStorageSourceStat: returns stat struct of a file via storage driver
1068 *
1069 * @src: file structure pointing to the file
1070 * @stat: stat structure to return data
1071 *
1072 * Returns 0 on success, -2 if the function isn't supported by the backend,
1073 * -1 on other failure. Errno is set in case of failure.
1074 */
1075 int
virStorageSourceStat(virStorageSource * src,struct stat * st)1076 virStorageSourceStat(virStorageSource *src,
1077 struct stat *st)
1078 {
1079 virStorageDriverData *drv = NULL;
1080 int ret;
1081
1082 if (!virStorageSourceIsInitialized(src)) {
1083 errno = ENOSYS;
1084 return -2;
1085 }
1086
1087 drv = src->drv;
1088
1089 if (!drv->backend->storageFileStat) {
1090 errno = ENOSYS;
1091 return -2;
1092 }
1093
1094 ret = drv->backend->storageFileStat(src, st);
1095
1096 VIR_DEBUG("stat of storage file %p: ret=%d, errno=%d",
1097 src, ret, errno);
1098
1099 return ret;
1100 }
1101
1102
1103 /**
1104 * virStorageSourceRead: read bytes from a file into a buffer
1105 *
1106 * @src: file structure pointing to the file
1107 * @offset: number of bytes to skip in the storage file
1108 * @len: maximum number of bytes read from the storage file
1109 * @buf: buffer to read the data into. (buffer shall be freed by caller)
1110 *
1111 * Returns the count of bytes read on success and -1 on failure, -2 if the
1112 * function isn't supported by the backend.
1113 * Libvirt error is reported on failure.
1114 */
1115 ssize_t
virStorageSourceRead(virStorageSource * src,size_t offset,size_t len,char ** buf)1116 virStorageSourceRead(virStorageSource *src,
1117 size_t offset,
1118 size_t len,
1119 char **buf)
1120 {
1121 virStorageDriverData *drv = NULL;
1122 ssize_t ret;
1123
1124 if (!virStorageSourceIsInitialized(src)) {
1125 virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1126 _("storage file backend not initialized"));
1127 return -1;
1128 }
1129
1130 drv = src->drv;
1131
1132 if (!drv->backend->storageFileRead)
1133 return -2;
1134
1135 ret = drv->backend->storageFileRead(src, offset, len, buf);
1136
1137 VIR_DEBUG("read '%zd' bytes from storage '%p' starting at offset '%zu'",
1138 ret, src, offset);
1139
1140 return ret;
1141 }
1142
1143
1144 /**
1145 * virStorageSourceAccess: Check accessibility of a storage file
1146 *
1147 * @src: storage file to check access permissions
1148 * @mode: accessibility check options (see man 2 access)
1149 *
1150 * Returns 0 on success, -1 on error and sets errno. No libvirt
1151 * error is reported. Returns -2 if the operation isn't supported
1152 * by libvirt storage backend.
1153 */
1154 int
virStorageSourceAccess(virStorageSource * src,int mode)1155 virStorageSourceAccess(virStorageSource *src,
1156 int mode)
1157 {
1158 virStorageDriverData *drv = NULL;
1159
1160 if (!virStorageSourceIsInitialized(src)) {
1161 errno = ENOSYS;
1162 return -2;
1163 }
1164
1165 drv = src->drv;
1166
1167 if (!drv->backend->storageFileAccess) {
1168 errno = ENOSYS;
1169 return -2;
1170 }
1171
1172 return drv->backend->storageFileAccess(src, mode);
1173 }
1174
1175
1176 /**
1177 * virStorageSourceChown: Change owner of a storage file
1178 *
1179 * @src: storage file to change owner of
1180 * @uid: new owner id
1181 * @gid: new group id
1182 *
1183 * Returns 0 on success, -1 on error and sets errno. No libvirt
1184 * error is reported. Returns -2 if the operation isn't supported
1185 * by libvirt storage backend.
1186 */
1187 int
virStorageSourceChown(const virStorageSource * src,uid_t uid,gid_t gid)1188 virStorageSourceChown(const virStorageSource *src,
1189 uid_t uid,
1190 gid_t gid)
1191 {
1192 virStorageDriverData *drv = NULL;
1193
1194 if (!virStorageSourceIsInitialized(src)) {
1195 errno = ENOSYS;
1196 return -2;
1197 }
1198
1199 drv = src->drv;
1200
1201 if (!drv->backend->storageFileChown) {
1202 errno = ENOSYS;
1203 return -2;
1204 }
1205
1206 VIR_DEBUG("chown of storage file %p to %u:%u",
1207 src, (unsigned int)uid, (unsigned int)gid);
1208
1209 return drv->backend->storageFileChown(src, uid, gid);
1210 }
1211
1212
1213 /**
1214 * virStorageSourceReportBrokenChain:
1215 *
1216 * @errcode: errno when accessing @src
1217 * @src: inaccessible file in the backing chain of @parent
1218 * @parent: root virStorageSource being checked
1219 *
1220 * Reports the correct error message if @src is missing in the backing chain
1221 * for @parent.
1222 */
1223 void
virStorageSourceReportBrokenChain(int errcode,virStorageSource * src,virStorageSource * parent)1224 virStorageSourceReportBrokenChain(int errcode,
1225 virStorageSource *src,
1226 virStorageSource *parent)
1227 {
1228 if (src->drv) {
1229 virStorageDriverData *drv = src->drv;
1230 unsigned int access_user = drv->uid;
1231 unsigned int access_group = drv->gid;
1232
1233 if (src == parent) {
1234 virReportSystemError(errcode,
1235 _("Cannot access storage file '%s' "
1236 "(as uid:%u, gid:%u)"),
1237 src->path, access_user, access_group);
1238 } else {
1239 virReportSystemError(errcode,
1240 _("Cannot access backing file '%s' "
1241 "of storage file '%s' (as uid:%u, gid:%u)"),
1242 src->path, parent->path, access_user, access_group);
1243 }
1244 } else {
1245 if (src == parent) {
1246 virReportSystemError(errcode,
1247 _("Cannot access storage file '%s'"),
1248 src->path);
1249 } else {
1250 virReportSystemError(errcode,
1251 _("Cannot access backing file '%s' "
1252 "of storage file '%s'"),
1253 src->path, parent->path);
1254 }
1255 }
1256 }
1257
1258
1259 static int
virStorageSourceGetMetadataRecurseReadHeader(virStorageSource * src,virStorageSource * parent,uid_t uid,gid_t gid,char ** buf,size_t * headerLen)1260 virStorageSourceGetMetadataRecurseReadHeader(virStorageSource *src,
1261 virStorageSource *parent,
1262 uid_t uid,
1263 gid_t gid,
1264 char **buf,
1265 size_t *headerLen)
1266 {
1267 int ret = -1;
1268 ssize_t len;
1269
1270 if (virStorageSourceInitAs(src, uid, gid) < 0)
1271 return -1;
1272
1273 if (virStorageSourceAccess(src, F_OK) < 0) {
1274 virStorageSourceReportBrokenChain(errno, src, parent);
1275 goto cleanup;
1276 }
1277
1278 if ((len = virStorageSourceRead(src, 0, VIR_STORAGE_MAX_HEADER, buf)) < 0)
1279 goto cleanup;
1280
1281 *headerLen = len;
1282 ret = 0;
1283
1284 cleanup:
1285 virStorageSourceDeinit(src);
1286 return ret;
1287 }
1288
1289
1290 /* Recursive workhorse for virStorageSourceGetMetadata. */
1291 static int
virStorageSourceGetMetadataRecurse(virStorageSource * src,virStorageSource * parent,uid_t uid,gid_t gid,bool report_broken,size_t max_depth,unsigned int depth)1292 virStorageSourceGetMetadataRecurse(virStorageSource *src,
1293 virStorageSource *parent,
1294 uid_t uid, gid_t gid,
1295 bool report_broken,
1296 size_t max_depth,
1297 unsigned int depth)
1298 {
1299 virStorageFileFormat orig_format = src->format;
1300 size_t headerLen;
1301 int rv;
1302 g_autofree char *buf = NULL;
1303 g_autoptr(virStorageSource) backingStore = NULL;
1304
1305 VIR_DEBUG("path=%s format=%d uid=%u gid=%u depth=%u",
1306 NULLSTR(src->path), src->format,
1307 (unsigned int)uid, (unsigned int)gid, depth);
1308
1309 if (depth > max_depth) {
1310 virReportError(VIR_ERR_INTERNAL_ERROR,
1311 _("backing store for %s is self-referential or too deeply nested"),
1312 NULLSTR(src->path));
1313 return -1;
1314 }
1315
1316 if (src->format == VIR_STORAGE_FILE_AUTO_SAFE)
1317 src->format = VIR_STORAGE_FILE_AUTO;
1318
1319 /* exit if we can't load information about the current image */
1320 rv = virStorageSourceSupportsBackingChainTraversal(src);
1321 if (rv <= 0) {
1322 if (orig_format == VIR_STORAGE_FILE_AUTO)
1323 return -2;
1324
1325 return rv;
1326 }
1327
1328 if (virStorageSourceGetMetadataRecurseReadHeader(src, parent, uid, gid,
1329 &buf, &headerLen) < 0)
1330 return -1;
1331
1332 if (virStorageFileProbeGetMetadata(src, buf, headerLen) < 0)
1333 return -1;
1334
1335 /* If we probed the format we MUST ensure that nothing else than the current
1336 * image is considered for security labelling and/or recursion. */
1337 if (orig_format == VIR_STORAGE_FILE_AUTO) {
1338 if (src->backingStoreRaw) {
1339 src->format = VIR_STORAGE_FILE_RAW;
1340 VIR_FREE(src->backingStoreRaw);
1341 return -2;
1342 }
1343 }
1344
1345 if (src->backingStoreRaw) {
1346 if ((rv = virStorageSourceNewFromBacking(src, &backingStore)) < 0)
1347 return -1;
1348
1349 /* the backing file would not be usable for VM usage */
1350 if (rv == 1)
1351 return 0;
1352
1353 if ((rv = virStorageSourceGetMetadataRecurse(backingStore, parent,
1354 uid, gid,
1355 report_broken,
1356 max_depth, depth + 1)) < 0) {
1357 if (!report_broken)
1358 return 0;
1359
1360 if (rv == -2) {
1361 virReportError(VIR_ERR_OPERATION_INVALID,
1362 _("format of backing image '%s' of image '%s' was not specified in the image metadata "
1363 "(See https://libvirt.org/kbase/backing_chains.html for troubleshooting)"),
1364 src->backingStoreRaw, NULLSTR(src->path));
1365 }
1366
1367 return -1;
1368 }
1369
1370 backingStore->id = depth;
1371 src->backingStore = g_steal_pointer(&backingStore);
1372 } else {
1373 /* add terminator */
1374 src->backingStore = virStorageSourceNew();
1375 }
1376
1377 return 0;
1378 }
1379
1380
1381 /**
1382 * virStorageSourceGetMetadata:
1383 *
1384 * Extract metadata about the storage volume with the specified
1385 * image format. If image format is VIR_STORAGE_FILE_AUTO, it
1386 * will probe to automatically identify the format. Recurses through
1387 * the chain up to @max_depth layers.
1388 *
1389 * Open files using UID and GID (or pass -1 for the current user/group).
1390 * Treat any backing files without explicit type as raw, unless ALLOW_PROBE.
1391 *
1392 * Callers are advised never to use VIR_STORAGE_FILE_AUTO as a
1393 * format, since a malicious guest can turn a raw file into any
1394 * other non-raw format at will.
1395 *
1396 * If @report_broken is true, the whole function fails with a possibly sane
1397 * error instead of just returning a broken chain. Note that the inability for
1398 * libvirt to traverse a given source is not considered an error.
1399 *
1400 * Caller MUST free result after use via virObjectUnref.
1401 */
1402 int
virStorageSourceGetMetadata(virStorageSource * src,uid_t uid,gid_t gid,size_t max_depth,bool report_broken)1403 virStorageSourceGetMetadata(virStorageSource *src,
1404 uid_t uid, gid_t gid,
1405 size_t max_depth,
1406 bool report_broken)
1407 {
1408 virStorageType actualType = virStorageSourceGetActualType(src);
1409
1410 VIR_DEBUG("path=%s format=%d uid=%u gid=%u max_depth=%zu report_broken=%d",
1411 src->path, src->format, (unsigned int)uid, (unsigned int)gid,
1412 max_depth, report_broken);
1413
1414 if (src->format <= VIR_STORAGE_FILE_NONE) {
1415 if (actualType == VIR_STORAGE_TYPE_DIR)
1416 src->format = VIR_STORAGE_FILE_DIR;
1417 else
1418 src->format = VIR_STORAGE_FILE_RAW;
1419 }
1420
1421 return virStorageSourceGetMetadataRecurse(src, src, uid, gid,
1422 report_broken, max_depth, 1);
1423 }
1424