HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/basic/path-util.c

46,163 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 71486cc9e061a662704e026568623443193a52b7

Lines 1001–1518 of 1,518

                if (next)
                        *next = path;
                if (ret)
                        *ret = NULL;
                return 0;
        }
 
        last_end = q + 1;
 
        while (q && *q != '/')
                q = PTR_SUB1(q, path);
 
        last_begin = q ? q + 1 : path;
        len = last_end - last_begin;
 
        if (len > NAME_MAX)
                return -EINVAL;
        if (!accept_dot_dot && len == 2 && strneq(last_begin, "..", 2))
                return -EINVAL;
 
        if (next) {
                q = skip_slash_or_dot_backward(path, q);
                *next = q ? q + 1 : path;
        }
 
        if (ret)
                *ret = last_begin;
        return len;
}
 
const char* last_path_component(const char *path) {
 
        /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
         *
         *    a/b/c → c
         *    a/b/c/ → c/
         *    x → x
         *    x/ → x/
         *    /y → y
         *    /y/ → y/
         *    / → /
         *    // → /
         *    /foo/a → a
         *    /foo/a/ → a/
         *
         *    Also, the empty string is mapped to itself.
         *
         * This is different than basename(), which returns "" when a trailing slash is present.
         *
         * This always succeeds (except if you pass NULL in which case it returns NULL, too).
         */
 
        unsigned l, k;
 
        if (!path)
                return NULL;
 
        l = k = strlen(path);
        if (l == 0) /* special case — an empty string */
                return path;
 
        while (k > 0 && path[k-1] == '/')
                k--;
 
        if (k == 0) /* the root directory */
                return path + l - 1;
 
        while (k > 0 && path[k-1] != '/')
                k--;
 
        return path + k;
}
 
int path_split_prefix_filename(const char *path, char **ret_dir, char **ret_filename) {
        _cleanup_free_ char *d = NULL;
        const char *c, *next = NULL;
        int r;
 
        POINTER_MAY_BE_NULL(path);
 
        /* Split the path into dir prefix/filename pair. Returns:
         *
         * -EINVAL        → if the path is not valid
         * -EADDRNOTAVAIL → if the path refers to the uppermost directory in hierarchy (i.e. has neither
         *                  dir prefix nor filename - the root dir itself or ".")
         * -EDESTADDRREQ  → if only a filename was passed, and caller only specifies ret_dir
         * -ENOMEM        → no memory
         *
         * Returns >= 0 on success. If the input path has a trailing slash, returns O_DIRECTORY, to
         * indicate the referenced file must be a directory.
         *
         * This function guarantees to return a fully valid filename, i.e. one that passes
         * filename_is_valid() – this means "." and ".." are not accepted. */
 
        if (isempty(path))
                return -EINVAL;
 
        r = path_find_last_component(path, /* accept_dot_dot = */ false, &next, &c);
        if (r < 0)
                return r;
        if (r == 0) /* root directory or "." */
                return -EADDRNOTAVAIL;
 
        if (ret_dir) {
                if (next == path) {
                        if (*path != '/') { /* filename only */
                                if (!ret_filename)
                                        return -EDESTADDRREQ;
                        } else {
                                d = strdup("/");
                                if (!d)
                                        return -ENOMEM;
                        }
                } else {
                        d = strndup(path, next - path);
                        if (!d)
                                return -ENOMEM;
 
                        path_simplify(d);
 
                        if (!path_is_valid(d))
                                return -EINVAL;
                }
 
        } else if (!path_is_valid(path))
                /* We didn't validate the dir prefix, hence check if the whole path is valid now */
                return -EINVAL;
 
        if (ret_filename) {
                char *fn = strndup(c, r);
                if (!fn)
                        return -ENOMEM;
 
                *ret_filename = fn;
        }
 
        if (ret_dir)
                *ret_dir = TAKE_PTR(d);
 
        return strlen(c) > (size_t) r ? O_DIRECTORY : 0;
}
 
bool filename_part_is_valid(const char *p) {
        const char *e;
 
        /* Checks f the specified string is OK to be *part* of a filename. This is different from
         * filename_is_valid() as "." and ".." and "" are OK by this call, but not by filename_is_valid(). */
 
        if (!p)
                return false;
 
        e = strchrnul(p, '/');
        if (*e != 0)
                return false;
 
        if (e - p > NAME_MAX) /* NAME_MAX is counted *without* the trailing NUL byte */
                return false;
 
        return true;
}
 
bool filename_is_valid(const char *p) {
 
        if (isempty(p))
                return false;
 
        if (dot_or_dot_dot(p)) /* Yes, in this context we consider "." and ".." invalid */
                return false;
 
        return filename_part_is_valid(p);
}
 
bool path_is_valid_full(const char *p, bool accept_dot_dot) {
        if (isempty(p))
                return false;
 
        for (const char *e = p;;) {
                int r;
 
                r = path_find_first_component(&e, accept_dot_dot, NULL);
                if (r < 0)
                        return false;
 
                if (e - p >= PATH_MAX) /* Already reached the maximum length for a path? (PATH_MAX is counted
                                        * *with* the trailing NUL byte) */
                        return false;
                if (*e == 0)           /* End of string? Yay! */
                        return true;
        }
}
 
bool path_is_normalized(const char *p) {
        if (!path_is_safe(p))
                return false;
 
        if (streq(p, ".") || startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
                return false;
 
        if (strstr(p, "//"))
                return false;
 
        return true;
}
 
int file_in_same_dir(const char *path, const char *filename, char **ret) {
        _cleanup_free_ char *b = NULL;
        int r;
 
        assert(path);
        assert(filename);
        assert(ret);
 
        /* This removes the last component of path and appends filename, unless the latter is absolute anyway
         * or the former isn't */
 
        if (path_is_absolute(filename))
                b = strdup(filename);
        else {
                _cleanup_free_ char *dn = NULL;
 
                r = path_extract_directory(path, &dn);
                if (r == -EDESTADDRREQ) /* no path prefix */
                        b = strdup(filename);
                else if (r < 0)
                        return r;
                else
                        b = path_join(dn, filename);
        }
        if (!b)
                return -ENOMEM;
 
        *ret = TAKE_PTR(b);
        return 0;
}
 
bool hidden_or_backup_file(const char *filename) {
        assert(filename);
 
        if (filename[0] == '.' ||
            STR_IN_SET(filename,
                       "lost+found",
                       "aquota.user",
                       "aquota.group") ||
            endswith(filename, "~"))
                return true;
 
        const char *dot = strrchr(filename, '.');
        if (!dot)
                return false;
 
        /* Please, let's not add more entries to the list below. If external projects think it's a good idea
         * to come up with always new suffixes and that everybody else should just adjust to that, then it
         * really should be on them. Hence, in future, let's not add any more entries. Instead, let's ask
         * those packages to instead adopt one of the generic suffixes/prefixes for hidden files or backups,
         * possibly augmented with an additional string. Specifically: there's now:
         *
         *    The generic suffixes "~" and ".bak" for backup files
         *    The generic prefix "." for hidden files
         *
         * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old",
         * ".foopkg-dist" or so registered, let's refuse that and ask them to use ".foopkg.new",
         * ".foopkg.old" or ".foopkg~" instead.
         */
 
        return STR_IN_SET(dot + 1,
                          "ignore",
                          "rpmnew",
                          "rpmsave",
                          "rpmorig",
                          "dpkg-old",
                          "dpkg-new",
                          "dpkg-tmp",
                          "dpkg-dist",
                          "dpkg-bak",
                          "dpkg-backup",
                          "dpkg-remove",
                          "ucf-new",
                          "ucf-old",
                          "ucf-dist",
                          "swp",
                          "bak",
                          "old",
                          "new");
}
 
bool is_device_path(const char *path) {
 
        /* Returns true for paths that likely refer to a device, either by path in sysfs or to something in
         * /dev. This accepts any path that starts with /dev/ or /sys/ and has something after that prefix.
         * It does not actually resolve the path.
         *
         * Examples:
         * /dev/sda, /dev/sda/foo, /sys/class, /dev/.., /sys/.., /./dev/foo → yes.
         * /../dev/sda, /dev, /sys, /usr/path, /usr/../dev/sda → no.
         */
 
        const char *p = PATH_STARTSWITH_SET(ASSERT_PTR(path), "/dev/", "/sys/");
        return !isempty(p);
}
 
bool valid_device_node_path(const char *path) {
 
        /* Some superficial checks whether the specified path is a valid device node path, all without
         * looking at the actual device node. */
 
        if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
                return false;
 
        if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
                return false;
 
        return path_is_normalized(path);
}
 
bool valid_device_allow_pattern(const char *path) {
        assert(path);
 
        /* Like valid_device_node_path(), but also allows full-subsystem expressions like those accepted by
         * DeviceAllow= and DeviceDeny=. */
 
        if (STARTSWITH_SET(path, "block-", "char-"))
                return true;
 
        return valid_device_node_path(path);
}
 
bool dot_or_dot_dot(const char *path) {
        if (!path)
                return false;
        if (path[0] != '.')
                return false;
        if (path[1] == 0)
                return true;
        if (path[1] != '.')
                return false;
 
        return path[2] == 0;
}
 
bool path_implies_directory(const char *path) {
 
        /* Sometimes, if we look at a path we already know it must refer to a directory, because it is
         * suffixed with a slash, or its last component is "." or ".." */
 
        if (!path)
                return false;
 
        if (dot_or_dot_dot(path))
                return true;
 
        return ENDSWITH_SET(path, "/", "/.", "/..");
}
 
bool empty_or_root(const char *path) {
 
        /* For operations relative to some root directory, returns true if the specified root directory is
         * redundant, i.e. either / or NULL or the empty string or any equivalent. */
 
        if (isempty(path))
                return true;
 
        return path_equal(path, "/");
}
 
const char* empty_to_root(const char *path) {
        return isempty(path) ? "/" : path;
}
 
int empty_or_root_harder_to_null(const char **path) {
        int r;
 
        assert(path);
 
        /* This nullifies the input path when the path is empty or points to "/". */
 
        if (empty_or_root(*path)) {
                *path = NULL;
                return 0;
        }
 
        r = path_is_root(*path);
        if (r < 0)
                return r;
        if (r > 0)
                *path = NULL;
 
        return 0;
}
 
bool path_strv_contains(char * const *l, const char *path) {
        assert(path);
 
        STRV_FOREACH(i, l)
                if (path_equal(*i, path))
                        return true;
 
        return false;
}
 
bool prefixed_path_strv_contains(char * const *l, const char *path) {
        assert(path);
 
        STRV_FOREACH(i, l) {
                const char *j = *i;
 
                if (*j == '-')
                        j++;
                if (*j == '+')
                        j++;
 
                if (path_equal(j, path))
                        return true;
        }
 
        return false;
}
 
int path_glob_can_match(const char *pattern, const char *prefix, char **ret) {
        assert(pattern);
        assert(prefix);
 
        for (const char *a = pattern, *b = prefix;;) {
                _cleanup_free_ char *g = NULL, *h = NULL;
                const char *p, *q;
                int r, s;
 
                r = path_find_first_component(&a, /* accept_dot_dot= */ false, &p);
                if (r < 0)
                        return r;
 
                s = path_find_first_component(&b, /* accept_dot_dot= */ false, &q);
                if (s < 0)
                        return s;
 
                if (s == 0) {
                        /* The pattern matches the prefix. */
                        if (ret) {
                                char *t;
 
                                t = path_join(prefix, p);
                                if (!t)
                                        return -ENOMEM;
 
                                *ret = t;
                        }
                        return true;
                }
 
                if (r == 0)
                        break;
 
                if (r == s && strneq(p, q, r))
                        continue; /* common component. Check next. */
 
                g = strndup(p, r);
                if (!g)
                        return -ENOMEM;
 
                if (!string_is_glob(g))
                        break;
 
                /* We found a glob component. Check if the glob pattern matches the prefix component. */
 
                h = strndup(q, s);
                if (!h)
                        return -ENOMEM;
 
                r = fnmatch(g, h, 0);
                if (r == FNM_NOMATCH)
                        break;
                if (r != 0) /* Failure to process pattern? */
                        return -EINVAL;
        }
 
        /* The pattern does not match the prefix. */
        if (ret)
                *ret = NULL;
        return false;
}
 
#if HAVE_SPLIT_BIN
static bool dir_is_split(const char *a, const char *b) {
        int r;
 
        r = inode_same(a, b, AT_NO_AUTOMOUNT);
        if (r < 0 && r != -ENOENT) {
                log_debug_errno(r, "Failed to compare \"%s\" and \"%s\", assuming split directories: %m", a, b);
                return true;
        }
        return r == 0;
}
#endif
 
const char* default_PATH(void) {
#if HAVE_SPLIT_BIN
        static const char *default_path = NULL;
 
        /* Return one of the three sets of paths:
         * a) split /usr/s?bin, /usr/local/sbin doesn't matter.
         * b) merged /usr/s?bin, /usr/sbin is a symlink, but /usr/local/sbin is not,
         * c) fully merged, neither /usr/sbin nor /usr/local/sbin are symlinks,
         *
         * On error the fallback to the safe value with both directories as configured is returned.
         */
 
        if (default_path)
                return default_path;
 
        if (dir_is_split("/usr/sbin", "/usr/bin"))
                return (default_path = DEFAULT_PATH_WITH_FULL_SBIN);  /* a */
        if (dir_is_split("/usr/local/sbin", "/usr/local/bin"))
                return (default_path = DEFAULT_PATH_WITH_LOCAL_SBIN); /* b */
        return (default_path = DEFAULT_PATH_WITHOUT_SBIN);            /* c */
#else
        return DEFAULT_PATH_WITHOUT_SBIN;
#endif
}