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(TAKE_PTR(j
), false);
649 /* PATH entries which we don't have access to are ignored, as per tradition. */
657 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
658 bool changed
= false;
659 const char* const* i
;
666 STRV_FOREACH(i
, paths
) {
670 if (stat(*i
, &stats
) < 0)
673 u
= timespec_load(&stats
.st_mtim
);
679 log_debug("timestamp of '%s' changed", *i
);
681 /* update timestamp */
692 static int binary_is_good(const char *binary
) {
693 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
696 r
= find_binary(binary
, &p
);
702 /* An fsck that is linked to /bin/true is a non-existent
705 r
= readlink_malloc(p
, &d
);
706 if (r
== -EINVAL
) /* not a symlink */
711 return !PATH_IN_SET(d
, "true"
717 int fsck_exists(const char *fstype
) {
722 if (streq(fstype
, "auto"))
725 checker
= strjoina("fsck.", fstype
);
726 return binary_is_good(checker
);
729 int mkfs_exists(const char *fstype
) {
734 if (streq(fstype
, "auto"))
737 mkfs
= strjoina("mkfs.", fstype
);
738 return binary_is_good(mkfs
);
741 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
746 * This function is intended to be used in command line
747 * parsers, to handle paths that are passed in. It makes the
748 * path absolute, and reduces it to NULL if omitted or
749 * root (the latter optionally).
751 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
752 * SUCCESS! Hence, do not pass in uninitialized pointers.
760 r
= path_make_absolute_cwd(path
, &p
);
762 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
764 path_simplify(p
, false);
765 if (suppress_root
&& empty_or_root(p
))
768 free_and_replace(*arg
, p
);
773 char* dirname_malloc(const char *path
) {
774 char *d
, *dir
, *dir2
;
794 const char *last_path_component(const char *path
) {
796 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
809 * Also, the empty string is mapped to itself.
811 * This is different than basename(), which returns "" when a trailing slash is present.
819 l
= k
= strlen(path
);
820 if (l
== 0) /* special case — an empty string */
823 while (k
> 0 && path
[k
-1] == '/')
826 if (k
== 0) /* the root directory */
829 while (k
> 0 && path
[k
-1] != '/')
835 int path_extract_filename(const char *p
, char **ret
) {
836 _cleanup_free_
char *a
= NULL
;
837 const char *c
, *e
= NULL
, *q
;
839 /* Extracts the filename part (i.e. right-most component) from a path, i.e. string that passes
840 * filename_is_valid(). A wrapper around last_path_component(), but eats up trailing slashes. */
845 c
= last_path_component(p
);
847 for (q
= c
; *q
!= 0; q
++)
851 if (!e
) /* no valid character? */
854 a
= strndup(c
, e
- c
);
858 if (!filename_is_valid(a
))
866 bool filename_is_valid(const char *p
) {
872 if (dot_or_dot_dot(p
))
875 e
= strchrnul(p
, '/');
879 if (e
- p
> FILENAME_MAX
) /* FILENAME_MAX is counted *without* the trailing NUL byte */
885 bool path_is_valid(const char *p
) {
890 if (strlen(p
) >= PATH_MAX
) /* PATH_MAX is counted *with* the trailing NUL byte */
896 bool path_is_normalized(const char *p
) {
898 if (!path_is_valid(p
))
901 if (dot_or_dot_dot(p
))
904 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
907 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
916 char *file_in_same_dir(const char *path
, const char *filename
) {
923 /* This removes the last component of path and appends
924 * filename, unless the latter is absolute anyway or the
927 if (path_is_absolute(filename
))
928 return strdup(filename
);
930 e
= strrchr(path
, '/');
932 return strdup(filename
);
934 k
= strlen(filename
);
935 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
939 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
943 bool hidden_or_backup_file(const char *filename
) {
948 if (filename
[0] == '.' ||
949 streq(filename
, "lost+found") ||
950 streq(filename
, "aquota.user") ||
951 streq(filename
, "aquota.group") ||
952 endswith(filename
, "~"))
955 p
= strrchr(filename
, '.');
959 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
960 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
961 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
962 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
963 * string. Specifically: there's now:
965 * The generic suffixes "~" and ".bak" for backup files
966 * The generic prefix "." for hidden files
968 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
969 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
972 return STR_IN_SET(p
+ 1,
992 bool is_device_path(const char *path
) {
994 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
996 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
999 bool valid_device_node_path(const char *path
) {
1001 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
1002 * actual device node. */
1004 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
1007 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
1010 return path_is_normalized(path
);
1013 bool valid_device_allow_pattern(const char *path
) {
1016 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
1019 if (STARTSWITH_SET(path
, "block-", "char-"))
1022 return valid_device_node_path(path
);
1025 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
1026 const char *pattern
;
1029 /* Try to guess if systemd installation is later than the specified version. This
1030 * is hacky and likely to yield false negatives, particularly if the installation
1031 * is non-standard. False positives should be relatively rare.
1034 NULSTR_FOREACH(pattern
,
1035 /* /lib works for systems without usr-merge, and for systems with a sane
1036 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
1037 * for Gentoo which does a merge without making /lib a symlink.
1039 "lib/systemd/libsystemd-shared-*.so\0"
1040 "lib64/systemd/libsystemd-shared-*.so\0"
1041 "usr/lib/systemd/libsystemd-shared-*.so\0"
1042 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
1044 _cleanup_strv_free_
char **names
= NULL
;
1045 _cleanup_free_
char *path
= NULL
;
1048 path
= path_join(root
, pattern
);
1052 r
= glob_extend(&names
, path
, 0);
1058 assert_se(c
= endswith(path
, "*.so"));
1059 *c
= '\0'; /* truncate the glob part */
1061 STRV_FOREACH(name
, names
) {
1062 /* This is most likely to run only once, hence let's not optimize anything. */
1066 t
= startswith(*name
, path
);
1070 t2
= endswith(t
, ".so");
1074 t2
[0] = '\0'; /* truncate the suffix */
1076 r
= safe_atou(t
, &version
);
1078 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
1082 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
1084 version
>= minimal_version
? "OK" : "too old");
1085 if (version
>= minimal_version
)
1093 bool dot_or_dot_dot(const char *path
) {
1103 return path
[2] == 0;
1106 bool empty_or_root(const char *root
) {
1108 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1109 * i.e. either / or NULL or the empty string or any equivalent. */
1114 return root
[strspn(root
, "/")] == 0;
1117 bool path_strv_contains(char **l
, const char *path
) {
1121 if (path_equal(*i
, path
))
1127 bool prefixed_path_strv_contains(char **l
, const char *path
) {
1130 STRV_FOREACH(i
, l
) {
1136 if (path_equal(j
, path
))