1 /* SPDX-License-Identifier: LGPL-2.1+ */
11 /* When we include libgen.h because we need dirname() we immediately
12 * undefine basename() since libgen.h defines it as a macro to the
13 * POSIX version which is really broken. We prefer GNU basename(). */
17 #include "alloc-util.h"
18 #include "extract-word.h"
20 //#include "glob-util.h"
24 #include "parse-util.h"
25 #include "path-util.h"
26 #include "stat-util.h"
27 #include "string-util.h"
29 #include "time-util.h"
32 bool path_is_absolute(const char *p) {
36 bool is_path(const char *p) {
37 return !!strchr(p, '/');
40 #if 0 /// UNNEEDED by elogind
41 int path_split_and_make_absolute(const char *p, char ***ret) {
48 l = strv_split(p, ":");
52 r = path_strv_make_absolute_cwd(l);
62 char *path_make_absolute(const char *p, const char *prefix) {
65 /* Makes every item in the list an absolute path by prepending
66 * the prefix, if specified and necessary */
68 if (path_is_absolute(p) || isempty(prefix))
71 if (endswith(prefix, "/"))
72 return strjoin(prefix, p);
74 return strjoin(prefix, "/", p);
78 int safe_getcwd(char **ret) {
81 cwd = get_current_dir_name();
83 return negative_errno();
85 /* Let's make sure the directory is really absolute, to protect us from the logic behind
96 int path_make_absolute_cwd(const char *p, char **ret) {
103 /* Similar to path_make_absolute(), but prefixes with the
104 * current working directory. */
106 if (path_is_absolute(p))
109 _cleanup_free_ char *cwd = NULL;
111 r = safe_getcwd(&cwd);
115 if (endswith(cwd, "/"))
118 c = strjoin(cwd, "/", p);
127 #if 0 /// UNNEEDED by elogind
128 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
130 unsigned n_parents = 0;
136 /* Strips the common part, and adds ".." elements as necessary. */
138 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
141 f = strdupa(from_dir);
142 t = strdupa(to_path);
144 path_simplify(f, true);
145 path_simplify(t, true);
147 /* Skip the common part. */
156 /* from_dir equals to_path. */
159 /* from_dir is a parent directory of to_path. */
174 if (a != b || memcmp(f, t, a) != 0)
181 /* If we're here, then "from_dir" has one or more elements that need to
182 * be replaced with "..". */
184 /* Count the number of necessary ".." elements. */
190 /* If this includes ".." we can't do a simple series of "..", refuse */
191 if (w == 2 && f[0] == '.' && f[1] == '.')
194 /* Count number of elements */
201 r = new(char, n_parents * 3 + strlen(t) + 1);
205 for (p = r; n_parents > 0; n_parents--)
206 p = mempcpy(p, "../", 3);
211 /* Remove trailing slash */
218 int path_strv_make_absolute_cwd(char **l) {
222 /* Goes through every item in the string list and makes it
223 * absolute. This works in place and won't rollback any
224 * changes on failure. */
229 r = path_make_absolute_cwd(*s, &t);
233 path_simplify(t, false);
234 free_and_replace(*s, t);
241 char **path_strv_resolve(char **l, const char *root) {
250 /* Goes through every item in the string list and canonicalize
251 * the path. This works in place and won't rollback any
252 * changes on failure. */
255 _cleanup_free_ char *orig = NULL;
258 if (!path_is_absolute(*s)) {
265 t = prefix_root(root, orig);
273 r = chase_symlinks(t, root, 0, &u);
291 x = path_startswith(u, root);
293 /* restore the slash if it was lost */
294 if (!startswith(x, "/"))
305 /* canonicalized path goes outside of
306 * prefix, keep the original path instead */
307 free_and_replace(u, orig);
323 char **path_strv_resolve_uniq(char **l, const char *root) {
328 if (!path_strv_resolve(l, root))
334 char *path_simplify(char *path, bool kill_dots) {
336 bool slash = false, ignore_slash = false, absolute;
340 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
341 * if kill_dots is true. Modifies the passed string in-place.
343 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
344 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
345 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
346 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
349 absolute = path_is_absolute(path);
352 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
357 for (t = path; *f; f++) {
365 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
370 ignore_slash = false;
378 /* Special rule, if we are talking of the root directory, a trailing slash is good */
379 if (absolute && t == path)
386 char* path_startswith(const char *path, const char *prefix) {
390 /* Returns a pointer to the start of the first component after the parts matched by
392 * - both paths are absolute or both paths are relative,
394 * - each component in prefix in turn matches a component in path at the same position.
395 * An empty string will be returned when the prefix and path are equivalent.
397 * Returns NULL otherwise.
400 if ((path[0] == '/') != (prefix[0] == '/'))
406 path += strspn(path, "/");
407 prefix += strspn(prefix, "/");
415 a = strcspn(path, "/");
416 b = strcspn(prefix, "/");
421 if (memcmp(path, prefix, a) != 0)
429 int path_compare(const char *a, const char *b) {
435 /* A relative path and an abolute path must not compare as equal.
436 * Which one is sorted before the other does not really matter.
437 * Here a relative path is ordered before an absolute path. */
438 d = (a[0] == '/') - (b[0] == '/');
448 if (*a == 0 && *b == 0)
451 /* Order prefixes first: "/foo" before "/foo/bar" */
460 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
461 d = memcmp(a, b, MIN(j, k));
463 return (d > 0) - (d < 0); /* sign of d */
465 /* Sort "/foo/a" before "/foo/aaa" */
466 d = (j > k) - (j < k); /* sign of (j - k) */
475 bool path_equal(const char *a, const char *b) {
476 return path_compare(a, b) == 0;
479 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
480 return path_equal(a, b) || files_same(a, b, flags) > 0;
483 char* path_join(const char *root, const char *path, const char *rest) {
487 return strjoin(root, endswith(root, "/") ? "" : "/",
488 path[0] == '/' ? path+1 : path,
489 rest ? (endswith(path, "/") ? "" : "/") : NULL,
490 rest && rest[0] == '/' ? rest+1 : rest);
493 rest ? (endswith(path, "/") ? "" : "/") : NULL,
494 rest && rest[0] == '/' ? rest+1 : rest);
497 int find_binary(const char *name, char **ret) {
504 if (access(name, X_OK) < 0)
508 r = path_make_absolute_cwd(name, ret);
517 * Plain getenv, not secure_getenv, because we want
518 * to actually allow the user to pick the binary.
524 last_error = -ENOENT;
527 _cleanup_free_ char *j = NULL, *element = NULL;
529 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
535 if (!path_is_absolute(element))
538 j = strjoin(element, "/", name);
542 if (access(j, X_OK) >= 0) {
546 *ret = path_simplify(j, false);
559 #if 0 /// UNNEEDED by elogind
560 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
561 bool changed = false;
562 const char* const* i;
569 STRV_FOREACH(i, paths) {
573 if (stat(*i, &stats) < 0)
576 u = timespec_load(&stats.st_mtim);
582 log_debug("timestamp of '%s' changed", *i);
584 /* update timestamp */
595 static int binary_is_good(const char *binary) {
596 _cleanup_free_ char *p = NULL, *d = NULL;
599 r = find_binary(binary, &p);
605 /* An fsck that is linked to /bin/true is a non-existent
608 r = readlink_malloc(p, &d);
609 if (r == -EINVAL) /* not a symlink */
614 return !PATH_IN_SET(d, "true"
620 int fsck_exists(const char *fstype) {
625 if (streq(fstype, "auto"))
628 checker = strjoina("fsck.", fstype);
629 return binary_is_good(checker);
632 int mkfs_exists(const char *fstype) {
637 if (streq(fstype, "auto"))
640 mkfs = strjoina("mkfs.", fstype);
641 return binary_is_good(mkfs);
645 char *prefix_root(const char *root, const char *path) {
649 /* If root is passed, prefixes path with it. Otherwise returns
654 /* First, drop duplicate prefixing slashes from the path */
655 while (path[0] == '/' && path[1] == '/')
658 if (empty_or_root(root))
661 l = strlen(root) + 1 + strlen(path) + 1;
669 while (p > n && p[-1] == '/')
679 #if 0 /// UNNEEDED by elogind
680 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
685 * This function is intended to be used in command line
686 * parsers, to handle paths that are passed in. It makes the
687 * path absolute, and reduces it to NULL if omitted or
688 * root (the latter optionally).
690 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
691 * SUCCESS! Hence, do not pass in uninitialized pointers.
699 r = path_make_absolute_cwd(path, &p);
701 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
703 path_simplify(p, false);
704 if (suppress_root && empty_or_root(p))
707 free_and_replace(*arg, p);
713 char* dirname_malloc(const char *path) {
714 char *d, *dir, *dir2;
734 const char *last_path_component(const char *path) {
736 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
749 * Also, the empty string is mapped to itself.
751 * This is different than basename(), which returns "" when a trailing slash is present.
756 l = k = strlen(path);
757 if (l == 0) /* special case — an empty string */
760 while (k > 0 && path[k-1] == '/')
763 if (k == 0) /* the root directory */
766 while (k > 0 && path[k-1] != '/')
772 bool filename_is_valid(const char *p) {
778 if (dot_or_dot_dot(p))
781 e = strchrnul(p, '/');
785 if (e - p > FILENAME_MAX)
791 bool path_is_normalized(const char *p) {
796 if (dot_or_dot_dot(p))
799 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
802 if (strlen(p)+1 > PATH_MAX)
805 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
814 char *file_in_same_dir(const char *path, const char *filename) {
821 /* This removes the last component of path and appends
822 * filename, unless the latter is absolute anyway or the
825 if (path_is_absolute(filename))
826 return strdup(filename);
828 e = strrchr(path, '/');
830 return strdup(filename);
832 k = strlen(filename);
833 ret = new(char, (e + 1 - path) + k + 1);
837 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
841 bool hidden_or_backup_file(const char *filename) {
846 if (filename[0] == '.' ||
847 streq(filename, "lost+found") ||
848 streq(filename, "aquota.user") ||
849 streq(filename, "aquota.group") ||
850 endswith(filename, "~"))
853 p = strrchr(filename, '.');
857 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
858 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
859 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
860 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
861 * string. Specifically: there's now:
863 * The generic suffixes "~" and ".bak" for backup files
864 * The generic prefix "." for hidden files
866 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
867 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
870 return STR_IN_SET(p + 1,
890 #if 0 /// UNNEEDED by elogind
891 bool is_device_path(const char *path) {
893 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
895 return PATH_STARTSWITH_SET(path, "/dev/", "/sys/");
898 bool valid_device_node_path(const char *path) {
900 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
901 * actual device node. */
903 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
906 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
909 return path_is_normalized(path);
912 bool valid_device_allow_pattern(const char *path) {
915 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
918 if (startswith(path, "block-") ||
919 startswith(path, "char-"))
922 return valid_device_node_path(path);
925 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
929 /* Try to guess if systemd installation is later than the specified version. This
930 * is hacky and likely to yield false negatives, particularly if the installation
931 * is non-standard. False positives should be relatively rare.
934 NULSTR_FOREACH(pattern,
935 /* /lib works for systems without usr-merge, and for systems with a sane
936 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
937 * for Gentoo which does a merge without making /lib a symlink.
939 "lib/systemd/libsystemd-shared-*.so\0"
940 "lib64/systemd/libsystemd-shared-*.so\0"
941 "usr/lib/systemd/libsystemd-shared-*.so\0"
942 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
944 _cleanup_strv_free_ char **names = NULL;
945 _cleanup_free_ char *path = NULL;
948 path = prefix_root(root, pattern);
952 r = glob_extend(&names, path);
958 assert_se(c = endswith(path, "*.so"));
959 *c = '\0'; /* truncate the glob part */
961 STRV_FOREACH(name, names) {
962 /* This is most likely to run only once, hence let's not optimize anything. */
966 t = startswith(*name, path);
970 t2 = endswith(t, ".so");
974 t2[0] = '\0'; /* truncate the suffix */
976 r = safe_atou(t, &version);
978 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
982 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
984 version >= minimal_version ? "OK" : "too old");
985 if (version >= minimal_version)
994 bool dot_or_dot_dot(const char *path) {
1004 return path[2] == 0;
1007 bool empty_or_root(const char *root) {
1009 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1010 * i.e. either / or NULL or the empty string or any equivalent. */
1015 return root[strspn(root, "/")] == 0;
1018 #if 0 /// UNNEEDED by elogind
1019 int path_simplify_and_warn(
1023 const char *filename,
1025 const char *lvalue) {
1027 bool absolute, fatal = flag & PATH_CHECK_FATAL;
1029 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
1031 if (!utf8_is_valid(path)) {
1032 log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
1036 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
1037 absolute = path_is_absolute(path);
1039 if (!absolute && (flag & PATH_CHECK_ABSOLUTE)) {
1040 log_syntax(unit, LOG_ERR, filename, line, 0,
1041 "%s= path is not absolute%s: %s",
1042 lvalue, fatal ? "" : ", ignoring", path);
1046 if (absolute && (flag & PATH_CHECK_RELATIVE)) {
1047 log_syntax(unit, LOG_ERR, filename, line, 0,
1048 "%s= path is absolute%s: %s",
1049 lvalue, fatal ? "" : ", ignoring", path);
1054 path_simplify(path, true);
1056 if (!path_is_normalized(path)) {
1057 log_syntax(unit, LOG_ERR, filename, line, 0,
1058 "%s= path is not normalized%s: %s",
1059 lvalue, fatal ? "" : ", ignoring", path);