1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2010-2012 Lennart Poettering
14 /* When we include libgen.h because we need dirname() we immediately
15 * undefine basename() since libgen.h defines it as a macro to the
16 * POSIX version which is really broken. We prefer GNU basename(). */
20 #include "alloc-util.h"
21 #include "extract-word.h"
23 //#include "glob-util.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "stat-util.h"
30 #include "string-util.h"
32 #include "time-util.h"
35 bool path_is_absolute(const char *p) {
39 bool is_path(const char *p) {
40 return !!strchr(p, '/');
43 #if 0 /// UNNEEDED by elogind
44 int path_split_and_make_absolute(const char *p, char ***ret) {
51 l = strv_split(p, ":");
55 r = path_strv_make_absolute_cwd(l);
65 char *path_make_absolute(const char *p, const char *prefix) {
68 /* Makes every item in the list an absolute path by prepending
69 * the prefix, if specified and necessary */
71 if (path_is_absolute(p) || isempty(prefix))
74 if (endswith(prefix, "/"))
75 return strjoin(prefix, p);
77 return strjoin(prefix, "/", p);
81 int safe_getcwd(char **ret) {
84 cwd = get_current_dir_name();
86 return negative_errno();
88 /* Let's make sure the directory is really absolute, to protect us from the logic behind
99 int path_make_absolute_cwd(const char *p, char **ret) {
106 /* Similar to path_make_absolute(), but prefixes with the
107 * current working directory. */
109 if (path_is_absolute(p))
112 _cleanup_free_ char *cwd = NULL;
114 r = safe_getcwd(&cwd);
118 if (endswith(cwd, "/"))
121 c = strjoin(cwd, "/", p);
130 #if 0 /// UNNEEDED by elogind
131 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
133 unsigned n_parents = 0;
139 /* Strips the common part, and adds ".." elements as necessary. */
141 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
144 f = strdupa(from_dir);
145 t = strdupa(to_path);
147 path_simplify(f, true);
148 path_simplify(t, true);
150 /* Skip the common part. */
159 /* from_dir equals to_path. */
162 /* from_dir is a parent directory of to_path. */
177 if (a != b || memcmp(f, t, a) != 0)
184 /* If we're here, then "from_dir" has one or more elements that need to
185 * be replaced with "..". */
187 /* Count the number of necessary ".." elements. */
193 /* If this includes ".." we can't do a simple series of "..", refuse */
194 if (w == 2 && f[0] == '.' && f[1] == '.')
197 /* Count number of elements */
204 r = new(char, n_parents * 3 + strlen(t) + 1);
208 for (p = r; n_parents > 0; n_parents--)
209 p = mempcpy(p, "../", 3);
214 /* Remove trailing slash */
221 int path_strv_make_absolute_cwd(char **l) {
225 /* Goes through every item in the string list and makes it
226 * absolute. This works in place and won't rollback any
227 * changes on failure. */
232 r = path_make_absolute_cwd(*s, &t);
236 path_simplify(t, false);
237 free_and_replace(*s, t);
244 char **path_strv_resolve(char **l, const char *root) {
253 /* Goes through every item in the string list and canonicalize
254 * the path. This works in place and won't rollback any
255 * changes on failure. */
258 _cleanup_free_ char *orig = NULL;
261 if (!path_is_absolute(*s)) {
268 t = prefix_root(root, orig);
276 r = chase_symlinks(t, root, 0, &u);
294 x = path_startswith(u, root);
296 /* restore the slash if it was lost */
297 if (!startswith(x, "/"))
308 /* canonicalized path goes outside of
309 * prefix, keep the original path instead */
310 free_and_replace(u, orig);
326 char **path_strv_resolve_uniq(char **l, const char *root) {
331 if (!path_strv_resolve(l, root))
337 char *path_simplify(char *path, bool kill_dots) {
339 bool slash = false, ignore_slash = false, absolute;
343 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
344 * if kill_dots is true. Modifies the passed string in-place.
346 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
347 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
348 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
349 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
352 absolute = path_is_absolute(path);
355 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
360 for (t = path; *f; f++) {
368 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
373 ignore_slash = false;
381 /* Special rule, if we are talking of the root directory, a trailing slash is good */
382 if (absolute && t == path)
389 char* path_startswith(const char *path, const char *prefix) {
393 /* Returns a pointer to the start of the first component after the parts matched by
395 * - both paths are absolute or both paths are relative,
397 * - each component in prefix in turn matches a component in path at the same position.
398 * An empty string will be returned when the prefix and path are equivalent.
400 * Returns NULL otherwise.
403 if ((path[0] == '/') != (prefix[0] == '/'))
409 path += strspn(path, "/");
410 prefix += strspn(prefix, "/");
418 a = strcspn(path, "/");
419 b = strcspn(prefix, "/");
424 if (memcmp(path, prefix, a) != 0)
432 int path_compare(const char *a, const char *b) {
438 /* A relative path and an abolute path must not compare as equal.
439 * Which one is sorted before the other does not really matter.
440 * Here a relative path is ordered before an absolute path. */
441 d = (a[0] == '/') - (b[0] == '/');
451 if (*a == 0 && *b == 0)
454 /* Order prefixes first: "/foo" before "/foo/bar" */
463 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
464 d = memcmp(a, b, MIN(j, k));
466 return (d > 0) - (d < 0); /* sign of d */
468 /* Sort "/foo/a" before "/foo/aaa" */
469 d = (j > k) - (j < k); /* sign of (j - k) */
478 bool path_equal(const char *a, const char *b) {
479 return path_compare(a, b) == 0;
482 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
483 return path_equal(a, b) || files_same(a, b, flags) > 0;
486 char* path_join(const char *root, const char *path, const char *rest) {
490 return strjoin(root, endswith(root, "/") ? "" : "/",
491 path[0] == '/' ? path+1 : path,
492 rest ? (endswith(path, "/") ? "" : "/") : NULL,
493 rest && rest[0] == '/' ? rest+1 : rest);
496 rest ? (endswith(path, "/") ? "" : "/") : NULL,
497 rest && rest[0] == '/' ? rest+1 : rest);
500 int find_binary(const char *name, char **ret) {
507 if (access(name, X_OK) < 0)
511 r = path_make_absolute_cwd(name, ret);
520 * Plain getenv, not secure_getenv, because we want
521 * to actually allow the user to pick the binary.
527 last_error = -ENOENT;
530 _cleanup_free_ char *j = NULL, *element = NULL;
532 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
538 if (!path_is_absolute(element))
541 j = strjoin(element, "/", name);
545 if (access(j, X_OK) >= 0) {
549 *ret = path_simplify(j, false);
562 #if 0 /// UNNEEDED by elogind
563 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
564 bool changed = false;
565 const char* const* i;
572 STRV_FOREACH(i, paths) {
576 if (stat(*i, &stats) < 0)
579 u = timespec_load(&stats.st_mtim);
585 log_debug("timestamp of '%s' changed", *i);
587 /* update timestamp */
598 static int binary_is_good(const char *binary) {
599 _cleanup_free_ char *p = NULL, *d = NULL;
602 r = find_binary(binary, &p);
608 /* An fsck that is linked to /bin/true is a non-existent
611 r = readlink_malloc(p, &d);
612 if (r == -EINVAL) /* not a symlink */
617 return !PATH_IN_SET(d, "true"
623 int fsck_exists(const char *fstype) {
628 if (streq(fstype, "auto"))
631 checker = strjoina("fsck.", fstype);
632 return binary_is_good(checker);
635 int mkfs_exists(const char *fstype) {
640 if (streq(fstype, "auto"))
643 mkfs = strjoina("mkfs.", fstype);
644 return binary_is_good(mkfs);
648 char *prefix_root(const char *root, const char *path) {
652 /* If root is passed, prefixes path with it. Otherwise returns
657 /* First, drop duplicate prefixing slashes from the path */
658 while (path[0] == '/' && path[1] == '/')
661 if (empty_or_root(root))
664 l = strlen(root) + 1 + strlen(path) + 1;
672 while (p > n && p[-1] == '/')
682 #if 0 /// UNNEEDED by elogind
683 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
688 * This function is intended to be used in command line
689 * parsers, to handle paths that are passed in. It makes the
690 * path absolute, and reduces it to NULL if omitted or
691 * root (the latter optionally).
693 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
694 * SUCCESS! Hence, do not pass in uninitialized pointers.
702 r = path_make_absolute_cwd(path, &p);
704 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
706 path_simplify(p, false);
707 if (suppress_root && empty_or_root(p))
710 free_and_replace(*arg, p);
716 char* dirname_malloc(const char *path) {
717 char *d, *dir, *dir2;
737 const char *last_path_component(const char *path) {
739 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
752 * Also, the empty string is mapped to itself.
754 * This is different than basename(), which returns "" when a trailing slash is present.
759 l = k = strlen(path);
760 if (l == 0) /* special case — an empty string */
763 while (k > 0 && path[k-1] == '/')
766 if (k == 0) /* the root directory */
769 while (k > 0 && path[k-1] != '/')
775 bool filename_is_valid(const char *p) {
781 if (dot_or_dot_dot(p))
784 e = strchrnul(p, '/');
788 if (e - p > FILENAME_MAX)
794 bool path_is_normalized(const char *p) {
799 if (dot_or_dot_dot(p))
802 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
805 if (strlen(p)+1 > PATH_MAX)
808 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
817 char *file_in_same_dir(const char *path, const char *filename) {
824 /* This removes the last component of path and appends
825 * filename, unless the latter is absolute anyway or the
828 if (path_is_absolute(filename))
829 return strdup(filename);
831 e = strrchr(path, '/');
833 return strdup(filename);
835 k = strlen(filename);
836 ret = new(char, (e + 1 - path) + k + 1);
840 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
844 bool hidden_or_backup_file(const char *filename) {
849 if (filename[0] == '.' ||
850 streq(filename, "lost+found") ||
851 streq(filename, "aquota.user") ||
852 streq(filename, "aquota.group") ||
853 endswith(filename, "~"))
856 p = strrchr(filename, '.');
860 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
861 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
862 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
863 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
864 * string. Specifically: there's now:
866 * The generic suffixes "~" and ".bak" for backup files
867 * The generic prefix "." for hidden files
869 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
870 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
873 return STR_IN_SET(p + 1,
893 #if 0 /// UNNEEDED by elogind
894 bool is_device_path(const char *path) {
896 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
898 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
901 bool valid_device_node_path(const char *path) {
903 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
904 * actual device node. */
906 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
909 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
912 return path_is_normalized(path);
915 bool valid_device_allow_pattern(const char *path) {
918 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
921 if (startswith(path, "block-") ||
922 startswith(path, "char-"))
925 return valid_device_node_path(path);
928 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
932 /* Try to guess if systemd installation is later than the specified version. This
933 * is hacky and likely to yield false negatives, particularly if the installation
934 * is non-standard. False positives should be relatively rare.
937 NULSTR_FOREACH(pattern,
938 /* /lib works for systems without usr-merge, and for systems with a sane
939 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
940 * for Gentoo which does a merge without making /lib a symlink.
942 "lib/systemd/libsystemd-shared-*.so\0"
943 "lib64/systemd/libsystemd-shared-*.so\0"
944 "usr/lib/systemd/libsystemd-shared-*.so\0"
945 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
947 _cleanup_strv_free_ char **names = NULL;
948 _cleanup_free_ char *path = NULL;
951 path = prefix_root(root, pattern);
955 r = glob_extend(&names, path);
961 assert_se(c = endswith(path, "*.so"));
962 *c = '\0'; /* truncate the glob part */
964 STRV_FOREACH(name, names) {
965 /* This is most likely to run only once, hence let's not optimize anything. */
969 t = startswith(*name, path);
973 t2 = endswith(t, ".so");
977 t2[0] = '\0'; /* truncate the suffix */
979 r = safe_atou(t, &version);
981 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
985 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
987 version >= minimal_version ? "OK" : "too old");
988 if (version >= minimal_version)
997 bool dot_or_dot_dot(const char *path) {
1007 return path[2] == 0;
1010 bool empty_or_root(const char *root) {
1012 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1013 * i.e. either / or NULL or the empty string or any equivalent. */
1018 return root[strspn(root, "/")] == 0;
1021 int path_simplify_and_warn(
1025 const char *filename,
1027 const char *lvalue) {
1029 bool absolute, fatal = flag & PATH_CHECK_FATAL;
1031 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
1033 if (!utf8_is_valid(path)) {
1034 log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
1038 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
1039 absolute = path_is_absolute(path);
1041 if (!absolute && (flag & PATH_CHECK_ABSOLUTE)) {
1042 log_syntax(unit, LOG_ERR, filename, line, 0,
1043 "%s= path is not absolute%s: %s",
1044 lvalue, fatal ? "" : ", ignoring", path);
1048 if (absolute && (flag & PATH_CHECK_RELATIVE)) {
1049 log_syntax(unit, LOG_ERR, filename, line, 0,
1050 "%s= path is absolute%s: %s",
1051 lvalue, fatal ? "" : ", ignoring", path);
1056 path_simplify(path, true);
1058 if (!path_is_normalized(path)) {
1059 log_syntax(unit, LOG_ERR, filename, line, 0,
1060 "%s= path is not normalized%s: %s",
1061 lvalue, fatal ? "" : ", ignoring", path);