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 return path_join(prefix
, p
);
74 int safe_getcwd(char **ret
) {
77 cwd
= get_current_dir_name();
79 return negative_errno();
81 /* Let's make sure the directory is really absolute, to protect us from the logic behind
92 int path_make_absolute_cwd(const char *p
, char **ret
) {
99 /* Similar to path_make_absolute(), but prefixes with the
100 * current working directory. */
102 if (path_is_absolute(p
))
105 _cleanup_free_
char *cwd
= NULL
;
107 r
= safe_getcwd(&cwd
);
111 c
= path_join(cwd
, p
);
120 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
122 unsigned n_parents
= 0;
128 /* Strips the common part, and adds ".." elements as necessary. */
130 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
133 f
= strdupa(from_dir
);
134 t
= strdupa(to_path
);
136 path_simplify(f
, true);
137 path_simplify(t
, true);
139 /* Skip the common part. */
148 /* from_dir equals to_path. */
151 /* from_dir is a parent directory of to_path. */
166 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
173 /* If we're here, then "from_dir" has one or more elements that need to
174 * be replaced with "..". */
176 /* Count the number of necessary ".." elements. */
182 /* If this includes ".." we can't do a simple series of "..", refuse */
183 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
186 /* Count number of elements */
193 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
197 for (p
= r
; n_parents
> 0; n_parents
--)
198 p
= mempcpy(p
, "../", 3);
203 /* Remove trailing slash */
210 int path_strv_make_absolute_cwd(char **l
) {
214 /* Goes through every item in the string list and makes it
215 * absolute. This works in place and won't rollback any
216 * changes on failure. */
221 r
= path_make_absolute_cwd(*s
, &t
);
225 path_simplify(t
, false);
226 free_and_replace(*s
, t
);
232 char **path_strv_resolve(char **l
, const char *root
) {
241 /* Goes through every item in the string list and canonicalize
242 * the path. This works in place and won't rollback any
243 * changes on failure. */
246 _cleanup_free_
char *orig
= NULL
;
249 if (!path_is_absolute(*s
)) {
256 t
= prefix_root(root
, orig
);
264 r
= chase_symlinks(t
, root
, 0, &u
);
282 x
= path_startswith(u
, root
);
284 /* restore the slash if it was lost */
285 if (!startswith(x
, "/"))
296 /* canonicalized path goes outside of
297 * prefix, keep the original path instead */
298 free_and_replace(u
, orig
);
314 char **path_strv_resolve_uniq(char **l
, const char *root
) {
319 if (!path_strv_resolve(l
, root
))
325 char *path_simplify(char *path
, bool kill_dots
) {
327 bool slash
= false, ignore_slash
= false, absolute
;
331 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
332 * if kill_dots is true. Modifies the passed string in-place.
334 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
335 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
336 * .//./foo//./bar/. becomes ././foo/./bar/. (if kill_dots is false)
337 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
343 absolute
= path_is_absolute(path
);
346 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
351 for (t
= path
; *f
; f
++) {
359 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
364 ignore_slash
= false;
372 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
373 * or "." for the current directory */
385 char* path_startswith(const char *path
, const char *prefix
) {
389 /* Returns a pointer to the start of the first component after the parts matched by
391 * - both paths are absolute or both paths are relative,
393 * - each component in prefix in turn matches a component in path at the same position.
394 * An empty string will be returned when the prefix and path are equivalent.
396 * Returns NULL otherwise.
399 if ((path
[0] == '/') != (prefix
[0] == '/'))
405 path
+= strspn(path
, "/");
406 prefix
+= strspn(prefix
, "/");
414 a
= strcspn(path
, "/");
415 b
= strcspn(prefix
, "/");
420 if (memcmp(path
, prefix
, a
) != 0)
428 int path_compare(const char *a
, const char *b
) {
434 /* A relative path and an absolute path must not compare as equal.
435 * Which one is sorted before the other does not really matter.
436 * Here a relative path is ordered before an absolute path. */
437 d
= (a
[0] == '/') - (b
[0] == '/');
447 if (*a
== 0 && *b
== 0)
450 /* Order prefixes first: "/foo" before "/foo/bar" */
459 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
460 d
= memcmp(a
, b
, MIN(j
, k
));
462 return (d
> 0) - (d
< 0); /* sign of d */
464 /* Sort "/foo/a" before "/foo/aaa" */
465 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
474 bool path_equal(const char *a
, const char *b
) {
475 return path_compare(a
, b
) == 0;
478 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
479 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
482 char* path_join_internal(const char *first
, ...) {
489 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
490 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
491 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
494 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
499 * path_join("foo", "bar") → "foo/bar"
500 * path_join("foo/", "bar") → "foo/bar"
501 * path_join("", "foo", "", "bar", "") → "foo/bar" */
503 sz
= strlen_ptr(first
);
505 while ((p
= va_arg(ap
, char*)) != (const char*) -1)
510 joined
= new(char, sz
+ 1);
514 if (!isempty(first
)) {
515 q
= stpcpy(joined
, first
);
516 slash
= endswith(first
, "/");
518 /* Skip empty items */
521 slash
= true; /* no need to generate a slash anymore */
525 while ((p
= va_arg(ap
, char*)) != (const char*) -1) {
529 if (!slash
&& p
[0] != '/')
533 slash
= endswith(p
, "/");
540 int find_binary(const char *name
, char **ret
) {
547 if (access(name
, X_OK
) < 0)
551 r
= path_make_absolute_cwd(name
, ret
);
560 * Plain getenv, not secure_getenv, because we want
561 * to actually allow the user to pick the binary.
567 last_error
= -ENOENT
;
570 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
572 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
578 if (!path_is_absolute(element
))
581 j
= path_join(element
, name
);
585 if (access(j
, X_OK
) >= 0) {
589 *ret
= path_simplify(j
, false);
602 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
603 bool changed
= false;
604 const char* const* i
;
611 STRV_FOREACH(i
, paths
) {
615 if (stat(*i
, &stats
) < 0)
618 u
= timespec_load(&stats
.st_mtim
);
624 log_debug("timestamp of '%s' changed", *i
);
626 /* update timestamp */
637 static int binary_is_good(const char *binary
) {
638 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
641 r
= find_binary(binary
, &p
);
647 /* An fsck that is linked to /bin/true is a non-existent
650 r
= readlink_malloc(p
, &d
);
651 if (r
== -EINVAL
) /* not a symlink */
656 return !PATH_IN_SET(d
, "true"
662 int fsck_exists(const char *fstype
) {
667 if (streq(fstype
, "auto"))
670 checker
= strjoina("fsck.", fstype
);
671 return binary_is_good(checker
);
674 int mkfs_exists(const char *fstype
) {
679 if (streq(fstype
, "auto"))
682 mkfs
= strjoina("mkfs.", fstype
);
683 return binary_is_good(mkfs
);
686 char *prefix_root(const char *root
, const char *path
) {
690 /* If root is passed, prefixes path with it. Otherwise returns
695 /* First, drop duplicate prefixing slashes from the path */
696 while (path
[0] == '/' && path
[1] == '/')
699 if (empty_or_root(root
))
702 l
= strlen(root
) + 1 + strlen(path
) + 1;
710 while (p
> n
&& p
[-1] == '/')
720 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
725 * This function is intended to be used in command line
726 * parsers, to handle paths that are passed in. It makes the
727 * path absolute, and reduces it to NULL if omitted or
728 * root (the latter optionally).
730 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
731 * SUCCESS! Hence, do not pass in uninitialized pointers.
739 r
= path_make_absolute_cwd(path
, &p
);
741 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
743 path_simplify(p
, false);
744 if (suppress_root
&& empty_or_root(p
))
747 free_and_replace(*arg
, p
);
752 char* dirname_malloc(const char *path
) {
753 char *d
, *dir
, *dir2
;
773 const char *last_path_component(const char *path
) {
775 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
788 * Also, the empty string is mapped to itself.
790 * This is different than basename(), which returns "" when a trailing slash is present.
798 l
= k
= strlen(path
);
799 if (l
== 0) /* special case — an empty string */
802 while (k
> 0 && path
[k
-1] == '/')
805 if (k
== 0) /* the root directory */
808 while (k
> 0 && path
[k
-1] != '/')
814 int path_extract_filename(const char *p
, char **ret
) {
815 _cleanup_free_
char *a
= NULL
;
816 const char *c
, *e
= NULL
, *q
;
818 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
819 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
824 c
= last_path_component(p
);
826 for (q
= c
; *q
!= 0; q
++)
830 if (!e
) /* no valid character? */
833 a
= strndup(c
, e
- c
);
837 if (!filename_is_valid(a
))
845 bool filename_is_valid(const char *p
) {
851 if (dot_or_dot_dot(p
))
854 e
= strchrnul(p
, '/');
858 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
864 bool path_is_valid(const char *p
) {
869 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
875 bool path_is_normalized(const char *p
) {
877 if (!path_is_valid(p
))
880 if (dot_or_dot_dot(p
))
883 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
886 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
895 char *file_in_same_dir(const char *path
, const char *filename
) {
902 /* This removes the last component of path and appends
903 * filename, unless the latter is absolute anyway or the
906 if (path_is_absolute(filename
))
907 return strdup(filename
);
909 e
= strrchr(path
, '/');
911 return strdup(filename
);
913 k
= strlen(filename
);
914 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
918 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
922 bool hidden_or_backup_file(const char *filename
) {
927 if (filename
[0] == '.' ||
928 streq(filename
, "lost+found") ||
929 streq(filename
, "aquota.user") ||
930 streq(filename
, "aquota.group") ||
931 endswith(filename
, "~"))
934 p
= strrchr(filename
, '.');
938 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
939 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
940 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
941 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
942 * string. Specifically: there's now:
944 * The generic suffixes "~" and ".bak" for backup files
945 * The generic prefix "." for hidden files
947 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
948 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
951 return STR_IN_SET(p
+ 1,
971 bool is_device_path(const char *path
) {
973 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
975 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
978 bool valid_device_node_path(const char *path
) {
980 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
981 * actual device node. */
983 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
986 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
989 return path_is_normalized(path
);
992 bool valid_device_allow_pattern(const char *path
) {
995 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
998 if (STARTSWITH_SET(path
, "block-", "char-"))
1001 return valid_device_node_path(path
);
1004 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1005 const char *pattern
;
1008 /* Try to guess if systemd installation is later than the specified version. This
1009 * is hacky and likely to yield false negatives, particularly if the installation
1010 * is non-standard. False positives should be relatively rare.
1013 NULSTR_FOREACH(pattern
,
1014 /* /lib works for systems without usr-merge, and for systems with a sane
1015 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1016 * for Gentoo which does a merge without making /lib a symlink.
1018 "lib/systemd/libsystemd-shared-*.so\0"
1019 "lib64/systemd/libsystemd-shared-*.so\0"
1020 "usr/lib/systemd/libsystemd-shared-*.so\0"
1021 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1023 _cleanup_strv_free_
char **names
= NULL
;
1024 _cleanup_free_
char *path
= NULL
;
1027 path
= prefix_root(root
, pattern
);
1031 r
= glob_extend(&names
, path
);
1037 assert_se(c
= endswith(path
, "*.so"));
1038 *c
= '\0'; /* truncate the glob part */
1040 STRV_FOREACH(name
, names
) {
1041 /* This is most likely to run only once, hence let's not optimize anything. */
1045 t
= startswith(*name
, path
);
1049 t2
= endswith(t
, ".so");
1053 t2
[0] = '\0'; /* truncate the suffix */
1055 r
= safe_atou(t
, &version
);
1057 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1061 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1063 version
>= minimal_version
? "OK" : "too old");
1064 if (version
>= minimal_version
)
1072 bool dot_or_dot_dot(const char *path
) {
1082 return path
[2] == 0;
1085 bool empty_or_root(const char *root
) {
1087 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1088 * i.e. either / or NULL or the empty string or any equivalent. */
1093 return root
[strspn(root
, "/")] == 0;
1096 int path_simplify_and_warn(
1100 const char *filename
,
1102 const char *lvalue
) {
1104 bool fatal
= flag
& PATH_CHECK_FATAL
;
1106 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
1108 if (!utf8_is_valid(path
))
1109 return log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
1111 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
1114 absolute
= path_is_absolute(path
);
1116 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
))
1117 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1118 "%s= path is not absolute%s: %s",
1119 lvalue
, fatal
? "" : ", ignoring", path
);
1121 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
))
1122 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1123 "%s= path is absolute%s: %s",
1124 lvalue
, fatal
? "" : ", ignoring", path
);
1127 path_simplify(path
, true);
1129 if (!path_is_valid(path
))
1130 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1131 "%s= path has invalid length (%zu bytes)%s.",
1132 lvalue
, strlen(path
), fatal
? "" : ", ignoring");
1134 if (!path_is_normalized(path
))
1135 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
1136 "%s= path is not normalized%s: %s",
1137 lvalue
, fatal
? "" : ", ignoring", path
);