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_kill_slashes(r);
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_kill_slashes(r);
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_kill_slashes(t);
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_kill_slashes(char *path) {
346 /* Removes redundant inner and trailing slashes. Modifies the
347 * passed string in-place.
349 * ///foo///bar/ becomes /foo/bar
352 for (f = path, t = path; *f; f++) {
367 /* Special rule, if we are talking of the root directory, a
368 trailing slash is good */
370 if (t == path && slash)
377 char* path_startswith(const char *path, const char *prefix) {
381 /* Returns a pointer to the start of the first component after the parts matched by
383 * - both paths are absolute or both paths are relative,
385 * - each component in prefix in turn matches a component in path at the same position.
386 * An empty string will be returned when the prefix and path are equivalent.
388 * Returns NULL otherwise.
391 if ((path[0] == '/') != (prefix[0] == '/'))
397 path += strspn(path, "/");
398 prefix += strspn(prefix, "/");
406 a = strcspn(path, "/");
407 b = strcspn(prefix, "/");
412 if (memcmp(path, prefix, a) != 0)
420 int path_compare(const char *a, const char *b) {
426 /* A relative path and an abolute path must not compare as equal.
427 * Which one is sorted before the other does not really matter.
428 * Here a relative path is ordered before an absolute path. */
429 d = (a[0] == '/') - (b[0] == '/');
439 if (*a == 0 && *b == 0)
442 /* Order prefixes first: "/foo" before "/foo/bar" */
451 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
452 d = memcmp(a, b, MIN(j, k));
454 return (d > 0) - (d < 0); /* sign of d */
456 /* Sort "/foo/a" before "/foo/aaa" */
457 d = (j > k) - (j < k); /* sign of (j - k) */
466 bool path_equal(const char *a, const char *b) {
467 return path_compare(a, b) == 0;
470 bool path_equal_or_files_same(const char *a, const char *b, int flags) {
471 return path_equal(a, b) || files_same(a, b, flags) > 0;
474 char* path_join(const char *root, const char *path, const char *rest) {
478 return strjoin(root, endswith(root, "/") ? "" : "/",
479 path[0] == '/' ? path+1 : path,
480 rest ? (endswith(path, "/") ? "" : "/") : NULL,
481 rest && rest[0] == '/' ? rest+1 : rest);
484 rest ? (endswith(path, "/") ? "" : "/") : NULL,
485 rest && rest[0] == '/' ? rest+1 : rest);
488 int find_binary(const char *name, char **ret) {
495 if (access(name, X_OK) < 0)
499 r = path_make_absolute_cwd(name, ret);
508 * Plain getenv, not secure_getenv, because we want
509 * to actually allow the user to pick the binary.
515 last_error = -ENOENT;
518 _cleanup_free_ char *j = NULL, *element = NULL;
520 r = extract_first_word(&p, &element, ":", EXTRACT_RELAX|EXTRACT_DONT_COALESCE_SEPARATORS);
526 if (!path_is_absolute(element))
529 j = strjoin(element, "/", name);
533 if (access(j, X_OK) >= 0) {
537 *ret = path_kill_slashes(j);
550 #if 0 /// UNNEEDED by elogind
551 bool paths_check_timestamp(const char* const* paths, usec_t *timestamp, bool update) {
552 bool changed = false;
553 const char* const* i;
560 STRV_FOREACH(i, paths) {
564 if (stat(*i, &stats) < 0)
567 u = timespec_load(&stats.st_mtim);
573 log_debug("timestamp of '%s' changed", *i);
575 /* update timestamp */
586 static int binary_is_good(const char *binary) {
587 _cleanup_free_ char *p = NULL, *d = NULL;
590 r = find_binary(binary, &p);
596 /* An fsck that is linked to /bin/true is a non-existent
599 r = readlink_malloc(p, &d);
600 if (r == -EINVAL) /* not a symlink */
605 return !PATH_IN_SET(d, "true"
611 int fsck_exists(const char *fstype) {
616 if (streq(fstype, "auto"))
619 checker = strjoina("fsck.", fstype);
620 return binary_is_good(checker);
623 int mkfs_exists(const char *fstype) {
628 if (streq(fstype, "auto"))
631 mkfs = strjoina("mkfs.", fstype);
632 return binary_is_good(mkfs);
636 char *prefix_root(const char *root, const char *path) {
640 /* If root is passed, prefixes path with it. Otherwise returns
645 /* First, drop duplicate prefixing slashes from the path */
646 while (path[0] == '/' && path[1] == '/')
649 if (isempty(root) || path_equal(root, "/"))
652 l = strlen(root) + 1 + strlen(path) + 1;
660 while (p > n && p[-1] == '/')
670 #if 0 /// UNNEEDED by elogind
671 int parse_path_argument_and_warn(const char *path, bool suppress_root, char **arg) {
676 * This function is intended to be used in command line
677 * parsers, to handle paths that are passed in. It makes the
678 * path absolute, and reduces it to NULL if omitted or
679 * root (the latter optionally).
681 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
682 * SUCCESS! Hence, do not pass in uninitialized pointers.
690 r = path_make_absolute_cwd(path, &p);
692 return log_error_errno(r, "Failed to parse path \"%s\" and make it absolute: %m", path);
694 path_kill_slashes(p);
695 if (suppress_root && path_equal(p, "/"))
704 char* dirname_malloc(const char *path) {
705 char *d, *dir, *dir2;
725 const char *last_path_component(const char *path) {
726 /* Finds the last component of the path, preserving the
727 * optional trailing slash that signifies a directory.
734 * This is different than basename, which returns "" when
735 * a trailing slash is present.
740 l = k = strlen(path);
741 if (l == 0) /* special case — an empty string */
744 while (k > 0 && path[k-1] == '/')
747 if (k == 0) /* the root directory */
750 while (k > 0 && path[k-1] != '/')
756 bool filename_is_valid(const char *p) {
762 if (dot_or_dot_dot(p))
765 e = strchrnul(p, '/');
769 if (e - p > FILENAME_MAX)
775 bool path_is_normalized(const char *p) {
780 if (dot_or_dot_dot(p))
783 if (startswith(p, "../") || endswith(p, "/..") || strstr(p, "/../"))
786 if (strlen(p)+1 > PATH_MAX)
789 if (startswith(p, "./") || endswith(p, "/.") || strstr(p, "/./"))
798 char *file_in_same_dir(const char *path, const char *filename) {
805 /* This removes the last component of path and appends
806 * filename, unless the latter is absolute anyway or the
809 if (path_is_absolute(filename))
810 return strdup(filename);
812 e = strrchr(path, '/');
814 return strdup(filename);
816 k = strlen(filename);
817 ret = new(char, (e + 1 - path) + k + 1);
821 memcpy(mempcpy(ret, path, e + 1 - path), filename, k + 1);
825 bool hidden_or_backup_file(const char *filename) {
830 if (filename[0] == '.' ||
831 streq(filename, "lost+found") ||
832 streq(filename, "aquota.user") ||
833 streq(filename, "aquota.group") ||
834 endswith(filename, "~"))
837 p = strrchr(filename, '.');
841 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
842 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
843 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
844 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
845 * string. Specifically: there's now:
847 * The generic suffixes "~" and ".bak" for backup files
848 * The generic prefix "." for hidden files
850 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
851 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
854 return STR_IN_SET(p + 1,
874 #if 0 /// UNNEEDED by elogind
875 bool is_device_path(const char *path) {
877 /* Returns true on paths that refer to a device, either in
878 * sysfs or in /dev */
880 return path_startswith(path, "/dev/") ||
881 path_startswith(path, "/sys/");
884 bool is_deviceallow_pattern(const char *path) {
885 return path_startswith(path, "/dev/") ||
886 startswith(path, "block-") ||
887 startswith(path, "char-");
890 int systemd_installation_has_version(const char *root, unsigned minimal_version) {
894 /* Try to guess if systemd installation is later than the specified version. This
895 * is hacky and likely to yield false negatives, particularly if the installation
896 * is non-standard. False positives should be relatively rare.
899 NULSTR_FOREACH(pattern,
900 /* /lib works for systems without usr-merge, and for systems with a sane
901 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
902 * for Gentoo which does a merge without making /lib a symlink.
904 "lib/systemd/libsystemd-shared-*.so\0"
905 "lib64/systemd/libsystemd-shared-*.so\0"
906 "usr/lib/systemd/libsystemd-shared-*.so\0"
907 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
909 _cleanup_strv_free_ char **names = NULL;
910 _cleanup_free_ char *path = NULL;
913 path = prefix_root(root, pattern);
917 r = glob_extend(&names, path);
923 assert_se((c = endswith(path, "*.so")));
924 *c = '\0'; /* truncate the glob part */
926 STRV_FOREACH(name, names) {
927 /* This is most likely to run only once, hence let's not optimize anything. */
931 t = startswith(*name, path);
935 t2 = endswith(t, ".so");
939 t2[0] = '\0'; /* truncate the suffix */
941 r = safe_atou(t, &version);
943 log_debug_errno(r, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name);
947 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
949 version >= minimal_version ? "OK" : "too old");
950 if (version >= minimal_version)
959 bool dot_or_dot_dot(const char *path) {