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 if (endswith(cwd
, "/"))
116 c
= strjoin(cwd
, "/", p
);
125 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
127 unsigned n_parents
= 0;
133 /* Strips the common part, and adds ".." elements as necessary. */
135 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
138 f
= strdupa(from_dir
);
139 t
= strdupa(to_path
);
141 path_simplify(f
, true);
142 path_simplify(t
, true);
144 /* Skip the common part. */
153 /* from_dir equals to_path. */
156 /* from_dir is a parent directory of to_path. */
171 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
178 /* If we're here, then "from_dir" has one or more elements that need to
179 * be replaced with "..". */
181 /* Count the number of necessary ".." elements. */
187 /* If this includes ".." we can't do a simple series of "..", refuse */
188 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
191 /* Count number of elements */
198 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
202 for (p
= r
; n_parents
> 0; n_parents
--)
203 p
= mempcpy(p
, "../", 3);
208 /* Remove trailing slash */
215 int path_strv_make_absolute_cwd(char **l
) {
219 /* Goes through every item in the string list and makes it
220 * absolute. This works in place and won't rollback any
221 * changes on failure. */
226 r
= path_make_absolute_cwd(*s
, &t
);
230 path_simplify(t
, false);
231 free_and_replace(*s
, t
);
237 char **path_strv_resolve(char **l
, const char *root
) {
246 /* Goes through every item in the string list and canonicalize
247 * the path. This works in place and won't rollback any
248 * changes on failure. */
251 _cleanup_free_
char *orig
= NULL
;
254 if (!path_is_absolute(*s
)) {
261 t
= prefix_root(root
, orig
);
269 r
= chase_symlinks(t
, root
, 0, &u
);
287 x
= path_startswith(u
, root
);
289 /* restore the slash if it was lost */
290 if (!startswith(x
, "/"))
301 /* canonicalized path goes outside of
302 * prefix, keep the original path instead */
303 free_and_replace(u
, orig
);
319 char **path_strv_resolve_uniq(char **l
, const char *root
) {
324 if (!path_strv_resolve(l
, root
))
330 char *path_simplify(char *path
, bool kill_dots
) {
332 bool slash
= false, ignore_slash
= false, absolute
;
336 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
337 * if kill_dots is true. Modifies the passed string in-place.
339 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
340 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
341 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
342 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
345 absolute
= path_is_absolute(path
);
348 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
353 for (t
= path
; *f
; f
++) {
361 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
366 ignore_slash
= false;
374 /* Special rule, if we are talking of the root directory, a trailing slash is good */
375 if (absolute
&& t
== path
)
382 char* path_startswith(const char *path
, const char *prefix
) {
386 /* Returns a pointer to the start of the first component after the parts matched by
388 * - both paths are absolute or both paths are relative,
390 * - each component in prefix in turn matches a component in path at the same position.
391 * An empty string will be returned when the prefix and path are equivalent.
393 * Returns NULL otherwise.
396 if ((path
[0] == '/') != (prefix
[0] == '/'))
402 path
+= strspn(path
, "/");
403 prefix
+= strspn(prefix
, "/");
411 a
= strcspn(path
, "/");
412 b
= strcspn(prefix
, "/");
417 if (memcmp(path
, prefix
, a
) != 0)
425 int path_compare(const char *a
, const char *b
) {
431 /* A relative path and an abolute path must not compare as equal.
432 * Which one is sorted before the other does not really matter.
433 * Here a relative path is ordered before an absolute path. */
434 d
= (a
[0] == '/') - (b
[0] == '/');
444 if (*a
== 0 && *b
== 0)
447 /* Order prefixes first: "/foo" before "/foo/bar" */
456 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
457 d
= memcmp(a
, b
, MIN(j
, k
));
459 return (d
> 0) - (d
< 0); /* sign of d */
461 /* Sort "/foo/a" before "/foo/aaa" */
462 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
471 bool path_equal(const char *a
, const char *b
) {
472 return path_compare(a
, b
) == 0;
475 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
476 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
479 char* path_join(const char *root
, const char *path
, const char *rest
) {
483 return strjoin(root
, endswith(root
, "/") ? "" : "/",
484 path
[0] == '/' ? path
+1 : path
,
485 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
486 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
489 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
490 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
493 int find_binary(const char *name
, char **ret
) {
500 if (access(name
, X_OK
) < 0)
504 r
= path_make_absolute_cwd(name
, ret
);
513 * Plain getenv, not secure_getenv, because we want
514 * to actually allow the user to pick the binary.
520 last_error
= -ENOENT
;
523 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
525 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
531 if (!path_is_absolute(element
))
534 j
= strjoin(element
, "/", name
);
538 if (access(j
, X_OK
) >= 0) {
542 *ret
= path_simplify(j
, false);
555 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
556 bool changed
= false;
557 const char* const* i
;
564 STRV_FOREACH(i
, paths
) {
568 if (stat(*i
, &stats
) < 0)
571 u
= timespec_load(&stats
.st_mtim
);
577 log_debug("timestamp of '%s' changed", *i
);
579 /* update timestamp */
590 static int binary_is_good(const char *binary
) {
591 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
594 r
= find_binary(binary
, &p
);
600 /* An fsck that is linked to /bin/true is a non-existent
603 r
= readlink_malloc(p
, &d
);
604 if (r
== -EINVAL
) /* not a symlink */
609 return !PATH_IN_SET(d
, "true"
615 int fsck_exists(const char *fstype
) {
620 if (streq(fstype
, "auto"))
623 checker
= strjoina("fsck.", fstype
);
624 return binary_is_good(checker
);
627 int mkfs_exists(const char *fstype
) {
632 if (streq(fstype
, "auto"))
635 mkfs
= strjoina("mkfs.", fstype
);
636 return binary_is_good(mkfs
);
639 char *prefix_root(const char *root
, const char *path
) {
643 /* If root is passed, prefixes path with it. Otherwise returns
648 /* First, drop duplicate prefixing slashes from the path */
649 while (path
[0] == '/' && path
[1] == '/')
652 if (empty_or_root(root
))
655 l
= strlen(root
) + 1 + strlen(path
) + 1;
663 while (p
> n
&& p
[-1] == '/')
673 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
678 * This function is intended to be used in command line
679 * parsers, to handle paths that are passed in. It makes the
680 * path absolute, and reduces it to NULL if omitted or
681 * root (the latter optionally).
683 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
684 * SUCCESS! Hence, do not pass in uninitialized pointers.
692 r
= path_make_absolute_cwd(path
, &p
);
694 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
696 path_simplify(p
, false);
697 if (suppress_root
&& empty_or_root(p
))
700 free_and_replace(*arg
, p
);
705 char* dirname_malloc(const char *path
) {
706 char *d
, *dir
, *dir2
;
726 const char *last_path_component(const char *path
) {
728 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
741 * Also, the empty string is mapped to itself.
743 * This is different than basename(), which returns "" when a trailing slash is present.
748 l
= k
= strlen(path
);
749 if (l
== 0) /* special case — an empty string */
752 while (k
> 0 && path
[k
-1] == '/')
755 if (k
== 0) /* the root directory */
758 while (k
> 0 && path
[k
-1] != '/')
764 bool filename_is_valid(const char *p
) {
770 if (dot_or_dot_dot(p
))
773 e
= strchrnul(p
, '/');
777 if (e
- p
> FILENAME_MAX
)
783 bool path_is_normalized(const char *p
) {
788 if (dot_or_dot_dot(p
))
791 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
794 if (strlen(p
)+1 > PATH_MAX
)
797 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
806 char *file_in_same_dir(const char *path
, const char *filename
) {
813 /* This removes the last component of path and appends
814 * filename, unless the latter is absolute anyway or the
817 if (path_is_absolute(filename
))
818 return strdup(filename
);
820 e
= strrchr(path
, '/');
822 return strdup(filename
);
824 k
= strlen(filename
);
825 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
829 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
833 bool hidden_or_backup_file(const char *filename
) {
838 if (filename
[0] == '.' ||
839 streq(filename
, "lost+found") ||
840 streq(filename
, "aquota.user") ||
841 streq(filename
, "aquota.group") ||
842 endswith(filename
, "~"))
845 p
= strrchr(filename
, '.');
849 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
850 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
851 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
852 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
853 * string. Specifically: there's now:
855 * The generic suffixes "~" and ".bak" for backup files
856 * The generic prefix "." for hidden files
858 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
859 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
862 return STR_IN_SET(p
+ 1,
882 bool is_device_path(const char *path
) {
884 /* Returns true on paths that likely refer to a device, either by path in sysfs or to something in /dev */
886 return PATH_STARTSWITH_SET(path
, "/dev/", "/sys/");
889 bool valid_device_node_path(const char *path
) {
891 /* Some superficial checks whether the specified path is a valid device node path, all without looking at the
892 * actual device node. */
894 if (!PATH_STARTSWITH_SET(path
, "/dev/", "/run/systemd/inaccessible/"))
897 if (endswith(path
, "/")) /* can't be a device node if it ends in a slash */
900 return path_is_normalized(path
);
903 bool valid_device_allow_pattern(const char *path
) {
906 /* Like valid_device_node_path(), but also allows full-subsystem expressions, like DeviceAllow= and DeviceDeny=
909 if (startswith(path
, "block-") ||
910 startswith(path
, "char-"))
913 return valid_device_node_path(path
);
916 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
920 /* Try to guess if systemd installation is later than the specified version. This
921 * is hacky and likely to yield false negatives, particularly if the installation
922 * is non-standard. False positives should be relatively rare.
925 NULSTR_FOREACH(pattern
,
926 /* /lib works for systems without usr-merge, and for systems with a sane
927 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
928 * for Gentoo which does a merge without making /lib a symlink.
930 "lib/systemd/libsystemd-shared-*.so\0"
931 "lib64/systemd/libsystemd-shared-*.so\0"
932 "usr/lib/systemd/libsystemd-shared-*.so\0"
933 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
935 _cleanup_strv_free_
char **names
= NULL
;
936 _cleanup_free_
char *path
= NULL
;
939 path
= prefix_root(root
, pattern
);
943 r
= glob_extend(&names
, path
);
949 assert_se(c
= endswith(path
, "*.so"));
950 *c
= '\0'; /* truncate the glob part */
952 STRV_FOREACH(name
, names
) {
953 /* This is most likely to run only once, hence let's not optimize anything. */
957 t
= startswith(*name
, path
);
961 t2
= endswith(t
, ".so");
965 t2
[0] = '\0'; /* truncate the suffix */
967 r
= safe_atou(t
, &version
);
969 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
973 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
975 version
>= minimal_version
? "OK" : "too old");
976 if (version
>= minimal_version
)
984 bool dot_or_dot_dot(const char *path
) {
997 bool empty_or_root(const char *root
) {
999 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
1000 * i.e. either / or NULL or the empty string or any equivalent. */
1005 return root
[strspn(root
, "/")] == 0;
1008 int path_simplify_and_warn(
1012 const char *filename
,
1014 const char *lvalue
) {
1016 bool absolute
, fatal
= flag
& PATH_CHECK_FATAL
;
1018 assert(!FLAGS_SET(flag
, PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
1020 if (!utf8_is_valid(path
)) {
1021 log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
1025 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
1026 absolute
= path_is_absolute(path
);
1028 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
)) {
1029 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1030 "%s= path is not absolute%s: %s",
1031 lvalue
, fatal
? "" : ", ignoring", path
);
1035 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
)) {
1036 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1037 "%s= path is absolute%s: %s",
1038 lvalue
, fatal
? "" : ", ignoring", path
);
1043 path_simplify(path
, true);
1045 if (!path_is_normalized(path
)) {
1046 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1047 "%s= path is not normalized%s: %s",
1048 lvalue
, fatal
? "" : ", ignoring", path
);