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(NULL
, 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)
342 absolute
= path_is_absolute(path
);
345 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
350 for (t
= path
; *f
; f
++) {
358 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
363 ignore_slash
= false;
371 /* Special rule, if we are talking of the root directory, a trailing slash is good */
372 if (absolute
&& t
== path
)
379 char* path_startswith(const char *path
, const char *prefix
) {
383 /* Returns a pointer to the start of the first component after the parts matched by
385 * - both paths are absolute or both paths are relative,
387 * - each component in prefix in turn matches a component in path at the same position.
388 * An empty string will be returned when the prefix and path are equivalent.
390 * Returns NULL otherwise.
393 if ((path
[0] == '/') != (prefix
[0] == '/'))
399 path
+= strspn(path
, "/");
400 prefix
+= strspn(prefix
, "/");
408 a
= strcspn(path
, "/");
409 b
= strcspn(prefix
, "/");
414 if (memcmp(path
, prefix
, a
) != 0)
422 int path_compare(const char *a
, const char *b
) {
428 /* A relative path and an abolute path must not compare as equal.
429 * Which one is sorted before the other does not really matter.
430 * Here a relative path is ordered before an absolute path. */
431 d
= (a
[0] == '/') - (b
[0] == '/');
441 if (*a
== 0 && *b
== 0)
444 /* Order prefixes first: "/foo" before "/foo/bar" */
453 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
454 d
= memcmp(a
, b
, MIN(j
, k
));
456 return (d
> 0) - (d
< 0); /* sign of d */
458 /* Sort "/foo/a" before "/foo/aaa" */
459 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
468 bool path_equal(const char *a
, const char *b
) {
469 return path_compare(a
, b
) == 0;
472 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
473 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
476 char* path_join(const char *root
, const char *path
, const char *rest
) {
480 return strjoin(root
, endswith(root
, "/") ? "" : "/",
481 path
[0] == '/' ? path
+1 : path
,
482 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
483 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
486 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
487 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
490 int find_binary(const char *name
, char **ret
) {
497 if (access(name
, X_OK
) < 0)
501 r
= path_make_absolute_cwd(name
, ret
);
510 * Plain getenv, not secure_getenv, because we want
511 * to actually allow the user to pick the binary.
517 last_error
= -ENOENT
;
520 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
522 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
528 if (!path_is_absolute(element
))
531 j
= strjoin(element
, "/", name
);
535 if (access(j
, X_OK
) >= 0) {
539 *ret
= path_simplify(j
, false);
552 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
553 bool changed
= false;
554 const char* const* i
;
561 STRV_FOREACH(i
, paths
) {
565 if (stat(*i
, &stats
) < 0)
568 u
= timespec_load(&stats
.st_mtim
);
574 log_debug("timestamp of '%s' changed", *i
);
576 /* update timestamp */
587 static int binary_is_good(const char *binary
) {
588 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
591 r
= find_binary(binary
, &p
);
597 /* An fsck that is linked to /bin/true is a non-existent
600 r
= readlink_malloc(p
, &d
);
601 if (r
== -EINVAL
) /* not a symlink */
606 return !PATH_IN_SET(d
, "true"
612 int fsck_exists(const char *fstype
) {
617 if (streq(fstype
, "auto"))
620 checker
= strjoina("fsck.", fstype
);
621 return binary_is_good(checker
);
624 int mkfs_exists(const char *fstype
) {
629 if (streq(fstype
, "auto"))
632 mkfs
= strjoina("mkfs.", fstype
);
633 return binary_is_good(mkfs
);
636 char *prefix_root(const char *root
, const char *path
) {
640 /* If root is passed, prefixes path with it. Otherwise returns
645 /* First, drop duplicate prefixing slashes from the path */
646 while (path
[0] == '/' && path
[1] == '/')
649 if (empty_or_root(root
))
652 l
= strlen(root
) + 1 + strlen(path
) + 1;
660 while (p
> n
&& p
[-1] == '/')
670 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
675 * This function is intended to be used in command line
676 * parsers, to handle paths that are passed in. It makes the
677 * path absolute, and reduces it to NULL if omitted or
678 * root (the latter optionally).
680 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
681 * SUCCESS! Hence, do not pass in uninitialized pointers.
689 r
= path_make_absolute_cwd(path
, &p
);
691 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
693 path_simplify(p
, false);
694 if (suppress_root
&& empty_or_root(p
))
697 free_and_replace(*arg
, p
);
702 char* dirname_malloc(const char *path
) {
703 char *d
, *dir
, *dir2
;
723 const char *last_path_component(const char *path
) {
725 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
738 * Also, the empty string is mapped to itself.
740 * This is different than basename(), which returns "" when a trailing slash is present.
745 l
= k
= strlen(path
);
746 if (l
== 0) /* special case — an empty string */
749 while (k
> 0 && path
[k
-1] == '/')
752 if (k
== 0) /* the root directory */
755 while (k
> 0 && path
[k
-1] != '/')
761 bool filename_is_valid(const char *p
) {
767 if (dot_or_dot_dot(p
))
770 e
= strchrnul(p
, '/');
774 if (e
- p
> FILENAME_MAX
)
780 bool path_is_normalized(const char *p
) {
785 if (dot_or_dot_dot(p
))
788 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
791 if (strlen(p
)+1 > PATH_MAX
)
794 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
803 char *file_in_same_dir(const char *path
, const char *filename
) {
810 /* This removes the last component of path and appends
811 * filename, unless the latter is absolute anyway or the
814 if (path_is_absolute(filename
))
815 return strdup(filename
);
817 e
= strrchr(path
, '/');
819 return strdup(filename
);
821 k
= strlen(filename
);
822 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
826 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
830 bool hidden_or_backup_file(const char *filename
) {
835 if (filename
[0] == '.' ||
836 streq(filename
, "lost+found") ||
837 streq(filename
, "aquota.user") ||
838 streq(filename
, "aquota.group") ||
839 endswith(filename
, "~"))
842 p
= strrchr(filename
, '.');
846 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
847 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
848 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
849 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
850 * string. Specifically: there's now:
852 * The generic suffixes "~" and ".bak" for backup files
853 * The generic prefix "." for hidden files
855 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
856 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
859 return STR_IN_SET(p
+ 1,
879 bool is_device_path(const char *path
) {
881 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
883 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
886 bool valid_device_node_path(const char *path
) {
888 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
889 * actual device node. */
891 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
894 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
897 return path_is_normalized(path
);
900 bool valid_device_allow_pattern(const char *path
) {
903 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
906 if (startswith(path
, "block-") ||
907 startswith(path
, "char-"))
910 return valid_device_node_path(path
);
913 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
917 /* Try to guess if systemd installation is later than the specified version. This
918 * is hacky and likely to yield false negatives, particularly if the installation
919 * is non-standard. False positives should be relatively rare.
922 NULSTR_FOREACH(pattern
,
923 /* /lib works for systems without usr-merge, and for systems with a sane
924 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
925 * for Gentoo which does a merge without making /lib a symlink.
927 "lib/systemd/libsystemd-shared-*.so\0"
928 "lib64/systemd/libsystemd-shared-*.so\0"
929 "usr/lib/systemd/libsystemd-shared-*.so\0"
930 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
932 _cleanup_strv_free_
char **names
= NULL
;
933 _cleanup_free_
char *path
= NULL
;
936 path
= prefix_root(root
, pattern
);
940 r
= glob_extend(&names
, path
);
946 assert_se(c
= endswith(path
, "*.so"));
947 *c
= '\0'; /* truncate the glob part */
949 STRV_FOREACH(name
, names
) {
950 /* This is most likely to run only once, hence let's not optimize anything. */
954 t
= startswith(*name
, path
);
958 t2
= endswith(t
, ".so");
962 t2
[0] = '\0'; /* truncate the suffix */
964 r
= safe_atou(t
, &version
);
966 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
970 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
972 version
>= minimal_version
? "OK" : "too old");
973 if (version
>= minimal_version
)
981 bool dot_or_dot_dot(const char *path
) {
994 bool empty_or_root(const char *root
) {
996 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
997 * i.e. either / or NULL or the empty string or any equivalent. */
1002 return root
[strspn(root
, "/")] == 0;
1005 int path_simplify_and_warn(
1009 const char *filename
,
1011 const char *lvalue
) {
1013 bool absolute
, fatal
= flag
& PATH_CHECK_FATAL
;
1015 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
1017 if (!utf8_is_valid(path
)) {
1018 log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
1022 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
1023 absolute
= path_is_absolute(path
);
1025 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
)) {
1026 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1027 "%s= path is not absolute%s: %s",
1028 lvalue
, fatal
? "" : ", ignoring", path
);
1032 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
)) {
1033 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1034 "%s= path is absolute%s: %s",
1035 lvalue
, fatal
? "" : ", ignoring", path
);
1040 path_simplify(path
, true);
1042 if (!path_is_normalized(path
)) {
1043 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1044 "%s= path is not normalized%s: %s",
1045 lvalue
, fatal
? "" : ", ignoring", path
);