static int ensureDir(rpmPlugins plugins, const char *p, int owned, int create)
{
    char *path = xstrdup(p);
    char *dp = path;
    char *sp = NULL, *bn;
    int oflags = O_RDONLY;

    int dirfd = fsmOpenat(-1, "/", oflags);
    int fd = dirfd; /* special case of "/" */

    while ((bn = strtok_r(dp, "/", &sp)) != NULL) {
	struct stat sb;
	fd = fsmOpenat(dirfd, bn, oflags);

	if (fd < 0 && errno == ENOENT && create) {
	    mode_t mode = S_IFDIR | (_dirPerms & 07777);
	    if (fsmDoMkDir(plugins, dirfd, bn, owned, mode) == 0) {
		fd = fsmOpenat(dirfd, bn, oflags|O_NOFOLLOW);
	    }
	}

	if (fd >= 0 && fstat(fd, &sb) == 0 && !S_ISDIR(sb.st_mode)) {
	    close(fd);
	    errno = ENOTDIR;
	    fd = -1;
	}

	close(dirfd);
	if (fd >= 0) {
	    dirfd = fd;
	} else {
	    dirfd = -1;
	    rpmlog(RPMLOG_ERR, _("failed to open dir %s of %s: %s\n"),
				bn, p, strerror(errno));
	    break;
	}

	dp = NULL;
    }

    free(path);
    return dirfd;
}