Welcome to little lamb

Code » limb » release » tree

[release] / src / liblimb / djbunix.h / fd_mkdirpat.c

/* This file is part of limb                           https://lila.oss/limb
 * Copyright (C) 2023 Olivier Brunel                          jjk@jjacky.com */
/* SPDX-License-Identifier: GPL-2.0-only */
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <limb/bytestr.h>
#include <limb/djbunix.h>

int
fd_mkdirpat(int bfd, const char *name, mode_t mode)
{
    size_t nlen = strlen(name);
    int fd = bfd;

    for (;;) {
        char buf[512];
        const char *n;
        size_t o = byte_chr(name, nlen, '/');
        if (o == nlen) {
            n = name;
        } else {
            n = buf;
            memcpy(buf, name, o);
            buf[o] = 0;
        }
        if (mkdirat(fd, n, mode) < 0 && errno != EEXIST)
            goto err;
        int dfd = open2_at(fd, n, O_RDONLY | O_DIRECTORY);
        if (dfd < 0) goto err;
        if (fd != bfd) fd_close(fd);
        fd = dfd;
        if (o == nlen) return fd;
        name += o + 1;
        nlen -= o + 1;
    }

err:
    if (fd != bfd) fd_close(fd);
    return -1;
}