1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010-2012 Lennart Poettering
16 /* When we include libgen.h because we need dirname() we immediately
17 * undefine basename() since libgen.h defines it as a macro to the
18 * POSIX version which is really broken. We prefer GNU basename(). */
22 #include "alloc-util.h"
23 #include "extract-word.h"
25 //#include "glob-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "stat-util.h"
32 #include "string-util.h"
34 #include "time-util.h"
37 bool path_is_absolute(const char *p) {
41 bool is_path(const char *p) {
42 return !!strchr(p, '/');
45 #if 0 /// UNNEEDED by elogind
46 int path_split_and_make_absolute(const char *p, char ***ret) {
53 l = strv_split(p, ":");
57 r = path_strv_make_absolute_cwd(l);
67 char *path_make_absolute(const char *p, const char *prefix) {
70 /* Makes every item in the list an absolute path by prepending
71 * the prefix, if specified and necessary */
73 if (path_is_absolute(p) || isempty(prefix))
76 if (endswith(prefix, "/"))
77 return strjoin(prefix, p);
79 return strjoin(prefix, "/", p);
83 int safe_getcwd(char **ret) {
86 cwd = get_current_dir_name();
88 return negative_errno();
90 /* Let's make sure the directory is really absolute, to protect us from the logic behind
101 int path_make_absolute_cwd(const char *p, char **ret) {
108 /* Similar to path_make_absolute(), but prefixes with the
109 * current working directory. */
111 if (path_is_absolute(p))
114 _cleanup_free_ char *cwd = NULL;
116 r = safe_getcwd(&cwd);
120 if (endswith(cwd, "/"))
123 c = strjoin(cwd, "/", p);
132 #if 0 /// UNNEEDED by elogind
133 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
135 unsigned n_parents = 0;
141 /* Strips the common part, and adds ".." elements as necessary. */
143 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
146 f = strdupa(from_dir);
147 t = strdupa(to_path);
149 path_simplify(f, true);
150 path_simplify(t, true);
152 /* Skip the common part. */
161 /* from_dir equals to_path. */
164 /* from_dir is a parent directory of to_path. */
179 if (a != b || memcmp(f, t, a) != 0)
186 /* If we're here, then "from_dir" has one or more elements that need to
187 * be replaced with "..". */
189 /* Count the number of necessary ".." elements. */
195 /* If this includes ".." we can't do a simple series of "..", refuse */
196 if (w == 2 && f[0] == '.' && f[1] == '.')
199 /* Count number of elements */
206 r = new(char, n_parents * 3 + strlen(t) + 1);
210 for (p = r; n_parents > 0; n_parents--)
211 p = mempcpy(p, "../", 3);
216 /* Remove trailing slash */
223 int path_strv_make_absolute_cwd(char **l) {
227 /* Goes through every item in the string list and makes it
228 * absolute. This works in place and won't rollback any
229 * changes on failure. */
234 r = path_make_absolute_cwd(*s, &t);
238 path_simplify(t, false);
239 free_and_replace(*s, t);
246 char **path_strv_resolve(char **l, const char *root) {
255 /* Goes through every item in the string list and canonicalize
256 * the path. This works in place and won't rollback any
257 * changes on failure. */
260 _cleanup_free_ char *orig = NULL;
263 if (!path_is_absolute(*s)) {
270 t = prefix_root(root, orig);
278 r = chase_symlinks(t, root, 0, &u);
296 x = path_startswith(u, root);
298 /* restore the slash if it was lost */
299 if (!startswith(x, "/"))
310 /* canonicalized path goes outside of
311 * prefix, keep the original path instead */
312 free_and_replace(u, orig);
328 char **path_strv_resolve_uniq(char **l, const char *root) {
333 if (!path_strv_resolve(l, root))
339 char *path_simplify(char *path, bool kill_dots) {
341 bool slash = false, ignore_slash = false, absolute;
345 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
346 * if kill_dots is true. Modifies the passed string in-place.
348 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
349 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
350 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
351 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
354 absolute = path_is_absolute(path);
357 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
362 for (t = path; *f; f++) {
370 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
375 ignore_slash = false;
383 /* Special rule, if we are talking of the root directory, a trailing slash is good */
384 if (absolute && t == path)
391 char* path_startswith(const char *path, const char *prefix) {
395 /* Returns a pointer to the start of the first component after the parts matched by
397 * - both paths are absolute or both paths are relative,
399 * - each component in prefix in turn matches a component in path at the same position.
400 * An empty string will be returned when the prefix and path are equivalent.
402 * Returns NULL otherwise.
405 if ((path[0] == '/') != (prefix[0] == '/'))
411 path += strspn(path, "/");
412 prefix += strspn(prefix, "/");
420 a = strcspn(path, "/");
421 b = strcspn(prefix, "/");
426 if (memcmp(path, prefix, a) != 0)
434 int path_compare(const char *a, const char *b) {
440 /* A relative path and an abolute path must not compare as equal.
441 * Which one is sorted before the other does not really matter.
442 * Here a relative path is ordered before an absolute path. */
443 d = (a[0] == '/') - (b[0] == '/');
453 if (*a == 0 && *b == 0)
456 /* Order prefixes first: "/foo" before "/foo/bar" */
465 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
466 d = memcmp(a, b, MIN(j, k));
468 return (d > 0) - (d < 0); /* sign of d */
470 /* Sort "/foo/a" before "/foo/aaa" */
471 d = (j > k) - (j < k); /* sign of (j - k) */
480 bool path_equal(const char *a, const char *b) {
481 return path_compare(a, b) == 0;
484 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
485 return path_equal(a, b) || files_same(a, b, flags) > 0;
488 char* path_join(const char *root, const char *path, const char *rest) {
492 return strjoin(root, endswith(root, "/") ? "" : "/",
493 path[0] == '/' ? path+1 : path,
494 rest ? (endswith(path, "/") ? "" : "/") : NULL,
495 rest && rest[0] == '/' ? rest+1 : rest);
498 rest ? (endswith(path, "/") ? "" : "/") : NULL,
499 rest && rest[0] == '/' ? rest+1 : rest);
502 int find_binary(const char *name, char **ret) {
509 if (access(name, X_OK) < 0)
513 r = path_make_absolute_cwd(name, ret);
522 * Plain getenv, not secure_getenv, because we want
523 * to actually allow the user to pick the binary.
529 last_error = -ENOENT;
532 _cleanup_free_ char *j = NULL, *element = NULL;
534 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
540 if (!path_is_absolute(element))
543 j = strjoin(element, "/", name);
547 if (access(j, X_OK) >= 0) {
551 *ret = path_simplify(j, false);
564 #if 0 /// UNNEEDED by elogind
565 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
566 bool changed = false;
567 const char* const* i;
574 STRV_FOREACH(i, paths) {
578 if (stat(*i, &stats) < 0)
581 u = timespec_load(&stats.st_mtim);
587 log_debug("timestamp of '%s' changed", *i);
589 /* update timestamp */
600 static int binary_is_good(const char *binary) {
601 _cleanup_free_ char *p = NULL, *d = NULL;
604 r = find_binary(binary, &p);
610 /* An fsck that is linked to /bin/true is a non-existent
613 r = readlink_malloc(p, &d);
614 if (r == -EINVAL) /* not a symlink */
619 return !PATH_IN_SET(d, "true"
625 int fsck_exists(const char *fstype) {
630 if (streq(fstype, "auto"))
633 checker = strjoina("fsck.", fstype);
634 return binary_is_good(checker);
637 int mkfs_exists(const char *fstype) {
642 if (streq(fstype, "auto"))
645 mkfs = strjoina("mkfs.", fstype);
646 return binary_is_good(mkfs);
650 char *prefix_root(const char *root, const char *path) {
654 /* If root is passed, prefixes path with it. Otherwise returns
659 /* First, drop duplicate prefixing slashes from the path */
660 while (path[0] == '/' && path[1] == '/')
663 if (empty_or_root(root))
666 l = strlen(root) + 1 + strlen(path) + 1;
674 while (p > n && p[-1] == '/')
684 #if 0 /// UNNEEDED by elogind
685 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
690 * This function is intended to be used in command line
691 * parsers, to handle paths that are passed in. It makes the
692 * path absolute, and reduces it to NULL if omitted or
693 * root (the latter optionally).
695 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
696 * SUCCESS! Hence, do not pass in uninitialized pointers.
704 r = path_make_absolute_cwd(path, &p);
706 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
708 path_simplify(p, false);
709 if (suppress_root && empty_or_root(p))
712 free_and_replace(*arg, p);
718 char* dirname_malloc(const char *path) {
719 char *d, *dir, *dir2;
739 const char *last_path_component(const char *path) {
741 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
754 * Also, the empty string is mapped to itself.
756 * This is different than basename(), which returns "" when a trailing slash is present.
761 l = k = strlen(path);
762 if (l == 0) /* special case — an empty string */
765 while (k > 0 && path[k-1] == '/')
768 if (k == 0) /* the root directory */
771 while (k > 0 && path[k-1] != '/')
777 bool filename_is_valid(const char *p) {
783 if (dot_or_dot_dot(p))
786 e = strchrnul(p, '/');
790 if (e - p > FILENAME_MAX)
796 bool path_is_normalized(const char *p) {
801 if (dot_or_dot_dot(p))
804 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
807 if (strlen(p)+1 > PATH_MAX)
810 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
819 char *file_in_same_dir(const char *path, const char *filename) {
826 /* This removes the last component of path and appends
827 * filename, unless the latter is absolute anyway or the
830 if (path_is_absolute(filename))
831 return strdup(filename);
833 e = strrchr(path, '/');
835 return strdup(filename);
837 k = strlen(filename);
838 ret = new(char, (e + 1 - path) + k + 1);
842 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
846 bool hidden_or_backup_file(const char *filename) {
851 if (filename[0] == '.' ||
852 streq(filename, "lost+found") ||
853 streq(filename, "aquota.user") ||
854 streq(filename, "aquota.group") ||
855 endswith(filename, "~"))
858 p = strrchr(filename, '.');
862 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
863 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
864 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
865 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
866 * string. Specifically: there's now:
868 * The generic suffixes "~" and ".bak" for backup files
869 * The generic prefix "." for hidden files
871 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
872 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
875 return STR_IN_SET(p + 1,
895 #if 0 /// UNNEEDED by elogind
896 bool is_device_path(const char *path) {
898 /* Returns true on paths that refer to a device, either in
899 * sysfs or in /dev */
901 return path_startswith(path, "/dev/") ||
902 path_startswith(path, "/sys/");
905 bool valid_device_node_path(const char *path) {
907 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
908 * actual device node. */
910 if (!PATH_STARTSWITH_SET(path, "/dev/", "/run/systemd/inaccessible/"))
913 if (endswith(path, "/")) /* can't be a device node if it ends in a slash */
916 return path_is_normalized(path);
919 bool valid_device_allow_pattern(const char *path) {
922 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
925 if (startswith(path, "block-") ||
926 startswith(path, "char-"))
929 return valid_device_node_path(path);
932 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
936 /* Try to guess if systemd installation is later than the specified version. This
937 * is hacky and likely to yield false negatives, particularly if the installation
938 * is non-standard. False positives should be relatively rare.
941 NULSTR_FOREACH(pattern,
942 /* /lib works for systems without usr-merge, and for systems with a sane
943 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
944 * for Gentoo which does a merge without making /lib a symlink.
946 "lib/systemd/libsystemd-shared-*.so\0"
947 "lib64/systemd/libsystemd-shared-*.so\0"
948 "usr/lib/systemd/libsystemd-shared-*.so\0"
949 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
951 _cleanup_strv_free_ char **names = NULL;
952 _cleanup_free_ char *path = NULL;
955 path = prefix_root(root, pattern);
959 r = glob_extend(&names, path);
965 assert_se(c = endswith(path, "*.so"));
966 *c = '\0'; /* truncate the glob part */
968 STRV_FOREACH(name, names) {
969 /* This is most likely to run only once, hence let's not optimize anything. */
973 t = startswith(*name, path);
977 t2 = endswith(t, ".so");
981 t2[0] = '\0'; /* truncate the suffix */
983 r = safe_atou(t, &version);
985 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
989 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
991 version >= minimal_version ? "OK" : "too old");
992 if (version >= minimal_version)
1001 bool dot_or_dot_dot(const char *path) {
1011 return path[2] == 0;
1014 bool empty_or_root(const char *root) {
1016 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1017 * i.e. either / or NULL or the empty string or any equivalent. */
1022 return root[strspn(root, "/")] == 0;
1025 int path_simplify_and_warn(
1029 const char *filename,
1031 const char *lvalue) {
1033 bool absolute, fatal = flag & PATH_CHECK_FATAL;
1035 assert(!FLAGS_SET(flag, PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE));
1037 if (!utf8_is_valid(path)) {
1038 log_syntax_invalid_utf8(unit, LOG_ERR, filename, line, path);
1042 if (flag & (PATH_CHECK_ABSOLUTE | PATH_CHECK_RELATIVE)) {
1043 absolute = path_is_absolute(path);
1045 if (!absolute && (flag & PATH_CHECK_ABSOLUTE)) {
1046 log_syntax(unit, LOG_ERR, filename, line, 0,
1047 "%s= path is not absolute%s: %s",
1048 lvalue, fatal ? "" : ", ignoring", path);
1052 if (absolute && (flag & PATH_CHECK_RELATIVE)) {
1053 log_syntax(unit, LOG_ERR, filename, line, 0,
1054 "%s= path is absolute%s: %s",
1055 lvalue, fatal ? "" : ", ignoring", path);
1060 path_simplify(path, true);
1062 if (!path_is_normalized(path)) {
1063 log_syntax(unit, LOG_ERR, filename, line, 0,
1064 "%s= path is not normalized%s: %s",
1065 lvalue, fatal ? "" : ", ignoring", path);