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 "parse-util.h"
25 #include "path-util.h"
26 #include "stat-util.h"
27 #include "string-util.h"
29 #include "time-util.h"
32 bool path_is_absolute(const char *p
) {
36 bool is_path(const char *p
) {
37 return !!strchr(p
, '/');
40 int path_split_and_make_absolute(const char *p
, char ***ret
) {
47 l
= strv_split(p
, ":");
51 r
= path_strv_make_absolute_cwd(l
);
61 char *path_make_absolute(const char *p
, const char *prefix
) {
64 /* Makes every item in the list an absolute path by prepending
65 * the prefix, if specified and necessary */
67 if (path_is_absolute(p
) || isempty(prefix
))
70 if (endswith(prefix
, "/"))
71 return strjoin(prefix
, p
);
73 return strjoin(prefix
, "/", p
);
76 int safe_getcwd(char **ret
) {
79 cwd
= get_current_dir_name();
81 return negative_errno();
83 /* Let's make sure the directory is really absolute, to protect us from the logic behind
94 int path_make_absolute_cwd(const char *p
, char **ret
) {
101 /* Similar to path_make_absolute(), but prefixes with the
102 * current working directory. */
104 if (path_is_absolute(p
))
107 _cleanup_free_
char *cwd
= NULL
;
109 r
= safe_getcwd(&cwd
);
113 c
= path_join(cwd
, p
);
122 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
124 unsigned n_parents
= 0;
130 /* Strips the common part, and adds ".." elements as necessary. */
132 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
135 f
= strdupa(from_dir
);
136 t
= strdupa(to_path
);
138 path_simplify(f
, true);
139 path_simplify(t
, true);
141 /* Skip the common part. */
150 /* from_dir equals to_path. */
153 /* from_dir is a parent directory of to_path. */
168 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
175 /* If we're here, then "from_dir" has one or more elements that need to
176 * be replaced with "..". */
178 /* Count the number of necessary ".." elements. */
184 /* If this includes ".." we can't do a simple series of "..", refuse */
185 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
188 /* Count number of elements */
195 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
199 for (p
= r
; n_parents
> 0; n_parents
--)
200 p
= mempcpy(p
, "../", 3);
205 /* Remove trailing slash */
212 int path_strv_make_absolute_cwd(char **l
) {
216 /* Goes through every item in the string list and makes it
217 * absolute. This works in place and won't rollback any
218 * changes on failure. */
223 r
= path_make_absolute_cwd(*s
, &t
);
227 path_simplify(t
, false);
228 free_and_replace(*s
, t
);
234 char **path_strv_resolve(char **l
, const char *root
) {
243 /* Goes through every item in the string list and canonicalize
244 * the path. This works in place and won't rollback any
245 * changes on failure. */
248 _cleanup_free_
char *orig
= NULL
;
251 if (!path_is_absolute(*s
)) {
258 t
= prefix_root(root
, orig
);
266 r
= chase_symlinks(t
, root
, 0, &u
);
284 x
= path_startswith(u
, root
);
286 /* restore the slash if it was lost */
287 if (!startswith(x
, "/"))
298 /* canonicalized path goes outside of
299 * prefix, keep the original path instead */
300 free_and_replace(u
, orig
);
316 char **path_strv_resolve_uniq(char **l
, const char *root
) {
321 if (!path_strv_resolve(l
, root
))
327 char *path_simplify(char *path
, bool kill_dots
) {
329 bool slash
= false, ignore_slash
= false, absolute
;
333 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
334 * if kill_dots is true. Modifies the passed string in-place.
336 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
337 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
338 * .//./foo//./bar/. becomes ././foo/./bar/. (if kill_dots is false)
339 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
345 absolute
= path_is_absolute(path
);
348 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
353 for (t
= path
; *f
; f
++) {
361 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
366 ignore_slash
= false;
374 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
375 * or "." for the current directory */
387 char* path_startswith(const char *path
, const char *prefix
) {
391 /* Returns a pointer to the start of the first component after the parts matched by
393 * - both paths are absolute or both paths are relative,
395 * - each component in prefix in turn matches a component in path at the same position.
396 * An empty string will be returned when the prefix and path are equivalent.
398 * Returns NULL otherwise.
401 if ((path
[0] == '/') != (prefix
[0] == '/'))
407 path
+= strspn(path
, "/");
408 prefix
+= strspn(prefix
, "/");
416 a
= strcspn(path
, "/");
417 b
= strcspn(prefix
, "/");
422 if (memcmp(path
, prefix
, a
) != 0)
430 int path_compare(const char *a
, const char *b
) {
436 /* A relative path and an absolute path must not compare as equal.
437 * Which one is sorted before the other does not really matter.
438 * Here a relative path is ordered before an absolute path. */
439 d
= (a
[0] == '/') - (b
[0] == '/');
449 if (*a
== 0 && *b
== 0)
452 /* Order prefixes first: "/foo" before "/foo/bar" */
461 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
462 d
= memcmp(a
, b
, MIN(j
, k
));
464 return (d
> 0) - (d
< 0); /* sign of d */
466 /* Sort "/foo/a" before "/foo/aaa" */
467 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
476 bool path_equal(const char *a
, const char *b
) {
477 return path_compare(a
, b
) == 0;
480 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
481 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
484 char* path_join_internal(const char *first
, ...) {
491 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
492 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
493 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
496 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
501 * path_join("foo", "bar") → "foo/bar"
502 * path_join("foo/", "bar") → "foo/bar"
503 * path_join("", "foo", "", "bar", "") → "foo/bar" */
505 sz
= strlen_ptr(first
);
507 while ((p
= va_arg(ap
, char*)) != (const char*) -1)
512 joined
= new(char, sz
+ 1);
516 if (!isempty(first
)) {
517 q
= stpcpy(joined
, first
);
518 slash
= endswith(first
, "/");
520 /* Skip empty items */
523 slash
= true; /* no need to generate a slash anymore */
527 while ((p
= va_arg(ap
, char*)) != (const char*) -1) {
531 if (!slash
&& p
[0] != '/')
535 slash
= endswith(p
, "/");
542 int find_binary(const char *name
, char **ret
) {
549 if (access(name
, X_OK
) < 0)
553 r
= path_make_absolute_cwd(name
, ret
);
562 * Plain getenv, not secure_getenv, because we want
563 * to actually allow the user to pick the binary.
569 last_error
= -ENOENT
;
572 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
574 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
580 if (!path_is_absolute(element
))
583 j
= strjoin(element
, "/", name
);
587 if (access(j
, X_OK
) >= 0) {
591 *ret
= path_simplify(j
, false);
604 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
605 bool changed
= false;
606 const char* const* i
;
613 STRV_FOREACH(i
, paths
) {
617 if (stat(*i
, &stats
) < 0)
620 u
= timespec_load(&stats
.st_mtim
);
626 log_debug("timestamp of '%s' changed", *i
);
628 /* update timestamp */
639 static int binary_is_good(const char *binary
) {
640 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
643 r
= find_binary(binary
, &p
);
649 /* An fsck that is linked to /bin/true is a non-existent
652 r
= readlink_malloc(p
, &d
);
653 if (r
== -EINVAL
) /* not a symlink */
658 return !PATH_IN_SET(d
, "true"
664 int fsck_exists(const char *fstype
) {
669 if (streq(fstype
, "auto"))
672 checker
= strjoina("fsck.", fstype
);
673 return binary_is_good(checker
);
676 int mkfs_exists(const char *fstype
) {
681 if (streq(fstype
, "auto"))
684 mkfs
= strjoina("mkfs.", fstype
);
685 return binary_is_good(mkfs
);
688 char *prefix_root(const char *root
, const char *path
) {
692 /* If root is passed, prefixes path with it. Otherwise returns
697 /* First, drop duplicate prefixing slashes from the path */
698 while (path
[0] == '/' && path
[1] == '/')
701 if (empty_or_root(root
))
704 l
= strlen(root
) + 1 + strlen(path
) + 1;
712 while (p
> n
&& p
[-1] == '/')
722 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
727 * This function is intended to be used in command line
728 * parsers, to handle paths that are passed in. It makes the
729 * path absolute, and reduces it to NULL if omitted or
730 * root (the latter optionally).
732 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
733 * SUCCESS! Hence, do not pass in uninitialized pointers.
741 r
= path_make_absolute_cwd(path
, &p
);
743 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
745 path_simplify(p
, false);
746 if (suppress_root
&& empty_or_root(p
))
749 free_and_replace(*arg
, p
);
754 char* dirname_malloc(const char *path
) {
755 char *d
, *dir
, *dir2
;
775 const char *last_path_component(const char *path
) {
777 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
790 * Also, the empty string is mapped to itself.
792 * This is different than basename(), which returns "" when a trailing slash is present.
800 l
= k
= strlen(path
);
801 if (l
== 0) /* special case — an empty string */
804 while (k
> 0 && path
[k
-1] == '/')
807 if (k
== 0) /* the root directory */
810 while (k
> 0 && path
[k
-1] != '/')
816 int path_extract_filename(const char *p
, char **ret
) {
817 _cleanup_free_
char *a
= NULL
;
818 const char *c
, *e
= NULL
, *q
;
820 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
821 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
826 c
= last_path_component(p
);
828 for (q
= c
; *q
!= 0; q
++)
832 if (!e
) /* no valid character? */
835 a
= strndup(c
, e
- c
);
839 if (!filename_is_valid(a
))
847 bool filename_is_valid(const char *p
) {
853 if (dot_or_dot_dot(p
))
856 e
= strchrnul(p
, '/');
860 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
866 bool path_is_valid(const char *p
) {
871 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
877 bool path_is_normalized(const char *p
) {
879 if (!path_is_valid(p
))
882 if (dot_or_dot_dot(p
))
885 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
888 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
897 char *file_in_same_dir(const char *path
, const char *filename
) {
904 /* This removes the last component of path and appends
905 * filename, unless the latter is absolute anyway or the
908 if (path_is_absolute(filename
))
909 return strdup(filename
);
911 e
= strrchr(path
, '/');
913 return strdup(filename
);
915 k
= strlen(filename
);
916 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
920 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
924 bool hidden_or_backup_file(const char *filename
) {
929 if (filename
[0] == '.' ||
930 streq(filename
, "lost+found") ||
931 streq(filename
, "aquota.user") ||
932 streq(filename
, "aquota.group") ||
933 endswith(filename
, "~"))
936 p
= strrchr(filename
, '.');
940 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
941 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
942 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
943 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
944 * string. Specifically: there's now:
946 * The generic suffixes "~" and ".bak" for backup files
947 * The generic prefix "." for hidden files
949 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
950 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
953 return STR_IN_SET(p
+ 1,
973 bool is_device_path(const char *path
) {
975 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
977 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
980 bool valid_device_node_path(const char *path
) {
982 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
983 * actual device node. */
985 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
988 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
991 return path_is_normalized(path
);
994 bool valid_device_allow_pattern(const char *path
) {
997 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1000 if (STARTSWITH_SET(path
, "block-", "char-"))
1003 return valid_device_node_path(path
);
1006 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1007 const char *pattern
;
1010 /* Try to guess if systemd installation is later than the specified version. This
1011 * is hacky and likely to yield false negatives, particularly if the installation
1012 * is non-standard. False positives should be relatively rare.
1015 NULSTR_FOREACH(pattern
,
1016 /* /lib works for systems without usr-merge, and for systems with a sane
1017 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1018 * for Gentoo which does a merge without making /lib a symlink.
1020 "lib/systemd/libsystemd-shared-*.so\0"
1021 "lib64/systemd/libsystemd-shared-*.so\0"
1022 "usr/lib/systemd/libsystemd-shared-*.so\0"
1023 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1025 _cleanup_strv_free_
char **names
= NULL
;
1026 _cleanup_free_
char *path
= NULL
;
1029 path
= prefix_root(root
, pattern
);
1033 r
= glob_extend(&names
, path
);
1039 assert_se(c
= endswith(path
, "*.so"));
1040 *c
= '\0'; /* truncate the glob part */
1042 STRV_FOREACH(name
, names
) {
1043 /* This is most likely to run only once, hence let's not optimize anything. */
1047 t
= startswith(*name
, path
);
1051 t2
= endswith(t
, ".so");
1055 t2
[0] = '\0'; /* truncate the suffix */
1057 r
= safe_atou(t
, &version
);
1059 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1063 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1065 version
>= minimal_version
? "OK" : "too old");
1066 if (version
>= minimal_version
)
1074 bool dot_or_dot_dot(const char *path
) {
1084 return path
[2] == 0;
1087 bool empty_or_root(const char *root
) {
1089 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1090 * i.e. either / or NULL or the empty string or any equivalent. */
1095 return root
[strspn(root
, "/")] == 0;
1098 int path_simplify_and_warn(
1102 const char *filename
,
1104 const char *lvalue
) {
1106 bool absolute
, fatal
= flag
& PATH_CHECK_FATAL
;
1108 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
1110 if (!utf8_is_valid(path
)) {
1111 log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
1115 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
1116 absolute
= path_is_absolute(path
);
1118 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
)) {
1119 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1120 "%s= path is not absolute%s: %s",
1121 lvalue
, fatal
? "" : ", ignoring", path
);
1125 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
)) {
1126 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1127 "%s= path is absolute%s: %s",
1128 lvalue
, fatal
? "" : ", ignoring", path
);
1133 path_simplify(path
, true);
1135 if (!path_is_normalized(path
)) {
1136 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1137 "%s= path is not normalized%s: %s",
1138 lvalue
, fatal
? "" : ", ignoring", path
);