1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 /* When we include libgen.h because we need dirname() we immediately
10 * undefine basename() since libgen.h defines it as a macro to the
11 * POSIX version which is really broken. We prefer GNU basename(). */
15 #include "alloc-util.h"
16 #include "extract-word.h"
18 #include "glob-util.h"
21 #include "nulstr-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "stat-util.h"
25 #include "string-util.h"
27 #include "time-util.h"
30 bool path_is_absolute(const char *p
) {
34 bool is_path(const char *p
) {
35 return !!strchr(p
, '/');
38 int path_split_and_make_absolute(const char *p
, char ***ret
) {
45 l
= strv_split(p
, ":");
49 r
= path_strv_make_absolute_cwd(l
);
59 char *path_make_absolute(const char *p
, const char *prefix
) {
62 /* Makes every item in the list an absolute path by prepending
63 * the prefix, if specified and necessary */
65 if (path_is_absolute(p
) || isempty(prefix
))
68 return path_join(prefix
, p
);
71 int safe_getcwd(char **ret
) {
74 cwd
= get_current_dir_name();
76 return negative_errno();
78 /* Let's make sure the directory is really absolute, to protect us from the logic behind
89 int path_make_absolute_cwd(const char *p
, char **ret
) {
96 /* Similar to path_make_absolute(), but prefixes with the
97 * current working directory. */
99 if (path_is_absolute(p
))
102 _cleanup_free_
char *cwd
= NULL
;
104 r
= safe_getcwd(&cwd
);
108 c
= path_join(cwd
, p
);
117 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
119 unsigned n_parents
= 0;
125 /* Strips the common part, and adds ".." elements as necessary. */
127 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
130 f
= strdupa(from_dir
);
131 t
= strdupa(to_path
);
133 path_simplify(f
, true);
134 path_simplify(t
, true);
136 /* Skip the common part. */
145 /* from_dir equals to_path. */
148 /* from_dir is a parent directory of to_path. */
163 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
170 /* If we're here, then "from_dir" has one or more elements that need to
171 * be replaced with "..". */
173 /* Count the number of necessary ".." elements. */
179 /* If this includes ".." we can't do a simple series of "..", refuse */
180 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
183 /* Count number of elements */
190 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
194 for (p
= r
; n_parents
> 0; n_parents
--)
195 p
= mempcpy(p
, "../", 3);
200 /* Remove trailing slash */
207 char* path_startswith_strv(const char *p
, char **set
) {
210 STRV_FOREACH(s
, set
) {
211 t
= path_startswith(p
, *s
);
219 int path_strv_make_absolute_cwd(char **l
) {
223 /* Goes through every item in the string list and makes it
224 * absolute. This works in place and won't rollback any
225 * changes on failure. */
230 r
= path_make_absolute_cwd(*s
, &t
);
234 path_simplify(t
, false);
235 free_and_replace(*s
, t
);
241 char **path_strv_resolve(char **l
, const char *root
) {
250 /* Goes through every item in the string list and canonicalize
251 * the path. This works in place and won't rollback any
252 * changes on failure. */
255 _cleanup_free_
char *orig
= NULL
;
258 if (!path_is_absolute(*s
)) {
265 t
= path_join(root
, orig
);
273 r
= chase_symlinks(t
, root
, 0, &u
, NULL
);
291 x
= path_startswith(u
, root
);
293 /* restore the slash if it was lost */
294 if (!startswith(x
, "/"))
305 /* canonicalized path goes outside of
306 * prefix, keep the original path instead */
307 free_and_replace(u
, orig
);
323 char **path_strv_resolve_uniq(char **l
, const char *root
) {
328 if (!path_strv_resolve(l
, root
))
334 char *path_simplify(char *path
, bool kill_dots
) {
336 bool slash
= false, ignore_slash
= false, absolute
;
340 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
341 * if kill_dots is true. Modifies the passed string in-place.
343 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
344 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
345 * .//./foo//./bar/. becomes ././foo/./bar/. (if kill_dots is false)
346 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
352 absolute
= path_is_absolute(path
);
355 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
360 for (t
= path
; *f
; f
++) {
368 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
373 ignore_slash
= false;
381 /* Special rule, if we stripped everything, we either need a "/" (for the root directory)
382 * or "." for the current directory */
394 int path_simplify_and_warn(
398 const char *filename
,
400 const char *lvalue
) {
402 bool fatal
= flag
& PATH_CHECK_FATAL
;
404 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
406 if (!utf8_is_valid(path
))
407 return log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
409 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
412 absolute
= path_is_absolute(path
);
414 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
))
415 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
416 "%s= path is not absolute%s: %s",
417 lvalue
, fatal
? "" : ", ignoring", path
);
419 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
))
420 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
421 "%s= path is absolute%s: %s",
422 lvalue
, fatal
? "" : ", ignoring", path
);
425 path_simplify(path
, true);
427 if (!path_is_valid(path
))
428 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
429 "%s= path has invalid length (%zu bytes)%s.",
430 lvalue
, strlen(path
), fatal
? "" : ", ignoring");
432 if (!path_is_normalized(path
))
433 return log_syntax(unit
, LOG_ERR
, filename
, line
, SYNTHETIC_ERRNO(EINVAL
),
434 "%s= path is not normalized%s: %s",
435 lvalue
, fatal
? "" : ", ignoring", path
);
440 char* path_startswith(const char *path
, const char *prefix
) {
444 /* Returns a pointer to the start of the first component after the parts matched by
446 * - both paths are absolute or both paths are relative,
448 * - each component in prefix in turn matches a component in path at the same position.
449 * An empty string will be returned when the prefix and path are equivalent.
451 * Returns NULL otherwise.
454 if ((path
[0] == '/') != (prefix
[0] == '/'))
460 path
+= strspn(path
, "/");
461 prefix
+= strspn(prefix
, "/");
469 a
= strcspn(path
, "/");
470 b
= strcspn(prefix
, "/");
475 if (memcmp(path
, prefix
, a
) != 0)
483 int path_compare(const char *a
, const char *b
) {
489 /* A relative path and an absolute path must not compare as equal.
490 * Which one is sorted before the other does not really matter.
491 * Here a relative path is ordered before an absolute path. */
492 d
= (a
[0] == '/') - (b
[0] == '/');
502 if (*a
== 0 && *b
== 0)
505 /* Order prefixes first: "/foo" before "/foo/bar" */
514 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
515 d
= memcmp(a
, b
, MIN(j
, k
));
517 return (d
> 0) - (d
< 0); /* sign of d */
519 /* Sort "/foo/a" before "/foo/aaa" */
520 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
529 bool path_equal(const char *a
, const char *b
) {
530 return path_compare(a
, b
) == 0;
533 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
534 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
537 char* path_join_internal(const char *first
, ...) {
544 /* Joins all listed strings until the sentinel and places a "/" between them unless the strings end/begin
545 * already with one so that it is unnecessary. Note that slashes which are already duplicate won't be
546 * removed. The string returned is hence always equal to or longer than the sum of the lengths of each
549 * Note: any listed empty string is simply skipped. This can be useful for concatenating strings of which some
554 * path_join("foo", "bar") → "foo/bar"
555 * path_join("foo/", "bar") → "foo/bar"
556 * path_join("", "foo", "", "bar", "") → "foo/bar" */
558 sz
= strlen_ptr(first
);
560 while ((p
= va_arg(ap
, char*)) != (const char*) -1)
565 joined
= new(char, sz
+ 1);
569 if (!isempty(first
)) {
570 q
= stpcpy(joined
, first
);
571 slash
= endswith(first
, "/");
573 /* Skip empty items */
576 slash
= true; /* no need to generate a slash anymore */
580 while ((p
= va_arg(ap
, char*)) != (const char*) -1) {
584 if (!slash
&& p
[0] != '/')
588 slash
= endswith(p
, "/");
595 int find_binary(const char *name
, char **ret
) {
602 if (access(name
, X_OK
) < 0)
606 r
= path_make_absolute_cwd(name
, ret
);
615 * Plain getenv, not secure_getenv, because we want
616 * to actually allow the user to pick the binary.
622 last_error
= -ENOENT
;
625 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
627 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
633 if (!path_is_absolute(element
))
636 j
= path_join(element
, name
);
640 if (access(j
, X_OK
) >= 0) {
644 *ret
= path_simplify(j
, false);
651 /* PATH entries which we don't have access to are ignored, as per tradition. */
659 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
660 bool changed
= false;
661 const char* const* i
;
668 STRV_FOREACH(i
, paths
) {
672 if (stat(*i
, &stats
) < 0)
675 u
= timespec_load(&stats
.st_mtim
);
681 log_debug("timestamp of '%s' changed", *i
);
683 /* update timestamp */
694 static int binary_is_good(const char *binary
) {
695 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
698 r
= find_binary(binary
, &p
);
704 /* An fsck that is linked to /bin/true is a non-existent
707 r
= readlink_malloc(p
, &d
);
708 if (r
== -EINVAL
) /* not a symlink */
713 return !PATH_IN_SET(d
, "true"
719 int fsck_exists(const char *fstype
) {
724 if (streq(fstype
, "auto"))
727 checker
= strjoina("fsck.", fstype
);
728 return binary_is_good(checker
);
731 int mkfs_exists(const char *fstype
) {
736 if (streq(fstype
, "auto"))
739 mkfs
= strjoina("mkfs.", fstype
);
740 return binary_is_good(mkfs
);
743 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
748 * This function is intended to be used in command line
749 * parsers, to handle paths that are passed in. It makes the
750 * path absolute, and reduces it to NULL if omitted or
751 * root (the latter optionally).
753 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
754 * SUCCESS! Hence, do not pass in uninitialized pointers.
762 r
= path_make_absolute_cwd(path
, &p
);
764 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
766 path_simplify(p
, false);
767 if (suppress_root
&& empty_or_root(p
))
770 free_and_replace(*arg
, p
);
775 char* dirname_malloc(const char *path
) {
776 char *d
, *dir
, *dir2
;
796 const char *last_path_component(const char *path
) {
798 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
811 * Also, the empty string is mapped to itself.
813 * This is different than basename(), which returns "" when a trailing slash is present.
821 l
= k
= strlen(path
);
822 if (l
== 0) /* special case — an empty string */
825 while (k
> 0 && path
[k
-1] == '/')
828 if (k
== 0) /* the root directory */
831 while (k
> 0 && path
[k
-1] != '/')
837 int path_extract_filename(const char *p
, char **ret
) {
838 _cleanup_free_
char *a
= NULL
;
839 const char *c
, *e
= NULL
, *q
;
841 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
842 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
847 c
= last_path_component(p
);
849 for (q
= c
; *q
!= 0; q
++)
853 if (!e
) /* no valid character? */
856 a
= strndup(c
, e
- c
);
860 if (!filename_is_valid(a
))
868 bool filename_is_valid(const char *p
) {
874 if (dot_or_dot_dot(p
))
877 e
= strchrnul(p
, '/');
881 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
887 bool path_is_valid(const char *p
) {
892 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
898 bool path_is_normalized(const char *p
) {
900 if (!path_is_valid(p
))
903 if (dot_or_dot_dot(p
))
906 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
909 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
918 char *file_in_same_dir(const char *path
, const char *filename
) {
925 /* This removes the last component of path and appends
926 * filename, unless the latter is absolute anyway or the
929 if (path_is_absolute(filename
))
930 return strdup(filename
);
932 e
= strrchr(path
, '/');
934 return strdup(filename
);
936 k
= strlen(filename
);
937 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
941 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
945 bool hidden_or_backup_file(const char *filename
) {
950 if (filename
[0] == '.' ||
951 streq(filename
, "lost+found") ||
952 streq(filename
, "aquota.user") ||
953 streq(filename
, "aquota.group") ||
954 endswith(filename
, "~"))
957 p
= strrchr(filename
, '.');
961 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
962 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
963 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
964 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
965 * string. Specifically: there's now:
967 * The generic suffixes "~" and ".bak" for backup files
968 * The generic prefix "." for hidden files
970 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
971 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
974 return STR_IN_SET(p
+ 1,
994 bool is_device_path(const char *path
) {
996 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
998 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
1001 bool valid_device_node_path(const char *path
) {
1003 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1004 * actual device node. */
1006 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
1009 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
1012 return path_is_normalized(path
);
1015 bool valid_device_allow_pattern(const char *path
) {
1018 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1021 if (STARTSWITH_SET(path
, "block-", "char-"))
1024 return valid_device_node_path(path
);
1027 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1028 const char *pattern
;
1031 /* Try to guess if systemd installation is later than the specified version. This
1032 * is hacky and likely to yield false negatives, particularly if the installation
1033 * is non-standard. False positives should be relatively rare.
1036 NULSTR_FOREACH(pattern
,
1037 /* /lib works for systems without usr-merge, and for systems with a sane
1038 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1039 * for Gentoo which does a merge without making /lib a symlink.
1041 "lib/systemd/libsystemd-shared-*.so\0"
1042 "lib64/systemd/libsystemd-shared-*.so\0"
1043 "usr/lib/systemd/libsystemd-shared-*.so\0"
1044 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1046 _cleanup_strv_free_
char **names
= NULL
;
1047 _cleanup_free_
char *path
= NULL
;
1050 path
= path_join(root
, pattern
);
1054 r
= glob_extend(&names
, path
, 0);
1060 assert_se(c
= endswith(path
, "*.so"));
1061 *c
= '\0'; /* truncate the glob part */
1063 STRV_FOREACH(name
, names
) {
1064 /* This is most likely to run only once, hence let's not optimize anything. */
1068 t
= startswith(*name
, path
);
1072 t2
= endswith(t
, ".so");
1076 t2
[0] = '\0'; /* truncate the suffix */
1078 r
= safe_atou(t
, &version
);
1080 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1084 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1086 version
>= minimal_version
? "OK" : "too old");
1087 if (version
>= minimal_version
)
1095 bool dot_or_dot_dot(const char *path
) {
1105 return path
[2] == 0;
1108 bool empty_or_root(const char *root
) {
1110 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1111 * i.e. either / or NULL or the empty string or any equivalent. */
1116 return root
[strspn(root
, "/")] == 0;
1119 bool path_strv_contains(char **l
, const char *path
) {
1123 if (path_equal(*i
, path
))
1129 bool prefixed_path_strv_contains(char **l
, const char *path
) {
1132 STRV_FOREACH(i
, l
) {
1138 if (path_equal(j
, path
))