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"
23 #include "nulstr-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 return path_join(prefix
, p
);
73 int safe_getcwd(char **ret
) {
76 cwd
= get_current_dir_name();
78 return negative_errno();
80 /* Let's make sure the directory is really absolute, to protect us from the logic behind
91 int path_make_absolute_cwd(const char *p
, char **ret
) {
98 /* Similar to path_make_absolute(), but prefixes with the
99 * current working directory. */
101 if (path_is_absolute(p
))
104 _cleanup_free_
char *cwd
= NULL
;
106 r
= safe_getcwd(&cwd
);
110 c
= path_join(cwd
, p
);
119 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
121 unsigned n_parents
= 0;
127 /* Strips the common part, and adds ".." elements as necessary. */
129 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
132 f
= strdupa(from_dir
);
133 t
= strdupa(to_path
);
135 path_simplify(f
, true);
136 path_simplify(t
, true);
138 /* Skip the common part. */
147 /* from_dir equals to_path. */
150 /* from_dir is a parent directory of to_path. */
165 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
172 /* If we're here, then "from_dir" has one or more elements that need to
173 * be replaced with "..". */
175 /* Count the number of necessary ".." elements. */
181 /* If this includes ".." we can't do a simple series of "..", refuse */
182 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
185 /* Count number of elements */
192 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
196 for (p
= r
; n_parents
> 0; n_parents
--)
197 p
= mempcpy(p
, "../", 3);
202 /* Remove trailing slash */
209 char* path_startswith_strv(const char *p
, char **set
) {
212 STRV_FOREACH(s
, set
) {
213 t
= path_startswith(p
, *s
);
221 int path_strv_make_absolute_cwd(char **l
) {
225 /* Goes through every item in the string list and makes it
226 * absolute. This works in place and won't rollback any
227 * changes on failure. */
232 r
= path_make_absolute_cwd(*s
, &t
);
236 path_simplify(t
, false);
237 free_and_replace(*s
, t
);
243 char **path_strv_resolve(char **l
, const char *root
) {
252 /* Goes through every item in the string list and canonicalize
253 * the path. This works in place and won't rollback any
254 * changes on failure. */
257 _cleanup_free_
char *orig
= NULL
;
260 if (!path_is_absolute(*s
)) {
267 t
= path_join(root
, orig
);
275 r
= chase_symlinks(t
, root
, 0, &u
, NULL
);
293 x
= path_startswith(u
, root
);
295 /* restore the slash if it was lost */
296 if (!startswith(x
, "/"))
307 /* canonicalized path goes outside of
308 * prefix, keep the original path instead */
309 free_and_replace(u
, orig
);
325 char **path_strv_resolve_uniq(char **l
, const char *root
) {
330 if (!path_strv_resolve(l
, root
))
336 char *path_simplify(char *path
, bool kill_dots
) {
338 bool slash
= false, ignore_slash
= false, absolute
;
342 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
343 * if kill_dots is true. Modifies the passed string in-place.
345 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
346 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
347 * .//./foo//./bar/. becomes ././foo/./bar/. (if kill_dots is false)
348 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
354 absolute
= path_is_absolute(path
);
357 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
362 for (t
= path
; *f
; f
++) {
370 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
375 ignore_slash
= false;
383 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
384 * or "." for the current directory */
396 int path_simplify_and_warn(
400 const char *filename
,
402 const char *lvalue
) {
404 bool fatal
= flag
& PATH_CHECK_FATAL
;
406 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
408 if (!utf8_is_valid(path
))
409 return log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
411 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
414 absolute
= path_is_absolute(path
);
416 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
))
417 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
418 "%s= path is not absolute%s: %s",
419 lvalue
, fatal
? "" : ", ignoring", path
);
421 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
))
422 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
423 "%s= path is absolute%s: %s",
424 lvalue
, fatal
? "" : ", ignoring", path
);
427 path_simplify(path
, true);
429 if (!path_is_valid(path
))
430 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
431 "%s= path has invalid length (%zu bytes)%s.",
432 lvalue
, strlen(path
), fatal
? "" : ", ignoring");
434 if (!path_is_normalized(path
))
435 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
436 "%s= path is not normalized%s: %s",
437 lvalue
, fatal
? "" : ", ignoring", path
);
442 char* path_startswith(const char *path
, const char *prefix
) {
446 /* Returns a pointer to the start of the first component after the parts matched by
448 * - both paths are absolute or both paths are relative,
450 * - each component in prefix in turn matches a component in path at the same position.
451 * An empty string will be returned when the prefix and path are equivalent.
453 * Returns NULL otherwise.
456 if ((path
[0] == '/') != (prefix
[0] == '/'))
462 path
+= strspn(path
, "/");
463 prefix
+= strspn(prefix
, "/");
471 a
= strcspn(path
, "/");
472 b
= strcspn(prefix
, "/");
477 if (memcmp(path
, prefix
, a
) != 0)
485 int path_compare(const char *a
, const char *b
) {
491 /* A relative path and an absolute path must not compare as equal.
492 * Which one is sorted before the other does not really matter.
493 * Here a relative path is ordered before an absolute path. */
494 d
= (a
[0] == '/') - (b
[0] == '/');
504 if (*a
== 0 && *b
== 0)
507 /* Order prefixes first: "/foo" before "/foo/bar" */
516 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
517 d
= memcmp(a
, b
, MIN(j
, k
));
519 return (d
> 0) - (d
< 0); /* sign of d */
521 /* Sort "/foo/a" before "/foo/aaa" */
522 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
531 bool path_equal(const char *a
, const char *b
) {
532 return path_compare(a
, b
) == 0;
535 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
536 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
539 char* path_join_internal(const char *first
, ...) {
546 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
547 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
548 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
551 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
556 * path_join("foo", "bar") → "foo/bar"
557 * path_join("foo/", "bar") → "foo/bar"
558 * path_join("", "foo", "", "bar", "") → "foo/bar" */
560 sz
= strlen_ptr(first
);
562 while ((p
= va_arg(ap
, char*)) != (const char*) -1)
567 joined
= new(char, sz
+ 1);
571 if (!isempty(first
)) {
572 q
= stpcpy(joined
, first
);
573 slash
= endswith(first
, "/");
575 /* Skip empty items */
578 slash
= true; /* no need to generate a slash anymore */
582 while ((p
= va_arg(ap
, char*)) != (const char*) -1) {
586 if (!slash
&& p
[0] != '/')
590 slash
= endswith(p
, "/");
597 int find_binary(const char *name
, char **ret
) {
604 if (access(name
, X_OK
) < 0)
608 r
= path_make_absolute_cwd(name
, ret
);
617 * Plain getenv, not secure_getenv, because we want
618 * to actually allow the user to pick the binary.
624 last_error
= -ENOENT
;
627 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
629 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
635 if (!path_is_absolute(element
))
638 j
= path_join(element
, name
);
642 if (access(j
, X_OK
) >= 0) {
646 *ret
= path_simplify(j
, false);
653 /* PATH entries which we don't have access to are ignored, as per tradition. */
661 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
662 bool changed
= false;
663 const char* const* i
;
670 STRV_FOREACH(i
, paths
) {
674 if (stat(*i
, &stats
) < 0)
677 u
= timespec_load(&stats
.st_mtim
);
683 log_debug("timestamp of '%s' changed", *i
);
685 /* update timestamp */
696 static int binary_is_good(const char *binary
) {
697 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
700 r
= find_binary(binary
, &p
);
706 /* An fsck that is linked to /bin/true is a non-existent
709 r
= readlink_malloc(p
, &d
);
710 if (r
== -EINVAL
) /* not a symlink */
715 return !PATH_IN_SET(d
, "true"
721 int fsck_exists(const char *fstype
) {
726 if (streq(fstype
, "auto"))
729 checker
= strjoina("fsck.", fstype
);
730 return binary_is_good(checker
);
733 int mkfs_exists(const char *fstype
) {
738 if (streq(fstype
, "auto"))
741 mkfs
= strjoina("mkfs.", fstype
);
742 return binary_is_good(mkfs
);
745 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
750 * This function is intended to be used in command line
751 * parsers, to handle paths that are passed in. It makes the
752 * path absolute, and reduces it to NULL if omitted or
753 * root (the latter optionally).
755 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
756 * SUCCESS! Hence, do not pass in uninitialized pointers.
764 r
= path_make_absolute_cwd(path
, &p
);
766 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
768 path_simplify(p
, false);
769 if (suppress_root
&& empty_or_root(p
))
772 free_and_replace(*arg
, p
);
777 char* dirname_malloc(const char *path
) {
778 char *d
, *dir
, *dir2
;
798 const char *last_path_component(const char *path
) {
800 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
813 * Also, the empty string is mapped to itself.
815 * This is different than basename(), which returns "" when a trailing slash is present.
823 l
= k
= strlen(path
);
824 if (l
== 0) /* special case — an empty string */
827 while (k
> 0 && path
[k
-1] == '/')
830 if (k
== 0) /* the root directory */
833 while (k
> 0 && path
[k
-1] != '/')
839 int path_extract_filename(const char *p
, char **ret
) {
840 _cleanup_free_
char *a
= NULL
;
841 const char *c
, *e
= NULL
, *q
;
843 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
844 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
849 c
= last_path_component(p
);
851 for (q
= c
; *q
!= 0; q
++)
855 if (!e
) /* no valid character? */
858 a
= strndup(c
, e
- c
);
862 if (!filename_is_valid(a
))
870 bool filename_is_valid(const char *p
) {
876 if (dot_or_dot_dot(p
))
879 e
= strchrnul(p
, '/');
883 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
889 bool path_is_valid(const char *p
) {
894 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
900 bool path_is_normalized(const char *p
) {
902 if (!path_is_valid(p
))
905 if (dot_or_dot_dot(p
))
908 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
911 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
920 char *file_in_same_dir(const char *path
, const char *filename
) {
927 /* This removes the last component of path and appends
928 * filename, unless the latter is absolute anyway or the
931 if (path_is_absolute(filename
))
932 return strdup(filename
);
934 e
= strrchr(path
, '/');
936 return strdup(filename
);
938 k
= strlen(filename
);
939 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
943 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
947 bool hidden_or_backup_file(const char *filename
) {
952 if (filename
[0] == '.' ||
953 streq(filename
, "lost+found") ||
954 streq(filename
, "aquota.user") ||
955 streq(filename
, "aquota.group") ||
956 endswith(filename
, "~"))
959 p
= strrchr(filename
, '.');
963 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
964 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
965 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
966 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
967 * string. Specifically: there's now:
969 * The generic suffixes "~" and ".bak" for backup files
970 * The generic prefix "." for hidden files
972 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
973 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
976 return STR_IN_SET(p
+ 1,
996 bool is_device_path(const char *path
) {
998 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
1000 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
1003 bool valid_device_node_path(const char *path
) {
1005 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1006 * actual device node. */
1008 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
1011 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
1014 return path_is_normalized(path
);
1017 bool valid_device_allow_pattern(const char *path
) {
1020 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1023 if (STARTSWITH_SET(path
, "block-", "char-"))
1026 return valid_device_node_path(path
);
1029 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1030 const char *pattern
;
1033 /* Try to guess if systemd installation is later than the specified version. This
1034 * is hacky and likely to yield false negatives, particularly if the installation
1035 * is non-standard. False positives should be relatively rare.
1038 NULSTR_FOREACH(pattern
,
1039 /* /lib works for systems without usr-merge, and for systems with a sane
1040 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1041 * for Gentoo which does a merge without making /lib a symlink.
1043 "lib/systemd/libsystemd-shared-*.so\0"
1044 "lib64/systemd/libsystemd-shared-*.so\0"
1045 "usr/lib/systemd/libsystemd-shared-*.so\0"
1046 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1048 _cleanup_strv_free_
char **names
= NULL
;
1049 _cleanup_free_
char *path
= NULL
;
1052 path
= path_join(root
, pattern
);
1056 r
= glob_extend(&names
, path
);
1062 assert_se(c
= endswith(path
, "*.so"));
1063 *c
= '\0'; /* truncate the glob part */
1065 STRV_FOREACH(name
, names
) {
1066 /* This is most likely to run only once, hence let's not optimize anything. */
1070 t
= startswith(*name
, path
);
1074 t2
= endswith(t
, ".so");
1078 t2
[0] = '\0'; /* truncate the suffix */
1080 r
= safe_atou(t
, &version
);
1082 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1086 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1088 version
>= minimal_version
? "OK" : "too old");
1089 if (version
>= minimal_version
)
1097 bool dot_or_dot_dot(const char *path
) {
1107 return path
[2] == 0;
1110 bool empty_or_root(const char *root
) {
1112 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1113 * i.e. either / or NULL or the empty string or any equivalent. */
1118 return root
[strspn(root
, "/")] == 0;