1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2010-2012 Lennart Poettering
16 /* When we include libgen.h because we need dirname() we immediately
17 * undefine basename() since libgen.h defines it as a macro to the
18 * POSIX version which is really broken. We prefer GNU basename(). */
22 #include "alloc-util.h"
23 #include "extract-word.h"
25 #include "glob-util.h"
29 #include "parse-util.h"
30 #include "path-util.h"
31 #include "stat-util.h"
32 #include "string-util.h"
34 #include "time-util.h"
37 bool path_is_absolute(const char *p
) {
41 bool is_path(const char *p
) {
42 return !!strchr(p
, '/');
45 int path_split_and_make_absolute(const char *p
, char ***ret
) {
52 l
= strv_split(p
, ":");
56 r
= path_strv_make_absolute_cwd(l
);
66 char *path_make_absolute(const char *p
, const char *prefix
) {
69 /* Makes every item in the list an absolute path by prepending
70 * the prefix, if specified and necessary */
72 if (path_is_absolute(p
) || isempty(prefix
))
75 if (endswith(prefix
, "/"))
76 return strjoin(prefix
, p
);
78 return strjoin(prefix
, "/", p
);
81 int safe_getcwd(char **ret
) {
84 cwd
= get_current_dir_name();
86 return negative_errno();
88 /* Let's make sure the directory is really absolute, to protect us from the logic behind
99 int path_make_absolute_cwd(const char *p
, char **ret
) {
106 /* Similar to path_make_absolute(), but prefixes with the
107 * current working directory. */
109 if (path_is_absolute(p
))
112 _cleanup_free_
char *cwd
= NULL
;
114 r
= safe_getcwd(&cwd
);
118 if (endswith(cwd
, "/"))
121 c
= strjoin(cwd
, "/", p
);
130 int path_make_relative(const char *from_dir
, const char *to_path
, char **_r
) {
132 unsigned n_parents
= 0;
138 /* Strips the common part, and adds ".." elements as necessary. */
140 if (!path_is_absolute(from_dir
) || !path_is_absolute(to_path
))
143 f
= strdupa(from_dir
);
144 t
= strdupa(to_path
);
146 path_simplify(f
, true);
147 path_simplify(t
, true);
149 /* Skip the common part. */
158 /* from_dir equals to_path. */
161 /* from_dir is a parent directory of to_path. */
176 if (a
!= b
|| memcmp(f
, t
, a
) != 0)
183 /* If we're here, then "from_dir" has one or more elements that need to
184 * be replaced with "..". */
186 /* Count the number of necessary ".." elements. */
192 /* If this includes ".." we can't do a simple series of "..", refuse */
193 if (w
== 2 && f
[0] == '.' && f
[1] == '.')
196 /* Count number of elements */
203 r
= new(char, n_parents
* 3 + strlen(t
) + 1);
207 for (p
= r
; n_parents
> 0; n_parents
--)
208 p
= mempcpy(p
, "../", 3);
213 /* Remove trailing slash */
220 int path_strv_make_absolute_cwd(char **l
) {
224 /* Goes through every item in the string list and makes it
225 * absolute. This works in place and won't rollback any
226 * changes on failure. */
231 r
= path_make_absolute_cwd(*s
, &t
);
235 path_simplify(t
, false);
236 free_and_replace(*s
, t
);
242 char **path_strv_resolve(char **l
, const char *root
) {
251 /* Goes through every item in the string list and canonicalize
252 * the path. This works in place and won't rollback any
253 * changes on failure. */
256 _cleanup_free_
char *orig
= NULL
;
259 if (!path_is_absolute(*s
)) {
266 t
= prefix_root(root
, orig
);
274 r
= chase_symlinks(t
, root
, 0, &u
);
292 x
= path_startswith(u
, root
);
294 /* restore the slash if it was lost */
295 if (!startswith(x
, "/"))
306 /* canonicalized path goes outside of
307 * prefix, keep the original path instead */
308 free_and_replace(u
, orig
);
324 char **path_strv_resolve_uniq(char **l
, const char *root
) {
329 if (!path_strv_resolve(l
, root
))
335 char *path_simplify(char *path
, bool kill_dots
) {
337 bool slash
= false, ignore_slash
= false, absolute
;
341 /* Removes redundant inner and trailing slashes. Also removes unnecessary dots
342 * if kill_dots is true. Modifies the passed string in-place.
344 * ///foo//./bar/. becomes /foo/./bar/. (if kill_dots is false)
345 * ///foo//./bar/. becomes /foo/bar (if kill_dots is true)
346 * .//./foo//./bar/. becomes ./foo/bar (if kill_dots is false)
347 * .//./foo//./bar/. becomes foo/bar (if kill_dots is true)
350 absolute
= path_is_absolute(path
);
353 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/')) {
358 for (t
= path
; *f
; f
++) {
366 if (kill_dots
&& *f
== '.' && IN_SET(f
[1], 0, '/'))
371 ignore_slash
= false;
379 /* Special rule, if we are talking of the root directory, a trailing slash is good */
380 if (absolute
&& t
== path
)
387 char* path_startswith(const char *path
, const char *prefix
) {
391 /* Returns a pointer to the start of the first component after the parts matched by
393 * - both paths are absolute or both paths are relative,
395 * - each component in prefix in turn matches a component in path at the same position.
396 * An empty string will be returned when the prefix and path are equivalent.
398 * Returns NULL otherwise.
401 if ((path
[0] == '/') != (prefix
[0] == '/'))
407 path
+= strspn(path
, "/");
408 prefix
+= strspn(prefix
, "/");
416 a
= strcspn(path
, "/");
417 b
= strcspn(prefix
, "/");
422 if (memcmp(path
, prefix
, a
) != 0)
430 int path_compare(const char *a
, const char *b
) {
436 /* A relative path and an abolute path must not compare as equal.
437 * Which one is sorted before the other does not really matter.
438 * Here a relative path is ordered before an absolute path. */
439 d
= (a
[0] == '/') - (b
[0] == '/');
449 if (*a
== 0 && *b
== 0)
452 /* Order prefixes first: "/foo" before "/foo/bar" */
461 /* Alphabetical sort: "/foo/aaa" before "/foo/b" */
462 d
= memcmp(a
, b
, MIN(j
, k
));
464 return (d
> 0) - (d
< 0); /* sign of d */
466 /* Sort "/foo/a" before "/foo/aaa" */
467 d
= (j
> k
) - (j
< k
); /* sign of (j - k) */
476 bool path_equal(const char *a
, const char *b
) {
477 return path_compare(a
, b
) == 0;
480 bool path_equal_or_files_same(const char *a
, const char *b
, int flags
) {
481 return path_equal(a
, b
) || files_same(a
, b
, flags
) > 0;
484 char* path_join(const char *root
, const char *path
, const char *rest
) {
488 return strjoin(root
, endswith(root
, "/") ? "" : "/",
489 path
[0] == '/' ? path
+1 : path
,
490 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
491 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
494 rest
? (endswith(path
, "/") ? "" : "/") : NULL
,
495 rest
&& rest
[0] == '/' ? rest
+1 : rest
);
498 int find_binary(const char *name
, char **ret
) {
505 if (access(name
, X_OK
) < 0)
509 r
= path_make_absolute_cwd(name
, ret
);
518 * Plain getenv, not secure_getenv, because we want
519 * to actually allow the user to pick the binary.
525 last_error
= -ENOENT
;
528 _cleanup_free_
char *j
= NULL
, *element
= NULL
;
530 r
= extract_first_word(&p
, &element
, ":", EXTRACT_RELAX
|EXTRACT_DONT_COALESCE_SEPARATORS
);
536 if (!path_is_absolute(element
))
539 j
= strjoin(element
, "/", name
);
543 if (access(j
, X_OK
) >= 0) {
547 *ret
= path_simplify(j
, false);
560 bool paths_check_timestamp(const char* const* paths
, usec_t
*timestamp
, bool update
) {
561 bool changed
= false;
562 const char* const* i
;
569 STRV_FOREACH(i
, paths
) {
573 if (stat(*i
, &stats
) < 0)
576 u
= timespec_load(&stats
.st_mtim
);
582 log_debug("timestamp of '%s' changed", *i
);
584 /* update timestamp */
595 static int binary_is_good(const char *binary
) {
596 _cleanup_free_
char *p
= NULL
, *d
= NULL
;
599 r
= find_binary(binary
, &p
);
605 /* An fsck that is linked to /bin/true is a non-existent
608 r
= readlink_malloc(p
, &d
);
609 if (r
== -EINVAL
) /* not a symlink */
614 return !PATH_IN_SET(d
, "true"
620 int fsck_exists(const char *fstype
) {
625 if (streq(fstype
, "auto"))
628 checker
= strjoina("fsck.", fstype
);
629 return binary_is_good(checker
);
632 int mkfs_exists(const char *fstype
) {
637 if (streq(fstype
, "auto"))
640 mkfs
= strjoina("mkfs.", fstype
);
641 return binary_is_good(mkfs
);
644 char *prefix_root(const char *root
, const char *path
) {
648 /* If root is passed, prefixes path with it. Otherwise returns
653 /* First, drop duplicate prefixing slashes from the path */
654 while (path
[0] == '/' && path
[1] == '/')
657 if (empty_or_root(root
))
660 l
= strlen(root
) + 1 + strlen(path
) + 1;
668 while (p
> n
&& p
[-1] == '/')
678 int parse_path_argument_and_warn(const char *path
, bool suppress_root
, char **arg
) {
683 * This function is intended to be used in command line
684 * parsers, to handle paths that are passed in. It makes the
685 * path absolute, and reduces it to NULL if omitted or
686 * root (the latter optionally).
688 * NOTE THAT THIS WILL FREE THE PREVIOUS ARGUMENT POINTER ON
689 * SUCCESS! Hence, do not pass in uninitialized pointers.
697 r
= path_make_absolute_cwd(path
, &p
);
699 return log_error_errno(r
, "Failed to parse path \"%s\" and make it absolute: %m", path
);
701 path_simplify(p
, false);
702 if (suppress_root
&& empty_or_root(p
))
705 free_and_replace(*arg
, p
);
710 char* dirname_malloc(const char *path
) {
711 char *d
, *dir
, *dir2
;
731 const char *last_path_component(const char *path
) {
733 /* Finds the last component of the path, preserving the optional trailing slash that signifies a directory.
746 * Also, the empty string is mapped to itself.
748 * This is different than basename(), which returns "" when a trailing slash is present.
753 l
= k
= strlen(path
);
754 if (l
== 0) /* special case — an empty string */
757 while (k
> 0 && path
[k
-1] == '/')
760 if (k
== 0) /* the root directory */
763 while (k
> 0 && path
[k
-1] != '/')
769 bool filename_is_valid(const char *p
) {
775 if (dot_or_dot_dot(p
))
778 e
= strchrnul(p
, '/');
782 if (e
- p
> FILENAME_MAX
)
788 bool path_is_normalized(const char *p
) {
793 if (dot_or_dot_dot(p
))
796 if (startswith(p
, "../") || endswith(p
, "/..") || strstr(p
, "/../"))
799 if (strlen(p
)+1 > PATH_MAX
)
802 if (startswith(p
, "./") || endswith(p
, "/.") || strstr(p
, "/./"))
811 char *file_in_same_dir(const char *path
, const char *filename
) {
818 /* This removes the last component of path and appends
819 * filename, unless the latter is absolute anyway or the
822 if (path_is_absolute(filename
))
823 return strdup(filename
);
825 e
= strrchr(path
, '/');
827 return strdup(filename
);
829 k
= strlen(filename
);
830 ret
= new(char, (e
+ 1 - path
) + k
+ 1);
834 memcpy(mempcpy(ret
, path
, e
+ 1 - path
), filename
, k
+ 1);
838 bool hidden_or_backup_file(const char *filename
) {
843 if (filename
[0] == '.' ||
844 streq(filename
, "lost+found") ||
845 streq(filename
, "aquota.user") ||
846 streq(filename
, "aquota.group") ||
847 endswith(filename
, "~"))
850 p
= strrchr(filename
, '.');
854 /* Please, let's not add more entries to the list below. If external projects think it's a good idea to come up
855 * with always new suffixes and that everybody else should just adjust to that, then it really should be on
856 * them. Hence, in future, let's not add any more entries. Instead, let's ask those packages to instead adopt
857 * one of the generic suffixes/prefixes for hidden files or backups, possibly augmented with an additional
858 * string. Specifically: there's now:
860 * The generic suffixes "~" and ".bak" for backup files
861 * The generic prefix "." for hidden files
863 * Thus, if a new package manager "foopkg" wants its own set of ".foopkg-new", ".foopkg-old", ".foopkg-dist"
864 * or so registered, let's refuse that and ask them to use ".foopkg.new", ".foopkg.old" or ".foopkg~" instead.
867 return STR_IN_SET(p
+ 1,
887 bool is_device_path(const char *path
) {
889 /* Returns true on paths that refer to a device, either in
890 * sysfs or in /dev */
892 return path_startswith(path
, "/dev/") ||
893 path_startswith(path
, "/sys/");
896 bool is_deviceallow_pattern(const char *path
) {
897 return path_startswith(path
, "/dev/") ||
898 startswith(path
, "block-") ||
899 startswith(path
, "char-");
902 int systemd_installation_has_version(const char *root
, unsigned minimal_version
) {
906 /* Try to guess if systemd installation is later than the specified version. This
907 * is hacky and likely to yield false negatives, particularly if the installation
908 * is non-standard. False positives should be relatively rare.
911 NULSTR_FOREACH(pattern
,
912 /* /lib works for systems without usr-merge, and for systems with a sane
913 * usr-merge, where /lib is a symlink to /usr/lib. /usr/lib is necessary
914 * for Gentoo which does a merge without making /lib a symlink.
916 "lib/systemd/libsystemd-shared-*.so\0"
917 "lib64/systemd/libsystemd-shared-*.so\0"
918 "usr/lib/systemd/libsystemd-shared-*.so\0"
919 "usr/lib64/systemd/libsystemd-shared-*.so\0") {
921 _cleanup_strv_free_
char **names
= NULL
;
922 _cleanup_free_
char *path
= NULL
;
925 path
= prefix_root(root
, pattern
);
929 r
= glob_extend(&names
, path
);
935 assert_se(c
= endswith(path
, "*.so"));
936 *c
= '\0'; /* truncate the glob part */
938 STRV_FOREACH(name
, names
) {
939 /* This is most likely to run only once, hence let's not optimize anything. */
943 t
= startswith(*name
, path
);
947 t2
= endswith(t
, ".so");
951 t2
[0] = '\0'; /* truncate the suffix */
953 r
= safe_atou(t
, &version
);
955 log_debug_errno(r
, "Found libsystemd shared at \"%s.so\", but failed to parse version: %m", *name
);
959 log_debug("Found libsystemd shared at \"%s.so\", version %u (%s).",
961 version
>= minimal_version
? "OK" : "too old");
962 if (version
>= minimal_version
)
970 bool dot_or_dot_dot(const char *path
) {
983 bool empty_or_root(const char *root
) {
985 /* For operations relative to some root directory, returns true if the specified root directory is redundant,
986 * i.e. either / or NULL or the empty string or any equivalent. */
991 return root
[strspn(root
, "/")] == 0;
994 int path_simplify_and_warn(
998 const char *filename
,
1000 const char *lvalue
) {
1002 bool fatal
, absolute
;
1004 assert((flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) != (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
));
1006 fatal
= flag
& PATH_CHECK_FATAL
;
1008 if (!utf8_is_valid(path
)) {
1009 log_syntax_invalid_utf8(unit
, LOG_ERR
, filename
, line
, path
);
1013 if (flag
& (PATH_CHECK_ABSOLUTE
| PATH_CHECK_RELATIVE
)) {
1014 absolute
= path_is_absolute(path
);
1016 if (!absolute
&& (flag
& PATH_CHECK_ABSOLUTE
)) {
1017 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1018 "%s= path is not absolute%s: %s",
1019 fatal
? "" : ", ignoring", lvalue
, path
);
1023 if (absolute
&& (flag
& PATH_CHECK_RELATIVE
)) {
1024 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1025 "%s= path is absolute%s: %s",
1026 fatal
? "" : ", ignoring", lvalue
, path
);
1031 path_simplify(path
, true);
1033 if (!path_is_normalized(path
)) {
1034 log_syntax(unit
, LOG_ERR
, filename
, line
, 0,
1035 "%s= path is not normalized%s: %s",
1036 fatal
? "" : ", ignoring", lvalue
, path
);