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 "nulstr-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "stat-util.h"
28 #include "string-util.h"
30 #include "time-util.h"
33 bool path_is_absolute(const char *p
) {
37 bool is_path(const char *p
) {
38 return !!strchr(p
, '/');
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
);
77 int safe_getcwd(char **ret
) {
80 cwd
= get_current_dir_name();
82 return negative_errno();
84 /* Let's make sure the directory is really absolute, to protect us from the logic behind
95 int path_make_absolute_cwd(const char *p
, char **ret
) {
102 /* Similar to path_make_absolute(), but prefixes with the
103 * current working directory. */
105 if (path_is_absolute(p
))
108 _cleanup_free_
char *cwd
= NULL
;
110 r
= safe_getcwd(&cwd
);
114 c
= path_join(cwd
, p
);
123 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
125 unsigned n_parents
= 0;
131 /* Strips the common part, and adds ".." elements as necessary. */
133 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
136 f
= strdupa(from_dir
);
137 t
= strdupa(to_path
);
139 path_simplify(f
, true);
140 path_simplify(t
, true);
142 /* Skip the common part. */
151 /* from_dir equals to_path. */
154 /* from_dir is a parent directory of to_path. */
169 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
176 /* If we're here, then "from_dir" has one or more elements that need to
177 * be replaced with "..". */
179 /* Count the number of necessary ".." elements. */
185 /* If this includes ".." we can't do a simple series of "..", refuse */
186 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
189 /* Count number of elements */
196 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
200 for (p
= r
; n_parents
> 0; n_parents
--)
201 p
= mempcpy(p
, "../", 3);
206 /* Remove trailing slash */
213 int path_strv_make_absolute_cwd(char **l
) {
217 /* Goes through every item in the string list and makes it
218 * absolute. This works in place and won't rollback any
219 * changes on failure. */
224 r
= path_make_absolute_cwd(*s
, &t
);
228 path_simplify(t
, false);
229 free_and_replace(*s
, t
);
235 char **path_strv_resolve(char **l
, const char *root
) {
244 /* Goes through every item in the string list and canonicalize
245 * the path. This works in place and won't rollback any
246 * changes on failure. */
249 _cleanup_free_
char *orig
= NULL
;
252 if (!path_is_absolute(*s
)) {
259 t
= prefix_root(root
, orig
);
267 r
= chase_symlinks(t
, root
, 0, &u
);
285 x
= path_startswith(u
, root
);
287 /* restore the slash if it was lost */
288 if (!startswith(x
, "/"))
299 /* canonicalized path goes outside of
300 * prefix, keep the original path instead */
301 free_and_replace(u
, orig
);
317 char **path_strv_resolve_uniq(char **l
, const char *root
) {
322 if (!path_strv_resolve(l
, root
))
328 char *path_simplify(char *path
, bool kill_dots
) {
330 bool slash
= false, ignore_slash
= false, absolute
;
334 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
335 * if kill_dots is true. Modifies the passed string in-place.
337 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
338 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
339 * .//./foo//./bar/. becomes ././foo/./bar/. (if kill_dots is false)
340 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
346 absolute
= path_is_absolute(path
);
349 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
354 for (t
= path
; *f
; f
++) {
362 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
367 ignore_slash
= false;
375 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
376 * or "." for the current directory */
388 char* path_startswith(const char *path
, const char *prefix
) {
392 /* Returns a pointer to the start of the first component after the parts matched by
394 * - both paths are absolute or both paths are relative,
396 * - each component in prefix in turn matches a component in path at the same position.
397 * An empty string will be returned when the prefix and path are equivalent.
399 * Returns NULL otherwise.
402 if ((path
[0] == '/') != (prefix
[0] == '/'))
408 path
+= strspn(path
, "/");
409 prefix
+= strspn(prefix
, "/");
417 a
= strcspn(path
, "/");
418 b
= strcspn(prefix
, "/");
423 if (memcmp(path
, prefix
, a
) != 0)
431 int path_compare(const char *a
, const char *b
) {
437 /* A relative path and an absolute path must not compare as equal.
438 * Which one is sorted before the other does not really matter.
439 * Here a relative path is ordered before an absolute path. */
440 d
= (a
[0] == '/') - (b
[0] == '/');
450 if (*a
== 0 && *b
== 0)
453 /* Order prefixes first: "/foo" before "/foo/bar" */
462 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
463 d
= memcmp(a
, b
, MIN(j
, k
));
465 return (d
> 0) - (d
< 0); /* sign of d */
467 /* Sort "/foo/a" before "/foo/aaa" */
468 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
477 bool path_equal(const char *a
, const char *b
) {
478 return path_compare(a
, b
) == 0;
481 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
482 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
485 char* path_join_internal(const char *first
, ...) {
492 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
493 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
494 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
497 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
502 * path_join("foo", "bar") → "foo/bar"
503 * path_join("foo/", "bar") → "foo/bar"
504 * path_join("", "foo", "", "bar", "") → "foo/bar" */
506 sz
= strlen_ptr(first
);
508 while ((p
= va_arg(ap
, char*)) != (const char*) -1)
513 joined
= new(char, sz
+ 1);
517 if (!isempty(first
)) {
518 q
= stpcpy(joined
, first
);
519 slash
= endswith(first
, "/");
521 /* Skip empty items */
524 slash
= true; /* no need to generate a slash anymore */
528 while ((p
= va_arg(ap
, char*)) != (const char*) -1) {
532 if (!slash
&& p
[0] != '/')
536 slash
= endswith(p
, "/");
543 int find_binary(const char *name
, char **ret
) {
550 if (access(name
, X_OK
) < 0)
554 r
= path_make_absolute_cwd(name
, ret
);
563 * Plain getenv, not secure_getenv, because we want
564 * to actually allow the user to pick the binary.
570 last_error
= -ENOENT
;
573 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
575 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
581 if (!path_is_absolute(element
))
584 j
= strjoin(element
, "/", name
);
588 if (access(j
, X_OK
) >= 0) {
592 *ret
= path_simplify(j
, false);
605 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
606 bool changed
= false;
607 const char* const* i
;
614 STRV_FOREACH(i
, paths
) {
618 if (stat(*i
, &stats
) < 0)
621 u
= timespec_load(&stats
.st_mtim
);
627 log_debug("timestamp of '%s' changed", *i
);
629 /* update timestamp */
640 static int binary_is_good(const char *binary
) {
641 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
644 r
= find_binary(binary
, &p
);
650 /* An fsck that is linked to /bin/true is a non-existent
653 r
= readlink_malloc(p
, &d
);
654 if (r
== -EINVAL
) /* not a symlink */
659 return !PATH_IN_SET(d
, "true"
665 int fsck_exists(const char *fstype
) {
670 if (streq(fstype
, "auto"))
673 checker
= strjoina("fsck.", fstype
);
674 return binary_is_good(checker
);
677 int mkfs_exists(const char *fstype
) {
682 if (streq(fstype
, "auto"))
685 mkfs
= strjoina("mkfs.", fstype
);
686 return binary_is_good(mkfs
);
689 char *prefix_root(const char *root
, const char *path
) {
693 /* If root is passed, prefixes path with it. Otherwise returns
698 /* First, drop duplicate prefixing slashes from the path */
699 while (path
[0] == '/' && path
[1] == '/')
702 if (empty_or_root(root
))
705 l
= strlen(root
) + 1 + strlen(path
) + 1;
713 while (p
> n
&& p
[-1] == '/')
723 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
728 * This function is intended to be used in command line
729 * parsers, to handle paths that are passed in. It makes the
730 * path absolute, and reduces it to NULL if omitted or
731 * root (the latter optionally).
733 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
734 * SUCCESS! Hence, do not pass in uninitialized pointers.
742 r
= path_make_absolute_cwd(path
, &p
);
744 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
746 path_simplify(p
, false);
747 if (suppress_root
&& empty_or_root(p
))
750 free_and_replace(*arg
, p
);
755 char* dirname_malloc(const char *path
) {
756 char *d
, *dir
, *dir2
;
776 const char *last_path_component(const char *path
) {
778 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
791 * Also, the empty string is mapped to itself.
793 * This is different than basename(), which returns "" when a trailing slash is present.
801 l
= k
= strlen(path
);
802 if (l
== 0) /* special case — an empty string */
805 while (k
> 0 && path
[k
-1] == '/')
808 if (k
== 0) /* the root directory */
811 while (k
> 0 && path
[k
-1] != '/')
817 int path_extract_filename(const char *p
, char **ret
) {
818 _cleanup_free_
char *a
= NULL
;
819 const char *c
, *e
= NULL
, *q
;
821 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
822 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
827 c
= last_path_component(p
);
829 for (q
= c
; *q
!= 0; q
++)
833 if (!e
) /* no valid character? */
836 a
= strndup(c
, e
- c
);
840 if (!filename_is_valid(a
))
848 bool filename_is_valid(const char *p
) {
854 if (dot_or_dot_dot(p
))
857 e
= strchrnul(p
, '/');
861 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
867 bool path_is_valid(const char *p
) {
872 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
878 bool path_is_normalized(const char *p
) {
880 if (!path_is_valid(p
))
883 if (dot_or_dot_dot(p
))
886 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
889 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
898 char *file_in_same_dir(const char *path
, const char *filename
) {
905 /* This removes the last component of path and appends
906 * filename, unless the latter is absolute anyway or the
909 if (path_is_absolute(filename
))
910 return strdup(filename
);
912 e
= strrchr(path
, '/');
914 return strdup(filename
);
916 k
= strlen(filename
);
917 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
921 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
925 bool hidden_or_backup_file(const char *filename
) {
930 if (filename
[0] == '.' ||
931 streq(filename
, "lost+found") ||
932 streq(filename
, "aquota.user") ||
933 streq(filename
, "aquota.group") ||
934 endswith(filename
, "~"))
937 p
= strrchr(filename
, '.');
941 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
942 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
943 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
944 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
945 * string. Specifically: there's now:
947 * The generic suffixes "~" and ".bak" for backup files
948 * The generic prefix "." for hidden files
950 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
951 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
954 return STR_IN_SET(p
+ 1,
974 bool is_device_path(const char *path
) {
976 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
978 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
981 bool valid_device_node_path(const char *path
) {
983 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
984 * actual device node. */
986 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
989 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
992 return path_is_normalized(path
);
995 bool valid_device_allow_pattern(const char *path
) {
998 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1001 if (STARTSWITH_SET(path
, "block-", "char-"))
1004 return valid_device_node_path(path
);
1007 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1008 const char *pattern
;
1011 /* Try to guess if systemd installation is later than the specified version. This
1012 * is hacky and likely to yield false negatives, particularly if the installation
1013 * is non-standard. False positives should be relatively rare.
1016 NULSTR_FOREACH(pattern
,
1017 /* /lib works for systems without usr-merge, and for systems with a sane
1018 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1019 * for Gentoo which does a merge without making /lib a symlink.
1021 "lib/systemd/libsystemd-shared-*.so\0"
1022 "lib64/systemd/libsystemd-shared-*.so\0"
1023 "usr/lib/systemd/libsystemd-shared-*.so\0"
1024 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1026 _cleanup_strv_free_
char **names
= NULL
;
1027 _cleanup_free_
char *path
= NULL
;
1030 path
= prefix_root(root
, pattern
);
1034 r
= glob_extend(&names
, path
);
1040 assert_se(c
= endswith(path
, "*.so"));
1041 *c
= '\0'; /* truncate the glob part */
1043 STRV_FOREACH(name
, names
) {
1044 /* This is most likely to run only once, hence let's not optimize anything. */
1048 t
= startswith(*name
, path
);
1052 t2
= endswith(t
, ".so");
1056 t2
[0] = '\0'; /* truncate the suffix */
1058 r
= safe_atou(t
, &version
);
1060 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1064 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1066 version
>= minimal_version
? "OK" : "too old");
1067 if (version
>= minimal_version
)
1075 bool dot_or_dot_dot(const char *path
) {
1085 return path
[2] == 0;
1088 bool empty_or_root(const char *root
) {
1090 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1091 * i.e. either / or NULL or the empty string or any equivalent. */
1096 return root
[strspn(root
, "/")] == 0;
1099 int path_simplify_and_warn(
1103 const char *filename
,
1105 const char *lvalue
) {
1107 bool fatal
= flag
& PATH_CHECK_FATAL
;
1109 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
1111 if (!utf8_is_valid(path
))
1112 return log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
1114 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
1117 absolute
= path_is_absolute(path
);
1119 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
))
1120 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1121 "%s= path is not absolute%s: %s",
1122 lvalue
, fatal
? "" : ", ignoring", path
);
1124 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
))
1125 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1126 "%s= path is absolute%s: %s",
1127 lvalue
, fatal
? "" : ", ignoring", path
);
1130 path_simplify(path
, true);
1132 if (!path_is_valid(path
))
1133 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1134 "%s= path has invalid length (%zu bytes)%s.",
1135 lvalue
, strlen(path
), fatal
? "" : ", ignoring");
1137 if (!path_is_normalized(path
))
1138 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1139 "%s= path is not normalized%s: %s",
1140 lvalue
, fatal
? "" : ", ignoring", path
);