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"
36 bool path_is_absolute(const char *p) {
40 bool is_path(const char *p) {
41 return !!strchr(p, '/');
44 #if 0 /// UNNEEDED by elogind
45 int path_split_and_make_absolute(const char *p, char ***ret) {
52 l = strv_split(p, ":");
56 r = path_strv_make_absolute_cwd(l);
66 char *path_make_absolute(const char *p, const char *prefix) {
69 /* Makes every item in the list an absolute path by prepending
70 * the prefix, if specified and necessary */
72 if (path_is_absolute(p) || isempty(prefix))
75 if (endswith(prefix, "/"))
76 return strjoin(prefix, p);
78 return strjoin(prefix, "/", p);
82 int safe_getcwd(char **ret) {
85 cwd = get_current_dir_name();
87 return negative_errno();
89 /* Let's make sure the directory is really absolute, to protect us from the logic behind
100 int path_make_absolute_cwd(const char *p, char **ret) {
107 /* Similar to path_make_absolute(), but prefixes with the
108 * current working directory. */
110 if (path_is_absolute(p))
113 _cleanup_free_ char *cwd = NULL;
115 r = safe_getcwd(&cwd);
119 if (endswith(cwd, "/"))
122 c = strjoin(cwd, "/", p);
131 #if 0 /// UNNEEDED by elogind
132 int path_make_relative(const char *from_dir, const char *to_path, char **_r) {
140 /* Strips the common part, and adds ".." elements as necessary. */
142 if (!path_is_absolute(from_dir))
145 if (!path_is_absolute(to_path))
148 /* Skip the common part. */
152 from_dir += strspn(from_dir, "/");
153 to_path += strspn(to_path, "/");
157 /* from_dir equals to_path. */
160 /* from_dir is a parent directory of to_path. */
165 path_simplify(r, false);
174 a = strcspn(from_dir, "/");
175 b = strcspn(to_path, "/");
180 if (memcmp(from_dir, to_path, a) != 0)
187 /* If we're here, then "from_dir" has one or more elements that need to
188 * be replaced with "..". */
190 /* Count the number of necessary ".." elements. */
191 for (n_parents = 0;;) {
194 from_dir += strspn(from_dir, "/");
199 w = strcspn(from_dir, "/");
201 /* If this includes ".." we can't do a simple series of "..", refuse */
202 if (w == 2 && from_dir[0] == '.' && from_dir[1] == '.')
205 /* Count number of elements, except if they are "." */
206 if (w != 1 || from_dir[0] != '.')
212 r = new(char, n_parents * 3 + strlen(to_path) + 1);
216 for (p = r; n_parents > 0; n_parents--)
217 p = mempcpy(p, "../", 3);
220 path_simplify(r, false);
226 int path_strv_make_absolute_cwd(char **l) {
230 /* Goes through every item in the string list and makes it
231 * absolute. This works in place and won't rollback any
232 * changes on failure. */
237 r = path_make_absolute_cwd(*s, &t);
241 path_simplify(t, false);
242 free_and_replace(*s, t);
249 char **path_strv_resolve(char **l, const char *root) {
258 /* Goes through every item in the string list and canonicalize
259 * the path. This works in place and won't rollback any
260 * changes on failure. */
263 _cleanup_free_ char *orig = NULL;
266 if (!path_is_absolute(*s)) {
273 t = prefix_root(root, orig);
281 r = chase_symlinks(t, root, 0, &u);
299 x = path_startswith(u, root);
301 /* restore the slash if it was lost */
302 if (!startswith(x, "/"))
313 /* canonicalized path goes outside of
314 * prefix, keep the original path instead */
315 free_and_replace(u, orig);
331 char **path_strv_resolve_uniq(char **l, const char *root) {
336 if (!path_strv_resolve(l, root))
342 char *path_simplify(char *path, bool kill_dots) {
344 bool slash = false, ignore_slash = false, absolute;
348 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
349 * if kill_dots is true. Modifies the passed string in-place.
351 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
352 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
353 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
354 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
357 absolute = path_is_absolute(path);
360 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
365 for (t = path; *f; f++) {
373 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
378 ignore_slash = false;
386 /* Special rule, if we are talking of the root directory, a trailing slash is good */
387 if (absolute && t == path)
394 char* path_startswith(const char *path, const char *prefix) {
398 /* Returns a pointer to the start of the first component after the parts matched by
400 * - both paths are absolute or both paths are relative,
402 * - each component in prefix in turn matches a component in path at the same position.
403 * An empty string will be returned when the prefix and path are equivalent.
405 * Returns NULL otherwise.
408 if ((path[0] == '/') != (prefix[0] == '/'))
414 path += strspn(path, "/");
415 prefix += strspn(prefix, "/");
423 a = strcspn(path, "/");
424 b = strcspn(prefix, "/");
429 if (memcmp(path, prefix, a) != 0)
437 int path_compare(const char *a, const char *b) {
443 /* A relative path and an abolute path must not compare as equal.
444 * Which one is sorted before the other does not really matter.
445 * Here a relative path is ordered before an absolute path. */
446 d = (a[0] == '/') - (b[0] == '/');
456 if (*a == 0 && *b == 0)
459 /* Order prefixes first: "/foo" before "/foo/bar" */
468 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
469 d = memcmp(a, b, MIN(j, k));
471 return (d > 0) - (d < 0); /* sign of d */
473 /* Sort "/foo/a" before "/foo/aaa" */
474 d = (j > k) - (j < k); /* sign of (j - k) */
483 bool path_equal(const char *a, const char *b) {
484 return path_compare(a, b) == 0;
487 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
488 return path_equal(a, b) || files_same(a, b, flags) > 0;
491 char* path_join(const char *root, const char *path, const char *rest) {
495 return strjoin(root, endswith(root, "/") ? "" : "/",
496 path[0] == '/' ? path+1 : path,
497 rest ? (endswith(path, "/") ? "" : "/") : NULL,
498 rest && rest[0] == '/' ? rest+1 : rest);
501 rest ? (endswith(path, "/") ? "" : "/") : NULL,
502 rest && rest[0] == '/' ? rest+1 : rest);
505 int find_binary(const char *name, char **ret) {
512 if (access(name, X_OK) < 0)
516 r = path_make_absolute_cwd(name, ret);
525 * Plain getenv, not secure_getenv, because we want
526 * to actually allow the user to pick the binary.
532 last_error = -ENOENT;
535 _cleanup_free_ char *j = NULL, *element = NULL;
537 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
543 if (!path_is_absolute(element))
546 j = strjoin(element, "/", name);
550 if (access(j, X_OK) >= 0) {
554 *ret = path_simplify(j, false);
567 #if 0 /// UNNEEDED by elogind
568 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
569 bool changed = false;
570 const char* const* i;
577 STRV_FOREACH(i, paths) {
581 if (stat(*i, &stats) < 0)
584 u = timespec_load(&stats.st_mtim);
590 log_debug("timestamp of '%s' changed", *i);
592 /* update timestamp */
603 static int binary_is_good(const char *binary) {
604 _cleanup_free_ char *p = NULL, *d = NULL;
607 r = find_binary(binary, &p);
613 /* An fsck that is linked to /bin/true is a non-existent
616 r = readlink_malloc(p, &d);
617 if (r == -EINVAL) /* not a symlink */
622 return !PATH_IN_SET(d, "true"
628 int fsck_exists(const char *fstype) {
633 if (streq(fstype, "auto"))
636 checker = strjoina("fsck.", fstype);
637 return binary_is_good(checker);
640 int mkfs_exists(const char *fstype) {
645 if (streq(fstype, "auto"))
648 mkfs = strjoina("mkfs.", fstype);
649 return binary_is_good(mkfs);
653 char *prefix_root(const char *root, const char *path) {
657 /* If root is passed, prefixes path with it. Otherwise returns
662 /* First, drop duplicate prefixing slashes from the path */
663 while (path[0] == '/' && path[1] == '/')
666 if (empty_or_root(root))
669 l = strlen(root) + 1 + strlen(path) + 1;
677 while (p > n && p[-1] == '/')
687 #if 0 /// UNNEEDED by elogind
688 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
693 * This function is intended to be used in command line
694 * parsers, to handle paths that are passed in. It makes the
695 * path absolute, and reduces it to NULL if omitted or
696 * root (the latter optionally).
698 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
699 * SUCCESS! Hence, do not pass in uninitialized pointers.
707 r = path_make_absolute_cwd(path, &p);
709 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
711 path_simplify(p, false);
712 if (suppress_root && empty_or_root(p))
715 free_and_replace(*arg, p);
721 char* dirname_malloc(const char *path) {
722 char *d, *dir, *dir2;
742 const char *last_path_component(const char *path) {
744 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
757 * Also, the empty string is mapped to itself.
759 * This is different than basename(), which returns "" when a trailing slash is present.
764 l = k = strlen(path);
765 if (l == 0) /* special case — an empty string */
768 while (k > 0 && path[k-1] == '/')
771 if (k == 0) /* the root directory */
774 while (k > 0 && path[k-1] != '/')
780 bool filename_is_valid(const char *p) {
786 if (dot_or_dot_dot(p))
789 e = strchrnul(p, '/');
793 if (e - p > FILENAME_MAX)
799 bool path_is_normalized(const char *p) {
804 if (dot_or_dot_dot(p))
807 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
810 if (strlen(p)+1 > PATH_MAX)
813 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
822 char *file_in_same_dir(const char *path, const char *filename) {
829 /* This removes the last component of path and appends
830 * filename, unless the latter is absolute anyway or the
833 if (path_is_absolute(filename))
834 return strdup(filename);
836 e = strrchr(path, '/');
838 return strdup(filename);
840 k = strlen(filename);
841 ret = new(char, (e + 1 - path) + k + 1);
845 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
849 bool hidden_or_backup_file(const char *filename) {
854 if (filename[0] == '.' ||
855 streq(filename, "lost+found") ||
856 streq(filename, "aquota.user") ||
857 streq(filename, "aquota.group") ||
858 endswith(filename, "~"))
861 p = strrchr(filename, '.');
865 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
866 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
867 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
868 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
869 * string. Specifically: there's now:
871 * The generic suffixes "~" and ".bak" for backup files
872 * The generic prefix "." for hidden files
874 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
875 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
878 return STR_IN_SET(p + 1,
898 #if 0 /// UNNEEDED by elogind
899 bool is_device_path(const char *path) {
901 /* Returns true on paths that refer to a device, either in
902 * sysfs or in /dev */
904 return path_startswith(path, "/dev/") ||
905 path_startswith(path, "/sys/");
908 bool is_deviceallow_pattern(const char *path) {
909 return path_startswith(path, "/dev/") ||
910 startswith(path, "block-") ||
911 startswith(path, "char-");
914 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
918 /* Try to guess if systemd installation is later than the specified version. This
919 * is hacky and likely to yield false negatives, particularly if the installation
920 * is non-standard. False positives should be relatively rare.
923 NULSTR_FOREACH(pattern,
924 /* /lib works for systems without usr-merge, and for systems with a sane
925 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
926 * for Gentoo which does a merge without making /lib a symlink.
928 "lib/systemd/libsystemd-shared-*.so\0"
929 "lib64/systemd/libsystemd-shared-*.so\0"
930 "usr/lib/systemd/libsystemd-shared-*.so\0"
931 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
933 _cleanup_strv_free_ char **names = NULL;
934 _cleanup_free_ char *path = NULL;
937 path = prefix_root(root, pattern);
941 r = glob_extend(&names, path);
947 assert_se(c = endswith(path, "*.so"));
948 *c = '\0'; /* truncate the glob part */
950 STRV_FOREACH(name, names) {
951 /* This is most likely to run only once, hence let's not optimize anything. */
955 t = startswith(*name, path);
959 t2 = endswith(t, ".so");
963 t2[0] = '\0'; /* truncate the suffix */
965 r = safe_atou(t, &version);
967 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
971 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
973 version >= minimal_version ? "OK" : "too old");
974 if (version >= minimal_version)
983 bool dot_or_dot_dot(const char *path) {
996 bool empty_or_root(const char *root) {
998 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
999 * i.e. either / or NULL or the empty string or any equivalent. */
1004 return root[strspn(root, "/")] == 0;