virfile.c 19.0 KB
Newer Older
1
/*
E
Eric Blake 已提交
2
 * virfile.c: safer file handling
3
 *
4
 * Copyright (C) 2010-2012 Red Hat, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 * Copyright (C) 2010 IBM Corporation
 * Copyright (C) 2010 Stefan Berger
 * Copyright (C) 2010 Eric Blake
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
20
 * License along with this library.  If not, see
O
Osier Yang 已提交
21
 * <http://www.gnu.org/licenses/>.
22 23 24 25
 *
 */

#include <config.h>
26
#include "internal.h"
27

28 29 30 31
#include "virfile.h"

#include <fcntl.h>
#include <sys/stat.h>
32
#include <unistd.h>
33 34
#include <dirent.h>

35
#if defined(__linux__) && HAVE_DECL_LO_FLAGS_AUTOCLEAR
36 37 38
# include <linux/loop.h>
# include <sys/ioctl.h>
#endif
39

40
#include "vircommand.h"
41
#include "configmake.h"
42
#include "viralloc.h"
43
#include "virerror.h"
44
#include "virlog.h"
45
#include "virstring.h"
46 47

#define VIR_FROM_THIS VIR_FROM_NONE
48

49
int virFileClose(int *fdptr, virFileCloseFlags flags)
50
{
51
    int saved_errno = 0;
52 53
    int rc = 0;

54 55 56
    if (*fdptr < 0)
        return 0;

57
    if (flags & VIR_FILE_CLOSE_PRESERVE_ERRNO)
58 59 60
        saved_errno = errno;

    rc = close(*fdptr);
61 62 63 64 65 66 67 68 69 70 71

    if (!(flags & VIR_FILE_CLOSE_DONT_LOG)) {
        if (rc < 0) {
            if (errno == EBADF) {
                if (!(flags & VIR_FILE_CLOSE_IGNORE_EBADF))
                    VIR_WARN("Tried to close invalid fd %d", *fdptr);
            } else {
                char ebuf[1024] ATTRIBUTE_UNUSED;
                VIR_DEBUG("Failed to close fd %d: %s",
                          *fdptr, virStrerror(errno, ebuf, sizeof(ebuf)));
            }
72
        } else {
73
            VIR_DEBUG("Closed fd %d", *fdptr);
74
        }
75
    }
76
    *fdptr = -1;
77 78

    if (flags & VIR_FILE_CLOSE_PRESERVE_ERRNO)
79
        errno = saved_errno;
80 81 82

    return rc;
}
83 84


E
Eric Blake 已提交
85
int virFileFclose(FILE **file, bool preserve_errno)
86
{
87
    int saved_errno = 0;
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
    int rc = 0;

    if (*file) {
        if (preserve_errno)
            saved_errno = errno;
        rc = fclose(*file);
        *file = NULL;
        if (preserve_errno)
            errno = saved_errno;
    }

    return rc;
}


E
Eric Blake 已提交
103
FILE *virFileFdopen(int *fdptr, const char *mode)
104 105 106 107 108 109 110 111 112 113 114 115 116
{
    FILE *file = NULL;

    if (*fdptr >= 0) {
        file = fdopen(*fdptr, mode);
        if (file)
            *fdptr = -1;
    } else {
        errno = EBADF;
    }

    return file;
}
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134


/**
 * virFileDirectFdFlag:
 *
 * Returns 0 if the kernel can avoid file system cache pollution
 * without any additional flags, O_DIRECT if the original fd must be
 * opened in direct mode, or -1 if there is no support for bypassing
 * the file system cache.
 */
int
virFileDirectFdFlag(void)
{
    /* XXX For now, Linux posix_fadvise is not powerful enough to
     * avoid O_DIRECT.  */
    return O_DIRECT ? O_DIRECT : -1;
}

J
Jiri Denemark 已提交
135 136 137 138
/* Opaque type for managing a wrapper around a fd.  For now,
 * read-write is not supported, just a single direction.  */
struct _virFileWrapperFd {
    virCommandPtr cmd; /* Child iohelper process to do the I/O.  */
139
    char *err_msg; /* stderr of @cmd */
J
Jiri Denemark 已提交
140 141 142
};

#ifndef WIN32
143
/**
J
Jiri Denemark 已提交
144
 * virFileWrapperFdNew:
145 146
 * @fd: pointer to fd to wrap
 * @name: name of fd, for diagnostics
J
Jiri Denemark 已提交
147 148 149 150 151 152 153 154
 * @flags: bitwise-OR of virFileWrapperFdFlags
 *
 * Update @fd so that it meets parameters requested by @flags.
 *
 * If VIR_FILE_WRAPPER_BYPASS_CACHE bit is set in @flags, @fd will be updated
 * in a way that all I/O to that file will bypass the system cache.  The
 * original fd must have been created with virFileDirectFdFlag() among the
 * flags to open().
155
 *
J
Jiri Denemark 已提交
156 157 158 159 160 161 162 163 164
 * If VIR_FILE_WRAPPER_NON_BLOCKING bit is set in @flags, @fd will be updated
 * to ensure it properly supports non-blocking I/O, i.e., it will report
 * EAGAIN.
 *
 * This must be called after open() and optional fchown() or fchmod(), but
 * before any seek or I/O, and only on seekable fd.  The file must be O_RDONLY
 * (to read the entire existing file) or O_WRONLY (to write to an empty file).
 * In some cases, @fd is changed to a non-seekable pipe; in this case, the
 * caller must not do anything further with the original fd.
165 166
 *
 * On success, the new wrapper object is returned, which must be later
J
Jiri Denemark 已提交
167
 * freed with virFileWrapperFdFree().  On failure, @fd is unchanged, an
168 169
 * error message is output, and NULL is returned.
 */
J
Jiri Denemark 已提交
170 171
virFileWrapperFdPtr
virFileWrapperFdNew(int *fd, const char *name, unsigned int flags)
172
{
J
Jiri Denemark 已提交
173
    virFileWrapperFdPtr ret = NULL;
174 175 176 177
    bool output = false;
    int pipefd[2] = { -1, -1 };
    int mode = -1;

J
Jiri Denemark 已提交
178
    if (!flags) {
179 180
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("invalid use with no flags"));
J
Jiri Denemark 已提交
181 182 183 184 185 186 187 188 189
        return NULL;
    }

    /* XXX support posix_fadvise rather than O_DIRECT, if the kernel support
     * for that is decent enough. In that case, we will also need to
     * explicitly support VIR_FILE_WRAPPER_NON_BLOCKING since
     * VIR_FILE_WRAPPER_BYPASS_CACHE alone will no longer require spawning
     * iohelper.
     */
190

J
Jiri Denemark 已提交
191
    if ((flags & VIR_FILE_WRAPPER_BYPASS_CACHE) && !O_DIRECT) {
192 193
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                       _("O_DIRECT unsupported on this platform"));
194 195 196 197 198 199 200 201 202 203 204
        return NULL;
    }

    if (VIR_ALLOC(ret) < 0) {
        virReportOOMError();
        return NULL;
    }

    mode = fcntl(*fd, F_GETFL);

    if (mode < 0) {
205 206
        virReportError(VIR_ERR_INTERNAL_ERROR, _("invalid fd %d for %s"),
                       *fd, name);
207 208 209 210
        goto error;
    } else if ((mode & O_ACCMODE) == O_WRONLY) {
        output = true;
    } else if ((mode & O_ACCMODE) != O_RDONLY) {
211 212
        virReportError(VIR_ERR_INTERNAL_ERROR, _("unexpected mode %x for %s"),
                       mode & O_ACCMODE, name);
213 214 215 216
        goto error;
    }

    if (pipe2(pipefd, O_CLOEXEC) < 0) {
217 218
        virReportError(VIR_ERR_INTERNAL_ERROR,
                       _("unable to create pipe for %s"), name);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233
        goto error;
    }

    ret->cmd = virCommandNewArgList(LIBEXECDIR "/libvirt_iohelper",
                                    name, "0", NULL);
    if (output) {
        virCommandSetInputFD(ret->cmd, pipefd[0]);
        virCommandSetOutputFD(ret->cmd, fd);
        virCommandAddArg(ret->cmd, "1");
    } else {
        virCommandSetInputFD(ret->cmd, *fd);
        virCommandSetOutputFD(ret->cmd, &pipefd[1]);
        virCommandAddArg(ret->cmd, "0");
    }

234 235
    /* In order to catch iohelper stderr, we must change
     * iohelper's env so virLog functions print to stderr
236 237
     */
    virCommandAddEnvPair(ret->cmd, "LIBVIRT_LOG_OUTPUTS", "1:stderr");
238 239
    virCommandSetErrorBuffer(ret->cmd, &ret->err_msg);
    virCommandDoAsyncIO(ret->cmd);
240

241 242 243 244
    if (virCommandRunAsync(ret->cmd, NULL) < 0)
        goto error;

    if (VIR_CLOSE(pipefd[!output]) < 0) {
245
        virReportError(VIR_ERR_INTERNAL_ERROR, "%s", _("unable to close pipe"));
246 247 248 249 250 251 252 253 254 255
        goto error;
    }

    VIR_FORCE_CLOSE(*fd);
    *fd = pipefd[output];
    return ret;

error:
    VIR_FORCE_CLOSE(pipefd[0]);
    VIR_FORCE_CLOSE(pipefd[1]);
J
Jiri Denemark 已提交
256
    virFileWrapperFdFree(ret);
257 258
    return NULL;
}
J
Jiri Denemark 已提交
259 260 261 262 263 264
#else
virFileWrapperFdPtr
virFileWrapperFdNew(int *fd ATTRIBUTE_UNUSED,
                    const char *name ATTRIBUTE_UNUSED,
                    unsigned int fdflags ATTRIBUTE_UNUSED)
{
265
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
J
Jiri Denemark 已提交
266 267 268 269
                 _("virFileWrapperFd unsupported on this platform"));
    return NULL;
}
#endif
270 271

/**
J
Jiri Denemark 已提交
272 273
 * virFileWrapperFdClose:
 * @wfd: fd wrapper, or NULL
274
 *
J
Jiri Denemark 已提交
275
 * If @wfd is valid, then ensure that I/O has completed, which may
276 277
 * include reaping a child process.  Return 0 if all data for the
 * wrapped fd is complete, or -1 on failure with an error emitted.
J
Jiri Denemark 已提交
278 279
 * This function intentionally returns 0 when @wfd is NULL, so that
 * callers can conditionally create a virFileWrapperFd wrapper but
280
 * unconditionally call the cleanup code.  To avoid deadlock, only
J
Jiri Denemark 已提交
281
 * call this after closing the fd resulting from virFileWrapperFdNew().
282 283
 */
int
J
Jiri Denemark 已提交
284
virFileWrapperFdClose(virFileWrapperFdPtr wfd)
285
{
286 287
    int ret;

J
Jiri Denemark 已提交
288
    if (!wfd)
289 290
        return 0;

291 292
    ret = virCommandWait(wfd->cmd, NULL);
    if (wfd->err_msg)
293 294
        VIR_WARN("iohelper reports: %s", wfd->err_msg);

295 296
    return ret;
}
297

298
/**
J
Jiri Denemark 已提交
299 300
 * virFileWrapperFdFree:
 * @wfd: fd wrapper, or NULL
301
 *
J
Jiri Denemark 已提交
302 303
 * Free all remaining resources associated with @wfd.  If
 * virFileWrapperFdClose() was not previously called, then this may
304
 * discard some previous I/O.  To avoid deadlock, only call this after
J
Jiri Denemark 已提交
305
 * closing the fd resulting from virFileWrapperFdNew().
306 307
 */
void
J
Jiri Denemark 已提交
308
virFileWrapperFdFree(virFileWrapperFdPtr wfd)
309
{
J
Jiri Denemark 已提交
310
    if (!wfd)
311 312
        return;

313 314
    VIR_FREE(wfd->err_msg);

J
Jiri Denemark 已提交
315 316
    virCommandFree(wfd->cmd);
    VIR_FREE(wfd);
317
}
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400


#ifndef WIN32
/**
 * virFileLock:
 * @fd: file descriptor to acquire the lock on
 * @shared: type of lock to acquire
 * @start: byte offset to start lock
 * @len: length of lock (0 to acquire entire remaining file from @start)
 *
 * Attempt to acquire a lock on the file @fd. If @shared
 * is true, then a shared lock will be acquired,
 * otherwise an exclusive lock will be acquired. If
 * the lock cannot be acquired, an error will be
 * returned. This will not wait to acquire the lock if
 * another process already holds it.
 *
 * The lock will be released when @fd is closed. The lock
 * will also be released if *any* other open file descriptor
 * pointing to the same underlying file is closed. As such
 * this function should not be relied on in multi-threaded
 * apps where other threads can be opening/closing arbitrary
 * files.
 *
 * Returns 0 on success, or -errno otherwise
 */
int virFileLock(int fd, bool shared, off_t start, off_t len)
{
    struct flock fl = {
        .l_type = shared ? F_RDLCK : F_WRLCK,
        .l_whence = SEEK_SET,
        .l_start = start,
        .l_len = len,
    };

    if (fcntl(fd, F_SETLK, &fl) < 0)
        return -errno;

    return 0;
}


/**
 * virFileUnlock:
 * @fd: file descriptor to release the lock on
 * @start: byte offset to start unlock
 * @len: length of lock (0 to release entire remaining file from @start)
 *
 * Release a lock previously acquired with virFileUnlock().
 * NB the lock will also be released if any open file descriptor
 * pointing to the same file as @fd is closed
 *
 * Returns 0 on succcess, or -errno on error
 */
int virFileUnlock(int fd, off_t start, off_t len)
{
    struct flock fl = {
        .l_type = F_UNLCK,
        .l_whence = SEEK_SET,
        .l_start = start,
        .l_len = len,
    };

    if (fcntl(fd, F_SETLK, &fl) < 0)
        return -errno;

    return 0;
}
#else
int virFileLock(int fd ATTRIBUTE_UNUSED,
                bool shared ATTRIBUTE_UNUSED,
                off_t start ATTRIBUTE_UNUSED,
                off_t len ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
int virFileUnlock(int fd ATTRIBUTE_UNUSED,
                  off_t start ATTRIBUTE_UNUSED,
                  off_t len ATTRIBUTE_UNUSED)
{
    return -ENOSYS;
}
#endif
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456

int
virFileRewrite(const char *path,
               mode_t mode,
               virFileRewriteFunc rewrite,
               void *opaque)
{
    char *newfile = NULL;
    int fd = -1;
    int ret = -1;

    if (virAsprintf(&newfile, "%s.new", path) < 0) {
        virReportOOMError();
        goto cleanup;
    }

    if ((fd = open(newfile, O_WRONLY | O_CREAT | O_TRUNC, mode)) < 0) {
        virReportSystemError(errno, _("cannot create file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (rewrite(fd, opaque) < 0) {
        virReportSystemError(errno, _("cannot write data to file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (fsync(fd) < 0) {
        virReportSystemError(errno, _("cannot sync file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("cannot save file '%s'"),
                             newfile);
        goto cleanup;
    }

    if (rename(newfile, path) < 0) {
        virReportSystemError(errno, _("cannot rename file '%s' as '%s'"),
                             newfile, path);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VIR_FORCE_CLOSE(fd);
    if (newfile) {
        unlink(newfile);
        VIR_FREE(newfile);
    }
    return ret;
}
457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477


int virFileTouch(const char *path, mode_t mode)
{
    int fd = -1;

    if ((fd = open(path, O_WRONLY | O_CREAT, mode)) < 0) {
        virReportSystemError(errno, _("cannot create file '%s'"),
                             path);
        return -1;
    }

    if (VIR_CLOSE(fd) < 0) {
        virReportSystemError(errno, _("cannot save file '%s'"),
                             path);
        VIR_FORCE_CLOSE(fd);
        return -1;
    }

    return 0;
}
478 479 480 481 482 483 484 485 486 487 488 489


#define MODE_BITS (S_ISUID | S_ISGID | S_ISVTX | S_IRWXU | S_IRWXG | S_IRWXO)

int virFileUpdatePerm(const char *path,
                      mode_t mode_remove,
                      mode_t mode_add)
{
    struct stat sb;
    mode_t mode;

    if (mode_remove & ~MODE_BITS || mode_add & ~MODE_BITS) {
490
        virReportError(VIR_ERR_INVALID_ARG, "%s", _("invalid mode"));
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        return -1;
    }

    if (stat(path, &sb) < 0) {
        virReportSystemError(errno, _("cannot stat '%s'"), path);
        return -1;
    }

    mode = sb.st_mode & MODE_BITS;

    if ((mode & mode_remove) == 0 && (mode & mode_add) == mode_add)
        return 0;

    mode &= MODE_BITS ^ mode_remove;
    mode |= mode_add;

    if (chmod(path, mode) < 0) {
        virReportSystemError(errno, _("cannot change permission of '%s'"),
                             path);
        return -1;
    }

    return 0;
}
515 516


517
#if defined(__linux__) && HAVE_DECL_LO_FLAGS_AUTOCLEAR
518 519 520 521 522
static int virFileLoopDeviceOpen(char **dev_name)
{
    int fd = -1;
    DIR *dh = NULL;
    struct dirent *de;
523
    char *looppath = NULL;
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566
    struct loop_info64 lo;

    VIR_DEBUG("Looking for loop devices in /dev");

    if (!(dh = opendir("/dev"))) {
        virReportSystemError(errno, "%s",
                             _("Unable to read /dev"));
        goto cleanup;
    }

    while ((de = readdir(dh)) != NULL) {
        if (!STRPREFIX(de->d_name, "loop"))
            continue;

        if (virAsprintf(&looppath, "/dev/%s", de->d_name) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        VIR_DEBUG("Checking up on device %s", looppath);
        if ((fd = open(looppath, O_RDWR)) < 0) {
            virReportSystemError(errno,
                                 _("Unable to open %s"), looppath);
            goto cleanup;
        }

        if (ioctl(fd, LOOP_GET_STATUS64, &lo) < 0) {
            /* Got a free device, return the fd */
            if (errno == ENXIO)
                goto cleanup;

            VIR_FORCE_CLOSE(fd);
            virReportSystemError(errno,
                                 _("Unable to get loop status on %s"),
                                 looppath);
            goto cleanup;
        }

        /* Oh well, try the next device */
        VIR_FORCE_CLOSE(fd);
        VIR_FREE(looppath);
    }

567 568
    virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
                   _("Unable to find a free loop device in /dev"));
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637

cleanup:
    if (fd != -1) {
        VIR_DEBUG("Got free loop device %s %d", looppath, fd);
        *dev_name = looppath;
    } else {
        VIR_DEBUG("No free loop devices available");
        VIR_FREE(looppath);
    }
    if (dh)
        closedir(dh);
    return fd;
}


int virFileLoopDeviceAssociate(const char *file,
                               char **dev)
{
    int lofd = -1;
    int fsfd = -1;
    struct loop_info64 lo;
    char *loname = NULL;
    int ret = -1;

    if ((lofd = virFileLoopDeviceOpen(&loname)) < 0)
        return -1;

    memset(&lo, 0, sizeof(lo));
    lo.lo_flags = LO_FLAGS_AUTOCLEAR;

    if ((fsfd = open(file, O_RDWR)) < 0) {
        virReportSystemError(errno,
                             _("Unable to open %s"), file);
        goto cleanup;
    }

    if (ioctl(lofd, LOOP_SET_FD, fsfd) < 0) {
        virReportSystemError(errno,
                             _("Unable to attach %s to loop device"),
                             file);
        goto cleanup;
    }

    if (ioctl(lofd, LOOP_SET_STATUS64, &lo) < 0) {
        virReportSystemError(errno, "%s",
                             _("Unable to mark loop device as autoclear"));

        if (ioctl(lofd, LOOP_CLR_FD, 0) < 0)
            VIR_WARN("Unable to detach %s from loop device", file);
        goto cleanup;
    }

    VIR_DEBUG("Attached loop device  %s %d to %s", file, lofd, loname);
    *dev = loname;
    loname = NULL;

    ret = 0;

cleanup:
    VIR_FREE(loname);
    VIR_FORCE_CLOSE(fsfd);
    if (ret == -1)
        VIR_FORCE_CLOSE(lofd);
    return lofd;
}

#else /* __linux__ */

int virFileLoopDeviceAssociate(const char *file,
638
                               char **dev ATTRIBUTE_UNUSED)
639 640 641 642
{
    virReportSystemError(ENOSYS,
                         _("Unable to associate file %s with loop device"),
                         file);
643 644
    *dev = NULL;
    return -1;
645 646 647
}

#endif /* __linux__ */
648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730


/**
 * virFileDeleteTree:
 *
 * Recursively deletes all files / directories
 * starting from the directory @dir. Does not
 * follow symlinks
 *
 * NB the algorithm is not efficient, and is subject to
 * race conditions which can be exploited by malicious
 * code. It should not be used in any scenarios where
 * performance is important, or security is critical.
 */
int virFileDeleteTree(const char *dir)
{
    DIR *dh = opendir(dir);
    struct dirent *de;
    char *filepath = NULL;
    int ret = -1;

    if (!dh) {
        virReportSystemError(errno, _("Cannot open dir '%s'"),
                             dir);
        return -1;
    }

    errno = 0;
    while ((de = readdir(dh)) != NULL) {
        struct stat sb;

        if (STREQ(de->d_name, ".") ||
            STREQ(de->d_name, ".."))
            continue;

        if (virAsprintf(&filepath, "%s/%s",
                        dir, de->d_name) < 0) {
            virReportOOMError();
            goto cleanup;
        }

        if (lstat(filepath, &sb) < 0) {
            virReportSystemError(errno, _("Cannot access '%s'"),
                                 filepath);
            goto cleanup;
        }

        if (S_ISDIR(sb.st_mode)) {
            if (virFileDeleteTree(filepath) < 0)
                goto cleanup;
        } else {
            if (unlink(filepath) < 0 && errno != ENOENT) {
                virReportSystemError(errno,
                                     _("Cannot delete file '%s'"),
                                     filepath);
                goto cleanup;
            }
        }

        VIR_FREE(filepath);
        errno = 0;
    }

    if (errno) {
        virReportSystemError(errno, _("Cannot read dir '%s'"),
                             dir);
        goto cleanup;
    }

    if (rmdir(dir) < 0 && errno != ENOENT) {
        virReportSystemError(errno,
                             _("Cannot delete directory '%s'"),
                             dir);
        goto cleanup;
    }

    ret = 0;

cleanup:
    VIR_FREE(filepath);
    closedir(dh);
    return ret;
}