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) {
134 unsigned n_parents = 0;
140 /* Strips the common part, and adds ".." elements as necessary. */
142 if (!path_is_absolute(from_dir) || !path_is_absolute(to_path))
145 f = strdupa(from_dir);
146 t = strdupa(to_path);
148 path_simplify(f, true);
149 path_simplify(t, true);
151 /* Skip the common part. */
160 /* from_dir equals to_path. */
163 /* from_dir is a parent directory of to_path. */
178 if (a != b || memcmp(f, t, a) != 0)
185 /* If we're here, then "from_dir" has one or more elements that need to
186 * be replaced with "..". */
188 /* Count the number of necessary ".." elements. */
194 /* If this includes ".." we can't do a simple series of "..", refuse */
195 if (w == 2 && f[0] == '.' && f[1] == '.')
198 /* Count number of elements */
205 r = new(char, n_parents * 3 + strlen(t) + 1);
209 for (p = r; n_parents > 0; n_parents--)
210 p = mempcpy(p, "../", 3);
215 /* Remove trailing slash */
222 int path_strv_make_absolute_cwd(char **l) {
226 /* Goes through every item in the string list and makes it
227 * absolute. This works in place and won't rollback any
228 * changes on failure. */
233 r = path_make_absolute_cwd(*s, &t);
237 path_simplify(t, false);
238 free_and_replace(*s, t);
245 char **path_strv_resolve(char **l, const char *root) {
254 /* Goes through every item in the string list and canonicalize
255 * the path. This works in place and won't rollback any
256 * changes on failure. */
259 _cleanup_free_ char *orig = NULL;
262 if (!path_is_absolute(*s)) {
269 t = prefix_root(root, orig);
277 r = chase_symlinks(t, root, 0, &u);
295 x = path_startswith(u, root);
297 /* restore the slash if it was lost */
298 if (!startswith(x, "/"))
309 /* canonicalized path goes outside of
310 * prefix, keep the original path instead */
311 free_and_replace(u, orig);
327 char **path_strv_resolve_uniq(char **l, const char *root) {
332 if (!path_strv_resolve(l, root))
338 char *path_simplify(char *path, bool kill_dots) {
340 bool slash = false, ignore_slash = false, absolute;
344 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
345 * if kill_dots is true. Modifies the passed string in-place.
347 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
348 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
349 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
350 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
353 absolute = path_is_absolute(path);
356 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/')) {
361 for (t = path; *f; f++) {
369 if (kill_dots && *f == '.' && IN_SET(f[1], 0, '/'))
374 ignore_slash = false;
382 /* Special rule, if we are talking of the root directory, a trailing slash is good */
383 if (absolute && t == path)
390 char* path_startswith(const char *path, const char *prefix) {
394 /* Returns a pointer to the start of the first component after the parts matched by
396 * - both paths are absolute or both paths are relative,
398 * - each component in prefix in turn matches a component in path at the same position.
399 * An empty string will be returned when the prefix and path are equivalent.
401 * Returns NULL otherwise.
404 if ((path[0] == '/') != (prefix[0] == '/'))
410 path += strspn(path, "/");
411 prefix += strspn(prefix, "/");
419 a = strcspn(path, "/");
420 b = strcspn(prefix, "/");
425 if (memcmp(path, prefix, a) != 0)
433 int path_compare(const char *a, const char *b) {
439 /* A relative path and an abolute path must not compare as equal.
440 * Which one is sorted before the other does not really matter.
441 * Here a relative path is ordered before an absolute path. */
442 d = (a[0] == '/') - (b[0] == '/');
452 if (*a == 0 && *b == 0)
455 /* Order prefixes first: "/foo" before "/foo/bar" */
464 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
465 d = memcmp(a, b, MIN(j, k));
467 return (d > 0) - (d < 0); /* sign of d */
469 /* Sort "/foo/a" before "/foo/aaa" */
470 d = (j > k) - (j < k); /* sign of (j - k) */
479 bool path_equal(const char *a, const char *b) {
480 return path_compare(a, b) == 0;
483 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
484 return path_equal(a, b) || files_same(a, b, flags) > 0;
487 char* path_join(const char *root, const char *path, const char *rest) {
491 return strjoin(root, endswith(root, "/") ? "" : "/",
492 path[0] == '/' ? path+1 : path,
493 rest ? (endswith(path, "/") ? "" : "/") : NULL,
494 rest && rest[0] == '/' ? rest+1 : rest);
497 rest ? (endswith(path, "/") ? "" : "/") : NULL,
498 rest && rest[0] == '/' ? rest+1 : rest);
501 int find_binary(const char *name, char **ret) {
508 if (access(name, X_OK) < 0)
512 r = path_make_absolute_cwd(name, ret);
521 * Plain getenv, not secure_getenv, because we want
522 * to actually allow the user to pick the binary.
528 last_error = -ENOENT;
531 _cleanup_free_ char *j = NULL, *element = NULL;
533 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
539 if (!path_is_absolute(element))
542 j = strjoin(element, "/", name);
546 if (access(j, X_OK) >= 0) {
550 *ret = path_simplify(j, false);
563 #if 0 /// UNNEEDED by elogind
564 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
565 bool changed = false;
566 const char* const* i;
573 STRV_FOREACH(i, paths) {
577 if (stat(*i, &stats) < 0)
580 u = timespec_load(&stats.st_mtim);
586 log_debug("timestamp of '%s' changed", *i);
588 /* update timestamp */
599 static int binary_is_good(const char *binary) {
600 _cleanup_free_ char *p = NULL, *d = NULL;
603 r = find_binary(binary, &p);
609 /* An fsck that is linked to /bin/true is a non-existent
612 r = readlink_malloc(p, &d);
613 if (r == -EINVAL) /* not a symlink */
618 return !PATH_IN_SET(d, "true"
624 int fsck_exists(const char *fstype) {
629 if (streq(fstype, "auto"))
632 checker = strjoina("fsck.", fstype);
633 return binary_is_good(checker);
636 int mkfs_exists(const char *fstype) {
641 if (streq(fstype, "auto"))
644 mkfs = strjoina("mkfs.", fstype);
645 return binary_is_good(mkfs);
649 char *prefix_root(const char *root, const char *path) {
653 /* If root is passed, prefixes path with it. Otherwise returns
658 /* First, drop duplicate prefixing slashes from the path */
659 while (path[0] == '/' && path[1] == '/')
662 if (empty_or_root(root))
665 l = strlen(root) + 1 + strlen(path) + 1;
673 while (p > n && p[-1] == '/')
683 #if 0 /// UNNEEDED by elogind
684 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
689 * This function is intended to be used in command line
690 * parsers, to handle paths that are passed in. It makes the
691 * path absolute, and reduces it to NULL if omitted or
692 * root (the latter optionally).
694 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
695 * SUCCESS! Hence, do not pass in uninitialized pointers.
703 r = path_make_absolute_cwd(path, &p);
705 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
707 path_simplify(p, false);
708 if (suppress_root && empty_or_root(p))
711 free_and_replace(*arg, p);
717 char* dirname_malloc(const char *path) {
718 char *d, *dir, *dir2;
738 const char *last_path_component(const char *path) {
740 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
753 * Also, the empty string is mapped to itself.
755 * This is different than basename(), which returns "" when a trailing slash is present.
760 l = k = strlen(path);
761 if (l == 0) /* special case — an empty string */
764 while (k > 0 && path[k-1] == '/')
767 if (k == 0) /* the root directory */
770 while (k > 0 && path[k-1] != '/')
776 bool filename_is_valid(const char *p) {
782 if (dot_or_dot_dot(p))
785 e = strchrnul(p, '/');
789 if (e - p > FILENAME_MAX)
795 bool path_is_normalized(const char *p) {
800 if (dot_or_dot_dot(p))
803 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
806 if (strlen(p)+1 > PATH_MAX)
809 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
818 char *file_in_same_dir(const char *path, const char *filename) {
825 /* This removes the last component of path and appends
826 * filename, unless the latter is absolute anyway or the
829 if (path_is_absolute(filename))
830 return strdup(filename);
832 e = strrchr(path, '/');
834 return strdup(filename);
836 k = strlen(filename);
837 ret = new(char, (e + 1 - path) + k + 1);
841 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
845 bool hidden_or_backup_file(const char *filename) {
850 if (filename[0] == '.' ||
851 streq(filename, "lost+found") ||
852 streq(filename, "aquota.user") ||
853 streq(filename, "aquota.group") ||
854 endswith(filename, "~"))
857 p = strrchr(filename, '.');
861 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
862 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
863 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
864 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
865 * string. Specifically: there's now:
867 * The generic suffixes "~" and ".bak" for backup files
868 * The generic prefix "." for hidden files
870 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
871 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
874 return STR_IN_SET(p + 1,
894 #if 0 /// UNNEEDED by elogind
895 bool is_device_path(const char *path) {
897 /* Returns true on paths that refer to a device, either in
898 * sysfs or in /dev */
900 return path_startswith(path, "/dev/") ||
901 path_startswith(path, "/sys/");
904 bool is_deviceallow_pattern(const char *path) {
905 return path_startswith(path, "/dev/") ||
906 startswith(path, "block-") ||
907 startswith(path, "char-");
910 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
914 /* Try to guess if systemd installation is later than the specified version. This
915 * is hacky and likely to yield false negatives, particularly if the installation
916 * is non-standard. False positives should be relatively rare.
919 NULSTR_FOREACH(pattern,
920 /* /lib works for systems without usr-merge, and for systems with a sane
921 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
922 * for Gentoo which does a merge without making /lib a symlink.
924 "lib/systemd/libsystemd-shared-*.so\0"
925 "lib64/systemd/libsystemd-shared-*.so\0"
926 "usr/lib/systemd/libsystemd-shared-*.so\0"
927 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
929 _cleanup_strv_free_ char **names = NULL;
930 _cleanup_free_ char *path = NULL;
933 path = prefix_root(root, pattern);
937 r = glob_extend(&names, path);
943 assert_se(c = endswith(path, "*.so"));
944 *c = '\0'; /* truncate the glob part */
946 STRV_FOREACH(name, names) {
947 /* This is most likely to run only once, hence let's not optimize anything. */
951 t = startswith(*name, path);
955 t2 = endswith(t, ".so");
959 t2[0] = '\0'; /* truncate the suffix */
961 r = safe_atou(t, &version);
963 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
967 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
969 version >= minimal_version ? "OK" : "too old");
970 if (version >= minimal_version)
979 bool dot_or_dot_dot(const char *path) {
992 bool empty_or_root(const char *root) {
994 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
995 * i.e. either / or NULL or the empty string or any equivalent. */
1000 return root[strspn(root, "/")] == 0;